KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > security > auth > module > Krb5LoginModule


1 /*
2  * @(#)Krb5LoginModule.java 1.30 06/09/22
3  *
4  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8
9 package com.sun.security.auth.module;
10
11 import java.io.*;
12 import java.net.*;
13 import java.text.MessageFormat JavaDoc;
14 import java.util.*;
15
16 import javax.security.auth.*;
17 import javax.security.auth.kerberos.*;
18 import javax.security.auth.callback.*;
19 import javax.security.auth.login.*;
20 import javax.security.auth.spi.*;
21
22 import sun.security.krb5.*;
23 import sun.security.krb5.Config;
24 import sun.security.krb5.RealmException;
25 import sun.security.util.AuthResources;
26 import sun.security.jgss.krb5.Krb5Util;
27 import sun.security.krb5.Credentials;
28 import sun.misc.HexDumpEncoder;
29
30 /**
31  * <p> This <code>LoginModule</code> authenticates users using
32  * Kerberos protocols.
33  *
34  * <p> The configuration entry for <code>Krb5LoginModule</code> has
35  * several options that control the authentication process and
36  * additions to the <code>Subject</code>'s private credential
37  * set. Irrespective of these options, the <code>Subject</code>'s
38  * principal set and private credentials set are updated only when
39  * <code>commit</code> is called.
40  * When <code>commit</code> is called, the <code>KerberosPrincipal</code>
41  * is added to the <code>Subject</code>'s
42  * principal set and <code>KerberosTicket</code> is
43  * added to the <code>Subject</code>'s private credentials.
44  *
45  * <p> If the configuration entry for <code>KerberosLoginModule</code>
46  * has the option <code>storeKey</code> set to true, then
47  * <code>KerberosKey</code> will also be added to the
48  * subject's private credentials. <code>KerberosKey</code>, the principal's
49  * key will be either obtained from the keytab or
50  * derived from user's password.
51  *
52  * <p> This <code>LoginModule</code> recognizes the <code>doNotPrompt</code>
53  * option. If set to true the user will not be prompted for the password.
54  *
55  * <p> The user can specify the location of the ticket cache by using
56  * the option <code>ticketCache</code> in the configuration entry.
57  *
58  * <p>The user can specify the keytab location by using
59  * the option <code>keyTab</code>
60  * in the configuration entry.
61  *
62  * <p> The principal name can be specified in the configuration entry
63  * by using the option <code>principal</code>. The principal name
64  * can either be a simple user name or a service name such as
65  * <code>host/mission.eng.sun.com</code>. The principal can also
66  * be set using the system property <code>sun.security.krb5.principal</code>.
67  * This property is checked during login. If this property is not set, then
68  * the principal name from the configuration is used. In the
69  * case where the principal property is not set and the principal
70  * entry also does not exist, the user is prompted for the name.
71  *
72  * <p> The following is a list of configuration options supported
73  * for <code>Krb5LoginModule</code>:
74  * <dl>
75  * <blockquote><dt><b><code>refreshKrb5Config</code></b>:</dt>
76  * <dd> Set this to true, if you want the configuration
77  * to be refreshed before the <code>login</code> method is called.</dd>
78  * <P>
79  * <dt><b><code>useTicketCache</code></b>:</dt>
80  * <dd>Set this to true, if you want the
81  * TGT to be obtained
82  * from the ticket cache. Set this option
83  * to false if you do not want this module to use the ticket cache.
84  * (Default is False).
85  * This module will
86  * search for the tickect
87  * cache in the following locations:
88  * For Windows 2000, it will use Local Security Authority (LSA) API
89  * to get the TGT. On Solaris and Linux
90  * it will look for the ticket cache in /tmp/krb5cc_<code>uid</code>
91  * where the uid is numeric user
92  * identifier. If the ticket cache is
93  * not available in either of the above locations, or if we are on a
94  * different Windows platform, it will look for the cache as
95  * {user.home}{file.separator}krb5cc_{user.name}.
96  * You can override the ticket cache location by using
97  * <code>ticketCache</code>
98  * <P>
99  * <dt><b><code>ticketCache</code></b>:</dt>
100  * <dd>Set this to the name of the ticket
101  * cache that contains user's TGT.
102  * If this is set, <code>useTicketCache</code>
103  * must also be set to true; Otherwise a configuration error will
104  * be returned.</dd>
105  * <P>
106  * <dt><b><code>renewTGT</code></b>:</dt>
107  * <dd>Set this to true, if you want to renew
108  * the TGT. If this is set, <code>useTicketCache</code> must also be
109  * set to true; otherwise a configuration error will be returned.</dd>
110  * <p>
111  * <dt><b><code>doNotPrompt</code></b>:</dt>
112  * <dd>Set this to true if you do not want to be
113  * prompted for the password
114  * if credentials can
115  * not be obtained from the cache or keytab.(Default is false)
116  * If set to true authentication will fail if credentials can
117  * not be obtained from the cache or keytab.</dd>
118  * <P>
119  * <dt><b><code>useKeyTab</code></b>:</dt>
120  * <dd>Set this to true if you
121  * want the module to get the principal's key from the
122  * the keytab.(default value is False)
123  * If <code>keyatb</code>
124  * is not set then
125  * the module will locate the keytab from the
126  * Kerberos configuration file.</dd>
127  * If it is not specifed in the Kerberos configuration file
128  * then it will look for the file
129  * <code>{user.home}{file.separator}</code>krb5.keytab.</dd>
130  * <P>
131  * <dt><b><code>keyTab</code></b>:</dt>
132  * <dd>Set this to the file name of the
133  * keytab to get principal's secret key.</dd>
134  * <P>
135  * <dt><b><code>storeKey</code></b>:</dt>
136  * <dd>Set this to true to if you want the
137  * principal's key to be stored in the Subject's private credentials. </dd>
138  * <p>
139  * <dt><b><code>principal</code></b>:</dt>
140  * <dd>The name of the principal that should
141  * be used. The principal can be a simple username such as
142  * "<code>testuser</code>" or a service name such as
143  * "<code>host/testhost.eng.sun.com</code>". You can use the
144  * <code>principal</code> option to set the principal when there are
145  * credentials for multiple principals in the
146  * <code>keyTab</code> or when you want a specific ticket cache only.
147  * The principal can also be set using the system property
148  * <code>sun.security.krb5.principal</code>. In addition, if this
149  * system property is defined, then it will be used. If this property
150  * is not set, then the principal name from the configuration will be
151  * used.</dd>
152  * <P>
153  * <dt><b><code>isInitiator</code></b>:</dt>
154  * <dd>Set this to true, if initiator. Set this to false, if acceptor only.
155  * (Default is true).
156  * Note: Do not set this value to false for initiators.</dd>
157  * </dl></blockquote>
158  *
159  * <p> This <code>LoginModule</code> also recognizes the following additional
160  * <code>Configuration</code>
161  * options that enable you to share username and passwords across different
162  * authentication modules:
163  * <pre>
164  *
165  * useFirstPass if, true, this LoginModule retrieves the
166  * username and password from the module's shared state,
167  * using "javax.security.auth.login.name" and
168  * "javax.security.auth.login.password" as the respective
169  * keys. The retrieved values are used for authentication.
170  * If authentication fails, no attempt for a retry
171  * is made, and the failure is reported back to the
172  * calling application.
173  *
174  * tryFirstPass if, true, this LoginModule retrieves the
175  * the username and password from the module's shared
176  * state using "javax.security.auth.login.name" and
177  * "javax.security.auth.login.password" as the respective
178  * keys. The retrieved values are used for
179  * authentication.
180  * If authentication fails, the module uses the
181  * CallbackHandler to retrieve a new username
182  * and password, and another attempt to authenticate
183  * is made. If the authentication fails,
184  * the failure is reported back to the calling application
185  *
186  * storePass if, true, this LoginModule stores the username and
187  * password obtained from the CallbackHandler in the
188  * modules shared state, using
189  * "javax.security.auth.login.name" and
190  * "javax.security.auth.login.password" as the respective
191  * keys. This is not performed if existing values already
192  * exist for the username and password in the shared
193  * state, or if authentication fails.
194  *
195  * clearPass if, true, this <code>LoginModule</code> clears the
196  * username and password stored in the module's shared
197  * state after both phases of authentication
198  * (login and commit) have completed.
199  * </pre>
200  * <p>Examples of some configuration values for Krb5LoginModule in
201  * JAAS config file and the results are:
202  * <ul>
203  * <p> <code>doNotPrompt</code>=true;
204  * </ul>
205  * <p> This is an illegal combination since <code>useTicketCache</code>
206  * is not set and the user can not be prompted for the password.
207  *<ul>
208  * <p> <code>ticketCache</code> = < filename >;
209  *</ul>
210  * <p> This is an illegal combination since <code>useTicketCache</code>
211  * is not set to true and the ticketCache is set. A configuration error
212  * will occur.
213  * <ul>
214  * <p> <code>renewTGT</code>=true;
215  *</ul>
216  * <p> This is an illegal combination since <code>useTicketCache</code> is
217  * not set to true and renewTGT is set. A configuration error will occur.
218  * <ul>
219  * <p> <code>storeKey</code>=true
220  * <code>useTicketCache</code> = true
221  * <code>doNotPrompt</code>=true;;
222  *</ul>
223  * <p> This is an illegal combination since <code>storeKey</code> is set to
224  * true but the key can not be obtained either by prompting the user or from
225  * the keytab.A configuration error will occur.
226  * <ul>
227  * <p> <code>keyTab</code> = < filename > <code>doNotPrompt</code>=true ;
228  * </ul>
229  * <p>This is an illegal combination since useKeyTab is not set to true and
230  * the keyTab is set. A configuration error will occur.
231  * <ul>
232  * <p> <code>debug=true </code>
233  *</ul>
234  * <p> Prompt the user for the principal name and the password.
235  * Use the authentication exchange to get TGT from the KDC and
236  * populate the <code>Subject</code> with the principal and TGT.
237  * Output debug messages.
238  * <ul>
239  * <p> <code>useTicketCache</code> = true <code>doNotPrompt</code>=true;
240  *</ul>
241  * <p>Check the default cache for TGT and populate the <code>Subject</code>
242  * with the principal and TGT. If the TGT is not available,
243  * do not prompt the user, instead fail the authentication.
244  * <ul>
245  * <p><code>principal</code>=< name ><code>useTicketCache</code> = true
246  * <code>doNotPrompt</code>=true;
247  *</ul>
248  * <p> Get the TGT from the default cache for the principal and populate the
249  * Subject's principal and private creds set. If ticket cache is
250  * not available or does not contain the principal's TGT
251  * authentication will fail.
252  * <ul>
253  * <p> <code>useTicketCache</code> = true
254  * <code>ticketCache</code>=< file name ><code>useKeyTab</code> = true
255  * <code> keyTab</code>=< keytab filename >
256  * <code>principal</code> = < principal name >
257  * <code>doNotPrompt</code>=true;
258  *</ul>
259  * <p> Search the cache for the principal's TGT. If it is not available
260  * use the key in the keytab to perform authentication exchange with the
261  * KDC and acquire the TGT.
262  * The Subject will be populated with the principal and the TGT.
263  * If the key is not available or valid then authentication will fail.
264  * <ul>
265  * <p><code>useTicketCache</code> = true
266  * <code>ticketCache</code>=< file name >
267  *</ul>
268  * <p> The TGT will be obtained from the cache specified.
269  * The Kerberos principal name used will be the principal name in
270  * the Ticket cache. If the TGT is not available in the
271  * ticket cache the user will be prompted for the principal name
272  * and the password. The TGT will be obtained using the authentication
273  * exchange with the KDC.
274  * The Subject will be populated with the TGT.
275  *<ul>
276  * <p> <code>useKeyTab</code> = true
277  * <code>keyTab</code>=< keytab filename >
278  * <code>principal</code>= < principal name >
279  * <code>storeKey</code>=true;
280  *</ul>
281  * <p> The key for the principal will be retrieved from the keytab.
282  * If the key is not available in the keytab the user will be prompted
283  * for the principal's password. The Subject will be populated
284  * with the principal's key either from the keytab or derived from the
285  * password entered.
286  * <ul>
287  * <p> <code>useKeyTab</code> = true
288  * <code>keyTab</code>=< keytabname >
289  * <code>storeKey</code>=true
290  * <code>doNotPrompt</code>=true;
291  *</ul>
292  * <p>The user will be prompted for the service principal name.
293  * If the principal's
294  * longterm key is available in the keytab , it will be added to the
295  * Subject's private credentials. An authentication exchange will be
296  * attempted with the principal name and the key from the Keytab.
297  * If successful the TGT will be added to the
298  * Subject's private credentials set. Otherwise the authentication will
299  * fail.
300  *<ul>
301  * <p><code>useKeyTab</code> = true
302  * <code>keyTab</code>=< file name > <code>storeKey</code>=true
303  * <code>principal</code>= < principal name >
304  * <code>useTicketCache</code>=true
305  * <code>ticketCache</code>=< file name >;
306  *</ul>
307  * <p>The principal's key will be retrieved from the keytab and added
308  * to the <code>Subject</code>'s private credentials. If the key
309  * is not available, the
310  * user will be prompted for the password; the key derived from the password
311  * will be added to the Subject's private credentials set. The
312  * client's TGT will be retrieved from the ticket cache and added to the
313  * <code>Subject</code>'s private credentials. If the TGT is not available
314  * in the ticket cache, it will be obtained using the authentication
315  * exchange and added to the Subject's private credentials.
316  * <ul>
317  * <p><code>isInitiator</code> = false
318  *</ul>
319  * <p>Configured to act as acceptor only, credentials are not acquired
320  * via AS exchange. For acceptors only, set this value to false.
321  * For initiators, do not set this value to false.
322  * <ul>
323  * <p><code>isInitiator</code> = true
324  *</ul>
325  * <p>Configured to act as initiator, credentials are acquired
326  * via AS exchange. For initiators, set this value to true, or leave this
327  * option unset, in which case default value (true) will be used.
328  *
329  * @version 1.18, 01/11/00
330  * @author Ram Marti
331  */

