9232b1c849e284a0e50b561f0943da5f368c25a6
[aai/aai-common.git] / aai-els-onap-logging / src / main / java / org / onap / aai / util / AAIApplicationConfig.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai.util;
22
23 import org.apache.commons.io.IOUtils;
24 import org.eclipse.jetty.util.security.Password;
25 import org.onap.aai.exceptions.AAIException;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.charset.Charset;
34 import java.util.Properties;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37
38 public class AAIApplicationConfig {
39
40     private static final Logger LOGGER = LoggerFactory.getLogger(AAIApplicationConfig.class);
41     private static String GLOBAL_PROP_FILE_NAME = "application.properties";
42     private static final String SERVER_CERTS_LOCATION_PROP_NAME = "server.certs.location";
43     private static final String PASSPHRASSES_FILENAME = ".passphrases";
44     private static final String PASSWORD_FILENAME = ".password";
45     private static final String TRUSTSTORE_PASSWORD_PROP_NAME = "cadi_truststore_password";
46     public static final String SERVER_SSL_KEYSTORE_PROP_NAME = "server.ssl.key-store";
47     public static final String SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME = "server.ssl.key-store.pkcs12";
48     public static final String SERVER_SSL_TRUSTSTORE_PROP_NAME = "server.ssl.trust-store";
49     public static final String TRUSTSTORE_PASSWORD_NAME = "server.ssl.trust-store-password";
50     public static final String KEYSTORE_PASSWORD_NAME = "server.ssl.key-store-password";
51     private static Properties serverProps;
52     private static boolean propsInitialized = false;
53     private static String TRUSTSTORE_PASSWORD = null;
54     private static String KEYSTORE_PASSWORD = null;
55     private static final String PROPERTY_REGEX = "\\$\\{([^\\$\\{\\}]+)\\}";
56
57     /**
58      * Instantiates a new AAI config.
59      */
60     // Don't instantiate
61     private AAIApplicationConfig() {
62     }
63
64     /**
65      * Inits the.
66      *
67      * @throws AAIException the AAI exception
68      */
69     public synchronized static void init() {
70
71         LOGGER.info("Initializing AAIApplicationConfig");
72         AAIApplicationConfig.reloadConfig();
73     }
74
75     /**
76      * Reload config.
77      */
78     public synchronized static void reloadConfig() {
79
80         Properties newServerProps = new Properties();
81         LOGGER.debug("Reloading config from " + GLOBAL_PROP_FILE_NAME);
82
83         try {
84             InputStream is = AAIApplicationConfig.class.getClassLoader().getResourceAsStream(GLOBAL_PROP_FILE_NAME);
85             newServerProps.load(is);
86             propsInitialized = true;
87             serverProps = newServerProps;
88             TRUSTSTORE_PASSWORD = retrieveTruststorePassword();
89             KEYSTORE_PASSWORD = retrieveKeystorePassword();
90         } catch (Exception fnfe) {
91             final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
92             LOGGER.info("Unable to find the application.properties from filesystem so using file in jar");
93             if (is != null) {
94                 try {
95                     newServerProps.load(is);
96                     serverProps = newServerProps;
97                     TRUSTSTORE_PASSWORD = retrieveTruststorePassword();
98                     KEYSTORE_PASSWORD = retrieveKeystorePassword();
99                 } catch (IOException e) {
100                     LOGGER.warn("Encountered IO Exception during loading of props from inputstream", e);
101                 }
102             } else {
103                 LOGGER.error("Expected to find the properties file in the jar but unable to find it");
104             }
105         }
106     }
107
108     /**
109      * Gets the key value
110      *
111      * @param key          the key
112      * @param defaultValue the default value
113      * @return the string
114      */
115     public static String get(String key, String defaultValue) {
116         String result = defaultValue;
117         try {
118             result = get(key);
119         } catch (AAIException a) {
120         }
121         if (result == null || result.isEmpty()) {
122             result = defaultValue;
123         }
124         return (result);
125     }
126
127     /**
128      * Gets the key value
129      *
130      * @param key the key
131      * @return the string
132      * @throws AAIException the AAI exception
133      */
134     public static String get(String key) throws AAIException {
135         String response = null;
136
137         if (!propsInitialized || (serverProps == null)) {
138             reloadConfig();
139         }
140
141         if ((key.endsWith("password") || key.endsWith("passwd") || key.endsWith("apisecret"))
142                 && serverProps.containsKey(key + ".x")) {
143             String valx = serverProps.getProperty(key + ".x");
144             return Password.deobfuscate(valx);
145         }
146
147         if (!serverProps.containsKey(key)) {
148             throw new AAIException("AAI_4005", "Property key " + key + " cannot be found");
149         } else {
150             response = serverProps.getProperty(key);
151             if (response == null || response.isEmpty()) {
152                 throw new AAIException("AAI_4005", "Property key " + key + " is null or empty");
153             }
154             response = replaceProperties(response);
155         }
156         return response;
157     }
158
159     /**
160      * Gets the keystore path
161      *
162      * @return the string
163      * @throws AAIException the AAI exception
164      */
165     public static String getKeystore() throws AAIException {
166         return (get(SERVER_SSL_KEYSTORE_PROP_NAME));
167     }
168     /**
169      * Gets the PKCS12 keystore path
170      *
171      * @return the string
172      * @throws AAIException the AAI exception
173      */
174     public static String getKeystorePkcs12() throws AAIException {
175         return (get(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME));
176     }
177     /**
178      * Gets the keystore path
179      *
180      * @return the string
181      * @throws AAIException the AAI exception
182      */
183     public static String getTruststore() throws AAIException {
184         return (get(SERVER_SSL_TRUSTSTORE_PROP_NAME));
185     }
186
187     /**
188      * Retrieve the keystore password
189      *
190      * @return the password
191      */
192     private static String retrieveKeystorePassword() {
193         String certPath = serverProps.getProperty(SERVER_CERTS_LOCATION_PROP_NAME);
194         if (certPath == null) {
195             return null;
196         }
197         try {
198             certPath = replaceProperties(certPath);
199         }
200         catch (AAIException e) {
201             return null;
202         }
203         return (retrieveKeystorePasswordWithCertPath(certPath));
204     }
205     /**
206      * Retrieve the keystore password
207      *
208      * @return the password
209      */
210     private static String retrieveKeystorePasswordWithCertPath(String certPath) {
211
212         File passwordFile = null;
213         InputStream passwordStream = null;
214         String keystorePassword = null;
215
216         // Override the passwords from application.properties if we find AAF certman files
217         try {
218             passwordFile = new File(certPath + PASSWORD_FILENAME);
219             passwordStream = new FileInputStream(passwordFile);
220             keystorePassword = IOUtils.toString(passwordStream, Charset.defaultCharset());
221             if (keystorePassword != null) {
222                 keystorePassword = keystorePassword.trim();
223             }
224
225         } catch (IOException e) {
226             LOGGER.warn("Not using AAF Certman password file, e=" + e.getMessage());
227         } catch (NullPointerException n) {
228             LOGGER.warn("Not using AAF Certman passphrases file, e=" + n.getMessage());
229         } finally {
230             if (passwordStream != null) {
231                 try {
232                     passwordStream.close();
233                 } catch (Exception e) {
234                 }
235             }
236         }
237         return keystorePassword;
238     }
239     /**
240      * Get the keystore password
241      *
242      * @return the password
243      */
244     public static String getKeystorePassword() {
245         return (KEYSTORE_PASSWORD);
246     }
247     /**
248      * Gets the truststore password
249      *
250      * @return the password
251      */
252     private static String retrieveTruststorePasswordWithCertPath(String certPath) {
253
254         File passphrasesFile = null;
255         InputStream passphrasesStream = null;
256         String truststorePassword = null;
257         try {
258             passphrasesFile = new File(certPath + PASSPHRASSES_FILENAME);
259             passphrasesStream = new FileInputStream(passphrasesFile);
260
261
262             Properties passphrasesProps = new Properties();
263             passphrasesProps.load(passphrasesStream);
264             truststorePassword = passphrasesProps.getProperty(TRUSTSTORE_PASSWORD_PROP_NAME);
265             if (truststorePassword != null) {
266                 truststorePassword = truststorePassword.trim();
267             }
268
269         } catch (IOException e) {
270             LOGGER.warn("Not using AAF Certman passphrases file, e=" + e.getMessage());
271         } catch (NullPointerException n) {
272             LOGGER.warn("Not using AAF Certman passphrases file, e=" + n.getMessage());
273         } finally {
274             if (passphrasesStream != null) {
275                 try {
276                     passphrasesStream.close();
277                 } catch (Exception e) {
278                 }
279             }
280         }
281
282         return truststorePassword;
283     }
284     /**
285      * Gets the truststore password
286      *
287      * @return the password
288      */
289     private static String retrieveTruststorePassword() {
290         String certPath = serverProps.getProperty(SERVER_CERTS_LOCATION_PROP_NAME);
291         if (certPath == null) {
292             return null;
293         }
294         try {
295             certPath = replaceProperties(certPath);
296         }
297         catch (AAIException e) {
298             return null;
299         }
300         return (retrieveTruststorePasswordWithCertPath(certPath));
301     }
302
303     /**
304      * Get the trustore password
305      *
306      * @return the password
307      */
308     public static String getTruststorePassword() {
309         return (TRUSTSTORE_PASSWORD);
310     }
311
312     /**
313      * Gets the int value for the key.
314      *
315      * @param key the key
316      * @return the int
317      * @throws AAIException the AAI exception
318      */
319     public static int getInt(String key) throws AAIException {
320         return Integer.parseInt(AAIApplicationConfig.get(key));
321     }
322
323     /**
324      * Gets the int.
325      *
326      * @param key the key
327      * @return the int
328      */
329     public static int getInt(String key, String value) {
330         return Integer.parseInt(AAIApplicationConfig.get(key, value));
331     }
332
333     /**
334      * Gets the server props.
335      *
336      * @return the server props
337      */
338     public static Properties getServerProps() {
339         return serverProps;
340     }
341
342     /**
343      * Check if a null or an Empty string is passed in.
344      *
345      * @param s the s
346      * @return boolean
347      */
348     public static boolean isEmpty(String s) {
349         return (s == null || s.length() == 0);
350     }
351
352     private static String replaceProperties(String originalValue) throws AAIException {
353         final Pattern p = Pattern.compile(PROPERTY_REGEX);
354         Matcher m = p.matcher(originalValue);
355         /*if (!m.matches()) {
356             return originalValue;
357         }*/
358         StringBuffer sb = new StringBuffer();
359         while(m.find()) {
360             String text = m.group(1);
361             String replacement = get(text);
362             m.appendReplacement(sb, replacement);
363         }
364         m.appendTail(sb);
365         return(sb.toString());
366     }
367
368     public static Properties retrieveKeystoreProps() throws AAIException {
369
370         Properties props = new Properties();
371         String truststorePath = System.getProperty(SERVER_SSL_TRUSTSTORE_PROP_NAME);
372         String truststorePassword = System.getProperty(TRUSTSTORE_PASSWORD_NAME);
373         String keystorePath = System.getProperty(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME);
374         String keystorePassword = System.getProperty(KEYSTORE_PASSWORD_NAME);
375         String certLocation = System.getProperty(SERVER_CERTS_LOCATION_PROP_NAME);
376
377         if (truststorePath == null || truststorePath.isEmpty()){
378             truststorePath = AAIApplicationConfig.getTruststore();
379         }
380         if (truststorePath != null) {
381             props.setProperty(SERVER_SSL_TRUSTSTORE_PROP_NAME, truststorePath);
382         }
383         if (truststorePassword == null || truststorePassword.isEmpty()) {
384             if (certLocation != null && (!certLocation.isEmpty())) {
385                 truststorePassword = AAIApplicationConfig.retrieveTruststorePasswordWithCertPath(certLocation);
386             }
387             else {
388                 truststorePassword = AAIApplicationConfig.getTruststorePassword();
389             }
390
391         }
392         if (truststorePassword != null) {
393             props.setProperty(TRUSTSTORE_PASSWORD_NAME, truststorePassword);
394         }
395         if (keystorePath == null || keystorePath.isEmpty()){
396             keystorePath = AAIApplicationConfig.getKeystorePkcs12();
397         }
398         if (keystorePath != null) {
399             props.setProperty(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME, keystorePath);
400         }
401         if (keystorePassword == null || keystorePassword.isEmpty()){
402             if (certLocation != null && (!certLocation.isEmpty())) {
403                 keystorePassword = AAIApplicationConfig.retrieveKeystorePasswordWithCertPath(certLocation);
404             }
405             else {
406                 keystorePassword = AAIApplicationConfig.getKeystorePassword();
407             }
408         }
409         if (keystorePassword != null) {
410             props.setProperty(KEYSTORE_PASSWORD_NAME, keystorePassword);
411         }
412         return(props);
413     }
414 }