-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
LdapRealm.java
330 lines (291 loc) · 13.1 KB
/
LdapRealm.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
/*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.security.enterprise.auth;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.SimpleRole;
import org.apache.shiro.authz.permission.RolePermissionResolver;
import org.apache.shiro.realm.ldap.JndiLdapContextFactory;
import org.apache.shiro.realm.ldap.JndiLdapRealm;
import org.apache.shiro.realm.ldap.LdapContextFactory;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import org.neo4j.kernel.api.security.AuthenticationResult;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.logging.Log;
import org.neo4j.logging.LogProvider;
/**
* Shiro realm for LDAP based on configuration settings
*/
public class LdapRealm extends JndiLdapRealm
{
private static final String GROUP_DELIMITER = ";";
private static final String KEY_VALUE_DELIMITER = "=";
private static final String ROLE_DELIMITER = ",";
private Boolean authenticationEnabled;
private Boolean authorizationEnabled;
private String userSearchBase;
private String userSearchFilter;
private String membershipAttributeName;
private Boolean useSystemAccountForAuthorization;
private Map<String,Collection<String>> groupToRoleMapping;
private final Log log;
private Map<String, SimpleAuthorizationInfo> authorizationInfoCache = new ConcurrentHashMap<>();
public LdapRealm( Config config, LogProvider logProvider )
{
super();
log = logProvider.getLog( getClass() );
setRolePermissionResolver( rolePermissionResolver );
configureRealm( config );
}
@Override
protected AuthenticationInfo queryForAuthenticationInfo( AuthenticationToken token,
LdapContextFactory ldapContextFactory )
throws NamingException
{
return authenticationEnabled ? super.queryForAuthenticationInfo( token, ldapContextFactory ) : null;
}
@Override
protected AuthorizationInfo queryForAuthorizationInfo( PrincipalCollection principals,
LdapContextFactory ldapContextFactory ) throws NamingException
{
if ( authorizationEnabled )
{
String username = (String) getAvailablePrincipal( principals );
if ( useSystemAccountForAuthorization )
{
// Perform context search using the system context
LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();
Set<String> roleNames;
try
{
roleNames = findRoleNamesForUser( username, ldapContext );
}
finally
{
LdapUtils.closeContext( ldapContext );
}
return new SimpleAuthorizationInfo( roleNames );
}
else
{
// Authorization info is cached during authentication
return authorizationInfoCache.get( username );
}
}
return null;
}
@Override
protected AuthenticationInfo createAuthenticationInfo( AuthenticationToken token, Object ldapPrincipal,
Object ldapCredentials, LdapContext ldapContext )
throws NamingException
{
// NOTE: This will be called only if authentication with the ldap context was successful
// If authorization is enabled but useSystemAccountForAuthorization is disabled, we should perform
// the search for groups directly here while the user's authenticated ldap context is open.
if ( authorizationEnabled && !useSystemAccountForAuthorization )
{
String username = (String) token.getPrincipal();
Set<String> roleNames = findRoleNamesForUser( username, ldapContext );
cacheAuthorizationInfo( username, roleNames );
}
return new ShiroAuthenticationInfo( token.getPrincipal(), token.getCredentials(), getName(),
AuthenticationResult.SUCCESS );
}
@Override
protected void clearCachedAuthorizationInfo( PrincipalCollection principals )
{
super.clearCachedAuthorizationInfo( principals );
String username = (String) getAvailablePrincipal( principals );
authorizationInfoCache.remove( username );
}
private void cacheAuthorizationInfo( String username, Set<String> roleNames )
{
// Ideally we would like to use the existing authorizationCache in our base class,
// but unfortunately it is private to AuthorizingRealm
authorizationInfoCache.put( username, new SimpleAuthorizationInfo( roleNames ) );
}
private final RolePermissionResolver rolePermissionResolver = new RolePermissionResolver()
{
@Override
public Collection<Permission> resolvePermissionsInRole( String roleString )
{
SimpleRole role = PredefinedRolesBuilder.roles.get( roleString );
if ( role != null )
{
return role.getPermissions();
}
else
{
return Collections.emptyList();
}
}
};
private void configureRealm( Config config )
{
JndiLdapContextFactory contextFactory = new JndiLdapContextFactory();
contextFactory.setUrl( "ldap://" + config.get( SecuritySettings.ldap_server ) );
contextFactory.setAuthenticationMechanism( config.get( SecuritySettings.ldap_auth_mechanism ) );
contextFactory.setReferral( config.get( SecuritySettings.ldap_referral ) );
contextFactory.setSystemUsername( config.get( SecuritySettings.ldap_system_username ) );
contextFactory.setSystemPassword( config.get( SecuritySettings.ldap_system_password ) );
setContextFactory( contextFactory );
String userDnTemplate = config.get( SecuritySettings.ldap_user_dn_template );
if ( userDnTemplate != null )
{
setUserDnTemplate( userDnTemplate );
}
authenticationEnabled = config.get( SecuritySettings.ldap_authentication_enabled );
authorizationEnabled = config.get( SecuritySettings.ldap_authorization_enabled );
userSearchBase = config.get( SecuritySettings.ldap_authorization_user_search_base );
userSearchFilter = config.get( SecuritySettings.ldap_authorization_user_search_filter );
membershipAttributeName = config.get( SecuritySettings.ldap_authorization_group_membership_attribute_name );
useSystemAccountForAuthorization = config.get( SecuritySettings.ldap_authorization_use_system_account );
groupToRoleMapping =
parseGroupToRoleMapping( config.get( SecuritySettings.ldap_authorization_group_to_role_mapping ) );
}
Map<String,Collection<String>> parseGroupToRoleMapping( String groupToRoleMappingString )
{
Map<String,Collection<String>> map = new HashMap<>();
if ( groupToRoleMappingString != null )
{
for ( String groupAndRoles : groupToRoleMappingString.split( GROUP_DELIMITER ) )
{
if ( !groupAndRoles.isEmpty() )
{
String[] parts = groupAndRoles.split( KEY_VALUE_DELIMITER, 2 );
if ( parts.length != 2 )
{
String errorMessage = String.format( "Failed to parse setting %s: wrong number of fields",
SecuritySettings.ldap_authorization_group_to_role_mapping.name() );
log.error( errorMessage );
throw new IllegalArgumentException( errorMessage );
}
String group = parts[0];
if ( group.isEmpty() )
{
String errorMessage = String.format( "Failed to parse setting %s: empty group name",
SecuritySettings.ldap_authorization_group_to_role_mapping.name() );
log.error( errorMessage );
throw new IllegalArgumentException( errorMessage );
}
Collection<String> roleList = new ArrayList<>();
for ( String role : parts[1].split( ROLE_DELIMITER ) )
{
if ( !role.isEmpty() )
{
roleList.add( role );
}
}
map.put( group, roleList );
}
}
}
return map;
}
Set<String> findRoleNamesForUser( String username, LdapContext ldapContext ) throws NamingException
{
Set<String> roleNames = new LinkedHashSet<String>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope( SearchControls.SUBTREE_SCOPE );
searchCtls.setReturningAttributes( new String[]{membershipAttributeName} );
// Use search argument to prevent potential code injection
String searchFilter = userSearchFilter;
Object[] searchArguments = new Object[]{username};
validateUserSearchFilter( searchFilter );
NamingEnumeration result = ldapContext.search( userSearchBase, searchFilter, searchArguments, searchCtls );
if ( result.hasMoreElements() )
{
SearchResult searchResult = (SearchResult) result.next();
if ( result.hasMoreElements() )
{
log.warn( String.format(
"LDAP user search for user principal '%s' is ambiguous. The first match that will be checked " +
"for group membership is '%s' " +
"but the search also matches '%s'. Please check your LDAP realm configuration.",
username,
// TODO: Check if it is ok to write this potentially sensitive information to the log
searchResult.toString(),
((SearchResult) result.next()).toString() ) );
}
Attributes attributes = searchResult.getAttributes();
if ( attributes != null )
{
NamingEnumeration attributeEnumeration = attributes.getAll();
while ( attributeEnumeration.hasMore() )
{
Attribute attribute = (Attribute) attributeEnumeration.next();
if ( attribute.getID().toLowerCase().equals( membershipAttributeName.toLowerCase() ) )
{
Collection<String> groupNames = LdapUtils.getAllAttributeValues( attribute );
Collection<String> rolesForGroups = getRoleNamesForGroups( groupNames );
roleNames.addAll( rolesForGroups );
break;
}
}
}
}
return roleNames;
}
private void validateUserSearchFilter( String searchFilter )
{
if ( !searchFilter.contains( "{0}" ) )
{
log.warn( "LDAP user search filter does not contain the argument placeholder {0}, so the search result " +
"will be independent of the user principal." );
}
}
private Collection<String> getRoleNamesForGroups( Collection<String> groupNames )
{
Collection<String> roles = new ArrayList<>();
for ( String group : groupNames )
{
Collection<String> rolesForGroup = groupToRoleMapping.get( group );
if ( rolesForGroup != null )
{
roles.addAll( rolesForGroup );
}
}
return roles;
}
// Exposed for testing
Map<String,Collection<String>> getGroupToRoleMapping()
{
return groupToRoleMapping;
}
}