332
333 public class Krb5LoginModule implements LoginModule {
334
335     // initial state
336
private Subject subject;
337     private CallbackHandler callbackHandler;
338     private Map sharedState;
339     private Map options;
340
341     // configurable option
342
private boolean debug = false;
343     private boolean storeKey = false;
344     private boolean doNotPrompt = false;
345     private boolean useTicketCache = false;
346     private boolean useKeyTab = false;
347     private String JavaDoc ticketCacheName = null;
348     private String JavaDoc keyTabName = null;
349     private String JavaDoc princName = null;
350
351     private boolean useFirstPass = false;
352     private boolean tryFirstPass = false;
353     private boolean storePass = false;
354     private boolean clearPass = false;
355     private boolean refreshKrb5Config = false;
356     private boolean renewTGT = false;
357
358     // specify if initiator.
359
// perform authentication exchange if initiator
360
private boolean isInitiator = true;
361
362     // the authentication status
363
private boolean succeeded = false;
364     private boolean commitSucceeded = false;
365     private String JavaDoc username;
366     private EncryptionKey[] encKeys = null;
367     private Credentials cred = null;
368
369     private PrincipalName principal = null;
370     private KerberosPrincipal kerbClientPrinc = null;
371     private KerberosTicket kerbTicket = null;
372     private KerberosKey[] kerbKeys = null;
373     private StringBuffer JavaDoc krb5PrincName = null;
374     private char[] password = null;
375
376     private static final String JavaDoc NAME = "javax.security.auth.login.name";
377     private static final String JavaDoc PWD = "javax.security.auth.login.password";
378     static final java.util.ResourceBundle JavaDoc rb =
379         java.util.ResourceBundle.getBundle("sun.security.util.AuthResources");
380
381     /**
382      * Initialize this <code>LoginModule</code>.
383      *
384      * <p>
385      * @param subject the <code>Subject</code> to be authenticated. <p>
386      *
387      * @param callbackHandler a <code>CallbackHandler</code> for
388      * communication with the end user (prompting for
389      * usernames and passwords, for example). <p>
390      *
391      * @param sharedState shared <code>LoginModule</code> state. <p>
392      *
393      * @param options options specified in the login
394      * <code>Configuration</code> for this particular
395      * <code>LoginModule</code>.
396      */

397
398     public void initialize(Subject subject,
399                CallbackHandler callbackHandler,
400                Map<String JavaDoc, ?> sharedState,
401                Map<String JavaDoc, ?> options) {
402  
403     this.subject = subject;
404     this.callbackHandler = callbackHandler;
405     this.sharedState = sharedState;
406     this.options = options;
407
408     // initialize any configured options
409

410     debug = "true".equalsIgnoreCase((String JavaDoc)options.get("debug"));
411     storeKey = "true".equalsIgnoreCase((String JavaDoc)options.get("storeKey"));
412     doNotPrompt = "true".equalsIgnoreCase((String JavaDoc)options.get
413                           ("doNotPrompt"));
414     useTicketCache = "true".equalsIgnoreCase((String JavaDoc)options.get
415                          ("useTicketCache"));
416     useKeyTab = "true".equalsIgnoreCase((String JavaDoc)options.get("useKeyTab"));
417     ticketCacheName = (String JavaDoc)options.get("ticketCache");
418     keyTabName = (String JavaDoc)options.get("keyTab");
419     princName = (String JavaDoc)options.get("principal");
420     refreshKrb5Config =
421         "true".equalsIgnoreCase((String JavaDoc)options.get("refreshKrb5Config"));
422     renewTGT =
423         "true".equalsIgnoreCase((String JavaDoc)options.get("renewTGT"));
424
425     // check isInitiator value
426
String JavaDoc isInitiatorValue = ((String JavaDoc)options.get("isInitiator"));
427     if (isInitiatorValue == null) {
428         // use default, if value not set
429
} else {
430         isInitiator = "true".equalsIgnoreCase(isInitiatorValue);
431     }
432
433     tryFirstPass =
434         "true".equalsIgnoreCase
435         ((String JavaDoc)options.get("tryFirstPass"));
436     useFirstPass =
437         "true".equalsIgnoreCase
438         ((String JavaDoc)options.get("useFirstPass"));
439     storePass =
440         "true".equalsIgnoreCase((String JavaDoc)options.get("storePass"));
441     clearPass =
442         "true".equalsIgnoreCase((String JavaDoc)options.get("clearPass"));
443     if (debug) {
444         System.out.print("Debug is " + debug
445                  + " storeKey " + storeKey
446                  + " useTicketCache " + useTicketCache
447                  + " useKeyTab " + useKeyTab
448                  + " doNotPrompt " + doNotPrompt
449                  + " ticketCache is " + ticketCacheName
450                  + " isInitiator " + isInitiator
451                  + " KeyTab is " + keyTabName
452                  + " refreshKrb5Config is " + refreshKrb5Config
453                      + " principal is " + princName
454                  + " tryFirstPass is " + tryFirstPass
455                  + " useFirstPass is " + useFirstPass
456                  + " storePass is " + storePass
457                  + " clearPass is " + clearPass + "\n");
458     }
459     }
460     
461
462     /**
463      * Authenticate the user
464      *
465      * <p>
466      *
467      * @return true in all cases since this <code>LoginModule</code>
468      * should not be ignored.
469      *
470      * @exception FailedLoginException if the authentication fails. <p>
471      *
472      * @exception LoginException if this <code>LoginModule</code>
473      * is unable to perform the authentication.
474      */

475     public boolean login() throws LoginException {
476
477     int len;
478     validateConfiguration();
479     if (refreshKrb5Config) {
480         try {
481         if (debug) {
482             System.out.println("Refreshing Kerberos configuration");
483         }
484             sun.security.krb5.Config.refresh();
485         } catch (KrbException ke) {
486             LoginException le = new LoginException(ke.getMessage());
487             le.initCause(ke);
488             throw le;
489         }
490     }
491     String JavaDoc principalProperty = System.getProperty
492         ("sun.security.krb5.principal");
493     if (principalProperty != null) {
494         krb5PrincName = new StringBuffer JavaDoc(principalProperty);
495     } else {
496         if (princName != null) {
497         krb5PrincName = new StringBuffer JavaDoc(princName);
498         }
499         }
500     
501     if (tryFirstPass) {
502         try {
503         attemptAuthentication(true);
504         if (debug)
505             System.out.println("\t\t[Krb5LoginModule] " +
506                        "authentication succeeded");
507         succeeded = true;
508         cleanState();
509         return true;
510         } catch (LoginException le) {
511         // authentication failed -- try again below by prompting
512
cleanState();
513         if (debug) {
514             System.out.println("\t\t[Krb5LoginModule] " +
515                        "tryFirstPass failed with:" +
516                        le.getMessage());
517         }
518         }
519     } else if (useFirstPass) {
520         try {
521         attemptAuthentication(true);
522         succeeded = true;
523         cleanState();
524         return true;
525         } catch (LoginException e) {
526         // authentication failed -- clean out state
527
if (debug) {
528             System.out.println("\t\t[Krb5LoginModule] " +
529                        "authentication failed \n" +
530                        e.getMessage());
531         }
532         succeeded = false;
533         cleanState();
534         throw e;
535         }
536     }
537     
538     // attempt the authentication by getting the username and pwd
539
// by prompting or configuration i.e. not from shared state
540

541     try {
542         attemptAuthentication(false);
543         succeeded = true;
544         cleanState();
545         return true;
546     } catch (LoginException e) {
547         // authentication failed -- clean out state
548
if (debug) {
549         System.out.println("\t\t[Krb5LoginModule] " +
550                    "authentication failed \n" +
551                    e.getMessage());
552         }
553         succeeded = false;
554         cleanState();
555         throw e;
556     }
557     }
558     /**
559      * process the configuration options
560      * Get the TGT either out of
561      * cache or from the KDC using the password entered
562      * Check the permission before getting the TGT
563      */

564
565     private void attemptAuthentication(boolean getPasswdFromSharedState)
566     throws LoginException {
567     
568     /*
569      * Check the creds cache to see whether
570      * we have TGT for this client principal
571      */

572     if (krb5PrincName != null) {
573         try {
574             principal = new PrincipalName
575             (krb5PrincName.toString(),
576              PrincipalName.KRB_NT_PRINCIPAL);
577         } catch (KrbException e) {
578         LoginException le = new LoginException(e.getMessage());
579         le.initCause(e);
580         throw le;
581         }
582     }
583
584     try {
585         if (useTicketCache) {
586         // ticketCacheName == null implies the default cache
587
if (debug)
588             System.out.println("Acquire TGT from Cache");
589         cred = Credentials.acquireTGTFromCache
590             (principal, ticketCacheName);
591
592         if (cred != null) {
593             // check to renew credentials
594
if (!isCurrent(cred)) {
595             if (renewTGT) {
596                 cred = renewCredentials(cred);
597             } else {
598                 // credentials have expired
599
cred = null;
600                 if (debug)
601                 System.out.println("Credentials are" +
602                         " no longer valid");
603             }
604             }
605         }
606
607         if (cred != null) {
608            // get the principal name from the ticket cache
609
if (principal == null) {
610             principal = cred.getClient();
611            }
612         }
613         if (debug) {
614             System.out.println("Principal is " + principal);
615             if (cred == null) {
616             System.out.println
617                 ("null credentials from Ticket Cache");
618             }
619         }
620         }
621
622         // cred = null indicates that we didn't get the creds
623
// from the cache or useTicketCache was false
624

625         if (cred == null) {
626         // We need the principal name whether we use keytab
627
// or AS Exchange
628
if (principal == null) {
629             promptForName(getPasswdFromSharedState);
630             principal = new PrincipalName
631             (krb5PrincName.toString(),
632              PrincipalName.KRB_NT_PRINCIPAL);
633         }
634         if (useKeyTab) {
635             encKeys =
636             EncryptionKey.acquireSecretKeys(principal, keyTabName);
637
638             if (debug) {
639             if (encKeys != null)
640                 System.out.println
641                 ("principal's key obtained from the keytab");
642             else
643                 System.out.println
644                 ("Key for the principal " +
645                  principal +
646                  " not available in " +
647                  ((keyTabName == null) ?
648                   "default key tab" : keyTabName));
649             }
650             
651         }
652         // We can't get the key from the keytab so prompt
653
if (encKeys == null) {
654             promptForPass(getPasswdFromSharedState);
655
656             encKeys = EncryptionKey.acquireSecretKeys(
657             password, principal.getSalt());
658
659             if (isInitiator) {
660             if (debug)
661                 System.out.println("Acquire TGT using AS Exchange");
662             cred = Credentials.acquireTGT(principal,
663                         encKeys, password);
664             // update keys after pre-auth
665
encKeys = EncryptionKey.acquireSecretKeys(password,
666                             principal.getSalt());
667             }
668         } else {
669             if (isInitiator) {
670             if (debug)
671                 System.out.println("Acquire TGT using AS Exchange");
672             cred = Credentials.acquireTGT(principal,
673                         encKeys, password);
674             }
675         }
676
677         // Get the TGT using AS Exchange
678
if (debug) {
679             System.out.println("principal is " + principal);
680             HexDumpEncoder hd = new HexDumpEncoder();
681             for (int i = 0; i < encKeys.length; i++) {
682             System.out.println("EncryptionKey: keyType=" +
683                 encKeys[i].getEType() + " keyBytes (hex dump)=" +
684                             hd.encode(encKeys[i].getBytes()));
685             }
686         }
687
688         // we should hava a non-null cred
689
if (isInitiator && (cred == null)) {
690             throw new LoginException
691             ("TGT Can not be obtained from the KDC ");
692         }
693
694         }
695     } catch (KrbException e) {
696         LoginException le = new LoginException(e.getMessage());
697         le.initCause(e);
698         throw le;
699     } catch (IOException ioe) {
700         LoginException ie = new LoginException(ioe.getMessage());
701         ie.initCause(ioe);
702         throw ie;
703     }
704     }
705     
706     private void promptForName(boolean getPasswdFromSharedState)
707     throws LoginException {
708     krb5PrincName = new StringBuffer JavaDoc("");
709     if (getPasswdFromSharedState) {
710         // use the name saved by the first module in the stack
711
username = (String JavaDoc)sharedState.get(NAME);
712         if (debug) {
713         System.out.println
714             ("username from shared state is " + username + "\n");
715         }
716         if (username == null) {
717         System.out.println
718             ("username from shared state is null\n");
719         throw new LoginException
720             ("Username can not be obtained from sharedstate ");
721         }
722         if (debug) {
723         System.out.println
724             ("username from shared state is " + username + "\n");
725         }
726         if (username != null && username.length() > 0) {
727         krb5PrincName.insert(0, username);
728         return;
729         }
730     }
731    
732     if (doNotPrompt) {
733         throw new LoginException
734         ("Unable to obtain Princpal Name for authentication ");
735     } else {
736         if (callbackHandler == null)
737         throw new LoginException("No CallbackHandler "
738                      + "available "
739                      + "to garner authentication "
740                      + "information from the user");
741         try {
742         String JavaDoc defUsername = System.getProperty("user.name");
743         
744         Callback[] callbacks = new Callback[1];
745         MessageFormat JavaDoc form = new MessageFormat JavaDoc(
746                        rb.getString(
747                        "Kerberos username [[defUsername]]: "));
748             Object JavaDoc[] source = {defUsername};
749         callbacks[0] = new NameCallback(form.format(source));
750         callbackHandler.handle(callbacks);
751         username = ((NameCallback)callbacks[0]).getName();
752         if (username == null || username.length() == 0)
753             username = defUsername;
754         krb5PrincName.insert(0, username);
755         
756         } catch (java.io.IOException JavaDoc ioe) {
757         throw new LoginException(ioe.getMessage());
758         } catch (UnsupportedCallbackException uce) {
759         throw new LoginException
760             (uce.getMessage()
761              +" not available to garner "
762              +" authentication information "
763              +" from the user");
764         }
765     }
766     }
767     
768     private void promptForPass(boolean getPasswdFromSharedState)
769     throws LoginException {
770
771     if (getPasswdFromSharedState) {
772         // use the password saved by the first module in the stack
773
password = (char[])sharedState.get(PWD);
774         if (password == null) {
775         if (debug) {
776             System.out.println
777             ("Password from shared state is null");
778         }
779         throw new LoginException
780             ("Password can not be obtained from sharedstate ");
781         }
782         if (debug) {
783         System.out.println
784             ("password is " + new String JavaDoc(password));
785         }
786         return;
787     }
788     if (doNotPrompt) {
789         throw new LoginException
790         ("Unable to obtain password from user\n");
791     } else {
792         if (callbackHandler == null)
793         throw new LoginException("No CallbackHandler "
794                      + "available "
795                      + "to garner authentication "
796                      + "information from the user");
797         try {
798         Callback[] callbacks = new Callback[1];
799         String JavaDoc userName = krb5PrincName.toString();
800         MessageFormat JavaDoc form = new MessageFormat JavaDoc(
801                      rb.getString(
802                      "Kerberos password for [username]: "));
803             Object JavaDoc[] source = {userName};
804         callbacks[0] = new PasswordCallback(
805                             form.format(source),
806                             false);
807         callbackHandler.handle(callbacks);
808         char[] tmpPassword = ((PasswordCallback)
809                       callbacks[0]).getPassword();
810         if (tmpPassword == null) {
811             // treat a NULL password as an empty password
812
tmpPassword = new char[0];
813         }
814         password = new char[tmpPassword.length];
815         System.arraycopy(tmpPassword, 0,
816                  password, 0, tmpPassword.length);
817         ((PasswordCallback)callbacks[0]).clearPassword();
818         
819
820         // clear tmpPassword
821
for (int i = 0; i < tmpPassword.length; i++)
822             tmpPassword[i] = ' ';
823         tmpPassword = null;
824         if (debug) {
825             System.out.println("\t\t[Krb5LoginModule] " +
826                        "user entered username: " +
827                        krb5PrincName);
828             System.out.println();
829         }
830         } catch (java.io.IOException JavaDoc ioe) {
831         throw new LoginException(ioe.getMessage());
832         } catch (UnsupportedCallbackException uce) {
833         throw new LoginException(uce.getMessage()
834                      +" not available to garner "
835                      +" authentication information "
836                      + "from the user");
837         }
838     }
839     }
840
841     private void validateConfiguration() throws LoginException {
842     if (doNotPrompt && !useTicketCache && !useKeyTab)
843         throw new LoginException
844         ("Configuration Error"
845          + " - either doNotPrompt should be "
846          + " false or useTicketCache/useKeyTab "
847          + " should be true");
848     if (ticketCacheName != null && !useTicketCache)
849         throw new LoginException
850         ("Configuration Error "
851          + " - useTicketCache should be set "
852          + "to true to use the ticket cache"
853          + ticketCacheName);
854     if (keyTabName != null & !useKeyTab)
855         throw new LoginException
856         ("Configuration Error - useKeyTab should be set to true "
857          + "to use the keytab" + keyTabName);
858     if (storeKey && doNotPrompt && !useKeyTab)
859         throw new LoginException
860         ("Configuration Error - either doNotPrompt "
861          + "should be set to false or "
862          + "useKeyTab must be set to true for storeKey option");
863     if (renewTGT && !useTicketCache)
864         throw new LoginException
865         ("Configuration Error"
866          + " - either useTicketCache should be "
867          + " true or renewTGT should be false");
868     }
869   
870     private boolean isCurrent(Credentials creds)
871     {
872     Date endTime = creds.getEndTime();
873     if (endTime != null) {
874         return (System.currentTimeMillis() <= endTime.getTime());
875     }
876     return true;
877     }
878
879     private Credentials renewCredentials(Credentials creds)
880     {
881     Credentials lcreds;
882     try {
883         if (!creds.isRenewable())
884         throw new RefreshFailedException("This ticket" +
885                 " is not renewable");
886         if (System.currentTimeMillis() > cred.getRenewTill().getTime())
887         throw new RefreshFailedException("This ticket is past "
888                                              + "its last renewal time.");
889         lcreds = creds.renew();
890         if (debug)
891         System.out.println("Renewed Kerberos Ticket");
892     } catch (Exception JavaDoc e) {
893         lcreds = null;
894         if (debug)
895         System.out.println("Ticket could not be renewed : "
896                 + e.getMessage());
897     }
898     return lcreds;
899     }
900
901     /**
902      * <p> This method is called if the LoginContext's
903      * overall authentication succeeded
904      * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL
905      * LoginModules succeeded).
906      *
907      * <p> If this LoginModule's own authentication attempt
908      * succeeded (checked by retrieving the private state saved by the
909      * <code>login</code> method), then this method associates a
910      * <code>Krb5Principal</code>
911      * with the <code>Subject</code> located in the
912      * <code>LoginModule</code>. It adds Kerberos Credentials to the
913      * the Subject's private credentials set. If this LoginModule's own
914      * authentication attempted failed, then this method removes
915      * any state that was originally saved.
916      *
917      * <p>
918      *
919      * @exception LoginException if the commit fails.
920      *
921      * @return true if this LoginModule's own login and commit
922      * attempts succeeded, or false otherwise.
923      */

924
925     public boolean commit() throws LoginException {
926
927     /*
928      * Let us add the Krb5 Creds to the Subject's
929      * private credentials. The credentials are of type
930      * KerberosKey or KerberosTicket
931      */

932     if (succeeded == false) {
933         return false;
934     } else {
935
936         if (isInitiator && (cred == null)) {
937         succeeded = false;
938         throw new LoginException("Null Client Credential");
939         }
940
941         if (subject.isReadOnly()) {
942             cleanKerberosCred();
943         throw new LoginException("Subject is Readonly");
944         }
945
946         /*
947          * Add the Principal (authenticated identity)
948          * to the Subject's principal set and
949          * add the credentials (TGT or Service key) to the
950          * Subject's private credentials
951          */

952
953         Set privCredSet = subject.getPrivateCredentials();
954         Set princSet = subject.getPrincipals();
955         kerbClientPrinc = new KerberosPrincipal(principal.getName());
956     
957         // create Kerberos Ticket
958
if (isInitiator) {
959         kerbTicket = Krb5Util.credsToTicket(cred);
960         }
961
962         if (storeKey) {
963         if (encKeys == null || encKeys.length <= 0) {
964             succeeded = false;
965             throw new LoginException("Null Server Key ");
966         }
967
968         kerbKeys = new KerberosKey[encKeys.length];
969         for (int i = 0; i < encKeys.length; i ++) {
970                 Integer JavaDoc temp = encKeys[i].getKeyVersionNumber();
971             kerbKeys[i] = new KerberosKey(kerbClientPrinc,
972                       encKeys[i].getBytes(),
973                       encKeys[i].getEType(),
974                       (temp == null?
975                       0: temp.intValue()));
976                 }
977         
978         }
979         // Let us add the kerbClientPrinc,kerbTicket and kerbKey (if
980
// storeKey is true)
981
if (!princSet.contains(kerbClientPrinc))
982         princSet.add(kerbClientPrinc);
983
984         // add the TGT
985
if (kerbTicket != null) {
986         if (!privCredSet.contains(kerbTicket))
987             privCredSet.add(kerbTicket);
988         }
989
990         if (storeKey) {
991         for (int i = 0; i < kerbKeys.length; i++) {
992             if (!privCredSet.contains(kerbKeys[i])) {
993                 privCredSet.add(kerbKeys[i]);
994             }
995             encKeys[i].destroy();
996             encKeys[i] = null;
997             if (debug) {
998                 System.out.println("Added server's key"
999                     + kerbKeys[i]);
1000                System.out.println("\t\t[Krb5LoginModule] " +
1001                       "added Krb5Principal " +
1002                       kerbClientPrinc.toString()
1003                       + " to Subject");
1004            }
1005        }
1006        }
1007    }
1008    commitSucceeded = true;
1009    if (debug)
1010        System.out.println("Commit Succeeded \n");
1011    return true;
1012    }
1013    
1014    /**
1015     * <p> This method is called if the LoginContext's
1016     * overall authentication failed.
1017     * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL
1018     * LoginModules did not succeed).
1019     *
1020     * <p> If this LoginModule's own authentication attempt
1021     * succeeded (checked by retrieving the private state saved by the
1022     * <code>login</code> and <code>commit</code> methods),
1023     * then this method cleans up any state that was originally saved.
1024     *
1025     * <p>
1026     *
1027     * @exception LoginException if the abort fails.
1028     *
1029     * @return false if this LoginModule's own login and/or commit attempts
1030     * failed, and true otherwise.
1031     */

1032
1033    public boolean abort() throws LoginException {
1034    if (succeeded == false) {
1035        return false;
1036    } else if (succeeded == true && commitSucceeded == false) {
1037        // login succeeded but overall authentication failed
1038
succeeded = false;
1039        cleanKerberosCred();
1040    } else {
1041        // overall authentication succeeded and commit succeeded,
1042
// but someone else's commit failed
1043
logout();
1044    }
1045    return true;
1046    }
1047    
1048    /**
1049     * Logout the user.
1050     *
1051     * <p> This method removes the <code>Krb5Principal</code>
1052     * that was added by the <code>commit</code> method.
1053     *
1054     * <p>
1055     *
1056     * @exception LoginException if the logout fails.
1057     *
1058     * @return true in all cases since this <code>LoginModule</code>
1059     * should not be ignored.
1060     */

1061    public boolean logout() throws LoginException {
1062
1063        if (debug) {
1064            System.out.println("\t\t[Krb5LoginModule]: " +
1065                "Entering logout");
1066        }
1067
1068        if (subject.isReadOnly()) {
1069        cleanKerberosCred();
1070            throw new LoginException("Subject is Readonly");
1071        }
1072    
1073    subject.getPrincipals().remove(kerbClientPrinc);
1074       // Let us remove all Kerberos credentials stored in the Subject
1075
Iterator it = subject.getPrivateCredentials().iterator();
1076    while (it.hasNext()) {
1077        Object JavaDoc o = it.next();
1078        if (o instanceof KerberosTicket ||
1079        o instanceof KerberosKey) {
1080        it.remove();
1081        }
1082    }
1083    // clean the kerberos ticket and keys
1084
cleanKerberosCred();
1085
1086    succeeded = false;
1087    commitSucceeded = false;
1088    if (debug) {
1089            System.out.println("\t\t[Krb5LoginModule]: " +
1090                   "logged out Subject");
1091        }
1092    return true;
1093    }
1094
1095    /**
1096     * Clean Kerberos credentials
1097     */

1098    private void cleanKerberosCred() throws LoginException {
1099    // Clean the ticket and server key
1100
try {
1101        if (kerbTicket != null)
1102        kerbTicket.destroy();
1103        if (kerbKeys != null) {
1104            for (int i = 0; i < kerbKeys.length; i++) {
1105            kerbKeys[i].destroy();
1106        }
1107            }
1108    } catch (DestroyFailedException e) {
1109        throw new LoginException
1110        ("Destroy Failed on Kerberos Private Credentials");
1111    }
1112    kerbTicket = null;
1113    kerbKeys = null;
1114    kerbClientPrinc = null;
1115    }
1116
1117    /**
1118     * Clean out the state
1119     */

1120    private void cleanState() {
1121       
1122    // save input as shared state only if
1123
// authentication succeeded
1124
if (succeeded) {
1125        if (storePass &&
1126        !sharedState.containsKey(NAME) &&
1127        !sharedState.containsKey(PWD)) {
1128        sharedState.put(NAME, username);
1129        sharedState.put(PWD, password);
1130        }
1131    }
1132    username = null;
1133    password = null;
1134    if (krb5PrincName != null && krb5PrincName.length() != 0)
1135        krb5PrincName.delete(0, krb5PrincName.length());
1136    krb5PrincName = null;
1137    if (clearPass) {
1138        sharedState.remove(NAME);
1139        sharedState.remove(PWD);
1140    }
1141    }
1142}
1143
Popular Tags