Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/security/krb5/auto/Context.java
38853 views
1
/*
2
* Copyright (c) 2008, 2018, 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.
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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
import com.sun.security.auth.module.Krb5LoginModule;
25
import java.io.IOException;
26
import java.lang.reflect.InvocationTargetException;
27
import java.security.PrivilegedActionException;
28
import java.security.PrivilegedExceptionAction;
29
import java.security.Key;
30
import java.util.Arrays;
31
import java.util.HashMap;
32
import java.util.Map;
33
import java.util.Set;
34
import javax.security.auth.Subject;
35
import javax.security.auth.callback.Callback;
36
import javax.security.auth.callback.CallbackHandler;
37
import javax.security.auth.callback.NameCallback;
38
import javax.security.auth.callback.PasswordCallback;
39
import javax.security.auth.callback.UnsupportedCallbackException;
40
import javax.security.auth.kerberos.KerberosKey;
41
import javax.security.auth.kerberos.KerberosTicket;
42
import javax.security.auth.login.LoginContext;
43
import org.ietf.jgss.GSSContext;
44
import org.ietf.jgss.GSSCredential;
45
import org.ietf.jgss.GSSException;
46
import org.ietf.jgss.GSSManager;
47
import org.ietf.jgss.GSSName;
48
import org.ietf.jgss.MessageProp;
49
import org.ietf.jgss.Oid;
50
import sun.security.jgss.krb5.Krb5Util;
51
import sun.security.krb5.Credentials;
52
import sun.security.krb5.internal.ccache.CredentialsCache;
53
54
import com.sun.security.jgss.ExtendedGSSContext;
55
import com.sun.security.jgss.InquireType;
56
import com.sun.security.jgss.AuthorizationDataEntry;
57
import com.sun.security.jgss.ExtendedGSSCredential;
58
import java.io.ByteArrayInputStream;
59
import java.io.ByteArrayOutputStream;
60
import java.security.Principal;
61
62
/**
63
* Context of a JGSS subject, encapsulating Subject and GSSContext.
64
*
65
* Three "constructors", which acquire the (private) credentials and fill
66
* it into the Subject:
67
*
68
* 1. static fromJAAS(): Creates a Context using a JAAS login config entry
69
* 2. static fromUserPass(): Creates a Context using a username and a password
70
* 3. delegated(): A new context which uses the delegated credentials from a
71
* previously established acceptor Context
72
*
73
* Two context initiators, which create the GSSContext object inside:
74
*
75
* 1. startAsClient()
76
* 2. startAsServer()
77
*
78
* Privileged action:
79
* doAs(): Performs an action in the name of the Subject
80
*
81
* Handshake process:
82
* static handShake(initiator, acceptor)
83
*
84
* A four-phase typical data communication which includes all four GSS
85
* actions (wrap, unwrap, getMic and veryfyMiC):
86
* static transmit(message, from, to)
87
*/
88
public class Context {
89
90
private Subject s;
91
private ExtendedGSSContext x;
92
private String name;
93
private GSSCredential cred; // see static method delegated().
94
95
static boolean usingStream = false;
96
97
private Context() {}
98
99
/**
100
* Using the delegated credentials from a previous acceptor
101
* @param c
102
*/
103
public Context delegated() throws Exception {
104
Context out = new Context();
105
out.s = s;
106
try {
107
out.cred = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
108
@Override
109
public GSSCredential run() throws Exception {
110
GSSCredential cred = x.getDelegCred();
111
if (cred == null && x.getCredDelegState() ||
112
cred != null && !x.getCredDelegState()) {
113
throw new Exception("getCredDelegState not match");
114
}
115
return cred;
116
}
117
});
118
} catch (PrivilegedActionException pae) {
119
throw pae.getException();
120
}
121
out.name = name + " as " + out.cred.getName().toString();
122
return out;
123
}
124
125
/**
126
* No JAAS login at all, can be used to test JGSS without JAAS
127
*/
128
public static Context fromThinAir() throws Exception {
129
Context out = new Context();
130
out.s = new Subject();
131
return out;
132
}
133
134
/**
135
* Logins with a JAAS login config entry name
136
*/
137
public static Context fromJAAS(final String name) throws Exception {
138
Context out = new Context();
139
out.name = name;
140
LoginContext lc = new LoginContext(name);
141
lc.login();
142
out.s = lc.getSubject();
143
return out;
144
}
145
146
/**
147
* Logins with username/password as a new Subject
148
*/
149
public static Context fromUserPass(
150
String user, char[] pass, boolean storeKey) throws Exception {
151
return fromUserPass(new Subject(), user, pass, storeKey);
152
}
153
154
/**
155
* Logins with username/password as an existing Subject. The
156
* same subject can be used multiple times to simulate multiple logins.
157
* @param s existing subject
158
*/
159
public static Context fromUserPass(Subject s,
160
String user, char[] pass, boolean storeKey) throws Exception {
161
Context out = new Context();
162
out.name = user;
163
out.s = s;
164
Krb5LoginModule krb5 = new Krb5LoginModule();
165
Map<String, String> map = new HashMap<>();
166
Map<String, Object> shared = new HashMap<>();
167
168
if (storeKey) {
169
map.put("storeKey", "true");
170
}
171
172
if (pass != null) {
173
krb5.initialize(out.s, new CallbackHandler() {
174
@Override
175
public void handle(Callback[] callbacks)
176
throws IOException, UnsupportedCallbackException {
177
for (Callback cb: callbacks) {
178
if (cb instanceof NameCallback) {
179
((NameCallback)cb).setName(user);
180
} else if (cb instanceof PasswordCallback) {
181
((PasswordCallback)cb).setPassword(pass);
182
}
183
}
184
}
185
}, shared, map);
186
} else {
187
map.put("doNotPrompt", "true");
188
map.put("useTicketCache", "true");
189
if (user != null) {
190
map.put("principal", user);
191
}
192
krb5.initialize(out.s, null, shared, map);
193
}
194
195
krb5.login();
196
krb5.commit();
197
198
return out;
199
}
200
201
/**
202
* Logins with username/keytab as an existing Subject. The
203
* same subject can be used multiple times to simulate multiple logins.
204
* @param s existing subject
205
*/
206
public static Context fromUserKtab(
207
String user, String ktab, boolean storeKey) throws Exception {
208
return fromUserKtab(new Subject(), user, ktab, storeKey);
209
}
210
211
/**
212
* Logins with username/keytab as a new subject,
213
*/
214
public static Context fromUserKtab(Subject s,
215
String user, String ktab, boolean storeKey) throws Exception {
216
Context out = new Context();
217
out.name = user;
218
out.s = s;
219
Krb5LoginModule krb5 = new Krb5LoginModule();
220
Map<String, String> map = new HashMap<>();
221
222
map.put("isInitiator", "false");
223
map.put("doNotPrompt", "true");
224
map.put("useTicketCache", "false");
225
map.put("useKeyTab", "true");
226
map.put("keyTab", ktab);
227
map.put("principal", user);
228
if (storeKey) {
229
map.put("storeKey", "true");
230
}
231
232
krb5.initialize(out.s, null, null, map);
233
krb5.login();
234
krb5.commit();
235
return out;
236
}
237
238
/**
239
* Starts as a client
240
* @param target communication peer
241
* @param mech GSS mech
242
* @throws java.lang.Exception
243
*/
244
public void startAsClient(final String target, final Oid mech) throws Exception {
245
doAs(new Action() {
246
@Override
247
public byte[] run(Context me, byte[] dummy) throws Exception {
248
GSSManager m = GSSManager.getInstance();
249
me.x = (ExtendedGSSContext)m.createContext(
250
target.indexOf('@') < 0 ?
251
m.createName(target, null) :
252
m.createName(target, GSSName.NT_HOSTBASED_SERVICE),
253
mech,
254
cred,
255
GSSContext.DEFAULT_LIFETIME);
256
return null;
257
}
258
}, null);
259
}
260
261
/**
262
* Starts as a server
263
* @param mech GSS mech
264
* @throws java.lang.Exception
265
*/
266
public void startAsServer(final Oid mech) throws Exception {
267
startAsServer(null, mech, false);
268
}
269
270
public void startAsServer(final String name, final Oid mech) throws Exception {
271
startAsServer(name, mech, false);
272
}
273
/**
274
* Starts as a server with the specified service name
275
* @param name the service name
276
* @param mech GSS mech
277
* @throws java.lang.Exception
278
*/
279
public void startAsServer(final String name, final Oid mech, final boolean asInitiator) throws Exception {
280
doAs(new Action() {
281
@Override
282
public byte[] run(Context me, byte[] dummy) throws Exception {
283
GSSManager m = GSSManager.getInstance();
284
me.cred = m.createCredential(
285
name == null ? null :
286
(name.indexOf('@') < 0 ?
287
m.createName(name, null) :
288
m.createName(name, GSSName.NT_HOSTBASED_SERVICE)),
289
GSSCredential.INDEFINITE_LIFETIME,
290
mech,
291
asInitiator?
292
GSSCredential.INITIATE_AND_ACCEPT:
293
GSSCredential.ACCEPT_ONLY);
294
me.x = (ExtendedGSSContext)m.createContext(me.cred);
295
return null;
296
}
297
}, null);
298
}
299
300
/**
301
* Accesses the internal GSSContext object. Currently it's used for --
302
*
303
* 1. calling requestXXX() before handshake
304
* 2. accessing source name
305
*
306
* Note: If the application needs to do any privileged call on this
307
* object, please use doAs(). Otherwise, it can be done directly. The
308
* methods listed above are all non-privileged calls.
309
*
310
* @return the GSSContext object
311
*/
312
public ExtendedGSSContext x() {
313
return x;
314
}
315
316
/**
317
* Accesses the internal subject.
318
* @return the subject
319
*/
320
public Subject s() {
321
return s;
322
}
323
324
/**
325
* Returns the cred inside, if there is one
326
*/
327
public GSSCredential cred() {
328
return cred;
329
}
330
331
/**
332
* Disposes the GSSContext within
333
* @throws org.ietf.jgss.GSSException
334
*/
335
public void dispose() throws GSSException {
336
x.dispose();
337
}
338
339
/**
340
* Does something using the Subject inside
341
* @param action the action
342
* @param in the input byte
343
* @return the output byte
344
* @throws java.lang.Exception
345
*/
346
public byte[] doAs(final Action action, final byte[] in) throws Exception {
347
try {
348
return Subject.doAs(s, new PrivilegedExceptionAction<byte[]>() {
349
350
@Override
351
public byte[] run() throws Exception {
352
return action.run(Context.this, in);
353
}
354
});
355
} catch (PrivilegedActionException pae) {
356
throw pae.getException();
357
}
358
}
359
360
/**
361
* Prints status of GSSContext and Subject
362
* @throws java.lang.Exception
363
*/
364
public void status() throws Exception {
365
System.out.println("STATUS OF " + name.toUpperCase());
366
try {
367
StringBuffer sb = new StringBuffer();
368
if (x.getAnonymityState()) {
369
sb.append("anon, ");
370
}
371
if (x.getConfState()) {
372
sb.append("conf, ");
373
}
374
if (x.getCredDelegState()) {
375
sb.append("deleg, ");
376
}
377
if (x.getIntegState()) {
378
sb.append("integ, ");
379
}
380
if (x.getMutualAuthState()) {
381
sb.append("mutual, ");
382
}
383
if (x.getReplayDetState()) {
384
sb.append("rep det, ");
385
}
386
if (x.getSequenceDetState()) {
387
sb.append("seq det, ");
388
}
389
if (x instanceof ExtendedGSSContext) {
390
if (((ExtendedGSSContext)x).getDelegPolicyState()) {
391
sb.append("deleg policy, ");
392
}
393
}
394
System.out.println("Context status of " + name + ": " + sb.toString());
395
System.out.println(x.getSrcName() + " -> " + x.getTargName());
396
} catch (Exception e) {
397
;// Don't care
398
}
399
if (s != null) {
400
System.out.println("====== START SUBJECT CONTENT =====");
401
for (Principal p: s.getPrincipals()) {
402
System.out.println(" Principal: " + p);
403
}
404
for (Object o : s.getPublicCredentials()) {
405
System.out.println(" " + o.getClass());
406
System.out.println(" " + o);
407
}
408
System.out.println("====== Private Credentials Set ======");
409
for (Object o : s.getPrivateCredentials()) {
410
System.out.println(" " + o.getClass());
411
if (o instanceof KerberosTicket) {
412
KerberosTicket kt = (KerberosTicket) o;
413
System.out.println(" " + kt.getServer() + " for " + kt.getClient());
414
} else if (o instanceof KerberosKey) {
415
KerberosKey kk = (KerberosKey) o;
416
System.out.print(" " + kk.getKeyType() + " " + kk.getVersionNumber() + " " + kk.getAlgorithm() + " ");
417
for (byte b : kk.getEncoded()) {
418
System.out.printf("%02X", b & 0xff);
419
}
420
System.out.println();
421
} else if (o instanceof Map) {
422
Map map = (Map) o;
423
for (Object k : map.keySet()) {
424
System.out.println(" " + k + ": " + map.get(k));
425
}
426
} else {
427
System.out.println(" " + o);
428
}
429
}
430
System.out.println("====== END SUBJECT CONTENT =====");
431
}
432
if (x != null && x instanceof ExtendedGSSContext) {
433
if (x.isEstablished()) {
434
ExtendedGSSContext ex = (ExtendedGSSContext)x;
435
Key k = (Key)ex.inquireSecContext(
436
InquireType.KRB5_GET_SESSION_KEY);
437
if (k == null) {
438
throw new Exception("Session key cannot be null");
439
}
440
System.out.println("Session key is: " + k);
441
boolean[] flags = (boolean[])ex.inquireSecContext(
442
InquireType.KRB5_GET_TKT_FLAGS);
443
if (flags == null) {
444
throw new Exception("Ticket flags cannot be null");
445
}
446
System.out.println("Ticket flags is: " + Arrays.toString(flags));
447
String authTime = (String)ex.inquireSecContext(
448
InquireType.KRB5_GET_AUTHTIME);
449
if (authTime == null) {
450
throw new Exception("Auth time cannot be null");
451
}
452
System.out.println("AuthTime is: " + authTime);
453
if (!x.isInitiator()) {
454
AuthorizationDataEntry[] ad = (AuthorizationDataEntry[])ex.inquireSecContext(
455
InquireType.KRB5_GET_AUTHZ_DATA);
456
System.out.println("AuthzData is: " + Arrays.toString(ad));
457
}
458
}
459
}
460
}
461
462
public byte[] wrap(byte[] t, final boolean privacy)
463
throws Exception {
464
return doAs(new Action() {
465
@Override
466
public byte[] run(Context me, byte[] input) throws Exception {
467
System.out.printf("wrap %s privacy from %s: ", privacy?"with":"without", me.name);
468
MessageProp p1 = new MessageProp(0, privacy);
469
byte[] out;
470
if (usingStream) {
471
ByteArrayOutputStream os = new ByteArrayOutputStream();
472
me.x.wrap(new ByteArrayInputStream(input), os, p1);
473
out = os.toByteArray();
474
} else {
475
out = me.x.wrap(input, 0, input.length, p1);
476
}
477
System.out.println(printProp(p1));
478
if ((x.getConfState() && privacy) != p1.getPrivacy()) {
479
throw new Exception("unexpected privacy status");
480
}
481
return out;
482
}
483
}, t);
484
}
485
486
public byte[] unwrap(byte[] t, final boolean privacyExpected)
487
throws Exception {
488
return doAs(new Action() {
489
@Override
490
public byte[] run(Context me, byte[] input) throws Exception {
491
System.out.printf("unwrap from %s", me.name);
492
MessageProp p1 = new MessageProp(0, true);
493
byte[] bytes;
494
if (usingStream) {
495
ByteArrayOutputStream os = new ByteArrayOutputStream();
496
me.x.unwrap(new ByteArrayInputStream(input), os, p1);
497
bytes = os.toByteArray();
498
} else {
499
bytes = me.x.unwrap(input, 0, input.length, p1);
500
}
501
System.out.println(printProp(p1));
502
if (p1.getPrivacy() != privacyExpected) {
503
throw new Exception("Unexpected privacy: " + p1.getPrivacy());
504
}
505
return bytes;
506
}
507
}, t);
508
}
509
510
public byte[] getMic(byte[] t) throws Exception {
511
return doAs(new Action() {
512
@Override
513
public byte[] run(Context me, byte[] input) throws Exception {
514
MessageProp p1 = new MessageProp(0, true);
515
byte[] bytes;
516
p1 = new MessageProp(0, true);
517
System.out.printf("getMic from %s: ", me.name);
518
if (usingStream) {
519
ByteArrayOutputStream os = new ByteArrayOutputStream();
520
me.x.getMIC(new ByteArrayInputStream(input), os, p1);
521
bytes = os.toByteArray();
522
} else {
523
bytes = me.x.getMIC(input, 0, input.length, p1);
524
}
525
System.out.println(printProp(p1));
526
return bytes;
527
}
528
}, t);
529
}
530
531
public void verifyMic(byte[] t, final byte[] msg) throws Exception {
532
doAs(new Action() {
533
@Override
534
public byte[] run(Context me, byte[] input) throws Exception {
535
MessageProp p1 = new MessageProp(0, true);
536
System.out.printf("verifyMic from %s: ", me.name);
537
if (usingStream) {
538
me.x.verifyMIC(new ByteArrayInputStream(input),
539
new ByteArrayInputStream(msg), p1);
540
} else {
541
me.x.verifyMIC(input, 0, input.length,
542
msg, 0, msg.length,
543
p1);
544
}
545
System.out.println(printProp(p1));
546
if (p1.isUnseqToken() || p1.isOldToken()
547
|| p1.isDuplicateToken() || p1.isGapToken()) {
548
throw new Exception("Wrong sequence number detected");
549
}
550
return null;
551
}
552
}, t);
553
}
554
555
/**
556
* Transmits a message from one Context to another. The sender wraps the
557
* message and sends it to the receiver. The receiver unwraps it, creates
558
* a MIC of the clear text and sends it back to the sender. The sender
559
* verifies the MIC against the message sent earlier.
560
* @param message the message
561
* @param s1 the sender
562
* @param s2 the receiver
563
* @throws java.lang.Exception If anything goes wrong
564
*/
565
static public void transmit(String message, final Context s1,
566
final Context s2) throws Exception {
567
transmit(message.getBytes(), s1, s2);
568
}
569
570
/**
571
* Transmits a message from one Context to another. The sender wraps the
572
* message and sends it to the receiver. The receiver unwraps it, creates
573
* a MIC of the clear text and sends it back to the sender. The sender
574
* verifies the MIC against the message sent earlier.
575
* @param messageBytes the message
576
* @param s1 the sender
577
* @param s2 the receiver
578
* @throws java.lang.Exception If anything goes wrong
579
*/
580
static public void transmit(byte[] messageBytes, final Context s1,
581
final Context s2) throws Exception {
582
System.out.printf("-------------------- TRANSMIT from %s to %s------------------------\n",
583
s1.name, s2.name);
584
byte[] wrapped = s1.wrap(messageBytes, true);
585
byte[] unwrapped = s2.unwrap(wrapped, s2.x.getConfState());
586
if (!Arrays.equals(messageBytes, unwrapped)) {
587
throw new Exception("wrap/unwrap mismatch");
588
}
589
byte[] mic = s2.getMic(unwrapped);
590
s1.verifyMic(mic, messageBytes);
591
}
592
593
/**
594
* Returns a string description of a MessageProp object
595
* @param prop the object
596
* @return the description
597
*/
598
static public String printProp(MessageProp prop) {
599
StringBuffer sb = new StringBuffer();
600
sb.append("MessagePop: ");
601
sb.append("QOP="+ prop.getQOP() + ", ");
602
sb.append(prop.getPrivacy()?"privacy, ":"");
603
sb.append(prop.isDuplicateToken()?"dup, ":"");
604
sb.append(prop.isGapToken()?"gap, ":"");
605
sb.append(prop.isOldToken()?"old, ":"");
606
sb.append(prop.isUnseqToken()?"unseq, ":"");
607
if (prop.getMinorStatus() != 0) {
608
sb.append(prop.getMinorString()+ "(" + prop.getMinorStatus()+")");
609
}
610
return sb.toString();
611
}
612
613
public Context impersonate(final String someone) throws Exception {
614
try {
615
GSSCredential creds = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
616
@Override
617
public GSSCredential run() throws Exception {
618
GSSManager m = GSSManager.getInstance();
619
GSSName other = m.createName(someone, GSSName.NT_USER_NAME);
620
if (Context.this.cred == null) {
621
Context.this.cred = m.createCredential(GSSCredential.INITIATE_ONLY);
622
}
623
return ((ExtendedGSSCredential)Context.this.cred).impersonate(other);
624
}
625
});
626
Context out = new Context();
627
out.s = s;
628
out.cred = creds;
629
out.name = name + " as " + out.cred.getName().toString();
630
return out;
631
} catch (PrivilegedActionException pae) {
632
Exception e = pae.getException();
633
if (e instanceof InvocationTargetException) {
634
throw (Exception)((InvocationTargetException) e).getTargetException();
635
} else {
636
throw e;
637
}
638
}
639
}
640
641
public byte[] take(final byte[] in) throws Exception {
642
return doAs(new Action() {
643
@Override
644
public byte[] run(Context me, byte[] input) throws Exception {
645
if (me.x.isEstablished()) {
646
System.out.println(name + " side established");
647
if (input != null) {
648
throw new Exception("Context established but " +
649
"still receive token at " + name);
650
}
651
return null;
652
} else {
653
if (me.x.isInitiator()) {
654
System.out.println(name + " call initSecContext");
655
return me.x.initSecContext(input, 0, input.length);
656
} else {
657
System.out.println(name + " call acceptSecContext");
658
return me.x.acceptSecContext(input, 0, input.length);
659
}
660
}
661
}
662
}, in);
663
}
664
665
/**
666
* Saves the tickets to a ccache file.
667
*
668
* @param file pathname of the ccache file
669
* @return true if created, false otherwise.
670
*/
671
public boolean ccache(String file) throws Exception {
672
Set<KerberosTicket> tickets
673
= s.getPrivateCredentials(KerberosTicket.class);
674
if (tickets != null && !tickets.isEmpty()) {
675
CredentialsCache cc = null;
676
for (KerberosTicket t : tickets) {
677
Credentials cred = Krb5Util.ticketToCreds(t);
678
if (cc == null) {
679
cc = CredentialsCache.create(cred.getClient(), file);
680
}
681
cc.update(cred.toCCacheCreds());
682
}
683
if (cc != null) {
684
cc.save();
685
return true;
686
}
687
}
688
return false;
689
}
690
691
/**
692
* Handshake (security context establishment process) between two Contexts
693
* @param c the initiator
694
* @param s the acceptor
695
* @throws java.lang.Exception
696
*/
697
static public void handshake(final Context c, final Context s) throws Exception {
698
byte[] t = new byte[0];
699
while (true) {
700
if (t != null || !c.x.isEstablished()) t = c.take(t);
701
if (t != null || !s.x.isEstablished()) t = s.take(t);
702
if (c.x.isEstablished() && s.x.isEstablished()) break;
703
}
704
}
705
}
706
707