New DR AAF certs for elalto branch
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / NodeUtils.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 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  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24
25 package org.onap.dmaap.datarouter.node;
26
27 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
28 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
29 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
30 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
31
32 import com.att.eelf.configuration.EELFLogger;
33 import com.att.eelf.configuration.EELFManager;
34 import java.io.File;
35 import java.io.FileInputStream;
36 import java.io.IOException;
37 import java.net.InetAddress;
38 import java.security.KeyStore;
39 import java.security.KeyStoreException;
40 import java.security.MessageDigest;
41 import java.security.NoSuchAlgorithmException;
42 import java.security.cert.CertificateException;
43 import java.security.cert.X509Certificate;
44 import java.text.SimpleDateFormat;
45 import java.util.Date;
46 import java.util.Enumeration;
47 import java.util.TimeZone;
48 import java.util.UUID;
49 import java.util.zip.GZIPInputStream;
50 import javax.naming.InvalidNameException;
51 import javax.naming.ldap.LdapName;
52 import javax.naming.ldap.Rdn;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletResponse;
55 import org.apache.commons.codec.binary.Base64;
56 import org.apache.commons.lang3.StringUtils;
57 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
58 import org.slf4j.MDC;
59
60 /**
61  * Utility functions for the data router node.
62  */
63 public class NodeUtils {
64
65     private static EELFLogger eelfLogger = EELFManager.getInstance()
66             .getLogger(NodeUtils.class);
67
68     private NodeUtils() {
69     }
70
71     /**
72      * Base64 encode a byte array.
73      *
74      * @param raw The bytes to be encoded
75      * @return The encoded string
76      */
77     public static String base64Encode(byte[] raw) {
78         return (Base64.encodeBase64String(raw));
79     }
80
81     /**
82      * Given a user and password, generate the credentials.
83      *
84      * @param user User name
85      * @param password User password
86      * @return Authorization header value
87      */
88     public static String getAuthHdr(String user, String password) {
89         if (user == null || password == null) {
90             return (null);
91         }
92         return ("Basic " + base64Encode((user + ":" + password).getBytes()));
93     }
94
95     /**
96      * Given a node name, generate the credentials.
97      *
98      * @param node Node name
99      */
100     public static String getNodeAuthHdr(String node, String key) {
101         try {
102             MessageDigest md = MessageDigest.getInstance("SHA");
103             md.update(key.getBytes());
104             md.update(node.getBytes());
105             md.update(key.getBytes());
106             return (getAuthHdr(node, base64Encode(md.digest())));
107         } catch (Exception exception) {
108             eelfLogger
109                     .error("Exception in generating Credentials for given node name:= " + exception.toString(),
110                             exception);
111             return (null);
112         }
113     }
114
115     /**
116      * Given a keystore file and its password, return the value of the CN of the first private key entry with a
117      * certificate.
118      *
119      * @param kstype The type of keystore
120      * @param ksfile The file name of the keystore
121      * @param kspass The password of the keystore
122      * @return CN of the certificate subject or null
123      */
124     public static String getCanonicalName(String kstype, String ksfile, String kspass) {
125         KeyStore ks;
126         try {
127             ks = KeyStore.getInstance(kstype);
128             if (loadKeyStore(ksfile, kspass, ks)) {
129                 return (null);
130             }
131         } catch (Exception e) {
132             setIpAndFqdnForEelf("getCanonicalName");
133             eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_LOAD_ERROR, e, ksfile);
134             return (null);
135         }
136         return (getCanonicalName(ks));
137     }
138
139     /**
140      * Given a keystore, return the value of the CN of the first private key entry with a certificate.
141      *
142      * @param ks The KeyStore
143      * @return CN of the certificate subject or null
144      */
145     public static String getCanonicalName(KeyStore ks) {
146         try {
147             Enumeration<String> aliases = ks.aliases();
148             while (aliases.hasMoreElements()) {
149                 String name = getNameFromSubject(ks, aliases);
150                 if (name != null) {
151                     return name;
152                 }
153             }
154         } catch (Exception e) {
155             eelfLogger.error("NODE0402 Error extracting my name from my keystore file " + e.toString(), e);
156         }
157         return (null);
158     }
159
160     /**
161      * Given a string representation of an IP address, get the corresponding byte array.
162      *
163      * @param ip The IP address as a string
164      * @return The IP address as a byte array or null if the address is invalid
165      */
166     public static byte[] getInetAddress(String ip) {
167         try {
168             return (InetAddress.getByName(ip).getAddress());
169         } catch (Exception exception) {
170             eelfLogger
171                     .error("Exception in generating byte array for given IP address := " + exception.toString(),
172                             exception);
173         }
174         return (null);
175     }
176
177     /**
178      * Given a uri with parameters, split out the feed ID and file ID.
179      */
180     public static String[] getFeedAndFileID(String uriandparams) {
181         int end = uriandparams.length();
182         int index = uriandparams.indexOf('#');
183         if (index != -1 && index < end) {
184             end = index;
185         }
186         index = uriandparams.indexOf('?');
187         if (index != -1 && index < end) {
188             end = index;
189         }
190         end = uriandparams.lastIndexOf('/', end);
191         if (end < 2) {
192             return (null);
193         }
194         index = uriandparams.lastIndexOf('/', end - 1);
195         if (index == -1) {
196             return (null);
197         }
198         return (new String[]{uriandparams.substring(index + 1, end), uriandparams.substring(end + 1)});
199     }
200
201     /**
202      * Escape fields that might contain vertical bar, backslash, or newline by replacing them with backslash p,
203      * backslash e and backslash n.
204      */
205     public static String loge(String string) {
206         if (string == null) {
207             return (string);
208         }
209         return (string.replaceAll("\\\\", "\\\\e").replaceAll("\\|", "\\\\p").replaceAll("\n", "\\\\n"));
210     }
211
212     /**
213      * Undo what loge does.
214      */
215     public static String unloge(String string) {
216         if (string == null) {
217             return (string);
218         }
219         return (string.replaceAll("\\\\p", "\\|").replaceAll("\\\\n", "\n").replaceAll("\\\\e", "\\\\"));
220     }
221
222     /**
223      * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
224      */
225     public static String logts(long when) {
226         return (logts(new Date(when)));
227     }
228
229     /**
230      * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
231      */
232     public static synchronized String logts(Date when) {
233         SimpleDateFormat logDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
234         logDate.setTimeZone(TimeZone.getTimeZone("GMT"));
235         return (logDate.format(when));
236     }
237
238     /** Method prints method name, server FQDN and IP Address of the machine in EELF logs.
239      *
240      * @param method Prints method name in EELF log.
241      */
242     public static void setIpAndFqdnForEelf(String method) {
243         MDC.clear();
244         MDC.put(MDC_SERVICE_NAME, method);
245         try {
246             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
247             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
248         } catch (Exception exception) {
249             eelfLogger
250                     .error("Exception in generating byte array for given IP address := " + exception.toString(),
251                             exception);
252         }
253
254     }
255
256     /** Method sets RequestIs and InvocationId for se in EELF logs.
257      *
258      * @param req Request used to get RequestId and InvocationId.
259      */
260     public static void setRequestIdAndInvocationId(HttpServletRequest req) {
261         String reqId = req.getHeader("X-ONAP-RequestID");
262         if (StringUtils.isBlank(reqId)) {
263             reqId = UUID.randomUUID().toString();
264         }
265         MDC.put(MDC_KEY_REQUEST_ID, reqId);
266         String invId = req.getHeader("X-InvocationID");
267         if (StringUtils.isBlank(invId)) {
268             invId = UUID.randomUUID().toString();
269         }
270         MDC.put("InvocationId", invId);
271     }
272
273     /**
274      * Sends error as response with error code input.
275      */
276     public static void sendResponseError(HttpServletResponse response, int errorCode, EELFLogger intlogger) {
277         try {
278             response.sendError(errorCode);
279         } catch (IOException ioe) {
280             intlogger.error("IOException", ioe);
281         }
282     }
283
284     /**
285      * Method to check to see if file is of type gzip.
286      *
287      * @param file The name of the file to be checked
288      * @return True if the file is of type gzip
289      */
290     public static boolean isFiletypeGzip(File file) {
291         try (FileInputStream fileInputStream = new FileInputStream(file);
292                 GZIPInputStream gzip = new GZIPInputStream(fileInputStream)) {
293
294             return true;
295         } catch (IOException e) {
296             eelfLogger.error("NODE0403 " + file.toString() + " Not in gzip(gz) format: " + e.toString() + e);
297             return false;
298         }
299     }
300
301
302     private static boolean loadKeyStore(String ksfile, String kspass, KeyStore ks)
303             throws NoSuchAlgorithmException, CertificateException {
304         try (FileInputStream fileInputStream = new FileInputStream(ksfile)) {
305             ks.load(fileInputStream, kspass.toCharArray());
306         } catch (IOException ioException) {
307             eelfLogger.error("IOException occurred while opening FileInputStream: " + ioException.getMessage(),
308                     ioException);
309             return true;
310         }
311         return false;
312     }
313
314
315     private static String getNameFromSubject(KeyStore ks, Enumeration<String> aliases) throws KeyStoreException {
316         String alias = aliases.nextElement();
317         if (ks.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
318             X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
319             if (cert != null) {
320                 String subject = cert.getSubjectX500Principal().getName();
321                 try {
322                     LdapName ln = new LdapName(subject);
323                     for (Rdn rdn : ln.getRdns()) {
324                         if (rdn.getType().equalsIgnoreCase("CN")) {
325                             return rdn.getValue().toString();
326                         }
327                     }
328                 } catch (InvalidNameException e) {
329                     eelfLogger.error("No valid CN not found for dr-node cert", e);
330                 }
331             }
332         }
333         return null;
334     }
335 }