-
Notifications
You must be signed in to change notification settings - Fork 0
/
AssertionVerifierServiceImpl.java
305 lines (272 loc) · 13.4 KB
/
AssertionVerifierServiceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/* (C)2023 */
package it.pagopa.tech.lollipop.consumer.service.impl;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.ThumbprintUtils;
import com.nimbusds.jose.util.Base64URL;
import it.pagopa.tech.lollipop.consumer.assertion.AssertionService;
import it.pagopa.tech.lollipop.consumer.config.LollipopConsumerRequestConfig;
import it.pagopa.tech.lollipop.consumer.enumeration.AssertionRefAlgorithms;
import it.pagopa.tech.lollipop.consumer.exception.*;
import it.pagopa.tech.lollipop.consumer.idp.IdpCertProvider;
import it.pagopa.tech.lollipop.consumer.model.IdpCertData;
import it.pagopa.tech.lollipop.consumer.model.LollipopConsumerRequest;
import it.pagopa.tech.lollipop.consumer.model.SamlAssertion;
import it.pagopa.tech.lollipop.consumer.service.AssertionVerifierService;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.inject.Inject;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import lombok.extern.java.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
@Log
/** Standard implementation of {@link AssertionVerifierService} */
public class AssertionVerifierServiceImpl implements AssertionVerifierService {
private final IdpCertProvider idpCertProvider;
private final AssertionService assertionService;
private final LollipopConsumerRequestConfig lollipopRequestConfig;
private static final String IN_RESPONSE_TO = "InResponseTo";
@Inject
public AssertionVerifierServiceImpl(
IdpCertProvider idpCertProvider,
AssertionService assertionService,
LollipopConsumerRequestConfig lollipopRequestConfig) {
this.idpCertProvider = idpCertProvider;
this.assertionService = assertionService;
this.lollipopRequestConfig = lollipopRequestConfig;
}
/**
* @see AssertionVerifierService#validateLollipop(LollipopConsumerRequest)
*/
@Override
public boolean validateLollipop(LollipopConsumerRequest request)
throws ErrorRetrievingAssertionException, AssertionPeriodException,
AssertionThumbprintException, AssertionUserIdException {
Map<String, String> headerParams = request.getHeaderParams();
SamlAssertion assertion =
getAssertion(
headerParams.get(lollipopRequestConfig.getAuthJWTHeader()),
headerParams.get(lollipopRequestConfig.getAssertionRefHeader()));
Document assertionDoc = buildDocumentFromAssertion(assertion);
boolean isAssertionPeriodValid = validateAssertionPeriod(assertionDoc);
if (!isAssertionPeriodValid) {
throw new AssertionPeriodException(
AssertionPeriodException.ErrorCode.INVALID_ASSERTION_PERIOD,
"The assertion has expired");
}
boolean isUserIdValid = validateUserId(request, assertionDoc);
if (!isUserIdValid) {
throw new AssertionUserIdException(
AssertionUserIdException.ErrorCode.INVALID_USER_ID,
"The user id in the assertion does not match the request header");
}
boolean isInResponseToValid = validateInResponseTo(request, assertionDoc);
if (!isInResponseToValid) {
throw new AssertionThumbprintException(
AssertionThumbprintException.ErrorCode.INVALID_IN_RESPONSE_TO,
"The hash of provided public key do not match the InResponseTo in the"
+ " assertion");
}
return true;
}
private SamlAssertion getAssertion(String jwt, String assertionRef)
throws ErrorRetrievingAssertionException {
try {
return assertionService.getAssertion(jwt, assertionRef);
} catch (OidcAssertionNotSupported e) {
throw new ErrorRetrievingAssertionException(
ErrorRetrievingAssertionException.ErrorCode.OIDC_TYPE_NOT_SUPPORTED,
e.getMessage(),
e);
} catch (LollipopAssertionNotFoundException e) {
throw new ErrorRetrievingAssertionException(
ErrorRetrievingAssertionException.ErrorCode.SAML_ASSERTION_NOT_FOUND,
e.getMessage(),
e);
}
}
private boolean validateAssertionPeriod(Document assertionDoc) throws AssertionPeriodException {
NodeList listElements =
assertionDoc.getElementsByTagNameNS(
lollipopRequestConfig.getSamlNamespaceAssertion(),
lollipopRequestConfig.getAssertionNotBeforeTag());
if (listElements == null || listElements.getLength() <= 0) {
return false;
}
String notBefore =
listElements.item(0).getAttributes().getNamedItem("NotBefore").getNodeValue();
long notBeforeMilliseconds;
try {
notBeforeMilliseconds =
new SimpleDateFormat(lollipopRequestConfig.getAssertionNotBeforeDateFormat())
.parse(notBefore)
.getTime();
} catch (ParseException e) {
throw new AssertionPeriodException(
AssertionPeriodException.ErrorCode.ERROR_PARSING_ASSERTION_NOT_BEFORE_DATE,
e.getMessage(),
e);
}
long dateNowMilliseconds = new Date().getTime();
long expiresAfterMilliseconds =
TimeUnit.DAYS.toMillis(lollipopRequestConfig.getAssertionExpireInDays());
long dateNowLessNotBefore = (dateNowMilliseconds - notBeforeMilliseconds);
return 0 <= dateNowLessNotBefore && (dateNowLessNotBefore <= expiresAfterMilliseconds);
}
private boolean validateUserId(LollipopConsumerRequest request, Document assertionDoc)
throws AssertionUserIdException {
String userIdHeader =
request.getHeaderParams().get(lollipopRequestConfig.getUserIdHeader());
String userIdFromAssertion = getUserIdFromAssertion(assertionDoc);
if (userIdFromAssertion == null) {
throw new AssertionUserIdException(
AssertionUserIdException.ErrorCode.FISCAL_CODE_FIELD_NOT_FOUND,
"Missing or invalid Fiscal Code in the retrieved saml assertion.");
}
return userIdFromAssertion.equals(userIdHeader);
}
private boolean validateInResponseTo(LollipopConsumerRequest request, Document assertionDoc)
throws AssertionThumbprintException {
NodeList listElements =
assertionDoc.getElementsByTagNameNS(
lollipopRequestConfig.getSamlNamespaceAssertion(),
lollipopRequestConfig.getAssertionInResponseToTag());
if (isInResponseToFieldFound(listElements)) {
throw new AssertionThumbprintException(
AssertionThumbprintException.ErrorCode.IN_RESPONSE_TO_FIELD_NOT_FOUND,
"Missing request id in the retrieved saml assertion");
}
String inResponseTo =
listElements.item(0).getAttributes().getNamedItem(IN_RESPONSE_TO).getNodeValue();
String inResponseToAlgorithm = retrieveInResponseToAlgorithm(inResponseTo);
String publicKey =
request.getHeaderParams().get(lollipopRequestConfig.getPublicKeyHeader());
String calculatedThumbprint = calculateThumbprint(inResponseToAlgorithm, publicKey);
String assertionRefHeader =
request.getHeaderParams().get(lollipopRequestConfig.getAssertionRefHeader());
return inResponseTo.equals(calculatedThumbprint) && inResponseTo.equals(assertionRefHeader);
}
private IdpCertData getIdpCertData(SamlAssertion assertion) {
return null;
}
private boolean validateSignature(SamlAssertion assertion, IdpCertData idpCertData) {
return false;
}
private static Document buildDocumentFromAssertion(SamlAssertion assertion)
throws ErrorRetrievingAssertionException {
String stringXml = assertion.getAssertionData();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// completely disable DOCTYPE declaration:
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(new StringReader(stringXml)));
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new ErrorRetrievingAssertionException(
ErrorRetrievingAssertionException.ErrorCode.ERROR_PARSING_ASSERTION,
e.getMessage(),
e);
}
}
private boolean isInResponseToFieldFound(NodeList listElements) {
return listElements == null
|| listElements.getLength() <= 0
|| listElements.item(0) == null
|| listElements.item(0).getAttributes() == null
|| listElements.item(0).getAttributes().getNamedItem(IN_RESPONSE_TO) == null
|| listElements.item(0).getAttributes().getNamedItem(IN_RESPONSE_TO).getNodeValue()
== null;
}
private String getUserIdFromAssertion(Document assertionDoc) throws AssertionUserIdException {
NodeList listElements =
assertionDoc.getElementsByTagNameNS(
lollipopRequestConfig.getSamlNamespaceAssertion(),
lollipopRequestConfig.getAssertionFiscalCodeTag());
if (listElements == null || listElements.getLength() <= 0) {
throw new AssertionUserIdException(
AssertionUserIdException.ErrorCode.FISCAL_CODE_FIELD_NOT_FOUND,
"Missing or invalid Fiscal Code in the retrieved saml assertion.");
}
for (int i = 0; i < listElements.getLength(); i++) {
Node item = listElements.item(i);
if (item == null || item.getAttributes() == null) {
continue;
}
Node name = item.getAttributes().getNamedItem("Name");
if (name != null
&& name.getNodeValue().equals("fiscalNumber")
&& item.getTextContent() != null) {
return item.getTextContent().trim().replace("TINIT-", "");
}
}
return null;
}
private String retrieveInResponseToAlgorithm(String inResponseTo)
throws AssertionThumbprintException {
boolean matchesSHA256 =
AssertionRefAlgorithms.SHA256.getPattern().matcher(inResponseTo).matches();
boolean matchesSHA384 =
AssertionRefAlgorithms.SHA384.getPattern().matcher(inResponseTo).matches();
boolean matchesSHA512 =
AssertionRefAlgorithms.SHA512.getPattern().matcher(inResponseTo).matches();
if (matchesSHA256) {
return AssertionRefAlgorithms.SHA256.getHashAlgorithm();
}
if (matchesSHA384) {
return AssertionRefAlgorithms.SHA384.getHashAlgorithm();
}
if (matchesSHA512) {
return AssertionRefAlgorithms.SHA512.getHashAlgorithm();
}
throw new AssertionThumbprintException(
AssertionThumbprintException.ErrorCode.IN_RESPONSE_TO_ALGORITHM_NOT_VALID,
"InResponseTo in the assertion do not contains a valid Assertion Ref or it contains"
+ " an invalid algorithm.");
}
private String calculateThumbprint(String inResponseToAlgorithm, String publicKey)
throws AssertionThumbprintException {
Base64URL thumbprint;
try {
publicKey = getPublicKey(publicKey);
thumbprint = ThumbprintUtils.compute(inResponseToAlgorithm, JWK.parse(publicKey));
} catch (JOSEException | ParseException e) {
String errMsg = String.format("Can not calculate JwkThumbprint: %S", e.getMessage());
throw new AssertionThumbprintException(
AssertionThumbprintException.ErrorCode.ERROR_CALCULATING_ASSERTION_THUMBPRINT,
errMsg,
e);
}
AssertionRefAlgorithms algo =
AssertionRefAlgorithms.getAlgorithmFromHash(inResponseToAlgorithm);
String calculatedThumbprint = String.format("%s-%s", algo.getAlgorithmName(), thumbprint);
if (!algo.getPattern().matcher(calculatedThumbprint).matches()) {
throw new AssertionThumbprintException(
AssertionThumbprintException.ErrorCode.ERROR_CALCULATING_ASSERTION_THUMBPRINT,
"The calculated thumbprint does not match the expected pattern: "
+ calculatedThumbprint);
}
return calculatedThumbprint;
}
private String getPublicKey(String publicKey) {
try {
publicKey = new String(Base64.getDecoder().decode(publicKey));
} catch (Exception e) {
log.log(Level.FINE, "Key not in Base64");
}
return publicKey;
}
}