View Javadoc
1   /*
2    * Copyright (c) 2006, 2011, 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  package sun.security.krb5;
27  
28  import java.util.Arrays;
29  import java.util.Hashtable;
30  import java.util.Random;
31  import java.util.StringTokenizer;
32  
33  import javax.naming.*;
34  import javax.naming.directory.*;
35  import javax.naming.spi.NamingManager;
36  
37  /**
38   * This class discovers the location of Kerberos services by querying DNS,
39   * as defined in RFC 4120.
40   *
41   * @author Seema Malkani
42   * @since 1.7
43   */
44  
45  class KrbServiceLocator {
46  
47      private static final String SRV_RR = "SRV";
48      private static final String[] SRV_RR_ATTR = new String[] {SRV_RR};
49  
50      private static final String SRV_TXT = "TXT";
51      private static final String[] SRV_TXT_ATTR = new String[] {SRV_TXT};
52  
53      private static final Random random = new Random();
54  
55      private KrbServiceLocator() {
56      }
57  
58      /**
59       * Locates the KERBEROS service for a given domain.
60       * Queries DNS for a list of KERBEROS Service Text Records (TXT) for a
61       * given domain name.
62       * Information on the mapping of DNS hostnames and domain names
63       * to Kerberos realms is stored using DNS TXT records
64       *
65       * @param domainName A string domain name.
66       * @param environment The possibly null environment of the context.
67       * @return An ordered list of hostports for the Kerberos service or null if
68       *          the service has not been located.
69       */
70      static String[] getKerberosService(String realmName) {
71  
72          // search realm in SRV TXT records
73          String dnsUrl = "dns:///_kerberos." + realmName;
74          String[] records = null;
75          try {
76              // Create the DNS context using NamingManager rather than using
77              // the initial context constructor. This avoids having the initial
78              // context constructor call itself (when processing the URL
79              // argument in the getAttributes call).
80              Context ctx = NamingManager.getURLContext("dns", new Hashtable<>(0));
81              if (!(ctx instanceof DirContext)) {
82                  return null; // cannot create a DNS context
83              }
84              Attributes attrs =
85                  ((DirContext)ctx).getAttributes(dnsUrl, SRV_TXT_ATTR);
86              Attribute attr;
87  
88              if (attrs != null && ((attr = attrs.get(SRV_TXT)) != null)) {
89                  int numValues = attr.size();
90                  int numRecords = 0;
91                  String[] txtRecords = new String[numValues];
92  
93                  // gather the text records
94                  int i = 0;
95                  int j = 0;
96                  while (i < numValues) {
97                      try {
98                          txtRecords[j] = (String)attr.get(i);
99                          j++;
100                     } catch (Exception e) {
101                         // ignore bad value
102                     }
103                     i++;
104                 }
105                 numRecords = j;
106 
107                 // trim
108                 if (numRecords < numValues) {
109                     String[] trimmed = new String[numRecords];
110                     System.arraycopy(txtRecords, 0, trimmed, 0, numRecords);
111                     records = trimmed;
112                 } else {
113                     records = txtRecords;
114                 }
115             }
116         } catch (NamingException e) {
117             // ignore
118         }
119         return records;
120     }
121 
122     /**
123      * Locates the KERBEROS service for a given domain.
124      * Queries DNS for a list of KERBEROS Service Location Records (SRV) for a
125      * given domain name.
126      *
127      * @param domainName A string domain name.
128      * @return An ordered list of hostports for the Kerberos service or null if
129      *          the service has not been located.
130      */
131     static String[] getKerberosService(String realmName, String protocol) {
132 
133         String dnsUrl = "dns:///_kerberos." + protocol + "." + realmName;
134         String[] hostports = null;
135 
136         try {
137             // Create the DNS context using NamingManager rather than using
138             // the initial context constructor. This avoids having the initial
139             // context constructor call itself (when processing the URL
140             // argument in the getAttributes call).
141             Context ctx = NamingManager.getURLContext("dns", new Hashtable<>(0));
142             if (!(ctx instanceof DirContext)) {
143                 return null; // cannot create a DNS context
144             }
145             Attributes attrs =
146                 ((DirContext)ctx).getAttributes(dnsUrl, SRV_RR_ATTR);
147             Attribute attr;
148 
149             if (attrs != null && ((attr = attrs.get(SRV_RR)) != null)) {
150                 int numValues = attr.size();
151                 int numRecords = 0;
152                 SrvRecord[] srvRecords = new SrvRecord[numValues];
153 
154                 // create the service records
155                 int i = 0;
156                 int j = 0;
157                 while (i < numValues) {
158                     try {
159                         srvRecords[j] = new SrvRecord((String) attr.get(i));
160                         j++;
161                     } catch (Exception e) {
162                         // ignore bad value
163                     }
164                     i++;
165                 }
166                 numRecords = j;
167 
168                 // trim
169                 if (numRecords < numValues) {
170                     SrvRecord[] trimmed = new SrvRecord[numRecords];
171                     System.arraycopy(srvRecords, 0, trimmed, 0, numRecords);
172                     srvRecords = trimmed;
173                 }
174 
175                 // Sort the service records in ascending order of their
176                 // priority value. For records with equal priority, move
177                 // those with weight 0 to the top of the list.
178                 if (numRecords > 1) {
179                     Arrays.sort(srvRecords);
180                 }
181 
182                 // extract the host and port number from each service record
183                 hostports = extractHostports(srvRecords);
184             }
185         } catch (NamingException e) {
186             // e.printStackTrace();
187             // ignore
188         }
189         return hostports;
190     }
191 
192     /**
193      * Extract hosts and port numbers from a list of SRV records.
194      * An array of hostports is returned or null if none were found.
195      */
196     private static String[] extractHostports(SrvRecord[] srvRecords) {
197         String[] hostports = null;
198 
199         int head = 0;
200         int tail = 0;
201         int sublistLength = 0;
202         int k = 0;
203         for (int i = 0; i < srvRecords.length; i++) {
204             if (hostports == null) {
205                 hostports = new String[srvRecords.length];
206             }
207             // find the head and tail of the list of records having the same
208             // priority value.
209             head = i;
210             while (i < srvRecords.length - 1 &&
211                 srvRecords[i].priority == srvRecords[i + 1].priority) {
212                 i++;
213             }
214             tail = i;
215 
216             // select hostports from the sublist
217             sublistLength = (tail - head) + 1;
218             for (int j = 0; j < sublistLength; j++) {
219                 hostports[k++] = selectHostport(srvRecords, head, tail);
220             }
221         }
222         return hostports;
223     }
224 
225     /*
226      * Randomly select a service record in the range [head, tail] and return
227      * its hostport value. Follows the algorithm in RFC 2782.
228      */
229     private static String selectHostport(SrvRecord[] srvRecords, int head,
230             int tail) {
231         if (head == tail) {
232             return srvRecords[head].hostport;
233         }
234 
235         // compute the running sum for records between head and tail
236         int sum = 0;
237         for (int i = head; i <= tail; i++) {
238             if (srvRecords[i] != null) {
239                 sum += srvRecords[i].weight;
240                 srvRecords[i].sum = sum;
241             }
242         }
243         String hostport = null;
244 
245         // If all records have zero weight, select first available one;
246         // otherwise, randomly select a record according to its weight
247         int target = (sum == 0 ? 0 : random.nextInt(sum + 1));
248         for (int i = head; i <= tail; i++) {
249             if (srvRecords[i] != null && srvRecords[i].sum >= target) {
250                 hostport = srvRecords[i].hostport;
251                 srvRecords[i] = null; // make this record unavailable
252                 break;
253             }
254         }
255         return hostport;
256     }
257 
258 /**
259  * This class holds a DNS service (SRV) record.
260  * See http://www.ietf.org/rfc/rfc2782.txt
261  */
262 
263 static class SrvRecord implements Comparable<SrvRecord> {
264 
265     int priority;
266     int weight;
267     int sum;
268     String hostport;
269 
270     /**
271      * Creates a service record object from a string record.
272      * DNS supplies the string record in the following format:
273      * <pre>
274      *          <Priority> " " <Weight> " " <Port> " " <Host>
275      * </pre>
276      */
277     SrvRecord(String srvRecord) throws Exception {
278         StringTokenizer tokenizer = new StringTokenizer(srvRecord, " ");
279         String port;
280 
281         if (tokenizer.countTokens() == 4) {
282             priority = Integer.parseInt(tokenizer.nextToken());
283             weight = Integer.parseInt(tokenizer.nextToken());
284             port = tokenizer.nextToken();
285             hostport = tokenizer.nextToken() + ":" + port;
286         } else {
287             throw new IllegalArgumentException();
288         }
289     }
290 
291     /*
292      * Sort records in ascending order of priority value. For records with
293      * equal priority move those with weight 0 to the top of the list.
294      */
295     public int compareTo(SrvRecord that) {
296         if (priority > that.priority) {
297             return 1; // this > that
298         } else if (priority < that.priority) {
299             return -1; // this < that
300         } else if (weight == 0 && that.weight != 0) {
301             return -1; // this < that
302         } else if (weight != 0 && that.weight == 0) {
303             return 1; // this > that
304         } else {
305             return 0; // this == that
306         }
307     }
308 }
309 }