View Javadoc
1   /*
2    * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4    *
5    * This code is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU General Public License version 2 only, as
7    * published by the Free Software Foundation.  Oracle designates this
8    * particular file as subject to the "Classpath" exception as provided
9    * by Oracle in the LICENSE file that accompanied this code.
10   *
11   * This code is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14   * version 2 for more details (a copy is included in the LICENSE file that
15   * accompanied this code).
16   *
17   * You should have received a copy of the GNU General Public License version
18   * 2 along with this work; if not, write to the Free Software Foundation,
19   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20   *
21   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22   * or visit www.oracle.com if you need additional information or have any
23   * questions.
24   */
25  
26  /*
27   *
28   *  (C) Copyright IBM Corp. 1999 All Rights Reserved.
29   *  Copyright 1997 The Open Group Research Institute.  All rights reserved.
30   */
31  package sun.security.krb5;
32  
33  import java.io.File;
34  import java.io.FileInputStream;
35  import java.util.Hashtable;
36  import java.util.Vector;
37  import java.util.ArrayList;
38  import java.io.BufferedReader;
39  import java.io.InputStreamReader;
40  import java.io.IOException;
41  import java.util.StringTokenizer;
42  import java.net.InetAddress;
43  import java.net.UnknownHostException;
44  import java.security.AccessController;
45  import java.security.PrivilegedExceptionAction;
46  import java.util.Arrays;
47  import java.util.List;
48  import java.util.Locale;
49  import sun.net.dns.ResolverConfiguration;
50  import sun.security.krb5.internal.crypto.EType;
51  import sun.security.krb5.internal.Krb5;
52  
53  /**
54   * This class maintains key-value pairs of Kerberos configurable constants
55   * from configuration file or from user specified system properties.
56   */
57  
58  public class Config {
59  
60      /*
61       * Only allow a single instance of Config.
62       */
63      private static Config singleton = null;
64  
65      /*
66       * Hashtable used to store configuration information.
67       */
68      private Hashtable<String,Object> stanzaTable = new Hashtable<>();
69  
70      private static boolean DEBUG = sun.security.krb5.internal.Krb5.DEBUG;
71  
72      // these are used for hexdecimal calculation.
73      private static final int BASE16_0 = 1;
74      private static final int BASE16_1 = 16;
75      private static final int BASE16_2 = 16 * 16;
76      private static final int BASE16_3 = 16 * 16 * 16;
77  
78      /**
79       * Specified by system properties. Must be both null or non-null.
80       */
81      private final String defaultRealm;
82      private final String defaultKDC;
83  
84      // used for native interface
85      private static native String getWindowsDirectory(boolean isSystem);
86  
87  
88      /**
89       * Gets an instance of Config class. One and only one instance (the
90       * singleton) is returned.
91       *
92       * @exception KrbException if error occurs when constructing a Config
93       * instance. Possible causes would be either of java.security.krb5.realm or
94       * java.security.krb5.kdc not specified, error reading configuration file.
95       */
96      public static synchronized Config getInstance() throws KrbException {
97          if (singleton == null) {
98              singleton = new Config();
99          }
100         return singleton;
101     }
102 
103     /**
104      * Refresh and reload the Configuration. This could involve,
105      * for example reading the Configuration file again or getting
106      * the java.security.krb5.* system properties again. This method
107      * also tries its best to update static fields in other classes
108      * that depend on the configuration.
109      *
110      * @exception KrbException if error occurs when constructing a Config
111      * instance. Possible causes would be either of java.security.krb5.realm or
112      * java.security.krb5.kdc not specified, error reading configuration file.
113      */
114 
115     public static synchronized void refresh() throws KrbException {
116         singleton = new Config();
117         KdcComm.initStatic();
118         EType.initStatic();
119         Checksum.initStatic();
120     }
121 
122 
123     private static boolean isMacosLionOrBetter() {
124         // split the "10.x.y" version number
125         String osname = getProperty("os.name");
126         if (!osname.contains("OS X")) {
127             return false;
128         }
129 
130         String osVersion = getProperty("os.version");
131         String[] fragments = osVersion.split("\\.");
132 
133         // sanity check the "10." part of the version
134         if (!fragments[0].equals("10")) return false;
135         if (fragments.length < 2) return false;
136 
137         // check if Mac OS X 10.7(.y)
138         try {
139             int minorVers = Integer.parseInt(fragments[1]);
140             if (minorVers >= 7) return true;
141         } catch (NumberFormatException e) {
142             // was not an integer
143         }
144 
145         return false;
146     }
147 
148     /**
149      * Private constructor - can not be instantiated externally.
150      */
151     private Config() throws KrbException {
152         /*
153          * If either one system property is specified, we throw exception.
154          */
155         String tmp = getProperty("java.security.krb5.kdc");
156         if (tmp != null) {
157             // The user can specify a list of kdc hosts separated by ":"
158             defaultKDC = tmp.replace(':', ' ');
159         } else {
160             defaultKDC = null;
161         }
162         defaultRealm = getProperty("java.security.krb5.realm");
163         if ((defaultKDC == null && defaultRealm != null) ||
164             (defaultRealm == null && defaultKDC != null)) {
165             throw new KrbException
166                 ("System property java.security.krb5.kdc and " +
167                  "java.security.krb5.realm both must be set or " +
168                  "neither must be set.");
169         }
170 
171         // Always read the Kerberos configuration file
172         try {
173             List<String> configFile;
174             String fileName = getJavaFileName();
175             if (fileName != null) {
176                 configFile = loadConfigFile(fileName);
177                 stanzaTable = parseStanzaTable(configFile);
178                 if (DEBUG) {
179                     System.out.println("Loaded from Java config");
180                 }
181             } else {
182                 boolean found = false;
183                 if (isMacosLionOrBetter()) {
184                     try {
185                         stanzaTable = SCDynamicStoreConfig.getConfig();
186                         if (DEBUG) {
187                             System.out.println("Loaded from SCDynamicStoreConfig");
188                         }
189                         found = true;
190                     } catch (IOException ioe) {
191                         // OK. Will go on with file
192                     }
193                 }
194                 if (!found) {
195                     fileName = getNativeFileName();
196                     configFile = loadConfigFile(fileName);
197                     stanzaTable = parseStanzaTable(configFile);
198                     if (DEBUG) {
199                         System.out.println("Loaded from native config");
200                     }
201                 }
202             }
203         } catch (IOException ioe) {
204             // I/O error, mostly like krb5.conf missing.
205             // No problem. We'll use DNS or system property etc.
206         }
207     }
208 
209     /**
210      * Gets the last-defined string value for the specified keys.
211      * @param keys the keys, as an array from section name, sub-section names
212      * (if any), to value name.
213      * @return the value. When there are multiple values for the same key,
214      * returns the last one. {@code null} is returned if not all the keys are
215      * defined. For example, {@code get("libdefaults", "forwardable")} will
216      * return null if "forwardable" is not defined in [libdefaults], and
217      * {@code get("realms", "R", "kdc")} will return null if "R" is not
218      * defined in [realms] or "kdc" is not defined for "R".
219      * @throws IllegalArgumentException if any of the keys is illegal, either
220      * because a key not the last one is not a (sub)section name or the last
221      * key is still a section name. For example, {@code get("libdefaults")}
222      * throws this exception because [libdefaults] is a section name instead of
223      * a value name, and {@code get("libdefaults", "forwardable", "tail")}
224      * also throws this exception because "forwardable" is already a value name
225      * and has no sub-key at all (given "forwardable" is defined, otherwise,
226      * this method has no knowledge if it's a value name or a section name),
227      */
228     public String get(String... keys) {
229         Vector<String> v = getString0(keys);
230         if (v == null) return null;
231         return v.lastElement();
232     }
233 
234     /**
235      * Gets all values for the specified keys.
236      * @throws IllegalArgumentException if any of the keys is illegal
237      *         (See {@link #get})
238      */
239     public String getAll(String... keys) {
240         Vector<String> v = getString0(keys);
241         if (v == null) return null;
242         StringBuilder sb = new StringBuilder();
243         boolean first = true;
244         for (String s: v) {
245             if (first) {
246                 sb.append(s);
247                 first = false;
248             } else {
249                 sb.append(' ').append(s);
250             }
251         }
252         return sb.toString();
253     }
254 
255     /**
256      * Returns true if keys exists, can be either final string(s) or sub-stanza
257      * @throws IllegalArgumentException if any of the keys is illegal
258      *         (See {@link #get})
259      */
260     public boolean exists(String... keys) {
261         return get0(keys) != null;
262     }
263 
264     // Returns final string value(s) for given keys.
265     @SuppressWarnings("unchecked")
266     private Vector<String> getString0(String... keys) {
267         try {
268             return (Vector<String>)get0(keys);
269         } catch (ClassCastException cce) {
270             throw new IllegalArgumentException(cce);
271         }
272     }
273 
274     // Internal method. Returns the value for keys, which can be a sub-stanza
275     // or final string value(s).
276     // The only method (except for toString) that reads stanzaTable directly.
277     @SuppressWarnings("unchecked")
278     private Object get0(String... keys) {
279         Object current = stanzaTable;
280         try {
281             for (String key: keys) {
282                 current = ((Hashtable<String,Object>)current).get(key);
283                 if (current == null) return null;
284             }
285             return current;
286         } catch (ClassCastException cce) {
287             throw new IllegalArgumentException(cce);
288         }
289     }
290 
291     /**
292      * Gets the int value for the specified keys.
293      * @param keys the keys
294      * @return the int value, Integer.MIN_VALUE is returned if it cannot be
295      * found or the value is not a legal integer.
296      * @throw IllegalArgumentException if any of the keys is illegal
297      * @see #get(java.lang.String[])
298      */
299     public int getIntValue(String... keys) {
300         String result = get(keys);
301         int value = Integer.MIN_VALUE;
302         if (result != null) {
303             try {
304                 value = parseIntValue(result);
305             } catch (NumberFormatException e) {
306                 if (DEBUG) {
307                     System.out.println("Exception in getting value of " +
308                                        Arrays.toString(keys) + " " +
309                                        e.getMessage());
310                     System.out.println("Setting " + Arrays.toString(keys) +
311                                        " to minimum value");
312                 }
313                 value = Integer.MIN_VALUE;
314             }
315         }
316         return value;
317     }
318 
319     /**
320      * Gets the boolean value for the specified keys.
321      * @param keys the keys
322      * @return the boolean value, false is returned if it cannot be
323      * found or the value is not "true" (case insensitive).
324      * @throw IllegalArgumentException if any of the keys is illegal
325      * @see #get(java.lang.String[])
326      */
327     public boolean getBooleanValue(String... keys) {
328         String val = get(keys);
329         if (val != null && val.equalsIgnoreCase("true")) {
330             return true;
331         } else {
332             return false;
333         }
334     }
335 
336     /**
337      * Parses a string to an integer. The convertible strings include the
338      * string representations of positive integers, negative integers, and
339      * hex decimal integers.  Valid inputs are, e.g., -1234, +1234,
340      * 0x40000.
341      *
342      * @param input the String to be converted to an Integer.
343      * @return an numeric value represented by the string
344      * @exception NumberFormationException if the String does not contain a
345      * parsable integer.
346      */
347     private int parseIntValue(String input) throws NumberFormatException {
348         int value = 0;
349         if (input.startsWith("+")) {
350             String temp = input.substring(1);
351             return Integer.parseInt(temp);
352         } else if (input.startsWith("0x")) {
353             String temp = input.substring(2);
354             char[] chars = temp.toCharArray();
355             if (chars.length > 8) {
356                 throw new NumberFormatException();
357             } else {
358                 for (int i = 0; i < chars.length; i++) {
359                     int index = chars.length - i - 1;
360                     switch (chars[i]) {
361                     case '0':
362                         value += 0;
363                         break;
364                     case '1':
365                         value += 1 * getBase(index);
366                         break;
367                     case '2':
368                         value += 2 * getBase(index);
369                         break;
370                     case '3':
371                         value += 3 * getBase(index);
372                         break;
373                     case '4':
374                         value += 4 * getBase(index);
375                         break;
376                     case '5':
377                         value += 5 * getBase(index);
378                         break;
379                     case '6':
380                         value += 6 * getBase(index);
381                         break;
382                     case '7':
383                         value += 7 * getBase(index);
384                         break;
385                     case '8':
386                         value += 8 * getBase(index);
387                         break;
388                     case '9':
389                         value += 9 * getBase(index);
390                         break;
391                     case 'a':
392                     case 'A':
393                         value += 10 * getBase(index);
394                         break;
395                     case 'b':
396                     case 'B':
397                         value += 11 * getBase(index);
398                         break;
399                     case 'c':
400                     case 'C':
401                         value += 12 * getBase(index);
402                         break;
403                     case 'd':
404                     case 'D':
405                         value += 13 * getBase(index);
406                         break;
407                     case 'e':
408                     case 'E':
409                         value += 14 * getBase(index);
410                         break;
411                     case 'f':
412                     case 'F':
413                         value += 15 * getBase(index);
414                         break;
415                     default:
416                         throw new NumberFormatException("Invalid numerical format");
417                     }
418                 }
419             }
420             if (value < 0) {
421                 throw new NumberFormatException("Data overflow.");
422             }
423         } else {
424             value = Integer.parseInt(input);
425         }
426         return value;
427     }
428 
429     private int getBase(int i) {
430         int result = 16;
431         switch (i) {
432         case 0:
433             result = BASE16_0;
434             break;
435         case 1:
436             result = BASE16_1;
437             break;
438         case 2:
439             result = BASE16_2;
440             break;
441         case 3:
442             result = BASE16_3;
443             break;
444         default:
445             for (int j = 1; j < i; j++) {
446                 result *= 16;
447             }
448         }
449         return result;
450     }
451 
452     /**
453      * Reads lines to the memory from the configuration file.
454      *
455      * Configuration file contains information about the default realm,
456      * ticket parameters, location of the KDC and the admin server for
457      * known realms, etc. The file is divided into sections. Each section
458      * contains one or more name/value pairs with one pair per line. A
459      * typical file would be:
460      * <pre>
461      * [libdefaults]
462      *          default_realm = EXAMPLE.COM
463      *          default_tgs_enctypes = des-cbc-md5
464      *          default_tkt_enctypes = des-cbc-md5
465      * [realms]
466      *          EXAMPLE.COM = {
467      *                  kdc = kerberos.example.com
468      *                  kdc = kerberos-1.example.com
469      *                  admin_server = kerberos.example.com
470      *                  }
471      *          SAMPLE_COM = {
472      *                  kdc = orange.sample.com
473      *                  admin_server = orange.sample.com
474      *                  }
475      * [domain_realm]
476      *          blue.sample.com = TEST.SAMPLE.COM
477      *          .backup.com     = EXAMPLE.COM
478      * </pre>
479      * @return an ordered list of strings representing the config file after
480      * some initial processing, including:<ol>
481      * <li> Comment lines and empty lines are removed
482      * <li> "{" not at the end of a line is appended to the previous line
483      * <li> The content of a section is also placed between "{" and "}".
484      * <li> Lines are trimmed</ol>
485      * @throws IOException if there is an I/O error
486      * @throws KrbException if there is a file format error
487      */
488     private List<String> loadConfigFile(final String fileName)
489             throws IOException, KrbException {
490         try {
491             List<String> v = new ArrayList<>();
492             try (BufferedReader br = new BufferedReader(new InputStreamReader(
493                 AccessController.doPrivileged(
494                     new PrivilegedExceptionAction<FileInputStream> () {
495                         public FileInputStream run() throws IOException {
496                             return new FileInputStream(fileName);
497                         }
498                     })))) {
499                 String line;
500                 String previous = null;
501                 while ((line = br.readLine()) != null) {
502                     line = line.trim();
503                     if (line.startsWith("#") || line.isEmpty()) {
504                         // ignore comments and blank line
505                         // Comments start with #.
506                         continue;
507                     }
508                     // In practice, a subsection might look like:
509                     //      [realms]
510                     //      EXAMPLE.COM =
511                     //      {
512                     //          kdc = kerberos.example.com
513                     //          ...
514                     //      }
515                     // Before parsed into stanza table, it needs to be
516                     // converted into a canonicalized style (no indent):
517                     //      realms = {
518                     //          EXAMPLE.COM = {
519                     //              kdc = kerberos.example.com
520                     //              ...
521                     //          }
522                     //      }
523                     //
524                     if (line.startsWith("[")) {
525                         if (!line.endsWith("]")) {
526                             throw new KrbException("Illegal config content:"
527                                     + line);
528                         }
529                         if (previous != null) {
530                             v.add(previous);
531                             v.add("}");
532                         }
533                         String title = line.substring(
534                                 1, line.length()-1).trim();
535                         if (title.isEmpty()) {
536                             throw new KrbException("Illegal config content:"
537                                     + line);
538                         }
539                         previous = title + " = {";
540                     } else if (line.startsWith("{")) {
541                         if (previous == null) {
542                             throw new KrbException(
543                                 "Config file should not start with \"{\"");
544                         }
545                         previous += " {";
546                         if (line.length() > 1) {
547                             // { and content on the same line
548                             v.add(previous);
549                             previous = line.substring(1).trim();
550                         }
551                     } else {
552                         if (previous == null) {
553                             throw new KrbException(
554                                 "Config file must starts with a section");
555                         }
556                         v.add(previous);
557                         previous = line;
558                     }
559                 }
560                 if (previous != null) {
561                     v.add(previous);
562                     v.add("}");
563                 }
564             }
565             return v;
566         } catch (java.security.PrivilegedActionException pe) {
567             throw (IOException)pe.getException();
568         }
569     }
570 
571     /**
572      * Parses stanza names and values from configuration file to
573      * stanzaTable (Hashtable). Hashtable key would be stanza names,
574      * (libdefaults, realms, domain_realms, etc), and the hashtable value
575      * would be another hashtable which contains the key-value pairs under
576      * a stanza name. The value of this sub-hashtable can be another hashtable
577      * containing another sub-sub-section or a vector of strings for
578      * final values (even if there is only one value defined).
579      * <p>
580      * For duplicates section names, the latter overwrites the former. For
581      * duplicate value names, the values are in a vector in its appearing order.
582      * </ol>
583      * Please note that this behavior is Java traditional. and it is
584      * not the same as the MIT krb5 behavior, where:<ol>
585      * <li>Duplicated root sections will be merged
586      * <li>For duplicated sub-sections, the former overwrites the latter
587      * <li>Duplicate keys for values are always saved in a vector
588      * </ol>
589      * @param v the strings in the file, never null, might be empty
590      * @throws KrbException if there is a file format error
591      */
592     @SuppressWarnings("unchecked")
593     private Hashtable<String,Object> parseStanzaTable(List<String> v)
594             throws KrbException {
595         Hashtable<String,Object> current = stanzaTable;
596         for (String line: v) {
597             // There are 3 kinds of lines
598             // 1. a = b
599             // 2. a = {
600             // 3. }
601             if (line.equals("}")) {
602                 // Go back to parent, see below
603                 current = (Hashtable<String,Object>)current.remove(" PARENT ");
604                 if (current == null) {
605                     throw new KrbException("Unmatched close brace");
606                 }
607             } else {
608                 int pos = line.indexOf('=');
609                 if (pos < 0) {
610                     throw new KrbException("Illegal config content:" + line);
611                 }
612                 String key = line.substring(0, pos).trim();
613                 String value = trimmed(line.substring(pos+1));
614                 if (value.equals("{")) {
615                     Hashtable<String,Object> subTable;
616                     if (current == stanzaTable) {
617                         key = key.toLowerCase(Locale.US);
618                     }
619                     subTable = new Hashtable<>();
620                     current.put(key, subTable);
621                     // A special entry for its parent. Put whitespaces around,
622                     // so will never be confused with a normal key
623                     subTable.put(" PARENT ", current);
624                     current = subTable;
625                 } else {
626                     Vector<String> values;
627                     if (current.containsKey(key)) {
628                         Object obj = current.get(key);
629                         // If a key first shows as a section and then a value,
630                         // this is illegal. However, we haven't really forbid
631                         // first value then section, which the final result
632                         // is a section.
633                         if (!(obj instanceof Vector)) {
634                             throw new KrbException("Key " + key
635                                     + "used for both value and section");
636                         }
637                         values = (Vector<String>)current.get(key);
638                     } else {
639                         values = new Vector<String>();
640                         current.put(key, values);
641                     }
642                     values.add(value);
643                 }
644             }
645         }
646         if (current != stanzaTable) {
647             throw new KrbException("Not closed");
648         }
649         return current;
650     }
651 
652     /**
653      * Gets the default Java configuration file name.
654      *
655      * If the system property "java.security.krb5.conf" is defined, we'll
656      * use its value, no matter if the file exists or not. Otherwise, we
657      * will look at $JAVA_HOME/lib/security directory with "krb5.conf" name,
658      * and return it if the file exists.
659      *
660      * The method returns null if it cannot find a Java config file.
661      */
662     private String getJavaFileName() {
663         String name = getProperty("java.security.krb5.conf");
664         if (name == null) {
665             name = getProperty("java.home") + File.separator +
666                                 "lib" + File.separator + "security" +
667                                 File.separator + "krb5.conf";
668             if (!fileExists(name)) {
669                 name = null;
670             }
671         }
672         if (DEBUG) {
673             System.out.println("Java config name: " + name);
674         }
675         return name;
676     }
677 
678     /**
679      * Gets the default native configuration file name.
680      *
681      * Depending on the OS type, the method returns the default native
682      * kerberos config file name, which is at windows directory with
683      * the name of "krb5.ini" for Windows, /etc/krb5/krb5.conf for Solaris,
684      * /etc/krb5.conf otherwise. Mac OSX X has a different file name.
685      *
686      * Note: When the Terminal Service is started in Windows (from 2003),
687      * there are two kinds of Windows directories: A system one (say,
688      * C:\Windows), and a user-private one (say, C:\Users\Me\Windows).
689      * We will first look for krb5.ini in the user-private one. If not
690      * found, try the system one instead.
691      *
692      * This method will always return a non-null non-empty file name,
693      * even if that file does not exist.
694      */
695     private String getNativeFileName() {
696         String name = null;
697         String osname = getProperty("os.name");
698         if (osname.startsWith("Windows")) {
699             try {
700                 Credentials.ensureLoaded();
701             } catch (Exception e) {
702                 // ignore exceptions
703             }
704             if (Credentials.alreadyLoaded) {
705                 String path = getWindowsDirectory(false);
706                 if (path != null) {
707                     if (path.endsWith("\\")) {
708                         path = path + "krb5.ini";
709                     } else {
710                         path = path + "\\krb5.ini";
711                     }
712                     if (fileExists(path)) {
713                         name = path;
714                     }
715                 }
716                 if (name == null) {
717                     path = getWindowsDirectory(true);
718                     if (path != null) {
719                         if (path.endsWith("\\")) {
720                             path = path + "krb5.ini";
721                         } else {
722                             path = path + "\\krb5.ini";
723                         }
724                         name = path;
725                     }
726                 }
727             }
728             if (name == null) {
729                 name = "c:\\winnt\\krb5.ini";
730             }
731         } else if (osname.startsWith("SunOS")) {
732             name =  "/etc/krb5/krb5.conf";
733         } else if (osname.contains("OS X")) {
734             name = findMacosConfigFile();
735         } else {
736             name =  "/etc/krb5.conf";
737         }
738         if (DEBUG) {
739             System.out.println("Native config name: " + name);
740         }
741         return name;
742     }
743 
744     private static String getProperty(String property) {
745         return java.security.AccessController.doPrivileged(
746                 new sun.security.action.GetPropertyAction(property));
747     }
748 
749     private String findMacosConfigFile() {
750         String userHome = getProperty("user.home");
751         final String PREF_FILE = "/Library/Preferences/edu.mit.Kerberos";
752         String userPrefs = userHome + PREF_FILE;
753 
754         if (fileExists(userPrefs)) {
755             return userPrefs;
756         }
757 
758         if (fileExists(PREF_FILE)) {
759             return PREF_FILE;
760         }
761 
762         return "/etc/krb5.conf";
763     }
764 
765     private static String trimmed(String s) {
766         s = s.trim();
767         if (s.isEmpty()) return s;
768         if (s.charAt(0) == '"' && s.charAt(s.length()-1) == '"' ||
769                 s.charAt(0) == '\'' && s.charAt(s.length()-1) == '\'') {
770             s = s.substring(1, s.length()-1).trim();
771         }
772         return s;
773     }
774 
775     /**
776      * For testing purpose. This method lists all information being parsed from
777      * the configuration file to the hashtable.
778      */
779     public void listTable() {
780         System.out.println(this);
781     }
782 
783     /**
784      * Returns all etypes specified in krb5.conf for the given configName,
785      * or all the builtin defaults. This result is always non-empty.
786      * If no etypes are found, an exception is thrown.
787      */
788     public int[] defaultEtype(String configName) throws KrbException {
789         String default_enctypes;
790         default_enctypes = get("libdefaults", configName);
791         int[] etype;
792         if (default_enctypes == null) {
793             if (DEBUG) {
794                 System.out.println("Using builtin default etypes for " +
795                     configName);
796             }
797             etype = EType.getBuiltInDefaults();
798         } else {
799             String delim = " ";
800             StringTokenizer st;
801             for (int j = 0; j < default_enctypes.length(); j++) {
802                 if (default_enctypes.substring(j, j + 1).equals(",")) {
803                     // only two delimiters are allowed to use
804                     // according to Kerberos DCE doc.
805                     delim = ",";
806                     break;
807                 }
808             }
809             st = new StringTokenizer(default_enctypes, delim);
810             int len = st.countTokens();
811             ArrayList<Integer> ls = new ArrayList<>(len);
812             int type;
813             for (int i = 0; i < len; i++) {
814                 type = Config.getType(st.nextToken());
815                 if (type != -1 && EType.isSupported(type)) {
816                     ls.add(type);
817                 }
818             }
819             if (ls.isEmpty()) {
820                 throw new KrbException("no supported default etypes for "
821                         + configName);
822             } else {
823                 etype = new int[ls.size()];
824                 for (int i = 0; i < etype.length; i++) {
825                     etype[i] = ls.get(i);
826                 }
827             }
828         }
829 
830         if (DEBUG) {
831             System.out.print("default etypes for " + configName + ":");
832             for (int i = 0; i < etype.length; i++) {
833                 System.out.print(" " + etype[i]);
834             }
835             System.out.println(".");
836         }
837         return etype;
838     }
839 
840 
841     /**
842      * Get the etype and checksum value for the specified encryption and
843      * checksum type.
844      *
845      */
846     /*
847      * This method converts the string representation of encryption type and
848      * checksum type to int value that can be later used by EType and
849      * Checksum classes.
850      */
851     public static int getType(String input) {
852         int result = -1;
853         if (input == null) {
854             return result;
855         }
856         if (input.startsWith("d") || (input.startsWith("D"))) {
857             if (input.equalsIgnoreCase("des-cbc-crc")) {
858                 result = EncryptedData.ETYPE_DES_CBC_CRC;
859             } else if (input.equalsIgnoreCase("des-cbc-md5")) {
860                 result = EncryptedData.ETYPE_DES_CBC_MD5;
861             } else if (input.equalsIgnoreCase("des-mac")) {
862                 result = Checksum.CKSUMTYPE_DES_MAC;
863             } else if (input.equalsIgnoreCase("des-mac-k")) {
864                 result = Checksum.CKSUMTYPE_DES_MAC_K;
865             } else if (input.equalsIgnoreCase("des-cbc-md4")) {
866                 result = EncryptedData.ETYPE_DES_CBC_MD4;
867             } else if (input.equalsIgnoreCase("des3-cbc-sha1") ||
868                 input.equalsIgnoreCase("des3-hmac-sha1") ||
869                 input.equalsIgnoreCase("des3-cbc-sha1-kd") ||
870                 input.equalsIgnoreCase("des3-cbc-hmac-sha1-kd")) {
871                 result = EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD;
872             }
873         } else if (input.startsWith("a") || (input.startsWith("A"))) {
874             // AES
875             if (input.equalsIgnoreCase("aes128-cts") ||
876                 input.equalsIgnoreCase("aes128-cts-hmac-sha1-96")) {
877                 result = EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96;
878             } else if (input.equalsIgnoreCase("aes256-cts") ||
879                 input.equalsIgnoreCase("aes256-cts-hmac-sha1-96")) {
880                 result = EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96;
881             // ARCFOUR-HMAC
882             } else if (input.equalsIgnoreCase("arcfour-hmac") ||
883                    input.equalsIgnoreCase("arcfour-hmac-md5")) {
884                 result = EncryptedData.ETYPE_ARCFOUR_HMAC;
885             }
886         // RC4-HMAC
887         } else if (input.equalsIgnoreCase("rc4-hmac")) {
888             result = EncryptedData.ETYPE_ARCFOUR_HMAC;
889         } else if (input.equalsIgnoreCase("CRC32")) {
890             result = Checksum.CKSUMTYPE_CRC32;
891         } else if (input.startsWith("r") || (input.startsWith("R"))) {
892             if (input.equalsIgnoreCase("rsa-md5")) {
893                 result = Checksum.CKSUMTYPE_RSA_MD5;
894             } else if (input.equalsIgnoreCase("rsa-md5-des")) {
895                 result = Checksum.CKSUMTYPE_RSA_MD5_DES;
896             }
897         } else if (input.equalsIgnoreCase("hmac-sha1-des3-kd")) {
898             result = Checksum.CKSUMTYPE_HMAC_SHA1_DES3_KD;
899         } else if (input.equalsIgnoreCase("hmac-sha1-96-aes128")) {
900             result = Checksum.CKSUMTYPE_HMAC_SHA1_96_AES128;
901         } else if (input.equalsIgnoreCase("hmac-sha1-96-aes256")) {
902             result = Checksum.CKSUMTYPE_HMAC_SHA1_96_AES256;
903         } else if (input.equalsIgnoreCase("hmac-md5-rc4") ||
904                 input.equalsIgnoreCase("hmac-md5-arcfour") ||
905                 input.equalsIgnoreCase("hmac-md5-enc")) {
906             result = Checksum.CKSUMTYPE_HMAC_MD5_ARCFOUR;
907         } else if (input.equalsIgnoreCase("NULL")) {
908             result = EncryptedData.ETYPE_NULL;
909         }
910 
911         return result;
912     }
913 
914     /**
915      * Resets the default kdc realm.
916      * We do not need to synchronize these methods since assignments are atomic
917      *
918      * This method was useless. Kept here in case some class still calls it.
919      */
920     public void resetDefaultRealm(String realm) {
921         if (DEBUG) {
922             System.out.println(">>> Config try resetting default kdc " + realm);
923         }
924     }
925 
926     /**
927      * Check to use addresses in tickets
928      * use addresses if "no_addresses" or "noaddresses" is set to false
929      */
930     public boolean useAddresses() {
931         boolean useAddr = false;
932         // use addresses if "no_addresses" is set to false
933         String value = get("libdefaults", "no_addresses");
934         useAddr = (value != null && value.equalsIgnoreCase("false"));
935         if (useAddr == false) {
936             // use addresses if "noaddresses" is set to false
937             value = get("libdefaults", "noaddresses");
938             useAddr = (value != null && value.equalsIgnoreCase("false"));
939         }
940         return useAddr;
941     }
942 
943     /**
944      * Check if need to use DNS to locate Kerberos services
945      */
946     private boolean useDNS(String name) {
947         String value = get("libdefaults", name);
948         if (value == null) {
949             value = get("libdefaults", "dns_fallback");
950             if ("false".equalsIgnoreCase(value)) {
951                 return false;
952             } else {
953                 return true;
954             }
955         } else {
956             return value.equalsIgnoreCase("true");
957         }
958     }
959 
960     /**
961      * Check if need to use DNS to locate the KDC
962      */
963     private boolean useDNS_KDC() {
964         return useDNS("dns_lookup_kdc");
965     }
966 
967     /*
968      * Check if need to use DNS to locate the Realm
969      */
970     private boolean useDNS_Realm() {
971         return useDNS("dns_lookup_realm");
972     }
973 
974     /**
975      * Gets default realm.
976      * @throws KrbException where no realm can be located
977      * @return the default realm, always non null
978      */
979     public String getDefaultRealm() throws KrbException {
980         if (defaultRealm != null) {
981             return defaultRealm;
982         }
983         Exception cause = null;
984         String realm = get("libdefaults", "default_realm");
985         if ((realm == null) && useDNS_Realm()) {
986             // use DNS to locate Kerberos realm
987             try {
988                 realm = getRealmFromDNS();
989             } catch (KrbException ke) {
990                 cause = ke;
991             }
992         }
993         if (realm == null) {
994             realm = java.security.AccessController.doPrivileged(
995                     new java.security.PrivilegedAction<String>() {
996                 @Override
997                 public String run() {
998                     String osname = System.getProperty("os.name");
999                     if (osname.startsWith("Windows")) {
1000                         return System.getenv("USERDNSDOMAIN");
1001                     }
1002                     return null;
1003                 }
1004             });
1005         }
1006         if (realm == null) {
1007             KrbException ke = new KrbException("Cannot locate default realm");
1008             if (cause != null) {
1009                 ke.initCause(cause);
1010             }
1011             throw ke;
1012         }
1013         return realm;
1014     }
1015 
1016     /**
1017      * Returns a list of KDC's with each KDC separated by a space
1018      *
1019      * @param realm the realm for which the KDC list is desired
1020      * @throws KrbException if there's no way to find KDC for the realm
1021      * @return the list of KDCs separated by a space, always non null
1022      */
1023     public String getKDCList(String realm) throws KrbException {
1024         if (realm == null) {
1025             realm = getDefaultRealm();
1026         }
1027         if (realm.equalsIgnoreCase(defaultRealm)) {
1028             return defaultKDC;
1029         }
1030         Exception cause = null;
1031         String kdcs = getAll("realms", realm, "kdc");
1032         if ((kdcs == null) && useDNS_KDC()) {
1033             // use DNS to locate KDC
1034             try {
1035                 kdcs = getKDCFromDNS(realm);
1036             } catch (KrbException ke) {
1037                 cause = ke;
1038             }
1039         }
1040         if (kdcs == null) {
1041             kdcs = java.security.AccessController.doPrivileged(
1042                     new java.security.PrivilegedAction<String>() {
1043                 @Override
1044                 public String run() {
1045                     String osname = System.getProperty("os.name");
1046                     if (osname.startsWith("Windows")) {
1047                         String logonServer = System.getenv("LOGONSERVER");
1048                         if (logonServer != null
1049                                 && logonServer.startsWith("\\\\")) {
1050                             logonServer = logonServer.substring(2);
1051                         }
1052                         return logonServer;
1053                     }
1054                     return null;
1055                 }
1056             });
1057         }
1058         if (kdcs == null) {
1059             if (defaultKDC != null) {
1060                 return defaultKDC;
1061             }
1062             KrbException ke = new KrbException("Cannot locate KDC");
1063             if (cause != null) {
1064                 ke.initCause(cause);
1065             }
1066             throw ke;
1067         }
1068         return kdcs;
1069     }
1070 
1071     /**
1072      * Locate Kerberos realm using DNS
1073      *
1074      * @return the Kerberos realm
1075      */
1076     private String getRealmFromDNS() throws KrbException {
1077         // use DNS to locate Kerberos realm
1078         String realm = null;
1079         String hostName = null;
1080         try {
1081             hostName = InetAddress.getLocalHost().getCanonicalHostName();
1082         } catch (UnknownHostException e) {
1083             KrbException ke = new KrbException(Krb5.KRB_ERR_GENERIC,
1084                 "Unable to locate Kerberos realm: " + e.getMessage());
1085             ke.initCause(e);
1086             throw (ke);
1087         }
1088         // get the domain realm mapping from the configuration
1089         String mapRealm = PrincipalName.mapHostToRealm(hostName);
1090         if (mapRealm == null) {
1091             // No match. Try search and/or domain in /etc/resolv.conf
1092             List<String> srchlist = ResolverConfiguration.open().searchlist();
1093             for (String domain: srchlist) {
1094                 realm = checkRealm(domain);
1095                 if (realm != null) {
1096                     break;
1097                 }
1098             }
1099         } else {
1100             realm = checkRealm(mapRealm);
1101         }
1102         if (realm == null) {
1103             throw new KrbException(Krb5.KRB_ERR_GENERIC,
1104                                 "Unable to locate Kerberos realm");
1105         }
1106         return realm;
1107     }
1108 
1109     /**
1110      * Check if the provided realm is the correct realm
1111      * @return the realm if correct, or null otherwise
1112      */
1113     private static String checkRealm(String mapRealm) {
1114         if (DEBUG) {
1115             System.out.println("getRealmFromDNS: trying " + mapRealm);
1116         }
1117         String[] records = null;
1118         String newRealm = mapRealm;
1119         while ((records == null) && (newRealm != null)) {
1120             // locate DNS TXT record
1121             records = KrbServiceLocator.getKerberosService(newRealm);
1122             newRealm = Realm.parseRealmComponent(newRealm);
1123             // if no DNS TXT records found, try again using sub-realm
1124         }
1125         if (records != null) {
1126             for (int i = 0; i < records.length; i++) {
1127                 if (records[i].equalsIgnoreCase(mapRealm)) {
1128                     return records[i];
1129                 }
1130             }
1131         }
1132         return null;
1133     }
1134 
1135     /**
1136      * Locate KDC using DNS
1137      *
1138      * @param realm the realm for which the master KDC is desired
1139      * @return the KDC
1140      */
1141     private String getKDCFromDNS(String realm) throws KrbException {
1142         // use DNS to locate KDC
1143         String kdcs = "";
1144         String[] srvs = null;
1145         // locate DNS SRV record using UDP
1146         if (DEBUG) {
1147             System.out.println("getKDCFromDNS using UDP");
1148         }
1149         srvs = KrbServiceLocator.getKerberosService(realm, "_udp");
1150         if (srvs == null) {
1151             // locate DNS SRV record using TCP
1152             if (DEBUG) {
1153                 System.out.println("getKDCFromDNS using TCP");
1154             }
1155             srvs = KrbServiceLocator.getKerberosService(realm, "_tcp");
1156         }
1157         if (srvs == null) {
1158             // no DNS SRV records
1159             throw new KrbException(Krb5.KRB_ERR_GENERIC,
1160                 "Unable to locate KDC for realm " + realm);
1161         }
1162         if (srvs.length == 0) {
1163             return null;
1164         }
1165         for (int i = 0; i < srvs.length; i++) {
1166             kdcs += srvs[i].trim() + " ";
1167         }
1168         kdcs = kdcs.trim();
1169         if (kdcs.equals("")) {
1170             return null;
1171         }
1172         return kdcs;
1173     }
1174 
1175     private boolean fileExists(String name) {
1176         return java.security.AccessController.doPrivileged(
1177                                 new FileExistsAction(name));
1178     }
1179 
1180     static class FileExistsAction
1181         implements java.security.PrivilegedAction<Boolean> {
1182 
1183         private String fileName;
1184 
1185         public FileExistsAction(String fileName) {
1186             this.fileName = fileName;
1187         }
1188 
1189         public Boolean run() {
1190             return new File(fileName).exists();
1191         }
1192     }
1193 
1194     // Shows the content of the Config object for debug purpose.
1195     //
1196     // {
1197     //      libdefaults = {
1198     //          default_realm = R
1199     //      }
1200     //      realms = {
1201     //          R = {
1202     //              kdc = [k1,k2]
1203     //          }
1204     //      }
1205     // }
1206 
1207     @Override
1208     public String toString() {
1209         StringBuffer sb = new StringBuffer();
1210         toStringInternal("", stanzaTable, sb);
1211         return sb.toString();
1212     }
1213     private static void toStringInternal(String prefix, Object obj,
1214             StringBuffer sb) {
1215         if (obj instanceof String) {
1216             // A string value, just print it
1217             sb.append(obj).append('\n');
1218         } else if (obj instanceof Hashtable) {
1219             // A table, start a new sub-section...
1220             Hashtable<?, ?> tab = (Hashtable<?, ?>)obj;
1221             sb.append("{\n");
1222             for (Object o: tab.keySet()) {
1223                 // ...indent, print "key = ", and
1224                 sb.append(prefix).append("    ").append(o).append(" = ");
1225                 // ...go recursively into value
1226                 toStringInternal(prefix + "    ", tab.get(o), sb);
1227             }
1228             sb.append(prefix).append("}\n");
1229         } else if (obj instanceof Vector) {
1230             // A vector of strings, print them inside [ and ]
1231             Vector<?> v = (Vector<?>)obj;
1232             sb.append("[");
1233             boolean first = true;
1234             for (Object o: v.toArray()) {
1235                 if (!first) sb.append(",");
1236                 sb.append(o);
1237                 first = false;
1238             }
1239             sb.append("]\n");
1240         }
1241     }
1242 }