1 /*******************************************************************************
2 * ============LICENSE_START=======================================================
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 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ============LICENSE_END=========================================================
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 *******************************************************************************/
22 package com.att.dmf.mr.security.impl;
24 import java.text.ParseException;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
28 import javax.servlet.http.HttpServletRequest;
30 import com.att.dmf.mr.beans.DMaaPContext;
31 import com.att.dmf.mr.security.DMaaPAuthenticator;
32 import com.att.eelf.configuration.EELFLogger;
33 import com.att.eelf.configuration.EELFManager;
34 import com.att.nsa.configs.ConfigDbException;
35 import com.att.nsa.drumlin.till.data.sha1HmacSigner;
36 import com.att.nsa.security.NsaApiKey;
37 import com.att.nsa.security.db.NsaApiDb;
40 * This authenticator handles an AWS-like authentication, originally used by the
41 * Cambria server (the API server for UEB).
47 public class DMaaPOriginalUebAuthenticator<K extends NsaApiKey> implements DMaaPAuthenticator<K> {
49 * constructor initialization
52 * @param requestTimeWindowMs
54 public DMaaPOriginalUebAuthenticator(NsaApiDb<K> db, long requestTimeWindowMs) {
56 fRequestTimeWindowMs = requestTimeWindowMs;
64 public boolean qualify(HttpServletRequest req) {
65 // accept anything that comes in with X-(Cambria)Auth in the header
66 final String xAuth = getFirstHeader(req, new String[] { "X-CambriaAuth", "X-Auth" });
71 * method for authentication
76 public K isAuthentic(HttpServletRequest req) {
77 final String remoteAddr = req.getRemoteAddr();
78 // Cambria originally used "Cambria..." headers, but as the API key
80 // general, we take either form.
81 final String xAuth = getFirstHeader(req, new String[] { "X-CambriaAuth", "X-Auth" });
82 final String xDate = getFirstHeader(req, new String[] { "X-CambriaDate", "X-Date" });
84 final String httpDate = req.getHeader("Date");
86 final String xNonce = getFirstHeader(req, new String[] { "X-Nonce" });
87 return authenticate(remoteAddr, xAuth, xDate, httpDate, xNonce);
91 * Authenticate a user's request. This method returns the API key if the
92 * user is authentic, null otherwise.
99 * @return an api key record, or null
101 public K authenticate(String remoteAddr, String xAuth, String xDate, String httpDate, String nonce) {
103 authLog("No X-Auth header on request", remoteAddr);
107 final String[] xAuthParts = xAuth.split(":");
108 if (xAuthParts.length != 2) {
109 authLog("Bad X-Auth header format (" + xAuth + ")", remoteAddr);
114 // get the api key and signature
115 final String clientApiKey = xAuthParts[0];
116 final String clientApiHash = xAuthParts[1];
117 if (clientApiKey.length() == 0 || clientApiHash.length() == 0) {
118 authLog("Bad X-Auth header format (" + xAuth + ")", remoteAddr);
121 // if the user provided X-Date, use that. Otherwise, go for Date
122 final String dateString = xDate != null ? xDate : httpDate;
123 final Date clientDate = getClientDate(dateString);
124 if (clientDate == null) {
125 authLog("Couldn't parse client date '" + dateString + "'. Preferring X-Date over Date.", remoteAddr);
128 // check the time range
129 final long nowMs = System.currentTimeMillis();
130 final long diffMs = Math.abs(nowMs - clientDate.getTime());
131 if (diffMs > fRequestTimeWindowMs) {
132 authLog("Client date is not in acceptable range of server date. Client:" + clientDate.getTime()
133 + ", Server: " + nowMs + ", Threshold: " + fRequestTimeWindowMs + ".", remoteAddr);
138 apiRecord = fDb.loadApiKey(clientApiKey);
139 if (apiRecord == null) {
140 authLog("No such API key " + clientApiKey, remoteAddr);
143 } catch (ConfigDbException e) {
144 authLog("Couldn't load API key " + clientApiKey + ": " + e.getMessage(), remoteAddr);
147 // make the signed content
148 final StringBuilder sb = new StringBuilder();
149 sb.append(dateString);
154 final String signedContent = sb.toString();
155 // now check the signed date string
156 final String serverCalculatedSignature = sha1HmacSigner.sign(signedContent, apiRecord.getSecret());
157 if (serverCalculatedSignature == null || !serverCalculatedSignature.equals(clientApiHash)) {
158 authLog("Signatures don't match. Rec'd " + clientApiHash + ", expect " + serverCalculatedSignature + ".",
162 authLog("authenticated " + apiRecord.getKey(), remoteAddr);
167 * Get the first value of the first existing header from the headers list
171 * @return a header value, or null if none exist
173 private static String getFirstHeader(HttpServletRequest req, String[] headers) {
174 for (String header : headers) {
175 final String result = req.getHeader(header);
183 * Parse the date string into a Date using one of the supported date
187 * @return a date, or null
189 private static Date getClientDate(String dateString) {
190 if (dateString == null) {
196 for (String dateFormat : kDateFormats) {
197 final SimpleDateFormat parser = new SimpleDateFormat(dateFormat, java.util.Locale.US);
198 if (!dateFormat.contains("z") && !dateFormat.contains("Z")) {
199 parser.setTimeZone(TIMEZONE_GMT);
203 result = parser.parse(dateString);
205 } catch (ParseException e) {
206 // presumably wrong format
212 private static void authLog(String msg, String remoteAddr) {
213 log.info("AUTH-LOG(" + remoteAddr + "): " + msg);
216 private final NsaApiDb<K> fDb;
217 private final long fRequestTimeWindowMs;
219 private static final java.util.TimeZone TIMEZONE_GMT = java.util.TimeZone.getTimeZone("GMT");
221 private static final String kDateFormats[] =
223 // W3C date format (RFC 3339).
224 "yyyy-MM-dd'T'HH:mm:ssz",
225 "yyyy-MM-dd'T'HH:mm:ssXXX", // as of Java 7, reqd to handle colon in TZ offset
227 // Preferred HTTP date format (RFC 1123).
228 "EEE, dd MMM yyyy HH:mm:ss zzz",
230 // simple unix command line 'date' format
231 "EEE MMM dd HH:mm:ss z yyyy",
233 // Common date format (RFC 822).
234 "EEE, dd MMM yy HH:mm:ss z",
235 "EEE, dd MMM yy HH:mm z",
236 "dd MMM yy HH:mm:ss z",
239 // Obsoleted HTTP date format (ANSI C asctime() format).
240 "EEE MMM dd HH:mm:ss yyyy",
242 // Obsoleted HTTP date format (RFC 1036).
243 "EEEE, dd-MMM-yy HH:mm:ss zzz",
264 // logger declaration
266 private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPOriginalUebAuthenticator.class);
269 // TODO Auto-generated method stub
273 public K authenticate(DMaaPContext ctx) {
288 public void addAuthenticator ( DMaaPAuthenticator<K> a )