Migrate bundles' configuration mgmt to ConfigurationService
[controller.git] / opendaylight / usermanager / api / src / main / java / org / opendaylight / controller / usermanager / UserConfig.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.usermanager;
10
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;
21
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;
26
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;
35
36 /**
37  * Configuration Java Object which represents a Local AAA user configuration
38  * information for User Manager.
39  */
40 @XmlRootElement
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;
53
54     static {
55         try {
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,
59                     e.getMessage()));
60         }
61         UserConfig.randomGenerator = new SecureRandom(BitBufferHelper.toByteArray(System.currentTimeMillis()));
62     }
63
64     /**
65      * User Id
66      */
67     @XmlElement
68     protected String user;
69
70     /**
71      * List of roles a user can have
72      * example
73      * System-Admin
74      * Network-Admin
75      * Network-Operator
76      */
77     @XmlElement
78     protected List<String> roles;
79
80     /**
81      * Password
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.
85      */
86     @XmlElement
87     private String password;
88
89     private byte[] salt;
90
91
92
93     public UserConfig() {
94     }
95
96     /**
97      * Construct a UserConfig object and takes care of hashing the user password
98      *
99      * @param user
100      *            the user name
101      * @param password
102      *            the plain text password
103      * @param roles
104      *            the list of roles
105      */
106     public UserConfig(String user, String password, List<String> roles) {
107         this.user = user;
108
109         /*
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.
115          */
116         if (validateClearTextPassword(password).isSuccess()) {
117             this.salt = BitBufferHelper.toByteArray(randomGenerator.nextLong());
118             this.password = hash(salt, password);
119         } else {
120             this.salt = null;
121             this.password = BAD_PASSWORD;
122         }
123
124         this.roles = (roles == null) ? Collections.<String>emptyList() : new ArrayList<String>(roles);
125     }
126
127     public String getUser() {
128         return user;
129     }
130
131     public String getPassword() {
132         return password;
133     }
134
135     public List<String> getRoles() {
136         return new ArrayList<String>(roles);
137     }
138
139     @Override
140     public int hashCode() {
141         final int prime = 31;
142         int result = 1;
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());
147         return result;
148     }
149
150     @Override
151     public boolean equals(Object obj) {
152         if (this == obj) {
153             return true;
154         }
155         if (obj == null) {
156             return false;
157         }
158         if (getClass() != obj.getClass()) {
159             return false;
160         }
161         UserConfig other = (UserConfig) obj;
162         if (password == null) {
163             if (other.password != null) {
164                 return false;
165             }
166         } else if (!password.equals(other.password)) {
167             return false;
168         }
169         if (roles == null) {
170             if (other.roles != null) {
171                 return false;
172             }
173         } else if (!roles.equals(other.roles)) {
174             return false;
175         }
176         if (user == null) {
177             if (other.user != null) {
178                 return false;
179             }
180         } else if (!user.equals(other.user)) {
181             return false;
182         }
183         return true;
184     }
185
186     @Override
187     public String toString() {
188         return "UserConfig[user=" + user + ", password=" + password + ", roles=" + roles +"]";
189     }
190
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");
199         }
200         if (validCheck.isSuccess()) {
201             validCheck = validateRoles();
202         }
203         return validCheck;
204     }
205
206     protected Status validateUsername() {
207         if (user == null || user.isEmpty()) {
208             return new Status(StatusCode.BADREQUEST, "Username cannot be empty");
209         }
210
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 ./#%;?\\");
217         }
218
219         return new Status(StatusCode.SUCCESS);
220     }
221
222     private Status validateClearTextPassword(String password) {
223         if (password == null || password.isEmpty()) {
224             return new Status(StatusCode.BADREQUEST, "Password cannot be empty");
225         }
226
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");
231         }
232         return new Status(StatusCode.SUCCESS);
233     }
234
235     protected Status validateRoles() {
236         if (roles == null || roles.isEmpty()) {
237             return new Status(StatusCode.BADREQUEST, "No role specified");
238         }
239         return new Status(StatusCode.SUCCESS);
240     }
241
242     public Status update(String currentPassword, String newPassword, List<String> newRoles) {
243
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");
248         }
249
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;
255
256         // Validate it
257         Status status = proposed.validate();
258         if (!status.isSuccess()) {
259             return status;
260         }
261
262         // Accept the modifications
263         this.user = proposed.user;
264         this.password = proposed.password;
265         this.roles = new ArrayList<String>(proposed.roles);
266
267         return status;
268     }
269
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());
275         } else {
276             locResponse.setStatus(AuthResultEnum.AUTH_REJECT_LOC);
277         }
278         return locResponse;
279     }
280
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()) {
287                 buffer.append(" ");
288                 buffer.append(iter.next());
289             }
290         }
291         return buffer.toString();
292     }
293
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;
300     }
301
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");
305             return message;
306         }
307         if (salt == null || salt.length == 0) {
308             log.warn("Password hash requested but empty or no salt provided");
309             return message;
310         }
311
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);
317
318         UserConfig.oneWayFunction.reset();
319         return HexEncode.bytesToHexString(UserConfig.oneWayFunction.digest(concatenate(salt, message)));
320     }
321
322     /**
323      * Returns UserConfig instance populated with the passed parameters. It does
324      * not run any checks on the passed parameters.
325      *
326      * @param userName
327      *            the user name
328      * @param password
329      *            the plain text password
330      * @param roles
331      *            the list of roles
332      * @return the UserConfig object populated with the passed parameters. No
333      *         validity check is run on the input parameters.
334      */
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;
341         return config;
342     }
343 }