2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.usermanager;
11 import java.io.Serializable;
12 import java.security.MessageDigest;
13 import java.security.NoSuchAlgorithmException;
14 import java.security.SecureRandom;
15 import java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
22 import javax.xml.bind.annotation.XmlAccessType;
23 import javax.xml.bind.annotation.XmlAccessorType;
24 import javax.xml.bind.annotation.XmlElement;
25 import javax.xml.bind.annotation.XmlRootElement;
27 import org.opendaylight.controller.configuration.ConfigurationObject;
28 import org.opendaylight.controller.sal.authorization.AuthResultEnum;
29 import org.opendaylight.controller.sal.packet.BitBufferHelper;
30 import org.opendaylight.controller.sal.utils.HexEncode;
31 import org.opendaylight.controller.sal.utils.Status;
32 import org.opendaylight.controller.sal.utils.StatusCode;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
37 * Configuration Java Object which represents a Local AAA user configuration
38 * information for User Manager.
41 @XmlAccessorType(XmlAccessType.NONE)
42 public class UserConfig extends ConfigurationObject implements Serializable {
43 private static final long serialVersionUID = 1L;
44 private static Logger log = LoggerFactory.getLogger(UserConfig.class);
45 private static final boolean strongPasswordCheck = Boolean.getBoolean("enableStrongPasswordCheck");
46 private static final String DIGEST_ALGORITHM = "SHA-384";
47 private static final String BAD_PASSWORD = "Bad Password";
48 private static final int USERNAME_MAXLENGTH = 32;
49 protected static final String PASSWORD_REGEX = "(?=.*[^a-zA-Z0-9])(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,256}$";
50 private static final Pattern INVALID_USERNAME_CHARACTERS = Pattern.compile("([/\\s\\.\\?#%;\\\\]+)");
51 private static MessageDigest oneWayFunction;
52 private static SecureRandom randomGenerator;
56 UserConfig.oneWayFunction = MessageDigest.getInstance(DIGEST_ALGORITHM);
57 } catch (NoSuchAlgorithmException e) {
58 log.error(String.format("Implementation of %s digest algorithm not found: %s", DIGEST_ALGORITHM,
61 UserConfig.randomGenerator = new SecureRandom(BitBufferHelper.toByteArray(System.currentTimeMillis()));
68 protected String user;
71 * List of roles a user can have
78 protected List<String> roles;
82 * Should be 8 to 256 characters long,
83 * contain both upper and lower case letters, at least one number,
84 * and at least one non alphanumeric character.
87 private String password;
97 * Construct a UserConfig object and takes care of hashing the user password
102 * the plain text password
106 public UserConfig(String user, String password, List<String> roles) {
110 * Password validation to be done on clear text password. If fails, mark
111 * the password with a well known label, so that object validation can
112 * report the proper error. Only if password is a valid one, generate
113 * salt, concatenate it with clear text password and hash the
114 * resulting string. Hash result is going to be our stored password.
116 if (validateClearTextPassword(password).isSuccess()) {
117 this.salt = BitBufferHelper.toByteArray(randomGenerator.nextLong());
118 this.password = hash(salt, password);
121 this.password = BAD_PASSWORD;
124 this.roles = (roles == null) ? Collections.<String>emptyList() : new ArrayList<String>(roles);
127 public String getUser() {
131 public String getPassword() {
135 public List<String> getRoles() {
136 return new ArrayList<String>(roles);
140 public int hashCode() {
141 final int prime = 31;
143 result = prime * result
144 + ((password == null) ? 0 : password.hashCode());
145 result = prime * result + ((roles == null) ? 0 : roles.hashCode());
146 result = prime * result + ((user == null) ? 0 : user.hashCode());
151 public boolean equals(Object obj) {
158 if (getClass() != obj.getClass()) {
161 UserConfig other = (UserConfig) obj;
162 if (password == null) {
163 if (other.password != null) {
166 } else if (!password.equals(other.password)) {
170 if (other.roles != null) {
173 } else if (!roles.equals(other.roles)) {
177 if (other.user != null) {
180 } else if (!user.equals(other.user)) {
187 public String toString() {
188 return "UserConfig[user=" + user + ", password=" + password + ", roles=" + roles +"]";
191 public Status validate() {
192 Status validCheck = validateUsername();
193 if (validCheck.isSuccess()) {
194 // Password validation was run at object construction time
195 validCheck = (!password.equals(BAD_PASSWORD)) ? new Status(StatusCode.SUCCESS) : new Status(
196 StatusCode.BADREQUEST,
197 "Password should be 8 to 256 characters long, contain both upper and lower case letters, "
198 + "at least one number and at least one non alphanumeric character");
200 if (validCheck.isSuccess()) {
201 validCheck = validateRoles();
206 protected Status validateUsername() {
207 if (user == null || user.isEmpty()) {
208 return new Status(StatusCode.BADREQUEST, "Username cannot be empty");
211 Matcher mUser = UserConfig.INVALID_USERNAME_CHARACTERS.matcher(user);
212 if (user.length() > UserConfig.USERNAME_MAXLENGTH || mUser.find() == true) {
213 return new Status(StatusCode.BADREQUEST,
214 "Username can have 1-32 non-whitespace "
215 + "alphanumeric characters and any special "
216 + "characters except ./#%;?\\");
219 return new Status(StatusCode.SUCCESS);
222 private Status validateClearTextPassword(String password) {
223 if (password == null || password.isEmpty()) {
224 return new Status(StatusCode.BADREQUEST, "Password cannot be empty");
227 if (strongPasswordCheck && !password.matches(UserConfig.PASSWORD_REGEX)) {
228 return new Status(StatusCode.BADREQUEST, "Password should be 8 to 256 characters long, "
229 + "contain both upper and lower case letters, at least one number "
230 + "and at least one non alphanumeric character");
232 return new Status(StatusCode.SUCCESS);
235 protected Status validateRoles() {
236 if (roles == null || roles.isEmpty()) {
237 return new Status(StatusCode.BADREQUEST, "No role specified");
239 return new Status(StatusCode.SUCCESS);
242 public Status update(String currentPassword, String newPassword, List<String> newRoles) {
244 // To make any changes to a user configured profile, current password
245 // must always be provided
246 if (!this.password.equals(hash(this.salt, currentPassword))) {
247 return new Status(StatusCode.BADREQUEST, "Current password is incorrect");
250 // Create a new object with the proposed modifications
251 UserConfig proposed = new UserConfig();
252 proposed.user = this.user;
253 proposed.password = (newPassword == null)? this.password : hash(this.salt, newPassword);
254 proposed.roles = (newRoles == null)? this.roles : newRoles;
257 Status status = proposed.validate();
258 if (!status.isSuccess()) {
262 // Accept the modifications
263 this.user = proposed.user;
264 this.password = proposed.password;
265 this.roles = new ArrayList<String>(proposed.roles);
270 public AuthResponse authenticate(String clearTextPassword) {
271 AuthResponse locResponse = new AuthResponse();
272 if (password.equals(hash(this.salt, clearTextPassword))) {
273 locResponse.setStatus(AuthResultEnum.AUTH_ACCEPT_LOC);
274 locResponse.addData(getRolesString());
276 locResponse.setStatus(AuthResultEnum.AUTH_REJECT_LOC);
281 protected String getRolesString() {
282 StringBuffer buffer = new StringBuffer();
283 if (!roles.isEmpty()) {
284 Iterator<String> iter = roles.iterator();
285 buffer.append(iter.next());
286 while (iter.hasNext()) {
288 buffer.append(iter.next());
291 return buffer.toString();
294 private static byte[] concatenate(byte[] salt, String password) {
295 byte[] messageArray = password.getBytes();
296 byte[] concatenation = new byte[salt.length + password.length()];
297 System.arraycopy(salt, 0, concatenation, 0, salt.length);
298 System.arraycopy(messageArray, 0, concatenation, salt.length, messageArray.length);
299 return concatenation;
302 private static String hash(byte[] salt, String message) {
303 if (message == null) {
304 log.warn("Password hash requested but empty or no password provided");
307 if (salt == null || salt.length == 0) {
308 log.warn("Password hash requested but empty or no salt provided");
312 // Concatenate salt and password
313 byte[] messageArray = message.getBytes();
314 byte[] concatenation = new byte[salt.length + message.length()];
315 System.arraycopy(salt, 0, concatenation, 0, salt.length);
316 System.arraycopy(messageArray, 0, concatenation, salt.length, messageArray.length);
318 UserConfig.oneWayFunction.reset();
319 return HexEncode.bytesToHexString(UserConfig.oneWayFunction.digest(concatenate(salt, message)));
323 * Returns UserConfig instance populated with the passed parameters. It does
324 * not run any checks on the passed parameters.
329 * the plain text password
332 * @return the UserConfig object populated with the passed parameters. No
333 * validity check is run on the input parameters.
335 public static UserConfig getUncheckedUserConfig(String userName, String password, List<String> roles) {
336 UserConfig config = new UserConfig();
337 config.user = userName;
338 config.salt = BitBufferHelper.toByteArray(randomGenerator.nextLong());
339 config.password = hash(config.salt, password);
340 config.roles = roles;