-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathServicePermission.java
More file actions
697 lines (605 loc) · 22.9 KB
/
ServicePermission.java
File metadata and controls
697 lines (605 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/*
* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth.kerberos;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* This class is used to protect Kerberos services and the
* credentials necessary to access those services. There is a one to
* one mapping of a service principal and the credentials necessary
* to access the service. Therefore granting access to a service
* principal implicitly grants access to the credential necessary to
* establish a security context with the service principal. This
* applies regardless of whether the credentials are in a cache
* or acquired via an exchange with the KDC. The credential can
* be either a ticket granting ticket, a service ticket or a secret
* key from a key table.
* <p>
* A ServicePermission contains a service principal name and
* a list of actions which specify the context the credential can be
* used within.
* <p>
* The service principal name is the canonical name of the
* {@code KerberosPrincipal} supplying the service, that is
* the KerberosPrincipal represents a Kerberos service
* principal. This name is treated in a case sensitive manner.
* An asterisk may appear by itself, to signify any service principal.
* <p>
* Granting this permission implies that the caller can use a cached
* credential (TGT, service ticket or secret key) within the context
* designated by the action. In the case of the TGT, granting this
* permission also implies that the TGT can be obtained by an
* Authentication Service exchange.
* <p>
* Granting this permission also implies creating {@link KerberosPrincipal}
* or {@link org.ietf.jgss.GSSName GSSName} without providing a Kerberos
* realm, as long as the permission's service principal is in this realm.
* <p>
* The possible actions are:
*
* <pre>
* initiate - allow the caller to use the credential to
* initiate a security context with a service
* principal.
*
* accept - allow the caller to use the credential to
* accept security context as a particular
* principal.
* </pre>
*
* For example, to specify the permission to access to the TGT to
* initiate a security context the permission is constructed as follows:
*
* <pre>
* ServicePermission("krbtgt/EXAMPLE.COM@EXAMPLE.COM", "initiate");
* </pre>
* <p>
* To obtain a service ticket to initiate a context with the "host"
* service the permission is constructed as follows:
* <pre>
* ServicePermission("host/foo.example.com@EXAMPLE.COM", "initiate");
* </pre>
* <p>
* For a Kerberized server the action is "accept". For example, the permission
* necessary to access and use the secret key of the Kerberized "host"
* service (telnet and the likes) would be constructed as follows:
*
* <pre>
* ServicePermission("host/foo.example.com@EXAMPLE.COM", "accept");
* </pre>
*
* @since 1.4
*/
public final class ServicePermission extends Permission
implements java.io.Serializable {
private static final long serialVersionUID = -1227585031618624935L;
/**
* Initiate a security context to the specified service
*/
private final static int INITIATE = 0x1;
/**
* Accept a security context
*/
private final static int ACCEPT = 0x2;
/**
* All actions
*/
private final static int ALL = INITIATE|ACCEPT;
/**
* No actions.
*/
private final static int NONE = 0x0;
// the actions mask
private transient int mask;
/**
* the actions string.
*
* @serial
*/
private String actions; // Left null as long as possible, then
// created and re-used in the getAction function.
/**
* Create a new {@code ServicePermission}
* with the specified {@code servicePrincipal}
* and {@code action}.
*
* @param servicePrincipal the name of the service principal.
* An asterisk may appear by itself, to signify any service principal.
*
* @param action the action string
*/
public ServicePermission(String servicePrincipal, String action) {
// Note: servicePrincipal can be "@REALM" which means any principal in
// this realm implies it. action can be "-" which means any
// action implies it.
super(servicePrincipal);
init(servicePrincipal, getMask(action));
}
/**
* Creates a ServicePermission object with the specified servicePrincipal
* and a pre-calculated mask. Avoids the overhead of re-computing the mask.
* Called by ServicePermissionCollection.
*/
ServicePermission(String servicePrincipal, int mask) {
super(servicePrincipal);
init(servicePrincipal, mask);
}
/**
* Initialize the ServicePermission object.
*/
private void init(String servicePrincipal, int mask) {
if (servicePrincipal == null)
throw new NullPointerException("service principal can't be null");
if ((mask & ALL) != mask)
throw new IllegalArgumentException("invalid actions mask");
this.mask = mask;
}
/**
* Checks if this Kerberos service permission object "implies" the
* specified permission.
* <P>
* More specifically, this method returns true if all of the following
* are true (and returns false if any of them are not):
* <ul>
* <li> <i>p</i> is an instanceof {@code ServicePermission},
* <li> <i>p</i>'s actions are a proper subset of this
* {@code ServicePermission}'s actions,
* <li> <i>p</i>'s name is equal to this {@code ServicePermission}'s name
* or this {@code ServicePermission}'s name is "*".
* </ul>
*
* @param p the permission to check against.
*
* @return true if the specified permission is implied by this object,
* false if not.
*/
@Override
public boolean implies(Permission p) {
if (!(p instanceof ServicePermission))
return false;
ServicePermission that = (ServicePermission) p;
return ((this.mask & that.mask) == that.mask) &&
impliesIgnoreMask(that);
}
boolean impliesIgnoreMask(ServicePermission p) {
if ((this.getName().equals("*")) ||
this.getName().equals(p.getName()) ||
(p.getName().startsWith("@") &&
this.getName().endsWith(p.getName())))
return true;
/*
* Empty realm in this or p is a wild-card. This is needed to support
* non-Kerberos ServicePermissions for GSS (a band-aid until we can
* implement a proper GssAcceptorPermission class), but also because
* users may not know and might not care what realm the service is in,
* especially when they are using a keytab.
*
* If the user is using a password, then the realm matters more. An
* untrusted actor could cause KDCs for a realm they control to see
* material they could attack offline, but that was already the case
* anyways, and the answer is the same in all cases: use stronger
* passwords, use randomized keys in a keytab, or let us implement
* SPAKE or similar alternatives to the venerable PA-ENC-TIMESTAMP.
*/
if ((this.getName().equals("krbtgt/@") &&
p.getName().startsWith("krbtgt/")) ||
(p.getName().equals("krbtgt/@") &&
this.getName().startsWith("krbtgt/")))
return true;
char[] n = this.getName().toCharArray();
int i;
for (i = 0; i < n.length; i++) {
if (n[i] == '\\') {
i++;
continue;
}
if (n[i] == '@') {
String s = new String(n, 0, i + 1);
return (p.getName().startsWith(s) &&
(p.getName().equals(s) || this.getName().equals(s)));
}
}
// No realm, not even empty -> fail
return false;
}
/**
* Checks two ServicePermission objects for equality.
*
* @param obj the object to test for equality with this object.
*
* @return true if {@code obj} is a ServicePermission, and has the
* same service principal, and actions as this
* ServicePermission object.
*/
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (! (obj instanceof ServicePermission))
return false;
ServicePermission that = (ServicePermission) obj;
return ((this.mask & that.mask) == that.mask) &&
this.getName().equals(that.getName());
}
/**
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
return (getName().hashCode() ^ mask);
}
/**
* Returns the "canonical string representation" of the actions in the
* specified mask.
* Always returns present actions in the following order:
* initiate, accept.
*
* @param mask a specific integer action mask to translate into a string
* @return the canonical string representation of the actions
*/
static String getActions(int mask)
{
StringBuilder sb = new StringBuilder();
boolean comma = false;
if ((mask & INITIATE) == INITIATE) {
if (comma) sb.append(',');
else comma = true;
sb.append("initiate");
}
if ((mask & ACCEPT) == ACCEPT) {
if (comma) sb.append(',');
else comma = true;
sb.append("accept");
}
return sb.toString();
}
/**
* Returns the canonical string representation of the actions.
* Always returns present actions in the following order:
* initiate, accept.
*/
@Override
public String getActions() {
if (actions == null)
actions = getActions(this.mask);
return actions;
}
/**
* Returns a PermissionCollection object for storing
* ServicePermission objects.
* <br>
* ServicePermission objects must be stored in a manner that
* allows them to be inserted into the collection in any order, but
* that also enables the PermissionCollection implies method to
* be implemented in an efficient (and consistent) manner.
*
* @return a new PermissionCollection object suitable for storing
* ServicePermissions.
*/
@Override
public PermissionCollection newPermissionCollection() {
return new KrbServicePermissionCollection();
}
/**
* Return the current action mask.
*
* @return the actions mask.
*/
int getMask() {
return mask;
}
/**
* Convert an action string to an integer actions mask.
*
* Note: if action is "-", action will be NONE, which means any
* action implies it.
*
* @param action the action string.
* @return the action mask
*/
private static int getMask(String action) {
if (action == null) {
throw new NullPointerException("action can't be null");
}
if (action.equals("")) {
throw new IllegalArgumentException("action can't be empty");
}
int mask = NONE;
char[] a = action.toCharArray();
if (a.length == 1 && a[0] == '-') {
return mask;
}
int i = a.length - 1;
while (i != -1) {
char c;
// skip whitespace
while ((i!=-1) && ((c = a[i]) == ' ' ||
c == '\r' ||
c == '\n' ||
c == '\f' ||
c == '\t'))
i--;
// check for the known strings
int matchlen;
if (i >= 7 && (a[i-7] == 'i' || a[i-7] == 'I') &&
(a[i-6] == 'n' || a[i-6] == 'N') &&
(a[i-5] == 'i' || a[i-5] == 'I') &&
(a[i-4] == 't' || a[i-4] == 'T') &&
(a[i-3] == 'i' || a[i-3] == 'I') &&
(a[i-2] == 'a' || a[i-2] == 'A') &&
(a[i-1] == 't' || a[i-1] == 'T') &&
(a[i] == 'e' || a[i] == 'E'))
{
matchlen = 8;
mask |= INITIATE;
} else if (i >= 5 && (a[i-5] == 'a' || a[i-5] == 'A') &&
(a[i-4] == 'c' || a[i-4] == 'C') &&
(a[i-3] == 'c' || a[i-3] == 'C') &&
(a[i-2] == 'e' || a[i-2] == 'E') &&
(a[i-1] == 'p' || a[i-1] == 'P') &&
(a[i] == 't' || a[i] == 'T'))
{
matchlen = 6;
mask |= ACCEPT;
} else {
// parse error
throw new IllegalArgumentException(
"invalid permission: " + action);
}
// make sure we didn't just match the tail of a word
// like "ackbarfaccept". Also, skip to the comma.
boolean seencomma = false;
while (i >= matchlen && !seencomma) {
switch(a[i-matchlen]) {
case ',':
seencomma = true;
break;
case ' ': case '\r': case '\n':
case '\f': case '\t':
break;
default:
throw new IllegalArgumentException(
"invalid permission: " + action);
}
i--;
}
// point i at the location of the comma minus one (or -1).
i -= matchlen;
}
return mask;
}
/**
* WriteObject is called to save the state of the ServicePermission
* to a stream. The actions are serialized, and the superclass
* takes care of the name.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the actions. The superclass takes care of the name
// call getActions to make sure actions field is initialized
if (actions == null)
getActions();
s.defaultWriteObject();
}
/**
* readObject is called to restore the state of the
* ServicePermission from a stream.
*/
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the action, then initialize the rest
s.defaultReadObject();
init(getName(),getMask(actions));
}
/*
public static void main(String[] args) throws Exception {
ServicePermission this_ =
new ServicePermission(args[0], "accept");
ServicePermission that_ =
new ServicePermission(args[1], "accept,initiate");
System.out.println("-----\n");
System.out.println("this.implies(that) = " + this_.implies(that_));
System.out.println("-----\n");
System.out.println("this = "+this_);
System.out.println("-----\n");
System.out.println("that = "+that_);
System.out.println("-----\n");
KrbServicePermissionCollection nps =
new KrbServicePermissionCollection();
nps.add(this_);
nps.add(new ServicePermission("nfs/example.com@EXAMPLE.COM",
"accept"));
nps.add(new ServicePermission("host/example.com@EXAMPLE.COM",
"initiate"));
System.out.println("nps.implies(that) = " + nps.implies(that_));
System.out.println("-----\n");
Enumeration e = nps.elements();
while (e.hasMoreElements()) {
ServicePermission x =
(ServicePermission) e.nextElement();
System.out.println("nps.e = " + x);
}
}
*/
}
final class KrbServicePermissionCollection extends PermissionCollection
implements java.io.Serializable {
// Key is the service principal, value is the ServicePermission.
// Not serialized; see serialization section at end of class
private transient ConcurrentHashMap<String, Permission> perms;
public KrbServicePermissionCollection() {
perms = new ConcurrentHashMap<>();
}
/**
* Check and see if this collection of permissions implies the permissions
* expressed in "permission".
*
* @param permission the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the collection, false if not.
*/
@Override
public boolean implies(Permission permission) {
if (! (permission instanceof ServicePermission))
return false;
ServicePermission np = (ServicePermission) permission;
int desired = np.getMask();
if (desired == 0) {
for (Permission p: perms.values()) {
ServicePermission sp = (ServicePermission)p;
if (sp.impliesIgnoreMask(np)) {
return true;
}
}
return false;
}
// first, check for wildcard principal
ServicePermission x = (ServicePermission)perms.get("*");
if (x != null) {
if ((x.getMask() & desired) == desired) {
return true;
}
}
// otherwise, check for match on principal
x = (ServicePermission)perms.get(np.getName());
if (x != null) {
//System.out.println(" trying "+x);
if ((x.getMask() & desired) == desired) {
return true;
}
}
return false;
}
/**
* Adds a permission to the ServicePermissions. The key for
* the hash is the name.
*
* @param permission the Permission object to add.
*
* @exception IllegalArgumentException - if the permission is not a
* ServicePermission
*
* @exception SecurityException - if this PermissionCollection object
* has been marked readonly
*/
@Override
public void add(Permission permission) {
if (! (permission instanceof ServicePermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
if (isReadOnly())
throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
ServicePermission sp = (ServicePermission)permission;
String princName = sp.getName();
// Add permission to map if it is absent, or replace with new
// permission if applicable. NOTE: cannot use lambda for
// remappingFunction parameter until JDK-8076596 is fixed.
perms.merge(princName, sp,
new java.util.function.BiFunction<>() {
@Override
public Permission apply(Permission existingVal,
Permission newVal) {
int oldMask = ((ServicePermission)existingVal).getMask();
int newMask = ((ServicePermission)newVal).getMask();
if (oldMask != newMask) {
int effective = oldMask | newMask;
if (effective == newMask) {
return newVal;
}
if (effective != oldMask) {
return new ServicePermission(princName, effective);
}
}
return existingVal;
}
}
);
}
/**
* Returns an enumeration of all the ServicePermission objects
* in the container.
*
* @return an enumeration of all the ServicePermission objects.
*/
@Override
public Enumeration<Permission> elements() {
return perms.elements();
}
private static final long serialVersionUID = -4118834211490102011L;
// Need to maintain serialization interoperability with earlier releases,
// which had the serializable field:
// private Vector permissions;
/**
* @serialField permissions java.util.Vector
* A list of ServicePermission objects.
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("permissions", Vector.class),
};
/**
* @serialData "permissions" field (a Vector containing the ServicePermissions).
*/
/*
* Writes the contents of the perms field out as a Vector for
* serialization compatibility with earlier releases.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
// Don't call out.defaultWriteObject()
// Write out Vector
Vector<Permission> permissions = new Vector<>(perms.values());
ObjectOutputStream.PutField pfields = out.putFields();
pfields.put("permissions", permissions);
out.writeFields();
}
/*
* Reads in a Vector of ServicePermissions and saves them in the perms field.
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Don't call defaultReadObject()
// Read in serialized fields
ObjectInputStream.GetField gfields = in.readFields();
// Get the one we want
Vector<Permission> permissions =
(Vector<Permission>)gfields.get("permissions", null);
perms = new ConcurrentHashMap<>(permissions.size());
for (Permission perm : permissions) {
perms.put(perm.getName(), perm);
}
}
}