| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: Alessandro Ventura |
| 5 |
*/ |
| 6 |
package org.h2.security.auth; |
| 7 |
|
| 8 |
import java.io.IOException; |
| 9 |
import java.net.URL; |
| 10 |
import java.util.ArrayList; |
| 11 |
import java.util.Collection; |
| 12 |
import java.util.HashMap; |
| 13 |
import java.util.HashSet; |
| 14 |
import java.util.List; |
| 15 |
import java.util.Map; |
| 16 |
import java.util.Set; |
| 17 |
import javax.xml.parsers.ParserConfigurationException; |
| 18 |
import org.h2.api.CredentialsValidator; |
| 19 |
import org.h2.api.UserToRolesMapper; |
| 20 |
import org.h2.engine.Database; |
| 21 |
import org.h2.engine.Right; |
| 22 |
import org.h2.engine.Role; |
| 23 |
import org.h2.engine.SysProperties; |
| 24 |
import org.h2.engine.User; |
| 25 |
import org.h2.engine.UserBuilder; |
| 26 |
import org.h2.message.Trace; |
| 27 |
import org.h2.security.auth.impl.AssignRealmNameRole; |
| 28 |
import org.h2.security.auth.impl.JaasCredentialsValidator; |
| 29 |
import org.h2.util.StringUtils; |
| 30 |
import org.xml.sax.SAXException; |
| 31 |
|
| 32 |
/** |
| 33 |
* Default authenticator implementation. |
| 34 |
* <p> |
| 35 |
* When client connectionInfo contains property AUTHREALM={realName} credentials |
| 36 |
* (typically user id and password) are validated by |
| 37 |
* {@link org.h2.api.CredentialsValidator} configured for that realm. |
| 38 |
* </p> |
| 39 |
* <p> |
| 40 |
* When client connectionInfo doesn't contains AUTHREALM property credentials |
| 41 |
* are validated internally on the database |
| 42 |
* </p> |
| 43 |
* <p> |
| 44 |
* Rights assignment can be managed through {@link org.h2.api.UserToRolesMapper} |
| 45 |
* </p> |
| 46 |
* <p> |
| 47 |
* Default configuration has a realm H2 that validate credentials through JAAS |
| 48 |
* api (appName=h2). To customize configuration set h2.authConfigFile system |
| 49 |
* property to refer a valid h2auth.xml config file |
| 50 |
* </p> |
| 51 |
*/ |
| 52 |
public class DefaultAuthenticator implements Authenticator { |
| 53 |
|
| 54 |
public static final String DEFAULT_REALMNAME = "H2"; |
| 55 |
|
| 56 |
private Map<String, CredentialsValidator> realms = new HashMap<>(); |
| 57 |
private List<UserToRolesMapper> userToRolesMappers = new ArrayList<>(); |
| 58 |
private boolean allowUserRegistration; |
| 59 |
private boolean persistUsers; |
| 60 |
private boolean createMissingRoles; |
| 61 |
private boolean skipDefaultInitialization; |
| 62 |
private boolean initialized; |
| 63 |
private static DefaultAuthenticator instance; |
| 64 |
|
| 65 |
protected static final DefaultAuthenticator getInstance() { |
| 66 |
if (instance == null) { |
| 67 |
instance = new DefaultAuthenticator(); |
| 68 |
} |
| 69 |
return instance; |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* Create the Authenticator with default configurations |
| 74 |
*/ |
| 75 |
public DefaultAuthenticator() { |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Create authenticator and optionally skip the default configuration. This |
| 80 |
* option is useful when the authenticator is configured at code level |
| 81 |
* |
| 82 |
* @param skipDefaultInitialization |
| 83 |
* if true default initialization is skipped |
| 84 |
*/ |
| 85 |
public DefaultAuthenticator(boolean skipDefaultInitialization) { |
| 86 |
this.skipDefaultInitialization = skipDefaultInitialization; |
| 87 |
} |
| 88 |
|
| 89 |
/** |
| 90 |
* If set save users externals defined during the authentication. |
| 91 |
* |
| 92 |
* @return {@code true} if user will be persisted, |
| 93 |
* otherwise returns {@code false} |
| 94 |
*/ |
| 95 |
public boolean isPersistUsers() { |
| 96 |
return persistUsers; |
| 97 |
} |
| 98 |
|
| 99 |
/** |
| 100 |
* If set to {@code true} saves users externals defined during the authentication. |
| 101 |
* |
| 102 |
* @param persistUsers {@code true} if user will be persisted, |
| 103 |
* otherwise {@code false}. |
| 104 |
*/ |
| 105 |
public void setPersistUsers(boolean persistUsers) { |
| 106 |
this.persistUsers = persistUsers; |
| 107 |
} |
| 108 |
|
| 109 |
/** |
| 110 |
* If set create external users in the database if not present. |
| 111 |
* |
| 112 |
* @return {@code true} if creation external user is allowed, |
| 113 |
* otherwise returns {@code false} |
| 114 |
*/ |
| 115 |
public boolean isAllowUserRegistration() { |
| 116 |
return allowUserRegistration; |
| 117 |
} |
| 118 |
|
| 119 |
/** |
| 120 |
* If set to{@code true} creates external users in the database if not present. |
| 121 |
* |
| 122 |
* @param allowUserRegistration {@code true} if creation external user is allowed, |
| 123 |
* otherwise returns {@code false} |
| 124 |
*/ |
| 125 |
public void setAllowUserRegistration(boolean allowUserRegistration) { |
| 126 |
this.allowUserRegistration = allowUserRegistration; |
| 127 |
} |
| 128 |
|
| 129 |
/** |
| 130 |
* When set create roles not found in the database. If not set roles not |
| 131 |
* found in the database are silently skipped. |
| 132 |
* |
| 133 |
* @return {@code true} if not found roles will be created, |
| 134 |
* {@code false} roles are silently skipped. |
| 135 |
*/ |
| 136 |
public boolean isCreateMissingRoles() { |
| 137 |
return createMissingRoles; |
| 138 |
} |
| 139 |
|
| 140 |
/** |
| 141 |
* Sets the flag that define behavior in case external roles not found in the database. |
| 142 |
* |
| 143 |
* |
| 144 |
* @param createMissingRoles when is {@code true} not found roles are created, |
| 145 |
* when is {@code false} roles are silently skipped. |
| 146 |
*/ |
| 147 |
public void setCreateMissingRoles(boolean createMissingRoles) { |
| 148 |
this.createMissingRoles = createMissingRoles; |
| 149 |
} |
| 150 |
|
| 151 |
/** |
| 152 |
* Add an authentication realm. Realms are case insensitive |
| 153 |
* |
| 154 |
* @param name |
| 155 |
* realm name |
| 156 |
* @param credentialsValidator |
| 157 |
* credentials validator for realm |
| 158 |
*/ |
| 159 |
public void addRealm(String name, CredentialsValidator credentialsValidator) { |
| 160 |
realms.put(StringUtils.toUpperEnglish(name), credentialsValidator); |
| 161 |
} |
| 162 |
|
| 163 |
/** |
| 164 |
* UserToRoleMappers assign roles to authenticated users |
| 165 |
* |
| 166 |
* @return current UserToRoleMappers active |
| 167 |
*/ |
| 168 |
public List<UserToRolesMapper> getUserToRolesMappers() { |
| 169 |
return userToRolesMappers; |
| 170 |
} |
| 171 |
|
| 172 |
public void setUserToRolesMappers(UserToRolesMapper... userToRolesMappers) { |
| 173 |
List<UserToRolesMapper> userToRolesMappersList = new ArrayList<>(); |
| 174 |
for (UserToRolesMapper current : userToRolesMappers) { |
| 175 |
userToRolesMappersList.add(current); |
| 176 |
} |
| 177 |
this.userToRolesMappers = userToRolesMappersList; |
| 178 |
} |
| 179 |
|
| 180 |
/** |
| 181 |
* Initializes the authenticator. |
| 182 |
* |
| 183 |
* this method is skipped if skipDefaultInitialization is set Order of |
| 184 |
* initialization is |
| 185 |
* <ol> |
| 186 |
* <li>Check h2.authConfigFile system property.</li> |
| 187 |
* <li>Use the default configuration hard coded</li> |
| 188 |
* </ol> |
| 189 |
* |
| 190 |
* @param database where authenticator is initialized |
| 191 |
*/ |
| 192 |
@Override |
| 193 |
public void init(Database database) throws AuthConfigException { |
| 194 |
if (skipDefaultInitialization) { |
| 195 |
return; |
| 196 |
} |
| 197 |
if (initialized) { |
| 198 |
return; |
| 199 |
} |
| 200 |
synchronized (this) { |
| 201 |
if (initialized) { |
| 202 |
return; |
| 203 |
} |
| 204 |
Trace trace = database.getTrace(Trace.DATABASE); |
| 205 |
URL h2AuthenticatorConfigurationUrl = null; |
| 206 |
try { |
| 207 |
String configFile = SysProperties.AUTH_CONFIG_FILE; |
| 208 |
if (configFile != null) { |
| 209 |
if (trace.isDebugEnabled()) { |
| 210 |
trace.debug("DefaultAuthenticator.config: configuration read from system property" |
| 211 |
+ " h2auth.configurationfile={0}", configFile); |
| 212 |
} |
| 213 |
h2AuthenticatorConfigurationUrl = new URL(configFile); |
| 214 |
} |
| 215 |
if (h2AuthenticatorConfigurationUrl == null) { |
| 216 |
if (trace.isDebugEnabled()) { |
| 217 |
trace.debug("DefaultAuthenticator.config: default configuration"); |
| 218 |
} |
| 219 |
defaultConfiguration(); |
| 220 |
} else { |
| 221 |
configureFromUrl(h2AuthenticatorConfigurationUrl); |
| 222 |
} |
| 223 |
} catch (Exception e) { |
| 224 |
trace.error(e, "DefaultAuthenticator.config: an error occurred during configuration from {0} ", |
| 225 |
h2AuthenticatorConfigurationUrl); |
| 226 |
throw new AuthConfigException( |
| 227 |
"Failed to configure authentication from " + h2AuthenticatorConfigurationUrl, e); |
| 228 |
} |
| 229 |
initialized = true; |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
private void defaultConfiguration() { |
| 234 |
createMissingRoles = false; |
| 235 |
allowUserRegistration = true; |
| 236 |
realms = new HashMap<>(); |
| 237 |
CredentialsValidator jaasCredentialsValidator = new JaasCredentialsValidator(); |
| 238 |
jaasCredentialsValidator.configure(new ConfigProperties()); |
| 239 |
realms.put(DEFAULT_REALMNAME, jaasCredentialsValidator); |
| 240 |
UserToRolesMapper assignRealmNameRole = new AssignRealmNameRole(); |
| 241 |
assignRealmNameRole.configure(new ConfigProperties()); |
| 242 |
userToRolesMappers.add(assignRealmNameRole); |
| 243 |
} |
| 244 |
|
| 245 |
/** |
| 246 |
* Configure the authenticator from a configuration file |
| 247 |
* |
| 248 |
* @param configUrl URL of configuration file |
| 249 |
* @throws AuthenticationException on failure |
| 250 |
* @throws SAXException on failure |
| 251 |
* @throws IOException on failure |
| 252 |
* @throws ParserConfigurationException on failure |
| 253 |
*/ |
| 254 |
public void configureFromUrl(URL configUrl) throws AuthenticationException, |
| 255 |
SAXException, IOException, ParserConfigurationException { |
| 256 |
H2AuthConfig config = H2AuthConfigXml.parseFrom(configUrl); |
| 257 |
configureFrom(config); |
| 258 |
} |
| 259 |
|
| 260 |
private void configureFrom(H2AuthConfig config) throws AuthenticationException { |
| 261 |
allowUserRegistration = config.isAllowUserRegistration(); |
| 262 |
createMissingRoles = config.isCreateMissingRoles(); |
| 263 |
HashMap<String, CredentialsValidator> newRealms = new HashMap<>(); |
| 264 |
for (RealmConfig currentRealmConfig : config.getRealms()) { |
| 265 |
String currentRealmName = currentRealmConfig.getName(); |
| 266 |
if (currentRealmName == null) { |
| 267 |
throw new AuthenticationException("Missing realm name"); |
| 268 |
} |
| 269 |
currentRealmName = currentRealmName.toUpperCase(); |
| 270 |
CredentialsValidator currentValidator = null; |
| 271 |
try { |
| 272 |
currentValidator = (CredentialsValidator) Class.forName(currentRealmConfig.getValidatorClass()) |
| 273 |
.getDeclaredConstructor().newInstance(); |
| 274 |
} catch (Exception e) { |
| 275 |
throw new AuthenticationException("invalid validator class fo realm " + currentRealmName, e); |
| 276 |
} |
| 277 |
currentValidator.configure(new ConfigProperties(currentRealmConfig.getProperties())); |
| 278 |
if (newRealms.putIfAbsent(currentRealmConfig.getName().toUpperCase(), currentValidator) != null) { |
| 279 |
throw new AuthenticationException("Duplicate realm " + currentRealmConfig.getName()); |
| 280 |
} |
| 281 |
} |
| 282 |
this.realms = newRealms; |
| 283 |
List<UserToRolesMapper> newUserToRolesMapper = new ArrayList<>(); |
| 284 |
for (UserToRolesMapperConfig currentUserToRolesMapperConfig : config.getUserToRolesMappers()) { |
| 285 |
UserToRolesMapper currentUserToRolesMapper = null; |
| 286 |
try { |
| 287 |
currentUserToRolesMapper = (UserToRolesMapper) Class |
| 288 |
.forName(currentUserToRolesMapperConfig.getClassName()).getDeclaredConstructor().newInstance(); |
| 289 |
} catch (Exception e) { |
| 290 |
throw new AuthenticationException("Invalid class in UserToRolesMapperConfig", e); |
| 291 |
} |
| 292 |
currentUserToRolesMapper.configure(new ConfigProperties(currentUserToRolesMapperConfig.getProperties())); |
| 293 |
newUserToRolesMapper.add(currentUserToRolesMapper); |
| 294 |
} |
| 295 |
this.userToRolesMappers = newUserToRolesMapper; |
| 296 |
} |
| 297 |
|
| 298 |
private boolean updateRoles(AuthenticationInfo authenticationInfo, User user, Database database) |
| 299 |
throws AuthenticationException { |
| 300 |
boolean updatedDb = false; |
| 301 |
Set<String> roles = new HashSet<>(); |
| 302 |
for (UserToRolesMapper currentUserToRolesMapper : userToRolesMappers) { |
| 303 |
Collection<String> currentRoles = currentUserToRolesMapper.mapUserToRoles(authenticationInfo); |
| 304 |
if (currentRoles != null && !currentRoles.isEmpty()) { |
| 305 |
roles.addAll(currentRoles); |
| 306 |
} |
| 307 |
} |
| 308 |
for (String currentRoleName : roles) { |
| 309 |
if (currentRoleName == null || currentRoleName.isEmpty()) { |
| 310 |
continue; |
| 311 |
} |
| 312 |
Role currentRole = database.findRole(currentRoleName); |
| 313 |
if (currentRole == null && isCreateMissingRoles()) { |
| 314 |
synchronized (database.getSystemSession()) { |
| 315 |
currentRole = new Role(database, database.allocateObjectId(), currentRoleName, false); |
| 316 |
database.addDatabaseObject(database.getSystemSession(), currentRole); |
| 317 |
database.getSystemSession().commit(false); |
| 318 |
updatedDb = true; |
| 319 |
} |
| 320 |
} |
| 321 |
if (currentRole == null) { |
| 322 |
continue; |
| 323 |
} |
| 324 |
if (user.getRightForRole(currentRole) == null) { |
| 325 |
// NON PERSISTENT |
| 326 |
Right currentRight = new Right(database, -1, user, currentRole); |
| 327 |
currentRight.setTemporary(true); |
| 328 |
user.grantRole(currentRole, currentRight); |
| 329 |
} |
| 330 |
} |
| 331 |
return updatedDb; |
| 332 |
} |
| 333 |
|
| 334 |
@Override |
| 335 |
public final User authenticate(AuthenticationInfo authenticationInfo, Database database) |
| 336 |
throws AuthenticationException { |
| 337 |
String userName = authenticationInfo.getFullyQualifiedName(); |
| 338 |
User user = database.findUser(userName); |
| 339 |
if (user == null && !isAllowUserRegistration()) { |
| 340 |
throw new AuthenticationException("User " + userName + " not found in db"); |
| 341 |
} |
| 342 |
CredentialsValidator validator = realms.get(authenticationInfo.getRealm()); |
| 343 |
if (validator == null) { |
| 344 |
throw new AuthenticationException("realm " + authenticationInfo.getRealm() + " not configured"); |
| 345 |
} |
| 346 |
try { |
| 347 |
if (!validator.validateCredentials(authenticationInfo)) { |
| 348 |
return null; |
| 349 |
} |
| 350 |
} catch (Exception e) { |
| 351 |
throw new AuthenticationException(e); |
| 352 |
} |
| 353 |
if (user == null) { |
| 354 |
synchronized (database.getSystemSession()) { |
| 355 |
user = UserBuilder.buildUser(authenticationInfo, database, isPersistUsers()); |
| 356 |
database.addDatabaseObject(database.getSystemSession(), user); |
| 357 |
database.getSystemSession().commit(false); |
| 358 |
} |
| 359 |
} |
| 360 |
user.revokeTemporaryRightsOnRoles(); |
| 361 |
updateRoles(authenticationInfo, user, database); |
| 362 |
return user; |
| 363 |
} |
| 364 |
} |