author | weijun |
Wed, 12 Nov 2008 16:01:06 +0800 | |
changeset 1575 | e0f1979051b5 |
parent 1456 | 1d3c6724de2f |
child 2942 | 37d9baeb7518 |
permissions | -rw-r--r-- |
1454 | 1 |
/* |
2 |
* Copyright 2008 Sun Microsystems, Inc. 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. |
|
8 |
* |
|
9 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
10 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
11 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
12 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
13 |
* accompanied this code). |
|
14 |
* |
|
15 |
* You should have received a copy of the GNU General Public License version |
|
16 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
17 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
18 |
* |
|
19 |
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, |
|
20 |
* CA 95054 USA or visit www.sun.com if you need additional information or |
|
21 |
* have any questions. |
|
22 |
*/ |
|
23 |
||
24 |
import java.lang.reflect.Constructor; |
|
25 |
import java.lang.reflect.Field; |
|
26 |
import java.lang.reflect.InvocationTargetException; |
|
27 |
import java.net.*; |
|
28 |
import java.io.*; |
|
29 |
import java.lang.reflect.Method; |
|
30 |
import java.security.SecureRandom; |
|
31 |
import java.util.*; |
|
32 |
import java.util.concurrent.*; |
|
33 |
import sun.security.krb5.*; |
|
34 |
import sun.security.krb5.internal.*; |
|
1575
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
35 |
import sun.security.krb5.internal.ccache.CredentialsCache; |
1454 | 36 |
import sun.security.krb5.internal.crypto.KeyUsage; |
37 |
import sun.security.krb5.internal.ktab.KeyTab; |
|
38 |
import sun.security.util.DerInputStream; |
|
39 |
import sun.security.util.DerOutputStream; |
|
40 |
import sun.security.util.DerValue; |
|
41 |
||
42 |
/** |
|
43 |
* A KDC server. |
|
44 |
* <p> |
|
45 |
* Features: |
|
46 |
* <ol> |
|
47 |
* <li> Supports TCP and UDP |
|
48 |
* <li> Supports AS-REQ and TGS-REQ |
|
49 |
* <li> Principal db and other settings hard coded in application |
|
50 |
* <li> Options, say, request preauth or not |
|
51 |
* </ol> |
|
52 |
* Side effects: |
|
53 |
* <ol> |
|
54 |
* <li> The Sun-internal class <code>sun.security.krb5.Config</code> is a |
|
55 |
* singleton and initialized according to Kerberos settings (krb5.conf and |
|
56 |
* java.security.krb5.* system properties). This means once it's initialized |
|
57 |
* it will not automatically notice any changes to these settings (or file |
|
58 |
* changes of krb5.conf). The KDC class normally does not touch these |
|
59 |
* settings (except for the <code>writeKtab()</code> method). However, to make |
|
60 |
* sure nothing ever goes wrong, if you want to make any changes to these |
|
61 |
* settings after calling a KDC method, call <code>Config.refresh()</code> to |
|
62 |
* make sure your changes are reflected in the <code>Config</code> object. |
|
63 |
* </ol> |
|
64 |
* Issues and TODOs: |
|
65 |
* <ol> |
|
66 |
* <li> Generates krb5.conf to be used on another machine, currently the kdc is |
|
67 |
* always localhost |
|
68 |
* <li> More options to KDC, say, error output, say, response nonce != |
|
69 |
* request nonce |
|
70 |
* </ol> |
|
71 |
* Note: This program uses internal krb5 classes (including reflection to |
|
72 |
* access private fields and methods). |
|
73 |
* <p> |
|
74 |
* Usages: |
|
75 |
* <p> |
|
76 |
* 1. Init and start the KDC: |
|
77 |
* <pre> |
|
78 |
* KDC kdc = KDC.create("REALM.NAME", port, isDaemon); |
|
79 |
* KDC kdc = KDC.create("REALM.NAME"); |
|
80 |
* </pre> |
|
81 |
* Here, <code>port</code> is the UDP and TCP port number the KDC server |
|
82 |
* listens on. If zero, a random port is chosen, which you can use getPort() |
|
83 |
* later to retrieve the value. |
|
84 |
* <p> |
|
85 |
* If <code>isDaemon</code> is true, the KDC worker threads will be daemons. |
|
86 |
* <p> |
|
87 |
* The shortcut <code>KDC.create("REALM.NAME")</code> has port=0 and |
|
88 |
* isDaemon=false, and is commonly used in an embedded KDC. |
|
89 |
* <p> |
|
90 |
* 2. Adding users: |
|
91 |
* <pre> |
|
92 |
* kdc.addPrincipal(String principal_name, char[] password); |
|
93 |
* kdc.addPrincipalRandKey(String principal_name); |
|
94 |
* </pre> |
|
95 |
* A service principal's name should look like "host/f.q.d.n". The second form |
|
96 |
* generates a random key. To expose this key, call <code>writeKtab()</code> to |
|
97 |
* save the keys into a keytab file. |
|
98 |
* <p> |
|
99 |
* Note that you need to add the principal name krbtgt/REALM.NAME yourself. |
|
100 |
* <p> |
|
101 |
* Note that you can safely add a principal at any time after the KDC is |
|
102 |
* started and before a user requests info on this principal. |
|
103 |
* <p> |
|
104 |
* 3. Other public methods: |
|
105 |
* <ul> |
|
106 |
* <li> <code>getPort</code>: Returns the port number the KDC uses |
|
107 |
* <li> <code>getRealm</code>: Returns the realm name |
|
108 |
* <li> <code>writeKtab</code>: Writes all principals' keys into a keytab file |
|
109 |
* <li> <code>saveConfig</code>: Saves a krb5.conf file to access this KDC |
|
110 |
* <li> <code>setOption</code>: Sets various options |
|
111 |
* </ul> |
|
112 |
* Read the javadoc for details. Lazy developer can use <code>OneKDC</code> |
|
113 |
* directly. |
|
114 |
*/ |
|
115 |
public class KDC { |
|
116 |
||
117 |
// Under the hood. |
|
118 |
||
119 |
// The random generator to generate random keys (including session keys) |
|
120 |
private static SecureRandom secureRandom = new SecureRandom(); |
|
121 |
// Principal db |
|
122 |
private Map<String,char[]> passwords = new HashMap<String,char[]>(); |
|
123 |
// Realm name |
|
124 |
private String realm; |
|
125 |
// The request/response job queue |
|
126 |
private BlockingQueue<Job> q = new ArrayBlockingQueue<Job>(100); |
|
127 |
// Service port number |
|
128 |
private int port; |
|
129 |
// Options |
|
130 |
private Map<Option,Object> options = new HashMap<Option,Object>(); |
|
131 |
||
132 |
/** |
|
133 |
* Option names, to be expanded forever. |
|
134 |
*/ |
|
135 |
public static enum Option { |
|
136 |
/** |
|
137 |
* Whether pre-authentication is required. Default Boolean.TRUE |
|
138 |
*/ |
|
139 |
PREAUTH_REQUIRED, |
|
140 |
}; |
|
141 |
||
142 |
/** |
|
143 |
* A standalone KDC server. |
|
144 |
* @param args |
|
145 |
* @throws java.lang.Exception |
|
146 |
*/ |
|
147 |
public static void main(String[] args) throws Exception { |
|
148 |
if (args.length > 0) { |
|
149 |
if (args[0].equals("-help") || args[0].equals("--help")) { |
|
150 |
System.out.println("Usage:"); |
|
151 |
System.out.println(" java " + KDC.class + " " + |
|
152 |
"Start KDC on port 8888"); |
|
153 |
return; |
|
154 |
} |
|
155 |
} |
|
1456 | 156 |
String localhost = "localhost"; |
157 |
try { |
|
158 |
localhost = InetAddress.getByName(localhost) |
|
159 |
.getCanonicalHostName(); |
|
160 |
} catch (UnknownHostException uhe) { |
|
161 |
; // Ignore, localhost is still "localhost" |
|
162 |
} |
|
1454 | 163 |
KDC kdc = create("RABBIT.HOLE", 8888, false); |
164 |
kdc.addPrincipal("dummy", "bogus".toCharArray()); |
|
165 |
kdc.addPrincipal("foo", "bar".toCharArray()); |
|
166 |
kdc.addPrincipalRandKey("krbtgt/" + kdc.realm); |
|
1456 | 167 |
kdc.addPrincipalRandKey("server/" + localhost); |
168 |
kdc.addPrincipalRandKey("backend/" + localhost); |
|
1454 | 169 |
} |
170 |
||
171 |
/** |
|
172 |
* Creates and starts a KDC running as a daemon on a random port. |
|
173 |
* @param realm the realm name |
|
174 |
* @return the running KDC instance |
|
175 |
* @throws java.io.IOException for any socket creation error |
|
176 |
*/ |
|
177 |
public static KDC create(String realm) throws IOException { |
|
178 |
return create(realm, 0, true); |
|
179 |
} |
|
180 |
||
181 |
/** |
|
182 |
* Creates and starts a KDC server. |
|
183 |
* @param realm the realm name |
|
184 |
* @param port the TCP and UDP port to listen to. A random port will to |
|
185 |
* chosen if zero. |
|
186 |
* @param asDaemon if true, KDC threads will be daemons. Otherwise, not. |
|
187 |
* @return the running KDC instance |
|
188 |
* @throws java.io.IOException for any socket creation error |
|
189 |
*/ |
|
190 |
public static KDC create(String realm, int port, boolean asDaemon) throws IOException { |
|
191 |
return new KDC(realm, port, asDaemon); |
|
192 |
} |
|
193 |
||
194 |
/** |
|
195 |
* Sets an option |
|
196 |
* @param key the option name |
|
197 |
* @param obj the value |
|
198 |
*/ |
|
199 |
public void setOption(Option key, Object value) { |
|
200 |
options.put(key, value); |
|
201 |
} |
|
202 |
||
203 |
/** |
|
204 |
* Write all principals' keys into a keytab file. Note that the keys for |
|
205 |
* the krbtgt principal for this realm will not be written. |
|
206 |
* <p> |
|
207 |
* Attention: This method references krb5.conf settings. If you need to |
|
208 |
* setup krb5.conf later, please call <code>Config.refresh()</code> after |
|
209 |
* the new setting. For example: |
|
210 |
* <pre> |
|
211 |
* kdc.writeKtab("/etc/kdc/ktab"); // Config is initialized, |
|
212 |
* System.setProperty("java.security.krb5.conf", "/home/mykrb5.conf"); |
|
213 |
* Config.refresh(); |
|
214 |
* </pre> |
|
215 |
* |
|
216 |
* Inside this method there are 2 places krb5.conf is used: |
|
217 |
* <ol> |
|
218 |
* <li> (Fatal) Generating keys: EncryptionKey.acquireSecretKeys |
|
219 |
* <li> (Has workaround) Creating PrincipalName |
|
220 |
* </ol> |
|
221 |
* @param tab The keytab filename to write to. |
|
222 |
* @throws java.io.IOException for any file output error |
|
223 |
* @throws sun.security.krb5.KrbException for any realm and/or principal |
|
224 |
* name error. |
|
225 |
*/ |
|
226 |
public void writeKtab(String tab) throws IOException, KrbException { |
|
227 |
KeyTab ktab = KeyTab.create(tab); |
|
228 |
for (String name : passwords.keySet()) { |
|
229 |
if (name.equals("krbtgt/" + realm)) { |
|
230 |
continue; |
|
231 |
} |
|
232 |
ktab.addEntry(new PrincipalName(name + "@" + realm, |
|
233 |
name.indexOf('/') < 0 ? |
|
234 |
PrincipalName.KRB_NT_UNKNOWN : |
|
235 |
PrincipalName.KRB_NT_SRV_HST), passwords.get(name)); |
|
236 |
} |
|
237 |
ktab.save(); |
|
238 |
} |
|
239 |
||
240 |
/** |
|
241 |
* Adds a new principal to this realm with a given password. |
|
242 |
* @param user the principal's name. For a service principal, use the |
|
243 |
* form of host/f.q.d.n |
|
244 |
* @param pass the password for the principal |
|
245 |
*/ |
|
246 |
public void addPrincipal(String user, char[] pass) { |
|
247 |
passwords.put(user, pass); |
|
248 |
} |
|
249 |
||
250 |
/** |
|
251 |
* Adds a new principal to this realm with a random password |
|
252 |
* @param user the principal's name. For a service principal, use the |
|
253 |
* form of host/f.q.d.n |
|
254 |
*/ |
|
255 |
public void addPrincipalRandKey(String user) { |
|
256 |
passwords.put(user, randomPassword()); |
|
257 |
} |
|
258 |
||
259 |
/** |
|
260 |
* Returns the name of this realm |
|
261 |
* @return the name of this realm |
|
262 |
*/ |
|
263 |
public String getRealm() { |
|
264 |
return realm; |
|
265 |
} |
|
266 |
||
267 |
/** |
|
268 |
* Writes a krb5.conf for one or more KDC that includes KDC locations for |
|
269 |
* each realm and the default realm name. You can also add extra strings |
|
270 |
* into the file. The method should be called like: |
|
271 |
* <pre> |
|
272 |
* KDC.saveConfig("krb5.conf", kdc1, kdc2, ..., line1, line2, ...); |
|
273 |
* </pre> |
|
274 |
* Here you can provide one or more kdc# and zero or more line# arguments. |
|
275 |
* The line# will be put after [libdefaults] and before [realms]. Therefore |
|
276 |
* you can append new lines into [libdefaults] and/or create your new |
|
277 |
* stanzas as well. Note that a newline character will be appended to |
|
278 |
* each line# argument. |
|
279 |
* <p> |
|
280 |
* For example: |
|
281 |
* <pre> |
|
282 |
* KDC.saveConfig("krb5.conf", this); |
|
283 |
* </pre> |
|
284 |
* generates: |
|
285 |
* <pre> |
|
286 |
* [libdefaults] |
|
287 |
* default_realm = REALM.NAME |
|
288 |
* |
|
289 |
* [realms] |
|
290 |
* REALM.NAME = { |
|
291 |
* kdc = localhost:port_number |
|
292 |
* } |
|
293 |
* </pre> |
|
294 |
* |
|
295 |
* Another example: |
|
296 |
* <pre> |
|
297 |
* KDC.saveConfig("krb5.conf", kdc1, kdc2, "forwardable = true", "", |
|
298 |
* "[domain_realm]", |
|
299 |
* ".kdc1.com = KDC1.NAME"); |
|
300 |
* </pre> |
|
301 |
* generates: |
|
302 |
* <pre> |
|
303 |
* [libdefaults] |
|
304 |
* default_realm = KDC1.NAME |
|
305 |
* forwardable = true |
|
306 |
* |
|
307 |
* [domain_realm] |
|
308 |
* .kdc1.com = KDC1.NAME |
|
309 |
* |
|
310 |
* [realms] |
|
311 |
* KDC1.NAME = { |
|
312 |
* kdc = localhost:port1 |
|
313 |
* } |
|
314 |
* KDC2.NAME = { |
|
315 |
* kdc = localhost:port2 |
|
316 |
* } |
|
317 |
* </pre> |
|
318 |
* @param file the name of the file to write into |
|
319 |
* @param kdc the first (and default) KDC |
|
320 |
* @param more more KDCs or extra lines (in their appearing order) to |
|
321 |
* insert into the krb5.conf file. This method reads each argument's type |
|
322 |
* to determine what it's for. This argument can be empty. |
|
323 |
* @throws java.io.IOException for any file output error |
|
324 |
*/ |
|
325 |
public static void saveConfig(String file, KDC kdc, Object... more) |
|
326 |
throws IOException { |
|
327 |
File f = new File(file); |
|
328 |
StringBuffer sb = new StringBuffer(); |
|
329 |
sb.append("[libdefaults]\ndefault_realm = "); |
|
330 |
sb.append(kdc.realm); |
|
331 |
sb.append("\n"); |
|
332 |
for (Object o: more) { |
|
333 |
if (o instanceof String) { |
|
334 |
sb.append(o); |
|
335 |
sb.append("\n"); |
|
336 |
} |
|
337 |
} |
|
338 |
sb.append("\n[realms]\n"); |
|
339 |
sb.append(realmLineForKDC(kdc)); |
|
340 |
for (Object o: more) { |
|
341 |
if (o instanceof KDC) { |
|
342 |
sb.append(realmLineForKDC((KDC)o)); |
|
343 |
} |
|
344 |
} |
|
345 |
FileOutputStream fos = new FileOutputStream(f); |
|
346 |
fos.write(sb.toString().getBytes()); |
|
347 |
fos.close(); |
|
348 |
} |
|
349 |
||
350 |
/** |
|
351 |
* Returns the service port of the KDC server. |
|
352 |
* @return the KDC service port |
|
353 |
*/ |
|
354 |
public int getPort() { |
|
355 |
return port; |
|
356 |
} |
|
357 |
||
358 |
// Private helper methods |
|
359 |
||
360 |
/** |
|
361 |
* Private constructor, cannot be called outside. |
|
362 |
* @param realm |
|
363 |
*/ |
|
364 |
private KDC(String realm) { |
|
365 |
this.realm = realm; |
|
366 |
} |
|
367 |
||
368 |
/** |
|
369 |
* A constructor that starts the KDC service also. |
|
370 |
*/ |
|
371 |
protected KDC(String realm, int port, boolean asDaemon) |
|
372 |
throws IOException { |
|
373 |
this(realm); |
|
374 |
startServer(port, asDaemon); |
|
375 |
} |
|
376 |
/** |
|
377 |
* Generates a 32-char random password |
|
378 |
* @return the password |
|
379 |
*/ |
|
380 |
private static char[] randomPassword() { |
|
381 |
char[] pass = new char[32]; |
|
382 |
for (int i=0; i<32; i++) |
|
383 |
pass[i] = (char)secureRandom.nextInt(); |
|
384 |
return pass; |
|
385 |
} |
|
386 |
||
387 |
/** |
|
388 |
* Generates a random key for the given encryption type. |
|
389 |
* @param eType the encryption type |
|
390 |
* @return the generated key |
|
391 |
* @throws sun.security.krb5.KrbException for unknown/unsupported etype |
|
392 |
*/ |
|
393 |
private static EncryptionKey generateRandomKey(int eType) |
|
394 |
throws KrbException { |
|
395 |
// Is 32 enough for AES256? I should have generated the keys directly |
|
396 |
// but different cryptos have different rules on what keys are valid. |
|
397 |
char[] pass = randomPassword(); |
|
398 |
String algo; |
|
399 |
switch (eType) { |
|
400 |
case EncryptedData.ETYPE_DES_CBC_MD5: algo = "DES"; break; |
|
401 |
case EncryptedData.ETYPE_DES3_CBC_HMAC_SHA1_KD: algo = "DESede"; break; |
|
402 |
case EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96: algo = "AES128"; break; |
|
403 |
case EncryptedData.ETYPE_ARCFOUR_HMAC: algo = "ArcFourHMAC"; break; |
|
404 |
case EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96: algo = "AES256"; break; |
|
405 |
default: algo = "DES"; break; |
|
406 |
} |
|
407 |
return new EncryptionKey(pass, "NOTHING", algo); // Silly |
|
408 |
} |
|
409 |
||
410 |
/** |
|
411 |
* Returns the password for a given principal |
|
412 |
* @param p principal |
|
413 |
* @return the password |
|
414 |
* @throws sun.security.krb5.KrbException when the principal is not inside |
|
415 |
* the database. |
|
416 |
*/ |
|
417 |
private char[] getPassword(PrincipalName p) throws KrbException { |
|
418 |
char[] pass = passwords.get(p.getNameString()); |
|
419 |
if (pass == null) { |
|
420 |
throw new KrbException(Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN); |
|
421 |
} |
|
422 |
return pass; |
|
423 |
} |
|
424 |
||
425 |
/** |
|
426 |
* Returns the salt string for the principal. For normal users, the |
|
427 |
* concatenation for the realm name and the sections of the principal; |
|
428 |
* for krgtgt/A@B and krbtgt/B@A, always return AB (so that inter-realm |
|
429 |
* principals have the same key). |
|
430 |
* @param p principal |
|
431 |
* @return the salt |
|
432 |
*/ |
|
433 |
private String getSalt(PrincipalName p) { |
|
434 |
String[] ns = p.getNameStrings(); |
|
435 |
if (ns[0].equals("krbtgt") && ns.length > 1) { |
|
436 |
// Shared cross-realm keys must be the same |
|
437 |
if (ns[1].compareTo(realm) < 0) { |
|
438 |
return ns[1] + realm; |
|
439 |
} else { |
|
440 |
return realm + ns[1]; |
|
441 |
} |
|
442 |
} else { |
|
443 |
String s = getRealm(); |
|
444 |
for (String n: p.getNameStrings()) { |
|
445 |
s += n; |
|
446 |
} |
|
447 |
return s; |
|
448 |
} |
|
449 |
} |
|
450 |
||
451 |
/** |
|
452 |
* Returns the key for a given principal of the given encryption type |
|
453 |
* @param p the principal |
|
454 |
* @param etype the encryption type |
|
455 |
* @return the key |
|
456 |
* @throws sun.security.krb5.KrbException for unknown/unsupported etype |
|
457 |
*/ |
|
458 |
private EncryptionKey keyForUser(PrincipalName p, int etype) throws KrbException { |
|
459 |
try { |
|
460 |
// Do not call EncryptionKey.acquireSecretKeys(), otherwise |
|
461 |
// the krb5.conf config file would be loaded. |
|
462 |
Method stringToKey = EncryptionKey.class.getDeclaredMethod("stringToKey", char[].class, String.class, byte[].class, Integer.TYPE); |
|
463 |
stringToKey.setAccessible(true); |
|
464 |
return new EncryptionKey((byte[]) stringToKey.invoke(null, getPassword(p), getSalt(p), null, etype), etype, null); |
|
465 |
} catch (InvocationTargetException ex) { |
|
466 |
KrbException ke = (KrbException)ex.getCause(); |
|
467 |
throw ke; |
|
468 |
} catch (Exception e) { |
|
469 |
throw new RuntimeException(e); // should not happen |
|
470 |
} |
|
471 |
} |
|
472 |
||
473 |
/** |
|
474 |
* Processes an incoming request and generates a response. |
|
475 |
* @param in the request |
|
476 |
* @return the response |
|
477 |
* @throws java.lang.Exception for various errors |
|
478 |
*/ |
|
479 |
private byte[] processMessage(byte[] in) throws Exception { |
|
480 |
if ((in[0] & 0x1f) == Krb5.KRB_AS_REQ) |
|
481 |
return processAsReq(in); |
|
482 |
else |
|
483 |
return processTgsReq(in); |
|
484 |
} |
|
485 |
||
486 |
/** |
|
487 |
* Processes a TGS_REQ and generates a TGS_REP (or KRB_ERROR) |
|
488 |
* @param in the request |
|
489 |
* @return the response |
|
490 |
* @throws java.lang.Exception for various errors |
|
491 |
*/ |
|
492 |
private byte[] processTgsReq(byte[] in) throws Exception { |
|
493 |
TGSReq tgsReq = new TGSReq(in); |
|
494 |
try { |
|
495 |
System.out.println(realm + "> " + tgsReq.reqBody.cname + |
|
496 |
" sends TGS-REQ for " + |
|
497 |
tgsReq.reqBody.sname); |
|
498 |
KDCReqBody body = tgsReq.reqBody; |
|
499 |
int etype = 0; |
|
500 |
||
501 |
// Reflection: PAData[] pas = tgsReq.pAData; |
|
502 |
Field f = KDCReq.class.getDeclaredField("pAData"); |
|
503 |
f.setAccessible(true); |
|
504 |
PAData[] pas = (PAData[])f.get(tgsReq); |
|
505 |
||
506 |
Ticket tkt = null; |
|
507 |
EncTicketPart etp = null; |
|
508 |
if (pas == null || pas.length == 0) { |
|
509 |
throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP); |
|
510 |
} else { |
|
511 |
for (PAData pa: pas) { |
|
512 |
if (pa.getType() == Krb5.PA_TGS_REQ) { |
|
513 |
APReq apReq = new APReq(pa.getValue()); |
|
514 |
EncryptedData ed = apReq.authenticator; |
|
515 |
tkt = apReq.ticket; |
|
516 |
etype = tkt.encPart.getEType(); |
|
517 |
EncryptionKey kkey = null; |
|
518 |
if (!tkt.realm.toString().equals(realm)) { |
|
519 |
if (tkt.sname.getNameString().equals("krbtgt/" + realm)) { |
|
520 |
kkey = keyForUser(new PrincipalName("krbtgt/" + tkt.realm.toString(), realm), etype); |
|
521 |
} |
|
522 |
} else { |
|
523 |
kkey = keyForUser(tkt.sname, etype); |
|
524 |
} |
|
525 |
byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET); |
|
526 |
DerInputStream derIn = new DerInputStream(bb); |
|
527 |
DerValue der = derIn.getDerValue(); |
|
528 |
etp = new EncTicketPart(der.toByteArray()); |
|
529 |
} |
|
530 |
} |
|
531 |
if (tkt == null) { |
|
532 |
throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP); |
|
533 |
} |
|
534 |
} |
|
535 |
EncryptionKey skey = keyForUser(body.sname, etype); |
|
536 |
if (skey == null) { |
|
537 |
throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO |
|
538 |
} |
|
539 |
||
540 |
// Session key for original ticket, TGT |
|
541 |
EncryptionKey ckey = etp.key; |
|
542 |
||
543 |
// Session key for session with the service |
|
544 |
EncryptionKey key = generateRandomKey(etype); |
|
545 |
||
546 |
// Check time, TODO |
|
547 |
KerberosTime till = body.till; |
|
548 |
if (till == null) { |
|
549 |
throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO |
|
550 |
} else if (till.isZero()) { |
|
551 |
till = new KerberosTime(new Date().getTime() + 1000 * 3600 * 11); |
|
552 |
} |
|
553 |
||
554 |
boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1]; |
|
555 |
if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) { |
|
556 |
bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true; |
|
557 |
} |
|
558 |
if (body.kdcOptions.get(KDCOptions.FORWARDED) || |
|
559 |
etp.flags.get(Krb5.TKT_OPTS_FORWARDED)) { |
|
560 |
bFlags[Krb5.TKT_OPTS_FORWARDED] = true; |
|
561 |
} |
|
562 |
if (body.kdcOptions.get(KDCOptions.RENEWABLE)) { |
|
563 |
bFlags[Krb5.TKT_OPTS_RENEWABLE] = true; |
|
564 |
//renew = new KerberosTime(new Date().getTime() + 1000 * 3600 * 24 * 7); |
|
565 |
} |
|
566 |
if (body.kdcOptions.get(KDCOptions.PROXIABLE)) { |
|
567 |
bFlags[Krb5.TKT_OPTS_PROXIABLE] = true; |
|
568 |
} |
|
569 |
if (body.kdcOptions.get(KDCOptions.POSTDATED)) { |
|
570 |
bFlags[Krb5.TKT_OPTS_POSTDATED] = true; |
|
571 |
} |
|
572 |
if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) { |
|
573 |
bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true; |
|
574 |
} |
|
575 |
bFlags[Krb5.TKT_OPTS_INITIAL] = true; |
|
576 |
||
577 |
TicketFlags tFlags = new TicketFlags(bFlags); |
|
578 |
EncTicketPart enc = new EncTicketPart( |
|
579 |
tFlags, |
|
580 |
key, |
|
581 |
etp.crealm, |
|
582 |
etp.cname, |
|
583 |
new TransitedEncoding(1, new byte[0]), // TODO |
|
584 |
new KerberosTime(new Date()), |
|
585 |
body.from, |
|
586 |
till, body.rtime, |
|
587 |
body.addresses, |
|
588 |
null); |
|
589 |
Ticket t = new Ticket( |
|
590 |
body.crealm, |
|
591 |
body.sname, |
|
592 |
new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET) |
|
593 |
); |
|
594 |
EncTGSRepPart enc_part = new EncTGSRepPart( |
|
595 |
key, |
|
596 |
new LastReq(new LastReqEntry[]{ |
|
597 |
new LastReqEntry(0, new KerberosTime(new Date().getTime() - 10000)) |
|
598 |
}), |
|
599 |
body.getNonce(), // TODO: detect replay |
|
600 |
new KerberosTime(new Date().getTime() + 1000 * 3600 * 24), |
|
601 |
// Next 5 and last MUST be same with ticket |
|
602 |
tFlags, |
|
603 |
new KerberosTime(new Date()), |
|
604 |
body.from, |
|
605 |
till, body.rtime, |
|
606 |
body.crealm, |
|
607 |
body.sname, |
|
608 |
body.addresses |
|
609 |
); |
|
610 |
EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_TGS_REP_PART_SESSKEY); |
|
611 |
TGSRep tgsRep = new TGSRep(null, |
|
612 |
etp.crealm, |
|
613 |
etp.cname, |
|
614 |
t, |
|
615 |
edata); |
|
616 |
System.out.println(" Return " + tgsRep.cname |
|
617 |
+ " ticket for " + tgsRep.ticket.sname); |
|
618 |
||
619 |
DerOutputStream out = new DerOutputStream(); |
|
620 |
out.write(DerValue.createTag(DerValue.TAG_APPLICATION, |
|
621 |
true, (byte)Krb5.KRB_TGS_REP), tgsRep.asn1Encode()); |
|
622 |
return out.toByteArray(); |
|
623 |
} catch (KrbException ke) { |
|
624 |
ke.printStackTrace(System.out); |
|
625 |
KRBError kerr = ke.getError(); |
|
626 |
KDCReqBody body = tgsReq.reqBody; |
|
627 |
System.out.println(" Error " + ke.returnCode() |
|
628 |
+ " " +ke.returnCodeMessage()); |
|
629 |
if (kerr == null) { |
|
630 |
kerr = new KRBError(null, null, null, |
|
631 |
new KerberosTime(new Date()), |
|
632 |
0, |
|
633 |
ke.returnCode(), |
|
634 |
body.crealm, body.cname, |
|
635 |
new Realm(getRealm()), body.sname, |
|
636 |
KrbException.errorMessage(ke.returnCode()), |
|
637 |
null); |
|
638 |
} |
|
639 |
return kerr.asn1Encode(); |
|
640 |
} |
|
641 |
} |
|
642 |
||
643 |
/** |
|
644 |
* Processes a AS_REQ and generates a AS_REP (or KRB_ERROR) |
|
645 |
* @param in the request |
|
646 |
* @return the response |
|
647 |
* @throws java.lang.Exception for various errors |
|
648 |
*/ |
|
649 |
private byte[] processAsReq(byte[] in) throws Exception { |
|
650 |
ASReq asReq = new ASReq(in); |
|
651 |
int[] eTypes = null; |
|
652 |
try { |
|
653 |
System.out.println(realm + "> " + asReq.reqBody.cname + |
|
654 |
" sends AS-REQ for " + |
|
655 |
asReq.reqBody.sname); |
|
656 |
||
657 |
KDCReqBody body = asReq.reqBody; |
|
658 |
||
659 |
// Reflection: int[] eType = body.eType; |
|
660 |
Field f = KDCReqBody.class.getDeclaredField("eType"); |
|
661 |
f.setAccessible(true); |
|
662 |
eTypes = (int[])f.get(body); |
|
663 |
int eType = eTypes[0]; |
|
664 |
||
665 |
EncryptionKey ckey = keyForUser(body.cname, eType); |
|
666 |
EncryptionKey skey = keyForUser(body.sname, eType); |
|
667 |
if (ckey == null) { |
|
668 |
throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP); |
|
669 |
} |
|
670 |
if (skey == null) { |
|
671 |
throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO |
|
672 |
} |
|
673 |
||
674 |
// Session key |
|
675 |
EncryptionKey key = generateRandomKey(eType); |
|
676 |
// Check time, TODO |
|
677 |
KerberosTime till = body.till; |
|
678 |
if (till == null) { |
|
679 |
throw new KrbException(Krb5.KDC_ERR_NEVER_VALID); // TODO |
|
680 |
} else if (till.isZero()) { |
|
681 |
till = new KerberosTime(new Date().getTime() + 1000 * 3600 * 11); |
|
682 |
} |
|
683 |
//body.from |
|
684 |
boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1]; |
|
685 |
if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) { |
|
686 |
bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true; |
|
687 |
} |
|
688 |
if (body.kdcOptions.get(KDCOptions.RENEWABLE)) { |
|
689 |
bFlags[Krb5.TKT_OPTS_RENEWABLE] = true; |
|
690 |
//renew = new KerberosTime(new Date().getTime() + 1000 * 3600 * 24 * 7); |
|
691 |
} |
|
692 |
if (body.kdcOptions.get(KDCOptions.PROXIABLE)) { |
|
693 |
bFlags[Krb5.TKT_OPTS_PROXIABLE] = true; |
|
694 |
} |
|
695 |
if (body.kdcOptions.get(KDCOptions.POSTDATED)) { |
|
696 |
bFlags[Krb5.TKT_OPTS_POSTDATED] = true; |
|
697 |
} |
|
698 |
if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) { |
|
699 |
bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true; |
|
700 |
} |
|
701 |
bFlags[Krb5.TKT_OPTS_INITIAL] = true; |
|
702 |
||
703 |
f = KDCReq.class.getDeclaredField("pAData"); |
|
704 |
f.setAccessible(true); |
|
705 |
PAData[] pas = (PAData[])f.get(asReq); |
|
706 |
if (pas == null || pas.length == 0) { |
|
707 |
Object preauth = options.get(Option.PREAUTH_REQUIRED); |
|
708 |
if (preauth == null || preauth.equals(Boolean.TRUE)) { |
|
709 |
throw new KrbException(Krb5.KDC_ERR_PREAUTH_REQUIRED); |
|
710 |
} |
|
711 |
} else { |
|
712 |
try { |
|
713 |
Constructor<EncryptedData> ctor = EncryptedData.class.getDeclaredConstructor(DerValue.class); |
|
714 |
ctor.setAccessible(true); |
|
715 |
EncryptedData data = ctor.newInstance(new DerValue(pas[0].getValue())); |
|
716 |
data.decrypt(ckey, KeyUsage.KU_PA_ENC_TS); |
|
717 |
} catch (Exception e) { |
|
718 |
throw new KrbException(Krb5.KDC_ERR_PREAUTH_FAILED); |
|
719 |
} |
|
720 |
bFlags[Krb5.TKT_OPTS_PRE_AUTHENT] = true; |
|
721 |
} |
|
722 |
||
723 |
TicketFlags tFlags = new TicketFlags(bFlags); |
|
724 |
EncTicketPart enc = new EncTicketPart( |
|
725 |
tFlags, |
|
726 |
key, |
|
727 |
body.crealm, |
|
728 |
body.cname, |
|
729 |
new TransitedEncoding(1, new byte[0]), |
|
730 |
new KerberosTime(new Date()), |
|
731 |
body.from, |
|
732 |
till, body.rtime, |
|
733 |
body.addresses, |
|
734 |
null); |
|
735 |
Ticket t = new Ticket( |
|
736 |
body.crealm, |
|
737 |
body.sname, |
|
738 |
new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET) |
|
739 |
); |
|
740 |
EncASRepPart enc_part = new EncASRepPart( |
|
741 |
key, |
|
742 |
new LastReq(new LastReqEntry[]{ |
|
743 |
new LastReqEntry(0, new KerberosTime(new Date().getTime() - 10000)) |
|
744 |
}), |
|
745 |
body.getNonce(), // TODO: detect replay? |
|
746 |
new KerberosTime(new Date().getTime() + 1000 * 3600 * 24), |
|
747 |
// Next 5 and last MUST be same with ticket |
|
748 |
tFlags, |
|
749 |
new KerberosTime(new Date()), |
|
750 |
body.from, |
|
751 |
till, body.rtime, |
|
752 |
body.crealm, |
|
753 |
body.sname, |
|
754 |
body.addresses |
|
755 |
); |
|
756 |
EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_AS_REP_PART); |
|
757 |
ASRep asRep = new ASRep(null, |
|
758 |
body.crealm, |
|
759 |
body.cname, |
|
760 |
t, |
|
761 |
edata); |
|
762 |
||
763 |
System.out.println(" Return " + asRep.cname |
|
764 |
+ " ticket for " + asRep.ticket.sname); |
|
765 |
||
766 |
DerOutputStream out = new DerOutputStream(); |
|
767 |
out.write(DerValue.createTag(DerValue.TAG_APPLICATION, |
|
768 |
true, (byte)Krb5.KRB_AS_REP), asRep.asn1Encode()); |
|
1575
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
769 |
byte[] result = out.toByteArray(); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
770 |
|
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
771 |
// Added feature: |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
772 |
// Write the current issuing TGT into a ccache file specified |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
773 |
// by the system property below. |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
774 |
String ccache = System.getProperty("test.kdc.save.ccache"); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
775 |
if (ccache != null) { |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
776 |
asRep.encKDCRepPart = enc_part; |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
777 |
sun.security.krb5.internal.ccache.Credentials credentials = |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
778 |
new sun.security.krb5.internal.ccache.Credentials(asRep); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
779 |
asReq.reqBody.cname.setRealm(getRealm()); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
780 |
CredentialsCache cache = |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
781 |
CredentialsCache.create(asReq.reqBody.cname, ccache); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
782 |
if (cache == null) { |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
783 |
throw new IOException("Unable to create the cache file " + |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
784 |
ccache); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
785 |
} |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
786 |
cache.update(credentials); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
787 |
cache.save(); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
788 |
new File(ccache).deleteOnExit(); |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
789 |
} |
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
790 |
|
e0f1979051b5
6765491: Krb5LoginModule a little too restrictive, and the doc is not clear.
weijun
parents:
1456
diff
changeset
|
791 |
return result; |
1454 | 792 |
} catch (KrbException ke) { |
793 |
ke.printStackTrace(System.out); |
|
794 |
KRBError kerr = ke.getError(); |
|
795 |
KDCReqBody body = asReq.reqBody; |
|
796 |
System.out.println(" Error " + ke.returnCode() |
|
797 |
+ " " +ke.returnCodeMessage()); |
|
798 |
byte[] eData = null; |
|
799 |
if (kerr == null) { |
|
800 |
if (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED || |
|
801 |
ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) { |
|
802 |
PAData pa; |
|
803 |
||
804 |
ETypeInfo2 ei2 = new ETypeInfo2(eTypes[0], null, null); |
|
805 |
DerOutputStream eid = new DerOutputStream(); |
|
806 |
eid.write(DerValue.tag_Sequence, ei2.asn1Encode()); |
|
807 |
||
808 |
pa = new PAData(Krb5.PA_ETYPE_INFO2, eid.toByteArray()); |
|
809 |
||
810 |
DerOutputStream bytes = new DerOutputStream(); |
|
811 |
bytes.write(new PAData(Krb5.PA_ENC_TIMESTAMP, new byte[0]).asn1Encode()); |
|
812 |
bytes.write(pa.asn1Encode()); |
|
813 |
||
814 |
boolean allOld = true; |
|
815 |
for (int i: eTypes) { |
|
816 |
if (i == EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96 || |
|
817 |
i == EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96) { |
|
818 |
allOld = false; |
|
819 |
break; |
|
820 |
} |
|
821 |
} |
|
822 |
if (allOld) { |
|
823 |
ETypeInfo ei = new ETypeInfo(eTypes[0], null); |
|
824 |
eid = new DerOutputStream(); |
|
825 |
eid.write(DerValue.tag_Sequence, ei.asn1Encode()); |
|
826 |
pa = new PAData(Krb5.PA_ETYPE_INFO, eid.toByteArray()); |
|
827 |
bytes.write(pa.asn1Encode()); |
|
828 |
} |
|
829 |
DerOutputStream temp = new DerOutputStream(); |
|
830 |
temp.write(DerValue.tag_Sequence, bytes); |
|
831 |
eData = temp.toByteArray(); |
|
832 |
} |
|
833 |
kerr = new KRBError(null, null, null, |
|
834 |
new KerberosTime(new Date()), |
|
835 |
0, |
|
836 |
ke.returnCode(), |
|
837 |
body.crealm, body.cname, |
|
838 |
new Realm(getRealm()), body.sname, |
|
839 |
KrbException.errorMessage(ke.returnCode()), |
|
840 |
eData); |
|
841 |
} |
|
842 |
return kerr.asn1Encode(); |
|
843 |
} |
|
844 |
} |
|
845 |
||
846 |
/** |
|
847 |
* Generates a line for a KDC to put inside [realms] of krb5.conf |
|
848 |
* @param kdc the KDC |
|
849 |
* @return REALM.NAME = { kdc = localhost:port } |
|
850 |
*/ |
|
851 |
private static String realmLineForKDC(KDC kdc) { |
|
852 |
return String.format(" %s = {\n kdc = localhost:%d\n }\n", kdc.realm, kdc.port); |
|
853 |
} |
|
854 |
||
855 |
/** |
|
856 |
* Start the KDC service. This server listens on both UDP and TCP using |
|
857 |
* the same port number. It uses three threads to deal with requests. |
|
858 |
* They can be set to daemon threads if requested. |
|
859 |
* @param port the port number to listen to. If zero, a random available |
|
860 |
* port no less than 8000 will be chosen and used. |
|
861 |
* @param asDaemon true if the KDC threads should be daemons |
|
862 |
* @throws java.io.IOException for any communication error |
|
863 |
*/ |
|
864 |
protected void startServer(int port, boolean asDaemon) throws IOException { |
|
865 |
DatagramSocket u1 = null; |
|
866 |
ServerSocket t1 = null; |
|
867 |
if (port > 0) { |
|
868 |
u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1")); |
|
869 |
t1 = new ServerSocket(port); |
|
870 |
} else { |
|
871 |
while (true) { |
|
872 |
// Try to find a port number that's both TCP and UDP free |
|
873 |
try { |
|
874 |
port = 8000 + new java.util.Random().nextInt(10000); |
|
875 |
u1 = null; |
|
876 |
u1 = new DatagramSocket(port, InetAddress.getByName("127.0.0.1")); |
|
877 |
t1 = new ServerSocket(port); |
|
878 |
break; |
|
879 |
} catch (Exception e) { |
|
880 |
if (u1 != null) u1.close(); |
|
881 |
} |
|
882 |
} |
|
883 |
} |
|
884 |
final DatagramSocket udp = u1; |
|
885 |
final ServerSocket tcp = t1; |
|
886 |
System.out.println("Start KDC on " + port); |
|
887 |
||
888 |
this.port = port; |
|
889 |
||
890 |
// The UDP consumer |
|
891 |
Thread thread = new Thread() { |
|
892 |
public void run() { |
|
893 |
while (true) { |
|
894 |
try { |
|
895 |
byte[] inbuf = new byte[8192]; |
|
896 |
DatagramPacket p = new DatagramPacket(inbuf, inbuf.length); |
|
897 |
udp.receive(p); |
|
898 |
System.out.println("-----------------------------------------------"); |
|
899 |
System.out.println(">>>>> UDP packet received"); |
|
900 |
q.put(new Job(processMessage(Arrays.copyOf(inbuf, p.getLength())), udp, p)); |
|
901 |
} catch (Exception e) { |
|
902 |
e.printStackTrace(); |
|
903 |
} |
|
904 |
} |
|
905 |
} |
|
906 |
}; |
|
907 |
thread.setDaemon(asDaemon); |
|
908 |
thread.start(); |
|
909 |
||
910 |
// The TCP consumer |
|
911 |
thread = new Thread() { |
|
912 |
public void run() { |
|
913 |
while (true) { |
|
914 |
try { |
|
915 |
Socket socket = tcp.accept(); |
|
916 |
System.out.println("-----------------------------------------------"); |
|
917 |
System.out.println(">>>>> TCP connection established"); |
|
918 |
DataInputStream in = new DataInputStream(socket.getInputStream()); |
|
919 |
DataOutputStream out = new DataOutputStream(socket.getOutputStream()); |
|
920 |
byte[] token = new byte[in.readInt()]; |
|
921 |
in.readFully(token); |
|
922 |
q.put(new Job(processMessage(token), socket, out)); |
|
923 |
} catch (Exception e) { |
|
924 |
e.printStackTrace(); |
|
925 |
} |
|
926 |
} |
|
927 |
} |
|
928 |
}; |
|
929 |
thread.setDaemon(asDaemon); |
|
930 |
thread.start(); |
|
931 |
||
932 |
// The dispatcher |
|
933 |
thread = new Thread() { |
|
934 |
public void run() { |
|
935 |
while (true) { |
|
936 |
try { |
|
937 |
q.take().send(); |
|
938 |
} catch (Exception e) { |
|
939 |
} |
|
940 |
} |
|
941 |
} |
|
942 |
}; |
|
943 |
thread.setDaemon(true); |
|
944 |
thread.start(); |
|
945 |
} |
|
946 |
||
947 |
/** |
|
948 |
* Helper class to encapsulate a job in a KDC. |
|
949 |
*/ |
|
950 |
private static class Job { |
|
951 |
byte[] token; // The received request at creation time and |
|
952 |
// the response at send time |
|
953 |
Socket s; // The TCP socket from where the request comes |
|
954 |
DataOutputStream out; // The OutputStream of the TCP socket |
|
955 |
DatagramSocket s2; // The UDP socket from where the request comes |
|
956 |
DatagramPacket dp; // The incoming UDP datagram packet |
|
957 |
boolean useTCP; // Whether TCP or UDP is used |
|
958 |
||
959 |
// Creates a job object for TCP |
|
960 |
Job(byte[] token, Socket s, DataOutputStream out) { |
|
961 |
useTCP = true; |
|
962 |
this.token = token; |
|
963 |
this.s = s; |
|
964 |
this.out = out; |
|
965 |
} |
|
966 |
||
967 |
// Creates a job object for UDP |
|
968 |
Job(byte[] token, DatagramSocket s2, DatagramPacket dp) { |
|
969 |
useTCP = false; |
|
970 |
this.token = token; |
|
971 |
this.s2 = s2; |
|
972 |
this.dp = dp; |
|
973 |
} |
|
974 |
||
975 |
// Sends the output back to the client |
|
976 |
void send() { |
|
977 |
try { |
|
978 |
if (useTCP) { |
|
979 |
System.out.println(">>>>> TCP request honored"); |
|
980 |
out.writeInt(token.length); |
|
981 |
out.write(token); |
|
982 |
s.close(); |
|
983 |
} else { |
|
984 |
System.out.println(">>>>> UDP request honored"); |
|
985 |
s2.send(new DatagramPacket(token, token.length, dp.getAddress(), dp.getPort())); |
|
986 |
} |
|
987 |
} catch (Exception e) { |
|
988 |
e.printStackTrace(); |
|
989 |
} |
|
990 |
} |
|
991 |
} |
|
992 |
} |