Fix vulnerability in code where password is
[music.git] / jar / src / main / java / org / onap / music / main / CachingUtil.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  * 
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22
23 package org.onap.music.main;
24
25 import java.util.Arrays;
26 import java.util.Calendar;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.Map;
30 import java.util.UUID;
31 import javax.ws.rs.core.HttpHeaders;
32 import javax.ws.rs.core.MediaType;
33 import org.apache.commons.codec.binary.Base64;
34 import org.apache.commons.jcs.JCS;
35 import org.apache.commons.jcs.access.CacheAccess;
36 import org.codehaus.jackson.map.ObjectMapper;
37 import org.mindrot.jbcrypt.BCrypt;
38 import org.onap.music.datastore.PreparedQueryObject;
39 import org.onap.music.datastore.jsonobjects.AAFResponse;
40 import org.onap.music.eelf.logging.EELFLoggerDelegate;
41 import org.onap.music.eelf.logging.format.AppMessages;
42 import org.onap.music.eelf.logging.format.ErrorSeverity;
43 import org.onap.music.eelf.logging.format.ErrorTypes;
44 import org.onap.music.exceptions.MusicServiceException;
45
46 import com.att.eelf.configuration.EELFLogger;
47 import com.datastax.driver.core.DataType;
48 import com.datastax.driver.core.ResultSet;
49 import com.datastax.driver.core.Row;
50 import com.datastax.driver.core.exceptions.InvalidQueryException;
51 import com.sun.jersey.api.client.Client;
52 import com.sun.jersey.api.client.ClientResponse;
53 import com.sun.jersey.api.client.WebResource;
54
55 /**
56  * All Caching related logic is handled by this class and a schedule cron runs to update cache.
57  * 
58  * @author Vikram
59  *
60  */
61 public class CachingUtil implements Runnable {
62
63     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
64
65     private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
66     private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
67     private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
68     private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
69     private static Map<String, Number> userAttempts = new HashMap<>();
70     private static Map<String, Calendar> lastFailedTime = new HashMap<>();
71
72     public boolean isCacheRefreshNeeded() {
73         if (aafCache.get("initBlankMap") == null)
74             return true;
75         return false;
76     }
77
78     public void initializeMusicCache() {
79         logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
80         musicCache.put("isInitialized", "true");
81     }
82
83     public void initializeAafCache() throws MusicServiceException {
84         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
85
86         String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
87         PreparedQueryObject pQuery = new PreparedQueryObject();
88         pQuery.appendQueryString(query);
89         try {
90             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
91         } catch (Exception e1) {
92             logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
93             e1.printStackTrace();
94         }
95         ResultSet rs = MusicCore.get(pQuery);
96         Iterator<Row> it = rs.iterator();
97         Map<String, String> map = null;
98         while (it.hasNext()) {
99             Row row = it.next();
100             String nameSpace = row.getString("keyspace_name");
101             String userId = row.getString("username");
102             String password = row.getString("password");
103             String keySpace = row.getString("application_name");
104             try {
105                 userAttempts.put(nameSpace, 0);
106                 AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
107                 if (responseObj.getNs().size() > 0) {
108                     map = new HashMap<>();
109                     map.put(userId, password);
110                     aafCache.put(nameSpace, map);
111                     musicCache.put(keySpace, nameSpace);
112                     logger.debug("Cronjob: Cache Updated with AAF response for namespace "
113                                     + nameSpace);
114                 }
115             } catch (Exception e) {
116                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
117                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
118                 e.printStackTrace();
119             }
120         }
121
122     }
123
124     @Override
125     public void run() {
126         logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
127         try {
128             initializeAafCache();
129         } catch (MusicServiceException e) {
130             logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
131         }
132     }
133
134     public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
135                     String keySpace) throws Exception {
136
137         if (aafCache.get(nameSpace) != null) {
138             if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
139                 logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
140             } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
141                 logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
142                 // reset invalid attempts to 0
143                 userAttempts.put(nameSpace, 0);
144                 return true;
145             } else {
146                 // call AAF update cache with new password
147                 if (userAttempts.get(nameSpace) == null)
148                     userAttempts.put(nameSpace, 0);
149                 if ((Integer) userAttempts.get(nameSpace) >= 3) {
150                     logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
151                     logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
152                     Calendar calendar = Calendar.getInstance();
153                     long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
154                     logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
155                     if( delayTime > 120000) {
156                         logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
157                         userAttempts.put(nameSpace, 0);
158                     } else {
159                         logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
160                         throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
161                     }
162                 }
163                 logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
164                 logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
165             }
166         }
167
168         AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
169         if (responseObj.getNs().size() > 0) {
170             if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
171                 //Map<String, String> map = new HashMap<>();
172                 //map.put(userId, password);
173                 //aafCache.put(nameSpace, map);
174                 return true;
175             }
176         }
177         logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
178         return false;
179     }
180
181     private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
182                     throws Exception {
183         if (MusicUtil.getAafEndpointUrl() == null) {
184             logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
185             throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
186         }
187         Client client = Client.create();
188         // WebResource webResource =
189         // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
190         WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
191         String plainCreds = userId + ":" + password;
192         byte[] plainCredsBytes = plainCreds.getBytes();
193         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
194         String base64Creds = new String(base64CredsBytes);
195
196         ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
197                         .header("Authorization", "Basic " + base64Creds)
198                         .header("content-type", "application/json").get(ClientResponse.class);
199         if (response.getStatus() != 200) {
200             if (userAttempts.get(nameSpace) == null)
201                 userAttempts.put(nameSpace, 0);
202             if ((Integer) userAttempts.get(nameSpace) >= 2) {
203                 lastFailedTime.put(nameSpace, Calendar.getInstance());
204                 userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
205                 throw new Exception(
206                                 "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
207             }
208             userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
209             throw new Exception(
210                             "Unable to authenticate. Please check the AAF credentials against namespace.");
211             // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
212             // for specific time.
213         }
214         response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
215                         Arrays.asList(MediaType.APPLICATION_JSON));
216         // AAFResponse output = response.getEntity(AAFResponse.class);
217         response.bufferEntity();
218         String x = response.getEntity(String.class);
219         AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);
220         
221         return responseObj;
222     }
223
224     public static void updateMusicCache(String keyspace, String nameSpace) {
225         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
226         musicCache.put(keyspace, nameSpace);
227     }
228
229     public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
230         logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
231         Map<String, String> map = new HashMap<>();
232         map.put(userId, password);
233         musicValidateCache.put(nameSpace, map);
234     }
235     
236     public static void updateisAAFCache(String namespace, String isAAF) {
237         appNameCache.put(namespace, isAAF);
238     }
239
240     public static String isAAFApplication(String namespace) throws MusicServiceException {
241         String isAAF = appNameCache.get(namespace);
242         if (isAAF == null) {
243             PreparedQueryObject pQuery = new PreparedQueryObject();
244             pQuery.appendQueryString(
245                             "SELECT is_aaf from admin.keyspace_master where application_name = '"
246                                             + namespace + "' allow filtering");
247             Row rs = null;
248             try {
249                 rs = MusicCore.get(pQuery).one();
250             } catch(InvalidQueryException e) {
251                 logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
252                 throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
253             }
254             try {
255                 isAAF = String.valueOf(rs.getBool("is_aaf"));
256                 if(isAAF != null)
257                     appNameCache.put(namespace, isAAF);
258             } catch (Exception e) {
259                 logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
260                 e.printStackTrace();
261             }
262         }
263         return isAAF;
264     }
265
266     public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
267         String uuid = null;
268         if (uuid == null) {
269             PreparedQueryObject pQuery = new PreparedQueryObject();
270             pQuery.appendQueryString(
271                             "SELECT uuid from admin.keyspace_master where keyspace_name = '"
272                                             + keyspace + "' allow filtering");
273             Row rs = MusicCore.get(pQuery).one();
274             try {
275                 uuid = rs.getUUID("uuid").toString();
276             } catch (Exception e) {
277                 logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
278                 e.printStackTrace();
279             }
280         }
281         return uuid;
282     }
283
284     public static String getAppName(String keyspace) throws MusicServiceException {
285         String appName = null;
286         PreparedQueryObject pQuery = new PreparedQueryObject();
287         pQuery.appendQueryString(
288                         "SELECT application_name from admin.keyspace_master where keyspace_name = '"
289                                         + keyspace + "' allow filtering");
290         Row rs = MusicCore.get(pQuery).one();
291         try {
292             appName = rs.getString("application_name");
293         } catch (Exception e) {
294             logger.error(EELFLoggerDelegate.errorLogger,  e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
295             e.printStackTrace();
296         }
297         return appName;
298     }
299
300     public static String generateUUID() {
301         String uuid = UUID.randomUUID().toString();
302         logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
303         return uuid;
304     }
305
306     public static Map<String, Object> validateRequest(String nameSpace, String userId,
307                     String password, String keyspace, String aid, String operation) {
308         Map<String, Object> resultMap = new HashMap<>();
309         if (!"createKeySpace".equals(operation)) {
310             if (nameSpace == null) {
311                 resultMap.put("Exception", "Application namespace is mandatory.");
312             }
313         }
314         return resultMap;
315
316     }
317
318     public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
319         Map<String, Object> resultMap = new HashMap<>();
320         if (ns == null || userId == null || password == null) {
321             logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
322             logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing.");
323             resultMap.put("Exception",
324                             "One or more required headers appName(ns), userId, password is missing. Please check.");
325             return resultMap;
326         }
327         PreparedQueryObject queryObject = new PreparedQueryObject();
328         queryObject.appendQueryString(
329                         "select * from admin.keyspace_master where application_name = ? allow filtering");
330         try {
331             queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
332         } catch(Exception e) {
333             resultMap.put("Exception",
334                     "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
335             return resultMap;
336         }
337         Row rs = null;
338         try {
339             rs = MusicCore.get(queryObject).one();
340         } catch (MusicServiceException e) {
341             // TODO Auto-generated catch block
342             e.printStackTrace();
343             resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
344             return resultMap;
345         } catch (InvalidQueryException e) {
346             logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
347             resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
348             return resultMap;
349         }
350         if (rs == null) {
351             logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
352             resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
353         } else {
354             if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
355                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
356                 logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
357                 resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
358                 return resultMap;
359             }
360         }
361         return resultMap;
362     }
363
364     public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
365            String keyspace) {
366         Map<String, Object> resultMap = new HashMap<>();
367         String pwd = null;
368         if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null) 
369                 && (musicValidateCache.get(nameSpace).containsKey(userId))) {
370             if(!musicCache.get(keyspace).equals(nameSpace)) {
371                 resultMap.put("Exception", "Namespace and keyspace doesn't match");
372                 return resultMap;
373             }
374             if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
375                 resultMap.put("Exception", "Namespace, userId and password doesn't match");
376                 return resultMap;
377             }
378             return resultMap;
379         }
380         PreparedQueryObject queryObject = new PreparedQueryObject();
381         queryObject.appendQueryString(
382                         "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
383         try {
384             queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
385         } catch (Exception e) {
386             e.printStackTrace();
387         }
388         Row rs = null;
389         try {
390             rs = MusicCore.get(queryObject).one();
391         } catch (MusicServiceException e) {
392             e.printStackTrace();
393             resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
394             return resultMap;
395         }
396         if(rs == null) {
397             resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
398             return resultMap;
399         }
400         else {
401             String user = rs.getString("username");
402             pwd = rs.getString("password");
403             String ns = rs.getString("application_name");
404             if(!ns.equals(nameSpace)) {
405             resultMap.put("Exception", "Namespace and keyspace doesn't match");
406             return resultMap;
407             }
408             if(!user.equals(userId)) {
409                 resultMap.put("Exception", "Invalid userId :"+userId);
410                 return resultMap;
411             }
412             if(!BCrypt.checkpw(password, pwd)) {
413                 resultMap.put("Exception", "Invalid password");
414                 return resultMap;
415             }
416         }
417         CachingUtil.updateMusicCache(keyspace, nameSpace);
418         CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
419         return resultMap;
420     }
421 }