PageRenderTime 788ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/openjdk/jdk/src/share/classes/sun/security/krb5/Config.java

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