diff options
author | vasraz <vasyl.razinkov@est.tech> | 2021-03-22 15:33:06 +0000 |
---|---|---|
committer | Christophe Closset <christophe.closset@intl.att.com> | 2021-03-24 06:59:47 +0000 |
commit | d378c37fbd1ecec7b43394926f1ca32a695e07de (patch) | |
tree | 5c8a085f8732f980d871d966ac49361644efa698 /openecomp-be/backend/openecomp-sdc-security-util | |
parent | a6ae7294ecd336d7e88f915710b08e2658eaee00 (diff) |
Reformat openecomp-be
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech>
Issue-ID: SDC-3449
Change-Id: I13e02322f8e00820cc5a1d85752caaeda9bf10d1
Diffstat (limited to 'openecomp-be/backend/openecomp-sdc-security-util')
12 files changed, 370 insertions, 396 deletions
diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookie.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookie.java index 56a4965381..4627fcee14 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookie.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookie.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,22 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; import java.util.Set; - -public class AuthenticationCookie { +public class AuthenticationCookie { private String userID; private Set<String> roles; private long maxSessionTime; private long currentSessionTime; - public AuthenticationCookie(){ } + public AuthenticationCookie() { + } - public AuthenticationCookie(AuthenticationCookie authenticationCookie){ + public AuthenticationCookie(AuthenticationCookie authenticationCookie) { this.userID = authenticationCookie.userID; this.roles = authenticationCookie.roles; this.maxSessionTime = authenticationCookie.maxSessionTime; @@ -41,10 +40,11 @@ public class AuthenticationCookie { /** * Create new cookie with max_session_time and current_session_time started with same value + * * @param userId */ public AuthenticationCookie(String userId) { - this.userID =userId; + this.userID = userId; long currentTimeMilliSec = System.currentTimeMillis(); this.maxSessionTime = currentTimeMilliSec; this.currentSessionTime = currentTimeMilliSec; @@ -74,7 +74,6 @@ public class AuthenticationCookie { this.maxSessionTime = maxSessionTime; } - public long getCurrentSessionTime() { return currentSessionTime; } @@ -85,14 +84,22 @@ public class AuthenticationCookie { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuthenticationCookie)) return false; - + if (this == o) { + return true; + } + if (!(o instanceof AuthenticationCookie)) { + return false; + } AuthenticationCookie that = (AuthenticationCookie) o; - - if (getMaxSessionTime() != that.getMaxSessionTime()) return false; - if (getCurrentSessionTime() != that.getCurrentSessionTime()) return false; - if (getUserID() != null ? !getUserID().equals(that.getUserID()) : that.getUserID() != null) return false; + if (getMaxSessionTime() != that.getMaxSessionTime()) { + return false; + } + if (getCurrentSessionTime() != that.getCurrentSessionTime()) { + return false; + } + if (getUserID() != null ? !getUserID().equals(that.getUserID()) : that.getUserID() != null) { + return false; + } return getRoles() != null ? getRoles().containsAll(that.getRoles()) : that.getRoles() == null; } @@ -107,11 +114,7 @@ public class AuthenticationCookie { @Override public String toString() { - return "AuthenticationCookie{" + - "userID='" + userID + '\'' + - ", roles=" + roles + - ", maxSessionTime=" + maxSessionTime + - ", currentSessionTime=" + currentSessionTime + - '}'; + return "AuthenticationCookie{" + "userID='" + userID + '\'' + ", roles=" + roles + ", maxSessionTime=" + maxSessionTime + + ", currentSessionTime=" + currentSessionTime + '}'; } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookieUtils.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookieUtils.java index f0a33da8a7..d71c8593f3 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookieUtils.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookieUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; +import java.io.IOException; +import javax.servlet.http.Cookie; import org.openecomp.sdc.securityutil.filters.SessionValidationFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.http.Cookie; -import java.io.IOException; - public class AuthenticationCookieUtils { private static final Logger log = LoggerFactory.getLogger(SessionValidationFilter.class.getName()); @@ -43,10 +41,12 @@ public class AuthenticationCookieUtils { * @throws CipherUtilException * @throws IOException */ - public static Cookie updateSessionTime(Cookie cookie, ISessionValidationFilterConfiguration filterConfiguration) throws CipherUtilException, IOException { + public static Cookie updateSessionTime(Cookie cookie, ISessionValidationFilterConfiguration filterConfiguration) + throws CipherUtilException, IOException { AuthenticationCookie authenticationCookie = getAuthenticationCookie(cookie, filterConfiguration); long newTime = System.currentTimeMillis(); - log.debug("SessionValidationFilter: Going to set new session time in cookie, old value: {}, new value: {}", authenticationCookie.getCurrentSessionTime(), newTime); + log.debug("SessionValidationFilter: Going to set new session time in cookie, old value: {}, new value: {}", + authenticationCookie.getCurrentSessionTime(), newTime); authenticationCookie.setCurrentSessionTime(newTime); String encryptedCookie = getEncryptedCookie(authenticationCookie, filterConfiguration); return createUpdatedCookie(cookie, encryptedCookie, filterConfiguration); @@ -54,13 +54,14 @@ public class AuthenticationCookieUtils { /** * Create new Cookie object with same attributes as original cookie + * * @param cookie * @param encryptedCookie * @param cookieConfiguration * @return */ public static Cookie createUpdatedCookie(Cookie cookie, String encryptedCookie, ISessionValidationCookieConfiguration cookieConfiguration) { - Cookie updatedCookie = new Cookie(cookie.getName(), encryptedCookie ); + Cookie updatedCookie = new Cookie(cookie.getName(), encryptedCookie); updatedCookie.setSecure(true); updatedCookie.setPath(cookieConfiguration.getCookiePath()); updatedCookie.setDomain(cookieConfiguration.getCookieDomain()); @@ -77,7 +78,8 @@ public class AuthenticationCookieUtils { * @throws IOException * @throws CipherUtilException */ - public static String getEncryptedCookie(AuthenticationCookie authenticationCookie, ISessionValidationFilterConfiguration filterConfiguration) throws IOException, CipherUtilException { + public static String getEncryptedCookie(AuthenticationCookie authenticationCookie, ISessionValidationFilterConfiguration filterConfiguration) + throws IOException, CipherUtilException { String changedCookieJson = RepresentationUtils.toRepresentation(authenticationCookie); return CipherUtil.encryptPKC(changedCookieJson, filterConfiguration.getSecurityKey()); } @@ -90,7 +92,8 @@ public class AuthenticationCookieUtils { * @return * @throws CipherUtilException */ - public static AuthenticationCookie getAuthenticationCookie(Cookie cookie, ISessionValidationFilterConfiguration filterConfiguration) throws CipherUtilException { + public static AuthenticationCookie getAuthenticationCookie(Cookie cookie, ISessionValidationFilterConfiguration filterConfiguration) + throws CipherUtilException { String originalCookieJson = CipherUtil.decryptPKC(cookie.getValue(), filterConfiguration.getSecurityKey()); return RepresentationUtils.fromRepresentation(originalCookieJson, AuthenticationCookie.class); } @@ -108,7 +111,8 @@ public class AuthenticationCookieUtils { long sessionExpirationDate = authenticationCookie.getMaxSessionTime() + filterConfiguration.getMaxSessionTimeOut(); long sessionTime = authenticationCookie.getCurrentSessionTime(); long currentTime = System.currentTimeMillis(); - log.debug("SessionValidationFilter: Checking if session expired: session time: {}, expiration time: {}, current time: {}", sessionTime, sessionExpirationDate, currentTime); + log.debug("SessionValidationFilter: Checking if session expired: session time: {}, expiration time: {}, current time: {}", sessionTime, + sessionExpirationDate, currentTime); return currentTime > sessionExpirationDate || isSessionIdle(sessionTime, currentTime, filterConfiguration); } @@ -123,8 +127,8 @@ public class AuthenticationCookieUtils { private static boolean isSessionIdle(long sessionTimeValue, long currentTime, ISessionValidationFilterConfiguration filterConfiguration) { long currentIdleTime = currentTime - sessionTimeValue; long maxIdleTime = filterConfiguration.getSessionIdleTimeOut(); - log.debug("SessionValidationFilter: Checking if session idle: session time: {}, current idle time: {}, max idle time: {}", currentTime, currentIdleTime, maxIdleTime); + log.debug("SessionValidationFilter: Checking if session idle: session time: {}, current idle time: {}, max idle time: {}", currentTime, + currentIdleTime, maxIdleTime); return currentIdleTime >= maxIdleTime; } - } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtil.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtil.java index 71ac6151f7..d69471e398 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtil.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtil.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; import java.security.SecureRandom; @@ -31,18 +30,17 @@ import org.slf4j.LoggerFactory; public class CipherUtil { - private static Logger log = LoggerFactory.getLogger(CipherUtil.class.getName()); + public static final int GCM_TAG_LENGTH = 16; + public static final int GCM_IV_LENGTH = 12; private static final String ALGORITHM = "AES"; private static final String ALGORITHM_DETAILS = ALGORITHM + "/GCM/NoPadding"; private static final String CIPHER_PROVIDER = "SunJCE"; - - public static final int GCM_TAG_LENGTH = 16; - public static final int GCM_IV_LENGTH = 12; - private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final String ALGORITHM_NAME = "SHA1PRNG"; + private static Logger log = LoggerFactory.getLogger(CipherUtil.class.getName()); - private CipherUtil() {} + private CipherUtil() { + } /** * Encrypt the text using the secret key in key.properties file @@ -59,11 +57,9 @@ public class CipherUtil { cipher = Cipher.getInstance(ALGORITHM_DETAILS, CIPHER_PROVIDER); SecureRandom secureRandom = SecureRandom.getInstance(ALGORITHM_NAME); secureRandom.nextBytes(iv); - GCMParameterSpec spec = - new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, iv); + GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, iv); cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(base64key), spec); finalByte = cipher.doFinal(value.getBytes()); - } catch (Exception ex) { log.error("encrypt failed", ex); throw new CipherUtilException(ex); @@ -74,12 +70,10 @@ public class CipherUtil { /** * Decrypts the text using the secret key in key.properties file. * - * @param message The encrypted string that must be decrypted using the ONAP Portal Encryption - * Key + * @param message The encrypted string that must be decrypted using the ONAP Portal Encryption Key * @return The String decrypted * @throws CipherUtilException if any decryption step fails */ - public static String decryptPKC(String message, String base64key) throws CipherUtilException { byte[] encryptedMessage = Base64.decodeBase64(message); Cipher cipher; @@ -87,12 +81,10 @@ public class CipherUtil { try { cipher = Cipher.getInstance(ALGORITHM_DETAILS, CIPHER_PROVIDER); byte[] initVector = Arrays.copyOfRange(encryptedMessage, 0, GCM_IV_LENGTH); - GCMParameterSpec spec = - new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector); + GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector); byte[] realData = subarray(encryptedMessage, GCM_IV_LENGTH, encryptedMessage.length); cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(base64key), spec); decrypted = cipher.doFinal(realData); - } catch (Exception ex) { log.error("decrypt failed", ex); throw new CipherUtilException(ex); @@ -129,11 +121,9 @@ public class CipherUtil { if (startIndexInclusive < 0) { startIndexInclusive = 0; } - if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } - int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_BYTE_ARRAY; diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtilException.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtilException.java index 5b1a602b58..9e202de3c4 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtilException.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtilException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -42,5 +42,4 @@ public class CipherUtilException extends Exception { public CipherUtilException(Throwable cause) { super(cause); } - } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationCookieConfiguration.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationCookieConfiguration.java index d684238db1..5371d0174f 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationCookieConfiguration.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationCookieConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; /** - * Configuration for Cookie object , have to be same over all components of application + * Configuration for Cookie object , have to be same over all components of application */ public interface ISessionValidationCookieConfiguration { String getCookieName(); + String getCookieDomain(); + String getCookiePath(); + boolean isCookieHttpOnly(); } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationFilterConfiguration.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationFilterConfiguration.java index ccae39423e..25e5683ebf 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationFilterConfiguration.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationFilterConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; import java.util.List; @@ -25,9 +24,12 @@ import java.util.List; public interface ISessionValidationFilterConfiguration extends ISessionValidationCookieConfiguration { String getSecurityKey(); + long getMaxSessionTimeOut(); + long getSessionIdleTimeOut(); // max idle time for session + String getRedirectURL(); - List<String> getExcludedUrls(); // comma separated URLs, like this "/config,/configmgr,/rest,/kibanaProxy" -} + List<String> getExcludedUrls(); // comma separated URLs, like this "/config,/configmgr,/rest,/kibanaProxy" +} diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/Passwords.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/Passwords.java index e10bd81d0f..bbaece44a2 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/Passwords.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/Passwords.java @@ -7,9 +7,9 @@ package org.openecomp.sdc.securityutil;/*- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,170 +18,171 @@ package org.openecomp.sdc.securityutil;/*- * ============LICENSE_END========================================================= */ -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; import java.util.Random; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class Passwords { - private static Logger log = LoggerFactory.getLogger( Passwords.class.getName()); - private static final Random RANDOM = new SecureRandom(); - private static final int SALT = 0; - private static final int HASH = 1; - private static final String HASH_ALGORITHM = "SHA-256"; - - /** - * static utility class - */ - private Passwords() { - } - - /** - * the method calculates a hash with a generated salt for the given password - * - * @param password - * @return a "salt:hash" value - */ - public static String hashPassword(String password) { - if (password!=null){ - byte[] salt = getNextSalt(); - byte byteData[] = hash(salt, password.getBytes()); - if (byteData != null) { - return toHex(salt) + ":" + toHex(byteData); - } - } - return null; - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param expectedHash - * @return - */ - public static boolean isExpectedPassword(String password, String expectedHash) { - if (password==null && expectedHash==null) - return true; - if (password==null || expectedHash==null) //iff exactly 1 is null - return false; - if (!expectedHash.contains(":")){ - log.error("invalid password expecting hash at the prefix of the password (ex. e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0)\n" + - "\t\t\t"); - return false; - } - String[] params = expectedHash.split(":"); - return isExpectedPassword(password, params[SALT], params[HASH]); - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param salt - * @param hash - * the hash generated using the salt - * @return true if the password matched the hash - */ - public static boolean isExpectedPassword(String password, String salt, String hash) { - if ( password == null && hash == null ) - return true; - if ( salt == null ){ - log.error("salt must be initialized"); - return false; - } - //unintialized params - if ( password == null || hash == null ) - return false; - byte[] saltBytes = fromHex(salt); - byte[] hashBytes = fromHex(hash); - - byte byteData[] = hash(saltBytes, password.getBytes()); - if (byteData != null) { - return Arrays.equals(byteData, hashBytes); - } - return false; - } - - public static void main(String[] args) { - if (args.length > 1 || args.length > 0) { - System.out.println("[" + hashPassword(args[0]) + "]"); - } else { - System.out.println("no passward passed."); - } - - } - - /** - * Returns a random salt to be used to hash a password. - * - * @return a 16 bytes random salt - */ - private static byte[] getNextSalt() { - byte[] salt = new byte[16]; - RANDOM.nextBytes(salt); - return salt; - } - - /** - * hase's the salt and value using the chosen algorithm - * - * @param salt - * @param password - * @return an array of bytes resulting from the hash - */ - private static byte[] hash(byte[] salt, byte[] password) { - MessageDigest md; - byte[] byteData = null; - try { - md = MessageDigest.getInstance(HASH_ALGORITHM); - md.update(salt); - md.update(password); - byteData = md.digest(); - } catch (NoSuchAlgorithmException e) { - System.out.println("invalid algorithm name"); - } - return byteData; - } - - /** - * Converts a string of hexadecimal characters into a byte array. - * - * @param hex - * the hex string - * @return the hex string decoded into a byte array - */ - private static byte[] fromHex(String hex) { - if ( hex == null ) - return null; - byte[] binary = new byte[hex.length() / 2]; - for (int i = 0; i < binary.length; i++) { - binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); - } - return binary; - } - - /** - * Converts a byte array into a hexadecimal string. - * - * @param array - * the byte array to convert - * @return a length*2 character string encoding the byte array - */ - private static String toHex(byte[] array) { - BigInteger bi = new BigInteger(1, array); - String hex = bi.toString(16); - int paddingLength = (array.length * 2) - hex.length(); - if (paddingLength > 0) - return String.format("%0" + paddingLength + "d", 0) + hex; - else - return hex; - } + private static final Random RANDOM = new SecureRandom(); + private static final int SALT = 0; + private static final int HASH = 1; + private static final String HASH_ALGORITHM = "SHA-256"; + private static Logger log = LoggerFactory.getLogger(Passwords.class.getName()); + + /** + * static utility class + */ + private Passwords() { + } + + /** + * the method calculates a hash with a generated salt for the given password + * + * @param password + * @return a "salt:hash" value + */ + public static String hashPassword(String password) { + if (password != null) { + byte[] salt = getNextSalt(); + byte byteData[] = hash(salt, password.getBytes()); + if (byteData != null) { + return toHex(salt) + ":" + toHex(byteData); + } + } + return null; + } + + /** + * the method checks if the given password matches the calculated hash + * + * @param password + * @param expectedHash + * @return + */ + public static boolean isExpectedPassword(String password, String expectedHash) { + if (password == null && expectedHash == null) { + return true; + } + if (password == null || expectedHash == null) //iff exactly 1 is null + { + return false; + } + if (!expectedHash.contains(":")) { + log.error( + "invalid password expecting hash at the prefix of the password (ex. e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0)\n" + + "\t\t\t"); + return false; + } + String[] params = expectedHash.split(":"); + return isExpectedPassword(password, params[SALT], params[HASH]); + } + + /** + * the method checks if the given password matches the calculated hash + * + * @param password + * @param salt + * @param hash the hash generated using the salt + * @return true if the password matched the hash + */ + public static boolean isExpectedPassword(String password, String salt, String hash) { + if (password == null && hash == null) { + return true; + } + if (salt == null) { + log.error("salt must be initialized"); + return false; + } + //unintialized params + if (password == null || hash == null) { + return false; + } + byte[] saltBytes = fromHex(salt); + byte[] hashBytes = fromHex(hash); + byte byteData[] = hash(saltBytes, password.getBytes()); + if (byteData != null) { + return Arrays.equals(byteData, hashBytes); + } + return false; + } + + public static void main(String[] args) { + if (args.length > 1 || args.length > 0) { + System.out.println("[" + hashPassword(args[0]) + "]"); + } else { + System.out.println("no passward passed."); + } + } + + /** + * Returns a random salt to be used to hash a password. + * + * @return a 16 bytes random salt + */ + private static byte[] getNextSalt() { + byte[] salt = new byte[16]; + RANDOM.nextBytes(salt); + return salt; + } + + /** + * hase's the salt and value using the chosen algorithm + * + * @param salt + * @param password + * @return an array of bytes resulting from the hash + */ + private static byte[] hash(byte[] salt, byte[] password) { + MessageDigest md; + byte[] byteData = null; + try { + md = MessageDigest.getInstance(HASH_ALGORITHM); + md.update(salt); + md.update(password); + byteData = md.digest(); + } catch (NoSuchAlgorithmException e) { + System.out.println("invalid algorithm name"); + } + return byteData; + } + + /** + * Converts a string of hexadecimal characters into a byte array. + * + * @param hex the hex string + * @return the hex string decoded into a byte array + */ + private static byte[] fromHex(String hex) { + if (hex == null) { + return null; + } + byte[] binary = new byte[hex.length() / 2]; + for (int i = 0; i < binary.length; i++) { + binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); + } + return binary; + } + + /** + * Converts a byte array into a hexadecimal string. + * + * @param array the byte array to convert + * @return a length*2 character string encoding the byte array + */ + private static String toHex(byte[] array) { + BigInteger bi = new BigInteger(1, array); + String hex = bi.toString(16); + int paddingLength = (array.length * 2) - hex.length(); + if (paddingLength > 0) { + return String.format("%0" + paddingLength + "d", 0) + hex; + } else { + return hex; + } + } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/RepresentationUtils.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/RepresentationUtils.java index 7fece5fda0..f47e61213e 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/RepresentationUtils.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/RepresentationUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - public class RepresentationUtils { private static final Logger log = LoggerFactory.getLogger(RepresentationUtils.class.getName()); @@ -41,7 +39,6 @@ public class RepresentationUtils { * @throws IOException */ public static <T> String toRepresentation(T elementToRepresent) throws IOException { - ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); @@ -67,7 +64,6 @@ public class RepresentationUtils { } catch (Exception e) { log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e); } // return null in case of exception - return object; } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/FilterServletOutputStream.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/FilterServletOutputStream.java index 30414e38b7..c5dbabfb30 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/FilterServletOutputStream.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/FilterServletOutputStream.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil.filters; -import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; public class FilterServletOutputStream extends ServletOutputStream { @@ -38,12 +37,12 @@ public class FilterServletOutputStream extends ServletOutputStream { stream.write(b); } - public void write(byte[] b) throws IOException { + public void write(byte[] b) throws IOException { stream.write(b); } - public void write(byte[] b, int off, int len) throws IOException { - stream.write(b,off,len); + public void write(byte[] b, int off, int len) throws IOException { + stream.write(b, off, len); } @Override @@ -53,6 +52,5 @@ public class FilterServletOutputStream extends ServletOutputStream { @Override public void setWriteListener(WriteListener writeListener) { - } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/ResponceWrapper.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/ResponceWrapper.java index dd4576e811..5ef821e542 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/ResponceWrapper.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/ResponceWrapper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil.filters; +import java.io.ByteArrayOutputStream; +import java.io.PrintWriter; import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; -import java.io.ByteArrayOutputStream; -import java.io.CharArrayWriter; -import java.io.IOException; -import java.io.PrintWriter; public class ResponceWrapper extends HttpServletResponseWrapper { + private ByteArrayOutputStream output; private int contentLength; private String contentType; @@ -51,23 +48,21 @@ public class ResponceWrapper extends HttpServletResponseWrapper { return new PrintWriter(getOutputStream(), true); } + public int getContentLength() { + return contentLength; + } + public void setContentLength(int length) { this.contentLength = length; super.setContentLength(length); } - public int getContentLength() { - return contentLength; + public String getContentType() { + return contentType; } public void setContentType(String type) { this.contentType = type; super.setContentType(type); } - - - public String getContentType() { - return contentType; - - } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SampleFilter.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SampleFilter.java index e54a08af6f..81cc4cd49d 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SampleFilter.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SampleFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,29 +17,39 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil.filters; - -import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; - -import javax.servlet.http.Cookie; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.servlet.http.Cookie; +import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; public class SampleFilter extends SessionValidationFilter { + @Override + public ISessionValidationFilterConfiguration getFilterConfiguration() { + return Configuration.getInstance(); + } + + @Override + protected Cookie addRoleToCookie(Cookie updatedCookie) { + return updatedCookie; + } + + @Override + protected boolean isRoleValid(Cookie cookie) { + return true; + } + private static class Configuration implements ISessionValidationFilterConfiguration { private static Configuration instance; - private String securityKey; private long maxSessionTimeOut; private long sessionIdleTimeOut; private String redirectURL; private List<String> excludedUrls; - private String cookieName; private String cookieDomain; private String cookiePath; @@ -48,40 +58,19 @@ public class SampleFilter extends SessionValidationFilter { private Configuration() { //security key should be exactly 16 characters long clear text and then encoded to base64 this.securityKey = "AGLDdG4D04BKm2IxIWEr8o=="; - this.maxSessionTimeOut = 24L*60L*60L*1000L; - this.sessionIdleTimeOut = 60L*60L*1000L; + this.maxSessionTimeOut = 24L * 60L * 60L * 1000L; + this.sessionIdleTimeOut = 60L * 60L * 1000L; this.redirectURL = "https://www.e-access.att.com/ecomp_portal_ist/ecompportal/process_csp"; - this.excludedUrls = new ArrayList<>(Arrays.asList("/config","/configmgr","/rest","/kibanaProxy","/healthcheck","/upload.*")); - + this.excludedUrls = new ArrayList<>(Arrays.asList("/config", "/configmgr", "/rest", "/kibanaProxy", "/healthcheck", "/upload.*")); this.cookieName = "kuku"; this.cookieDomain = ""; this.cookiePath = "/"; this.isCookieHttpOnly = true; } - public void setSecurityKey(String securityKey) { - this.securityKey = securityKey; - } - - public void setMaxSessionTimeOut(long maxSessionTimeOut) { - this.maxSessionTimeOut = maxSessionTimeOut; - } - - public void setCookieName(String cookieName) { - this.cookieName = cookieName; - } - - public void setRedirectURL(String redirectURL) { - this.redirectURL = redirectURL; - } - - public void setExcludedUrls(List<String> excludedUrls) { - this.excludedUrls = excludedUrls; - } - - public static Configuration getInstance(){ - if (instance == null ){ - instance = new Configuration(); + public static Configuration getInstance() { + if (instance == null) { + instance = new Configuration(); } return instance; } @@ -91,11 +80,19 @@ public class SampleFilter extends SessionValidationFilter { return securityKey; } + public void setSecurityKey(String securityKey) { + this.securityKey = securityKey; + } + @Override public long getMaxSessionTimeOut() { return maxSessionTimeOut; } + public void setMaxSessionTimeOut(long maxSessionTimeOut) { + this.maxSessionTimeOut = maxSessionTimeOut; + } + @Override public long getSessionIdleTimeOut() { return sessionIdleTimeOut; @@ -106,6 +103,10 @@ public class SampleFilter extends SessionValidationFilter { return cookieName; } + public void setCookieName(String cookieName) { + this.cookieName = cookieName; + } + @Override public String getCookieDomain() { return cookieDomain; @@ -126,27 +127,17 @@ public class SampleFilter extends SessionValidationFilter { return redirectURL; } + public void setRedirectURL(String redirectURL) { + this.redirectURL = redirectURL; + } + @Override public List<String> getExcludedUrls() { return excludedUrls; } - } - - @Override - public ISessionValidationFilterConfiguration getFilterConfiguration() { - return Configuration.getInstance(); - } - - @Override - protected Cookie addRoleToCookie(Cookie updatedCookie) { - return updatedCookie; - } - @Override - protected boolean isRoleValid(Cookie cookie) { - return true; + public void setExcludedUrls(List<String> excludedUrls) { + this.excludedUrls = excludedUrls; + } } - } - - diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SessionValidationFilter.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SessionValidationFilter.java index de235bff89..cf24874f38 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SessionValidationFilter.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SessionValidationFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil.filters; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.openecomp.sdc.securityutil.AuthenticationCookieUtils; -import org.openecomp.sdc.securityutil.CipherUtilException; -import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.apache.commons.lang.StringUtils; - +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -38,33 +34,70 @@ import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; +import org.apache.commons.lang.StringUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.securityutil.AuthenticationCookieUtils; +import org.openecomp.sdc.securityutil.CipherUtilException; +import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; public abstract class SessionValidationFilter implements Filter { - private static final Logger log = LoggerFactory.getLogger(SessionValidationFilter.class.getName()); - private ISessionValidationFilterConfiguration filterConfiguration; - private List<String> excludedUrls; + private static final Logger log = LoggerFactory.getLogger(SessionValidationFilter.class.getName()); private static final String REQUEST_ID = ONAPLogConstants.MDCs.REQUEST_ID; private static final String ONAP_REQUEST_ID_HEADER = ONAPLogConstants.Headers.REQUEST_ID; private static final String REQUEST_ID_HEADER = "X-RequestID"; private static final String TRANSACTION_ID_HEADER = "X-TransactionId"; private static final String ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; - private static final String PARTNER_NAME = ONAPLogConstants.MDCs.PARTNER_NAME; private static final String USER_ID_HEADER = "USER_ID"; private static final String ONAP_PARTNER_NAME_HEADER = ONAPLogConstants.Headers.PARTNER_NAME; private static final String USER_AGENT_HEADER = "User-Agent"; private static final String UNKNOWN = "UNKNOWN"; + private ISessionValidationFilterConfiguration filterConfiguration; + private List<String> excludedUrls; + public static void fillMDCFromHeaders(HttpServletRequest httpServletRequest) { + fillRequestIdFromHeader(httpServletRequest); + fillPartnerNameFromHeader(httpServletRequest); + } + + private static void fillRequestIdFromHeader(HttpServletRequest httpServletRequest) { + if (MDC.get(REQUEST_ID) == null) { + if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ONAP_REQUEST_ID_HEADER))) { + MDC.put(REQUEST_ID, httpServletRequest.getHeader(ONAP_REQUEST_ID_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(REQUEST_ID_HEADER))) { + MDC.put(REQUEST_ID, httpServletRequest.getHeader(REQUEST_ID_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(TRANSACTION_ID_HEADER))) { + MDC.put(REQUEST_ID, httpServletRequest.getHeader(TRANSACTION_ID_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ECOMP_REQUEST_ID_HEADER))) { + MDC.put(REQUEST_ID, httpServletRequest.getHeader(ECOMP_REQUEST_ID_HEADER)); + } else { + MDC.put(REQUEST_ID, UUID.randomUUID().toString()); + } + } + } + + private static void fillPartnerNameFromHeader(HttpServletRequest httpServletRequest) { + if (MDC.get(PARTNER_NAME) == null) { + if (StringUtils.isNotEmpty(httpServletRequest.getHeader(USER_ID_HEADER))) { + MDC.put(PARTNER_NAME, httpServletRequest.getHeader(USER_ID_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ONAP_PARTNER_NAME_HEADER))) { + MDC.put(PARTNER_NAME, httpServletRequest.getHeader(ONAP_PARTNER_NAME_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(USER_AGENT_HEADER))) { + MDC.put(PARTNER_NAME, httpServletRequest.getHeader(USER_AGENT_HEADER)); + } else { + MDC.put(PARTNER_NAME, UNKNOWN); + } + } + } public abstract ISessionValidationFilterConfiguration getFilterConfiguration(); + protected abstract Cookie addRoleToCookie(Cookie updatedCookie); + protected abstract boolean isRoleValid(Cookie cookie); @Override @@ -74,52 +107,52 @@ public abstract class SessionValidationFilter implements Filter { } @Override - public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; - long startTime = System.nanoTime(); fillMDCFromHeaders(httpRequest); log.debug("SessionValidationFilter: Validation started, received request with URL {}", httpRequest.getRequestURL()); - // request preprocessing boolean isContinueProcessing = preProcessingRequest(servletRequest, servletResponse, filterChain, httpRequest, httpResponse, startTime); List<Cookie> cookies = null; Cookie extractedCookie = null; - // request processing if (isContinueProcessing) { cookies = extractAuthenticationCookies(httpRequest.getCookies()); extractedCookie = cookies.get(0); isContinueProcessing = processRequest(httpRequest, httpResponse, extractedCookie); } - // response processing - if(isContinueProcessing){ - log.debug("SessionValidationFilter: Cookie from request {} is valid, passing request to session extension ...", httpRequest.getRequestURL()); + if (isContinueProcessing) { + log.debug("SessionValidationFilter: Cookie from request {} is valid, passing request to session extension ...", + httpRequest.getRequestURL()); Cookie updatedCookie = processResponse(extractedCookie); cleanResponceFromLeftoverCookies(httpResponse, cookies); log.debug("SessionValidationFilter: request {} passed all validations, passing request to endpoint ...", httpRequest.getRequestURL()); httpResponse.addCookie(updatedCookie); long durationSec = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); long durationMil = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); - log.debug("SessionValidationFilter: Validation ended, running time for URL {} is: {} seconds {} miliseconds", httpRequest.getPathInfo(), durationSec, durationMil); + log.debug("SessionValidationFilter: Validation ended, running time for URL {} is: {} seconds {} miliseconds", httpRequest.getPathInfo(), + durationSec, durationMil); filterChain.doFilter(servletRequest, httpResponse); } } - - private boolean preProcessingRequest(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain, HttpServletRequest httpRequest, HttpServletResponse httpResponse, long startTime) throws IOException, ServletException { - + private boolean preProcessingRequest(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain, + HttpServletRequest httpRequest, HttpServletResponse httpResponse, long startTime) + throws IOException, ServletException { boolean isPreProcessingSucceeded = true; if (isUrlFromWhiteList(httpRequest)) { - log.debug("SessionValidationFilter: URL {} excluded from access validation , passing request to endpoint ... ", httpRequest.getRequestURL()); + log.debug("SessionValidationFilter: URL {} excluded from access validation , passing request to endpoint ... ", + httpRequest.getRequestURL()); long durationSec = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); long durationMil = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); - log.debug("SessionValidationFilter: Validation ended, running time for URL {} is: {} seconds {} miliseconds", httpRequest.getPathInfo(), durationSec, durationMil); + log.debug("SessionValidationFilter: Validation ended, running time for URL {} is: {} seconds {} miliseconds", httpRequest.getPathInfo(), + durationSec, durationMil); filterChain.doFilter(servletRequest, servletResponse); isPreProcessingSucceeded = false; - } else if (!isCookiePresent(httpRequest.getCookies())) { //redirect to portal app log.debug("SessionValidationFilter: Cookie from request {} is not valid, redirecting request to portal", httpRequest.getRequestURL()); @@ -130,7 +163,7 @@ public abstract class SessionValidationFilter implements Filter { } private boolean processRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Cookie cookie) throws IOException { - boolean isProcessSuccessful= true; + boolean isProcessSuccessful = true; try { if (AuthenticationCookieUtils.isSessionExpired(cookie, filterConfiguration)) { //redirect to portal app @@ -143,7 +176,6 @@ public abstract class SessionValidationFilter implements Filter { log.debug("SessionValidationFilter: Cookie decryption error : {}", e.getMessage(), e); isProcessSuccessful = false; } - if (!isRoleValid(cookie)) { //redirect to portal app log.debug("SessionValidationFilter: Role is not valid, redirecting request {} to portal", httpRequest.getRequestURL()); @@ -184,33 +216,32 @@ public abstract class SessionValidationFilter implements Filter { log.debug("SessionValidationFilter: Extracting authentication cookies, {} cookies in request", cookies.length); List<Cookie> authenticationCookies = Arrays.stream(cookies).filter(c -> isCookieNameMatch(actualCookieName, c)).collect(Collectors.toList()); log.debug("SessionValidationFilter: Extracted {} authentication cookies from request", authenticationCookies.size()); - if( authenticationCookies.size() > 1 ){ - authenticationCookies.forEach( cookie -> log.debug("SessionValidationFilter: Multiple cookies found cookie name, {} cookie value {}", cookie.getName(), cookie.getValue())); + if (authenticationCookies.size() > 1) { + authenticationCookies.forEach(cookie -> log + .debug("SessionValidationFilter: Multiple cookies found cookie name, {} cookie value {}", cookie.getName(), cookie.getValue())); } return authenticationCookies; } - // use contains for matching due issue with ecomp portal ( change cookie name, add prefix ), temp solution private boolean isCookieNameMatch(String actualCookieName, Cookie c) { return c.getName().contains(actualCookieName); } private boolean isUrlFromWhiteList(HttpServletRequest httpRequest) { - if (httpRequest.getPathInfo() == null){ + if (httpRequest.getPathInfo() == null) { final String servletPath = httpRequest.getServletPath().toLowerCase(); - log.debug("SessionValidationFilter: pathInfo is null, trying to check by servlet path white list validation -> ServletPath: {} ", servletPath); - return excludedUrls.stream(). - anyMatch( e -> servletPath.matches(e)); + log.debug("SessionValidationFilter: pathInfo is null, trying to check by servlet path white list validation -> ServletPath: {} ", + servletPath); + return excludedUrls.stream().anyMatch(e -> servletPath.matches(e)); } String pathInfo = httpRequest.getPathInfo().toLowerCase(); log.debug("SessionValidationFilter: white list validation -> PathInfo: {} ", pathInfo); - return excludedUrls.stream(). - anyMatch( e -> pathInfo.matches(e)); + return excludedUrls.stream().anyMatch(e -> pathInfo.matches(e)); } private void cleanResponceFromLeftoverCookies(HttpServletResponse httpResponse, List<Cookie> cookiesList) { - for (Cookie cookie:cookiesList){ + for (Cookie cookie : cookiesList) { Cookie cleanCookie = AuthenticationCookieUtils.createUpdatedCookie(cookie, null, filterConfiguration); cleanCookie.setMaxAge(0); log.debug("SessionValidationFilter Cleaning Cookie cookie name: {} added to responce", cleanCookie.getName()); @@ -218,45 +249,7 @@ public abstract class SessionValidationFilter implements Filter { } } - public static void fillMDCFromHeaders(HttpServletRequest httpServletRequest) { - fillRequestIdFromHeader(httpServletRequest); - fillPartnerNameFromHeader(httpServletRequest); - - } - - private static void fillRequestIdFromHeader(HttpServletRequest httpServletRequest){ - if (MDC.get(REQUEST_ID) == null) { - if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ONAP_REQUEST_ID_HEADER))) { - MDC.put(REQUEST_ID, httpServletRequest.getHeader(ONAP_REQUEST_ID_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(REQUEST_ID_HEADER))) { - MDC.put(REQUEST_ID, httpServletRequest.getHeader(REQUEST_ID_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(TRANSACTION_ID_HEADER))) { - MDC.put(REQUEST_ID, httpServletRequest.getHeader(TRANSACTION_ID_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ECOMP_REQUEST_ID_HEADER))) { - MDC.put(REQUEST_ID, httpServletRequest.getHeader(ECOMP_REQUEST_ID_HEADER)); - } else { - MDC.put(REQUEST_ID, UUID.randomUUID().toString()); - } - } - } - - private static void fillPartnerNameFromHeader(HttpServletRequest httpServletRequest){ - if (MDC.get(PARTNER_NAME) == null) { - if (StringUtils.isNotEmpty(httpServletRequest.getHeader(USER_ID_HEADER))) { - MDC.put(PARTNER_NAME, httpServletRequest.getHeader(USER_ID_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ONAP_PARTNER_NAME_HEADER))) { - MDC.put(PARTNER_NAME, httpServletRequest.getHeader(ONAP_PARTNER_NAME_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(USER_AGENT_HEADER))) { - MDC.put(PARTNER_NAME, httpServletRequest.getHeader(USER_AGENT_HEADER)); - } else { - MDC.put(PARTNER_NAME, UNKNOWN); - } - } - } - - @Override public void destroy() { - } } |