Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/lang/SecurityManager/CheckPackageMatching.java
41149 views
1
/*
2
* Copyright (c) 2015, 2017, 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
/*
25
* @test
26
* @bug 8072692
27
* @summary Check the matching implemented by SecurityManager.checkPackageAccess
28
* @run main/othervm -Djava.security.manager=allow CheckPackageMatching
29
*/
30
31
import java.security.Security;
32
import java.util.ArrayList;
33
import java.util.Arrays;
34
import java.util.Collection;
35
import java.util.Collections;
36
import java.util.List;
37
import java.util.StringTokenizer;
38
39
/*
40
* The purpose of this test is not to verify the content of the package
41
* access list - but to ensure that the matching implemented by the
42
* SecurityManager is correct. This is why we have our own pattern matching
43
* algorithm here.
44
*/
45
public class CheckPackageMatching {
46
47
/**
48
* The restricted packages listed in the package.access property of the
49
* java.security file.
50
*/
51
private static final String[] packages = actual().toArray(new String[0]);
52
53
/**
54
* Returns the list of restricted packages in the package.access property.
55
*/
56
private static List<String> actual() {
57
String prop = Security.getProperty("package.access");
58
List<String> packages = new ArrayList<>();
59
if (prop != null && !prop.equals("")) {
60
StringTokenizer tok = new StringTokenizer(prop, ",");
61
while (tok.hasMoreElements()) {
62
String s = tok.nextToken().trim();
63
packages.add(s);
64
}
65
}
66
return packages;
67
}
68
69
/**
70
* PackageMatcher implements a state machine that matches package
71
* names against packages parsed from the package access list.
72
*/
73
private abstract static class PackageMatcher {
74
// For each state, chars[state] contains the chars that matches.
75
private final char[][] chars;
76
// For each state, states[state][i] contains the next state to go
77
// to when chars[state][i] matches the current character.
78
private final int[][] states;
79
80
// Some markers. We're making the assumption that 0
81
// cannot be a valid character for a package name.
82
//
83
// We use 0 for marking that we expect an end of string in
84
// char[state][i].
85
private static final char END_OF_STRING = 0;
86
// This special state value indicates that we expect the string to end
87
// there.
88
private static final int END_STATE = -1;
89
// This special state value indicates that we can accept any character
90
// from now on.
91
private static final int WILDCARD_STATE = Integer.MIN_VALUE;
92
93
// Create the data for a new state machine to match package names from
94
// the array of package names passed as argument.
95
// Each package name in the array is expected to end with '.'
96
// For each package in packages we're going to compile state data
97
// that will match the regexp:
98
// ^packages[i].substring(0, packages[i].length()-1).replace(".","\\.")$|^packages[i].replace(".","\\.").*
99
//
100
// Let's say the package array is:
101
//
102
// String[] packages = { "sun.", "com.sun.jmx.", "com.sun.proxy.",
103
// "apple." };
104
//
105
// then the state machine will need data that looks like:
106
//
107
// char[][] chars = {
108
// { 'a', 'c', 's' }, { 'p' }, { 'p' }, { 'l' }, { 'e' }, { 0, '.' },
109
// { 'o' }, { 'm' }, { '.' }, { 's' }, { 'u' }, { 'n' }, { '.' },
110
// { 'j', 'p'},
111
// { 'm' }, { 'x' }, { 0, '.' },
112
// { 'r' }, { 'o' }, { 'x' }, { 'y' }, { 0, '.' },
113
// { 'u' }, { 'n' }, { 0, '.' }
114
// }
115
// int[][] states = {
116
// { 1, 6, 22 }, { 2 }, { 3 }, { 4 }, { 5 },
117
// { END_STATE, WILDCARD_STATE },
118
// { 7 }, { 8 }, { 9 }, { 10 }, { 11 }, { 12 }, { 13 }, { 14, 17 },
119
// { 15 }, { 16 }, { END_STATE, WILDCARD_STATE },
120
// { 18 }, { 19 }, { 20 }, { 21 }, { END_STATE, WILDCARD_STATE },
121
// { 23 }, { 24 }, { END_STATE, WILDCARD_STATE }
122
// }
123
//
124
// The machine will start by loading the chars and states for state 0
125
// chars[0] => { 'a', 'c', 's' } states[0] => { 1, 6, 22 }
126
// then it examines the char at index 0 in the candidate name.
127
// if the char matches one of the characters in chars[0], then it goes
128
// to the corresponding state in states[0]. For instance - if the first
129
// char in the candidate name is 's', which corresponds to chars[0][2] -
130
// then it will proceed with the next char in the candidate name and go
131
// to state 22 (as indicated by states[0][2]) - where it will load the
132
// chars and states for states 22: chars[22] = { 'u' },
133
// states[22] = { 23 } etc... until the candidate char at the current
134
// index matches no char in chars[states] => the candidate name doesn't
135
// match - or until it finds a success termination condition: the
136
// candidate chars are exhausted and states[state][0] is END_STATE, or
137
// the candidate chars are not exhausted - and
138
// states[state][chars[state]] is WILDCARD_STATE indicating a '.*' like
139
// regexp.
140
//
141
// [Note that the chars in chars[i] are sorted]
142
//
143
// The compile(...) method is reponsible for building the state machine
144
// data and is called only once in the constructor.
145
//
146
// The matches(String candidate) method will tell whether the candidate
147
// matches by implementing the algorithm described above.
148
//
149
PackageMatcher(String[] packages) {
150
final boolean[] selected = new boolean[packages.length];
151
Arrays.fill(selected, true);
152
final ArrayList<char[]> charList = new ArrayList<>();
153
final ArrayList<int[]> stateList = new ArrayList<>();
154
compile(0, 0, packages, selected, charList, stateList);
155
chars = charList.toArray(new char[0][0]);
156
states = stateList.toArray(new int[0][0]);
157
}
158
159
/**
160
* Compiles the state machine data (recursive).
161
*
162
* @param step The index of the character which we're looking at in
163
* this step.
164
* @param state The current state (starts at 0).
165
* @param pkgs The list of packages from which the automaton is built.
166
* @param selected Indicates which packages we're looking at in this
167
step.
168
* @param charList The list from which we will build
169
{@code char[][] chars;}
170
* @param stateList The list from which we will build
171
{@code int[][] states;}
172
* @return the next available state.
173
*/
174
private int compile(int step, int state, String[] pkgs,
175
boolean[] selected, ArrayList<char[]> charList,
176
ArrayList<int[]> stateList) {
177
final char[] next = new char[pkgs.length];
178
final int[] nexti = new int[pkgs.length];
179
int j = 0;
180
char min = Character.MAX_VALUE; char max = 0;
181
for (int i = 0; i < pkgs.length; i++) {
182
if (!selected[i]) continue;
183
final String p = pkgs[i];
184
final int len = p.length();
185
if (step > len) {
186
selected[i] = false;
187
continue;
188
}
189
if (len - 1 == step) {
190
boolean unknown = true;
191
for (int k = 0; k < j ; k++) {
192
if (next[k] == END_OF_STRING) {
193
unknown = false;
194
break;
195
}
196
}
197
if (unknown) {
198
next[j] = END_OF_STRING;
199
j++;
200
}
201
nexti[i] = END_STATE;
202
}
203
final char c = p.charAt(step);
204
nexti[i] = len - 1 == step ? END_STATE : c;
205
boolean unknown = j == 0 || c < min || c > max;
206
if (!unknown) {
207
if (c != min || c != max) {
208
unknown = true;
209
for (int k = 0; k < j ; k++) {
210
if (next[k] == c) {
211
unknown = false;
212
break;
213
}
214
}
215
}
216
}
217
if (unknown) {
218
min = min > c ? c : min;
219
max = max < c ? c : max;
220
next[j] = c;
221
j++;
222
}
223
}
224
final char[] nc = new char[j];
225
final int[] nst = new int[j];
226
System.arraycopy(next, 0, nc, 0, nc.length);
227
Arrays.sort(nc);
228
final boolean ns[] = new boolean[pkgs.length];
229
230
charList.ensureCapacity(state + 1);
231
stateList.ensureCapacity(state + 1);
232
charList.add(state, nc);
233
stateList.add(state, nst);
234
state = state + 1;
235
for (int k = 0; k < nc.length; k++) {
236
int selectedCount = 0;
237
boolean endStateFound = false;
238
boolean wildcardFound = false;
239
for (int l = 0; l < nexti.length; l++) {
240
if (!(ns[l] = selected[l])) {
241
continue;
242
}
243
ns[l] = nexti[l] == nc[k] || nexti[l] == END_STATE
244
&& nc[k] == '.';
245
endStateFound = endStateFound || nc[k] == END_OF_STRING
246
&& nexti[l] == END_STATE;
247
wildcardFound = wildcardFound || nc[k] == '.'
248
&& nexti[l] == END_STATE;
249
if (ns[l]) {
250
selectedCount++;
251
}
252
}
253
nst[k] = (endStateFound ? END_STATE
254
: wildcardFound ? WILDCARD_STATE : state);
255
if (selectedCount == 0 || wildcardFound) {
256
continue;
257
}
258
state = compile(step + 1, state, pkgs, ns, charList, stateList);
259
}
260
return state;
261
}
262
263
/**
264
* Matches 'pkg' against the list of package names compiled in the
265
* state machine data.
266
*
267
* @param pkg The package name to match. Must not end with '.'.
268
* @return true if the package name matches, false otherwise.
269
*/
270
public boolean matches(String pkg) {
271
int state = 0;
272
int i;
273
final int len = pkg.length();
274
next: for (i = 0; i <= len; i++) {
275
if (state == WILDCARD_STATE) {
276
return true; // all characters will match.
277
}
278
if (state == END_STATE) {
279
return i == len;
280
}
281
final char[] ch = chars[state];
282
final int[] st = states[state];
283
if (i == len) {
284
// matches only if we have exhausted the string.
285
return st[0] == END_STATE;
286
}
287
if (st[0] == END_STATE && st.length == 1) {
288
// matches only if we have exhausted the string.
289
return i == len;
290
}
291
final char c = pkg.charAt(i); // look at next char...
292
for (int j = st[0] == END_STATE ? 1 : 0; j < ch.length; j++) {
293
final char n = ch[j];
294
if (c == n) { // found a match
295
state = st[j]; // get the next state.
296
continue next; // go to next state
297
} else if (c < n) {
298
break; // chars are sorted. we won't find it. no match.
299
}
300
}
301
break; // no match
302
}
303
return false;
304
}
305
}
306
307
private static final class TestPackageMatcher extends PackageMatcher {
308
private final List<String> list;
309
310
TestPackageMatcher(String[] packages) {
311
super(packages);
312
this.list = Collections.unmodifiableList(Arrays.asList(packages));
313
}
314
315
@Override
316
public boolean matches(String pkg) {
317
final boolean match1 = super.matches(pkg);
318
boolean match2 = false;
319
String p2 = pkg + ".";
320
for (String p : list) {
321
if (pkg.startsWith(p) || p2.equals(p)) {
322
match2 = true;
323
break;
324
}
325
}
326
if (match1 != match2) {
327
System.err.println("Test Bug: PackageMatcher.matches(\"" +
328
pkg + "\") returned " + match1);
329
System.err.println("Package Access List is: " + list);
330
throw new Error("Test Bug: PackageMatcher.matches(\"" +
331
pkg + "\") returned " + match1);
332
}
333
return match1;
334
}
335
}
336
337
private static void smokeTest() {
338
// these checks should pass.
339
System.getSecurityManager().checkPackageAccess("com.sun.blah");
340
System.getSecurityManager().checkPackageAccess("com.sun.jm");
341
System.getSecurityManager().checkPackageAccess("com.sun.jmxa");
342
System.getSecurityManager().checkPackageAccess("jmx");
343
List<String> actual = Arrays.asList(packages);
344
if (!actual.contains("sun.misc.")) {
345
throw new Error("package.access does not contain 'sun.misc.'");
346
}
347
}
348
349
// This is a sanity test for our own test code.
350
private static void testTheTest(String[] pkgs, char[][] chars,
351
int[][] states) {
352
353
PackageMatcher m = new TestPackageMatcher(pkgs);
354
String unexpected = "";
355
if (!Arrays.deepEquals(chars, m.chars)) {
356
System.err.println("Char arrays differ");
357
if (chars.length != m.chars.length) {
358
System.err.println("Char array lengths differ: expected="
359
+ chars.length + " actual=" + m.chars.length);
360
}
361
System.err.println(Arrays.deepToString(m.chars).replace((char)0,
362
'0'));
363
unexpected = "chars[]";
364
}
365
if (!Arrays.deepEquals(states, m.states)) {
366
System.err.println("State arrays differ");
367
if (states.length != m.states.length) {
368
System.err.println("Char array lengths differ: expected="
369
+ states.length + " actual=" + m.states.length);
370
}
371
System.err.println(Arrays.deepToString(m.states));
372
if (unexpected.length() > 0) {
373
unexpected = unexpected + " and ";
374
}
375
unexpected = unexpected + "states[]";
376
}
377
378
if (unexpected.length() > 0) {
379
throw new Error("Unexpected "+unexpected+" in PackageMatcher");
380
}
381
382
testMatches(m, pkgs);
383
}
384
385
// This is a sanity test for our own test code.
386
private static void testTheTest() {
387
final String[] packages2 = { "sun.", "com.sun.jmx.",
388
"com.sun.proxy.", "apple." };
389
390
final int END_STATE = PackageMatcher.END_STATE;
391
final int WILDCARD_STATE = PackageMatcher.WILDCARD_STATE;
392
393
final char[][] chars2 = {
394
{ 'a', 'c', 's' }, { 'p' }, { 'p' }, { 'l' }, { 'e' }, { 0, '.' },
395
{ 'o' }, { 'm' }, { '.' }, { 's' }, { 'u' }, { 'n' }, { '.' },
396
{ 'j', 'p'},
397
{ 'm' }, { 'x' }, { 0, '.' },
398
{ 'r' }, { 'o' }, { 'x' }, { 'y' }, { 0, '.' },
399
{ 'u' }, { 'n' }, { 0, '.' }
400
};
401
402
final int[][] states2 = {
403
{ 1, 6, 22 }, { 2 }, { 3 }, { 4 }, { 5 },
404
{ END_STATE, WILDCARD_STATE },
405
{ 7 }, { 8 }, { 9 }, { 10 }, { 11 }, { 12 }, { 13 }, { 14, 17 },
406
{ 15 }, { 16 }, { END_STATE, WILDCARD_STATE },
407
{ 18 }, { 19 }, { 20 }, { 21 }, { END_STATE, WILDCARD_STATE },
408
{ 23 }, { 24 }, { END_STATE, WILDCARD_STATE }
409
};
410
411
testTheTest(packages2, chars2, states2);
412
413
final String[] packages3 = { "sun.", "com.sun.pro.",
414
"com.sun.proxy.", "apple." };
415
416
final char[][] chars3 = {
417
{ 'a', 'c', 's' }, { 'p' }, { 'p' }, { 'l' }, { 'e' }, { 0, '.' },
418
{ 'o' }, { 'm' }, { '.' }, { 's' }, { 'u' }, { 'n' }, { '.' },
419
{ 'p' }, { 'r' }, { 'o' }, { 0, '.', 'x' },
420
{ 'y' }, { 0, '.' },
421
{ 'u' }, { 'n' }, { 0, '.' }
422
};
423
424
final int[][] states3 = {
425
{ 1, 6, 19 }, { 2 }, { 3 }, { 4 }, { 5 },
426
{ END_STATE, WILDCARD_STATE },
427
{ 7 }, { 8 }, { 9 }, { 10 }, { 11 }, { 12 }, { 13 }, { 14 },
428
{ 15 }, { 16 }, { END_STATE, WILDCARD_STATE, 17 },
429
{ 18 }, { END_STATE, WILDCARD_STATE },
430
{ 20 }, { 21 }, { END_STATE, WILDCARD_STATE }
431
};
432
433
testTheTest(packages3, chars3, states3);
434
}
435
436
private static volatile boolean sanityTesting = false;
437
438
public static void main(String[] args) {
439
System.setSecurityManager(new SecurityManager());
440
441
// Some smoke tests.
442
smokeTest();
443
System.out.println("Smoke tests passed.");
444
445
// Test our own pattern matching algorithm. Here we actually test
446
// the PackageMatcher class from our own test code.
447
sanityTesting = true;
448
try {
449
testTheTest();
450
System.out.println("Sanity tests passed.");
451
} finally {
452
sanityTesting = false;
453
}
454
455
// Now test the package matching in the security manager.
456
PackageMatcher matcher = new TestPackageMatcher(packages);
457
458
// These should not match.
459
for (String pkg : new String[] {"gloups.machin", "su",
460
"org.jcp.xml.dsig.inter",
461
"com.sun.jm", "com.sun.jmxa"}) {
462
testMatch(matcher, pkg, false, true);
463
}
464
465
// These should match.
466
for (String pkg : Arrays.asList(
467
new String[] {"sun.misc.gloups.machin", "sun.misc",
468
"sun.reflect"})) {
469
testMatch(matcher, pkg, true, true);
470
}
471
472
// Derive a list of packages that should match or not match from
473
// the list in 'packages' - and check that the security manager
474
// throws the appropriate exception.
475
testMatches(matcher, packages);
476
}
477
478
private static void testMatches(PackageMatcher matcher, String[] pkgs) {
479
Collection<String> pkglist = Arrays.asList(pkgs);
480
PackageMatcher ref = new TestPackageMatcher(packages);
481
482
for (String pkg : pkgs) {
483
String candidate = pkg + "toto";
484
boolean expected = true;
485
testMatch(matcher, candidate, expected,
486
ref.matches(candidate) == expected);
487
}
488
489
for (String pkg : pkgs) {
490
String candidate = pkg.substring(0, pkg.length() - 1);
491
boolean expected = pkglist.contains(candidate + ".");
492
testMatch(matcher, candidate, expected,
493
ref.matches(candidate) == expected);
494
}
495
496
for (String pkg : pkgs) {
497
String candidate = pkg.substring(0, pkg.length() - 2);
498
boolean expected = pkglist.contains(candidate + ".");
499
testMatch(matcher, candidate, expected,
500
ref.matches(candidate) == expected);
501
}
502
}
503
504
private static void testMatch(PackageMatcher matcher, String candidate,
505
boolean expected, boolean testSecurityManager)
506
{
507
final boolean m = matcher.matches(candidate);
508
if (m != expected) {
509
final String msg = "\"" + candidate + "\": " +
510
(m ? "matches" : "does not match");
511
throw new Error("PackageMatcher does not give expected results: "
512
+ msg);
513
}
514
515
if (sanityTesting) {
516
testSecurityManager = false;
517
}
518
519
if (testSecurityManager) {
520
System.out.println("Access to " + candidate + " should be " +
521
(expected ? "rejected" : "granted"));
522
final String errormsg = "\"" + candidate + "\" : " +
523
(expected ? "granted" : "not granted");
524
try {
525
System.getSecurityManager().checkPackageAccess(candidate);
526
if (expected) {
527
System.err.println(errormsg);
528
throw new Error("Expected exception not thrown: " +
529
errormsg);
530
}
531
} catch (SecurityException x) {
532
if (!expected) {
533
System.err.println(errormsg);
534
throw new Error(errormsg + " - unexpected exception: " +
535
x, x);
536
} else {
537
System.out.println("Got expected exception: " + x);
538
}
539
}
540
}
541
}
542
}
543
544