-
Notifications
You must be signed in to change notification settings - Fork 8
/
DefaultPrincipalMapper.java
450 lines (360 loc) · 19.4 KB
/
DefaultPrincipalMapper.java
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
/*
* Copyright (c) 2023 Contributors to Eclipse Foundation.
* Copyright (c) 2019 OmniFaces. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.exousia.mapping;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.list;
import jakarta.security.jacc.PrincipalMapper;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.security.auth.Subject;
/**
* TODO: much or all of this should be removed and/or refactored.
* The servers supported here via reflection don't support this version of authorization
* at all, and have no need to be longer supported here.
*
* @author Arjan Tijms
*/
public class DefaultPrincipalMapper implements PrincipalMapper {
private static Object geronimoPolicyConfigurationFactoryInstance;
private static ConcurrentMap<String, Map<Principal, Set<String>>> geronimoContextToRoleMapping;
private Map<String, List<String>> groupToRoles = new HashMap<>();
private boolean oneToOneMapping;
private boolean anyAuthenticatedUserRoleMapped = false;
@Override
public Principal getCallerPrincipal(Subject subject) {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<String> getMappedRoles(Subject subject) {
return new HashSet<>(getMappedRoles(subject.getPrincipals(), subject));
}
public static void onFactoryCreated() {
tryInitGeronimo();
}
private static void tryInitGeronimo() {
try {
// Geronimo 3.0.1 contains a protection mechanism to ensure only a Geronimo policy provider is installed.
// This protection can be beat by creating an instance of GeronimoPolicyConfigurationFactory once. This instance
// will statically register itself with an internal Geronimo class
geronimoPolicyConfigurationFactoryInstance =
Class.forName("org.apache.geronimo.security.jacc.mappingprovider.GeronimoPolicyConfigurationFactory").getDeclaredConstructor().newInstance();
geronimoContextToRoleMapping = new ConcurrentHashMap<>();
} catch (Exception e) {
// ignore
}
}
public static void onPolicyConfigurationCreated(final String contextID) {
// Are we dealing with Geronimo?
if (geronimoPolicyConfigurationFactoryInstance != null) {
// PrincipalRoleConfiguration
try {
Class<?> geronimoPolicyConfigurationClass = Class.forName("org.apache.geronimo.security.jacc.mappingprovider.GeronimoPolicyConfiguration");
Object geronimoPolicyConfigurationProxy = Proxy.newProxyInstance(DefaultPrincipalMapper.class.getClassLoader(), new Class[] {geronimoPolicyConfigurationClass}, new InvocationHandler() {
@SuppressWarnings("unchecked")
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Take special action on the following method:
// void setPrincipalRoleMapping(Map<Principal, Set<String>> principalRoleMap) throws PolicyContextException;
if (method.getName().equals("setPrincipalRoleMapping")) {
geronimoContextToRoleMapping.put(contextID, (Map<Principal, Set<String>>) args[0]);
}
return null;
}
});
// Set the proxy on the GeronimoPolicyConfigurationFactory so it will call us back later with the role mapping via the following method:
// public void setPolicyConfiguration(String contextID, GeronimoPolicyConfiguration configuration) {
Class.forName("org.apache.geronimo.security.jacc.mappingprovider.GeronimoPolicyConfigurationFactory")
.getMethod("setPolicyConfiguration", String.class, geronimoPolicyConfigurationClass)
.invoke(geronimoPolicyConfigurationFactoryInstance, contextID, geronimoPolicyConfigurationProxy);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// Ignore
}
}
}
public DefaultPrincipalMapper(String contextID, Collection<String> allDeclaredRoles) {
// Initialize the groupToRoles map
// Try to get a hold of the proprietary role mapper of each known
// AS. Sad that this is needed :(
if (tryGlassFish(contextID, allDeclaredRoles)) {
return;
} else if (tryWebLogic(contextID, allDeclaredRoles)) {
return;
} else if (tryGeronimo(contextID, allDeclaredRoles)) {
return;
} else {
oneToOneMapping = true;
}
}
public List<String> getMappedRoles(Principal[] principals, Subject subject) {
return getMappedRoles(asList(principals), subject);
}
@Override
public boolean isAnyAuthenticatedUserRoleMapped() {
return anyAuthenticatedUserRoleMapped;
}
/**
* Tries to get the roles from the principals list and only if it fails,
* falls back to looking at the Subject.
*
* Liberty is the only known server that falls back.
*
* @param principals the primary entities to look in for roles
* @param subject the fall back to use if looking at principals fails
* @return a list of mapped roles
*/
public List<String> getMappedRoles(Iterable<Principal> principals, Subject subject) {
// Extract the list of groups from the principals. These principals typically contain
// different kind of principals, some groups, some others. The groups are unfortunately vendor
// specific.
List<String> groups = getGroups(principals, subject);
// Map the groups to roles. E.g. map "admin" to "administrator". Some servers require this.
return mapGroupsToRoles(groups);
}
private List<String> mapGroupsToRoles(List<String> groups) {
if (oneToOneMapping) {
// There is no mapping used, groups directly represent roles.
return groups;
}
List<String> roles = new ArrayList<>();
for (String group : groups) {
if (groupToRoles.containsKey(group)) {
roles.addAll(groupToRoles.get(group));
} else {
// Default to 1:1 mapping when group is not explicitly mapped
roles.add(group);
}
}
return roles;
}
private boolean tryGlassFish(String contextID, Collection<String> allDeclaredRoles) {
try {
Class<?> SecurityRoleMapperFactoryClass = Class.forName("org.glassfish.deployment.common.SecurityRoleMapperFactory");
Object factoryInstance = Class.forName("org.glassfish.internal.api.Globals")
.getMethod("get", SecurityRoleMapperFactoryClass.getClass())
.invoke(null, SecurityRoleMapperFactoryClass);
Object securityRoleMapperInstance = SecurityRoleMapperFactoryClass.getMethod("getRoleMapper", String.class)
.invoke(factoryInstance, contextID);
@SuppressWarnings("unchecked")
Map<String, Subject> roleToSubjectMap = (Map<String, Subject>) Class.forName("org.glassfish.deployment.common.SecurityRoleMapper")
.getMethod("getRoleToSubjectMapping")
.invoke(securityRoleMapperInstance);
for (String role : allDeclaredRoles) {
if (roleToSubjectMap.containsKey(role)) {
Set<Principal> principals = roleToSubjectMap.get(role).getPrincipals();
List<String> groups = getGroups(principals, null);
for (String group : groups) {
if (!groupToRoles.containsKey(group)) {
groupToRoles.put(group, new ArrayList<String>());
}
groupToRoles.get(group).add(role);
}
if ("**".equals(role) && !groups.isEmpty()) {
// JACC spec 3.2 states:
//
// "For the any "authenticated user role", "**", and unless an application specific mapping has
// been established for this role,
// the provider must ensure that all permissions added to the role are granted to any
// authenticated user."
//
// Here we check for the "unless" part mentioned above. If we're dealing with the "**" role here
// and groups is not
// empty, then there's an application specific mapping and "**" maps only to those groups, not
// to any authenticated user.
anyAuthenticatedUserRoleMapped = true;
}
}
}
return true;
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
return false;
}
}
private boolean tryWebLogic(String contextID, Collection<String> allDeclaredRoles) {
try {
// See http://docs.oracle.com/cd/E21764_01/apirefs.1111/e13941/weblogic/security/jacc/RoleMapperFactory.html
Class<?> roleMapperFactoryClass = Class.forName("weblogic.security.jacc.RoleMapperFactory");
// RoleMapperFactory implementation class always seems to be the value of what is passed on the commandline
// via the -Dweblogic.security.jacc.RoleMapperFactory.provider option.
// See http://docs.oracle.com/cd/E57014_01/wls/SCPRG/server_prot.htm
Object roleMapperFactoryInstance = roleMapperFactoryClass.getMethod("getRoleMapperFactory")
.invoke(null);
// See http://docs.oracle.com/cd/E21764_01/apirefs.1111/e13941/weblogic/security/jacc/RoleMapperFactory.html#getRoleMapperForContextID(java.lang.String)
Object roleMapperInstance = roleMapperFactoryClass.getMethod("getRoleMapperForContextID", String.class)
.invoke(roleMapperFactoryInstance, contextID);
// This seems really awkward; the Map contains BOTH group names and user names, without ANY way to
// distinguish between the two.
// If a user now has a name that happens to be a role as well, we have an issue :X
@SuppressWarnings("unchecked")
Map<String, String[]> roleToPrincipalNamesMap = (Map<String, String[]>) Class.forName("weblogic.security.jacc.simpleprovider.RoleMapperImpl")
.getMethod("getRolesToPrincipalNames")
.invoke(roleMapperInstance);
for (String role : allDeclaredRoles) {
if (roleToPrincipalNamesMap.containsKey(role)) {
List<String> groupsOrUserNames = asList(roleToPrincipalNamesMap.get(role));
for (String groupOrUserName : roleToPrincipalNamesMap.get(role)) {
// Ignore the fact that the collection also contains user names and hope
// that there are no user names in the application with the same name as a group
if (!groupToRoles.containsKey(groupOrUserName)) {
groupToRoles.put(groupOrUserName, new ArrayList<String>());
}
groupToRoles.get(groupOrUserName).add(role);
}
if ("**".equals(role) && !groupsOrUserNames.isEmpty()) {
// JACC spec 3.2 states: [...]
anyAuthenticatedUserRoleMapped = true;
}
}
}
return true;
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
return false;
}
}
private boolean tryGeronimo(String contextID, Collection<String> allDeclaredRoles) {
if (geronimoContextToRoleMapping != null) {
if (geronimoContextToRoleMapping.containsKey(contextID)) {
Map<Principal, Set<String>> principalsToRoles = geronimoContextToRoleMapping.get(contextID);
for (Map.Entry<Principal, Set<String>> entry : principalsToRoles.entrySet()) {
// Convert the principal that's used as the key in the Map to a list of zero or more groups.
// (for Geronimo we know that using the default role mapper it's always zero or one group)
for (String group : principalToGroups(entry.getKey())) {
if (!groupToRoles.containsKey(group)) {
groupToRoles.put(group, new ArrayList<String>());
}
groupToRoles.get(group).addAll(entry.getValue());
if (entry.getValue().contains("**")) {
// JACC spec 3.2 states: [...]
anyAuthenticatedUserRoleMapped = true;
}
}
}
}
return true;
}
return false;
}
/**
* Extracts the groups from the vendor specific principals.
*
* @param principals the primary entities to look in for groups
* @param subject the fall back to use for finding groups, may be null
* @return a list of (non-mapped) groups
*/
@SuppressWarnings("unchecked")
public List<String> getGroups(Iterable<Principal> principals, Subject subject) {
List<String> groups = new ArrayList<>();
for (Principal principal : principals) {
if (principalToGroups(principal, groups)) {
// return value of true means we're done early. This can be used
// when we know there's only 1 principal holding all the groups
return groups;
}
}
if (subject == null) {
return groups;
}
Set<Principal> privatePrincipals = subject.getPrivateCredentials(Principal.class);
for (Principal principal : privatePrincipals) {
if (principalToGroups(principal, groups)) {
// return value of true means we're done early. This can be used
// when we know there's only 1 principal holding all the groups
return groups;
}
}
@SuppressWarnings("rawtypes")
Set<Hashtable> tables = subject.getPrivateCredentials(Hashtable.class);
if (tables != null && !tables.isEmpty()) {
@SuppressWarnings("rawtypes")
Hashtable table = tables.iterator().next();
groups = (List<String>) table.get("com.ibm.wsspi.security.cred.groups");
return groups != null ? groups : emptyList();
}
return groups;
}
public List<String> principalToGroups(Principal principal) {
List<String> groups = new ArrayList<>();
principalToGroups(principal, groups);
return groups;
}
public boolean principalToGroups(Principal principal, List<String> groups) {
switch (principal.getClass().getName()) {
case "org.glassfish.security.common.Group": // GlassFish & Payara
case "org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal": // Geronimo
case "weblogic.security.principal.WLSGroupImpl": // WebLogic
case "jeus.security.resource.GroupPrincipalImpl": // JEUS
groups.add(principal.getName());
break;
case "org.apache.openejb.core.security.AbstractSecurityService$Group": // TomEE 1
case "org.jboss.security.SimpleGroup": // JBoss EAP/WildFly
if (principal.getName().equals("Roles") && principal.getClass().getName().equals("org.jboss.security.SimpleGroup")) {
try {
@SuppressWarnings("unchecked")
Enumeration<? extends Principal> groupMembers = (Enumeration<? extends Principal>)
Class.forName("org.jboss.security.SimpleGroup")
.getMethod("members")
.invoke(principal);
for (Principal groupPrincipal : list(groupMembers)) {
groups.add(groupPrincipal.getName());
}
} catch (Exception e) {
}
// Should only be one group holding the roles, so can exit the loop
// early
return true;
}
case "org.apache.tomee.catalina.TomcatSecurityService$TomcatUser": // TomEE 2
try {
groups.addAll(
asList((String[]) Class.forName("org.apache.catalina.realm.GenericPrincipal")
.getMethod("getRoles")
.invoke(
Class.forName("org.apache.tomee.catalina.TomcatSecurityService$TomcatUser")
.getMethod("getTomcatPrincipal")
.invoke(principal))));
} catch (Exception e) {
}
break;
case "org.apache.catalina.realm.GenericPrincipal": // Tomcat
try {
groups.addAll(
asList((String[]) Class.forName("org.apache.catalina.realm.GenericPrincipal")
.getMethod("getRoles")
.invoke(principal)));
} catch (Exception e) {
}
}
return false;
}
}