1 package com.jsql.util;
2
3 import com.jsql.model.InjectionModel;
4 import com.jsql.model.exception.JSqlException;
5 import com.jsql.model.injection.method.AbstractMethodInjection;
6 import org.apache.commons.lang3.StringUtils;
7 import org.apache.logging.log4j.LogManager;
8 import org.apache.logging.log4j.Logger;
9
10 import java.util.AbstractMap;
11 import java.util.List;
12 import java.util.stream.Stream;
13
14 public class CookiesUtil {
15
16 private static final Logger LOGGER = LogManager.getRootLogger();
17 public static final String COOKIE = "Cookie";
18
19 private final InjectionModel injectionModel;
20
21 public CookiesUtil(InjectionModel injectionModel) {
22 this.injectionModel = injectionModel;
23 }
24
25 public boolean testParameters(boolean hasFoundInjection) {
26 if (!hasFoundInjection) {
27 if (!this.injectionModel.getMediatorUtils().preferencesUtil().isCheckingAllCookieParam()) {
28 return false;
29 }
30 LOGGER.log(
31 LogLevelUtil.CONSOLE_DEFAULT,
32 "{} cookies...",
33 () -> I18nUtil.valueByKey(AbstractMethodInjection.LOG_CHECKING)
34 );
35 } else {
36 return true;
37 }
38
39 String rawHeader = this.injectionModel.getMediatorUtils().parameterUtil().getRawHeader();
40
41 List<AbstractMap.SimpleEntry<String, String>> cookies = this.injectionModel.getMediatorUtils().parameterUtil().getListHeader()
42 .stream()
43 .filter(entry -> CookiesUtil.COOKIE.equalsIgnoreCase(entry.getKey()))
44 .findFirst()
45 .map(cookieHeader -> cookieHeader.getValue().split(";"))
46 .stream()
47 .flatMap(Stream::of)
48 .filter(cookie -> cookie != null && cookie.contains("="))
49 .map(cookie -> cookie.split("=", 2))
50 .map(arrayEntry -> new AbstractMap.SimpleEntry<>(
51 arrayEntry[0].trim(),
52 arrayEntry[1] == null ? StringUtils.EMPTY : arrayEntry[1].trim()
53 ))
54 .toList();
55
56 for (AbstractMap.SimpleEntry<String, String> cookie: cookies) {
57 String keyValue = cookie.getKey() + "=" + cookie.getValue();
58 String headerCookieWithStar = rawHeader.replace(keyValue, keyValue + InjectionModel.STAR);
59
60 this.injectionModel.getMediatorUtils().parameterUtil().initHeader(headerCookieWithStar);
61
62 try {
63 LOGGER.log(
64 LogLevelUtil.CONSOLE_DEFAULT,
65 "{} cookie [key:{}, value:{}]",
66 () -> I18nUtil.valueByKey(AbstractMethodInjection.LOG_CHECKING),
67 cookie::getKey,
68 () -> cookie.getValue().replace(InjectionModel.STAR, StringUtils.EMPTY)
69 );
70 if (this.injectionModel.getMediatorMethod().getHeader().testParameters()) {
71 return true;
72 }
73 } catch (JSqlException e) {
74 LOGGER.log(
75 LogLevelUtil.CONSOLE_ERROR,
76 String.format(
77 "No Cookie injection for %s=%s",
78 cookie.getKey(),
79 cookie.getValue().replace(InjectionModel.STAR, StringUtils.EMPTY)
80 )
81 );
82 }
83 }
84 return false;
85 }
86 }