PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/share/classes/sun/security/krb5/Config.java

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