package org.apereo.cas.web.support;

import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.CipherExecutor;
import org.apereo.cas.util.cipher.NoOpCipherExecutor;
import org.apereo.inspektr.common.web.ClientInfo;
import org.apereo.inspektr.common.web.ClientInfoHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * The {@link DefaultCasCookieValueManager} is responsible creating
 * the CAS SSO cookie and encrypting and signing its value.
 *
 * @author Misagh Moayyed
 * @since 4.1
 */
public class DefaultCasCookieValueManager implements CookieValueManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCasCookieValueManager.class);
    private static final char COOKIE_FIELD_SEPARATOR = '@';
    private static final int COOKIE_FIELDS_LENGTH = 3;

    /**
     * The cipher exec that is responsible for encryption and signing of the cookie.
     */
    private CipherExecutor<Serializable, String> cipherExecutor = NoOpCipherExecutor.getInstance();

    /**
     * Instantiates a new Cas cookie value manager.
     *
     * @param cipherExecutor the cipher executor
     */
    public DefaultCasCookieValueManager(final CipherExecutor cipherExecutor) {
        this.cipherExecutor = cipherExecutor;
    }

    @Override
    public String buildCookieValue(final String givenCookieValue, final HttpServletRequest request) {
        final ClientInfo clientInfo = ClientInfoHolder.getClientInfo();
        final StringBuilder builder = new StringBuilder(givenCookieValue)
                .append(COOKIE_FIELD_SEPARATOR)
                .append(clientInfo.getClientIpAddress());
        
        final String userAgent = WebUtils.getHttpServletRequestUserAgent(request);
        if (StringUtils.isBlank(userAgent)) {
            throw new IllegalStateException("Request does not specify a user-agent");
        }
        builder.append(COOKIE_FIELD_SEPARATOR)
                .append(userAgent);

        final String res = builder.toString();
        LOGGER.debug("Encoding cookie value [{}]", res);
        return this.cipherExecutor.encode(res);
    }

    @Override
    public String obtainCookieValue(final Cookie cookie, final HttpServletRequest request) {
        final String cookieValue = this.cipherExecutor.decode(cookie.getValue());
        LOGGER.debug("Decoded cookie value is [{}]", cookieValue);
        if (StringUtils.isBlank(cookieValue)) {
            LOGGER.debug("Retrieved decoded cookie value is blank. Failed to decode cookie [{}]", cookie.getName());
            return null;
        }

        final String[] cookieParts = cookieValue.split(String.valueOf(COOKIE_FIELD_SEPARATOR));
        if (cookieParts.length != COOKIE_FIELDS_LENGTH) {
            throw new IllegalStateException("Invalid cookie. Required fields are missing");
        }
        final String value = cookieParts[0];
        final String remoteAddr = cookieParts[1];
        final String userAgent = cookieParts[2];

        if (StringUtils.isBlank(value) || StringUtils.isBlank(remoteAddr)
                || StringUtils.isBlank(userAgent)) {
            throw new IllegalStateException("Invalid cookie. Required fields are empty");
        }

        if (!remoteAddr.equals(request.getRemoteAddr())) {
            throw new IllegalStateException("Invalid cookie. Required remote address does not match "
                    + request.getRemoteAddr());
        }

        final String agent = WebUtils.getHttpServletRequestUserAgent(request);
        if (!userAgent.equals(agent)) {
            throw new IllegalStateException("Invalid cookie. Required user-agent does not match " + agent);
        }
        return value;
    }
}

@@ -1739,24 +1739,16 @@
 ess());%0A
-        
 %0A       
@@ -2011,33 +2011,16 @@
 PARATOR)
-%0A                
 .append(
@@ -3122,32 +3122,16 @@
 oteAddr)
-%0A               
  %7C%7C Stri
@@ -3152,32 +3152,32 @@
 k(userAgent)) %7B%0A
+
             thro
@@ -3253,32 +3253,104 @@
 y%22);%0A        %7D%0A%0A
+        final ClientInfo clientInfo = ClientInfoHolder.getClientInfo();%0A
         if (!rem
@@ -3364,37 +3364,45 @@
 .equals(
-request.getRemote
+clientInfo.getClientIp
 Addr
+ess
 ())) %7B%0A 
@@ -3485,31 +3485,16 @@
 address 
-does not match 
 %22%0A      
@@ -3515,27 +3515,69 @@
 + re
-quest.getRemote
+moteAddr + %22 does not match %22 + clientInfo.getClientIp
 Addr
+ess
 ());
@@ -3699,32 +3699,32 @@
 quals(agent)) %7B%0A
-
             thro
@@ -3787,16 +3787,34 @@
 er-agent
+ %22 + userAgent + %22
  does no

Fix bug in validating CAS cookie; use the true client ip address Rather than what’s advertised via the request