SamlAuthenticationHandler.java
40.9 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.granite.crypto.CryptoException
* com.adobe.granite.crypto.CryptoSupport
* com.adobe.granite.keystore.KeyStoreNotInitialisedException
* com.adobe.granite.keystore.KeyStoreService
* com.day.crx.security.token.TokenUtil
* javax.annotation.Nonnull
* javax.annotation.Nullable
* javax.jcr.AccessDeniedException
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.Value
* javax.jcr.ValueFactory
* javax.servlet.ServletOutputStream
* javax.servlet.http.Cookie
* javax.servlet.http.HttpServletRequest
* javax.servlet.http.HttpServletResponse
* org.apache.commons.codec.binary.Base64
* org.apache.commons.codec.binary.StringUtils
* org.apache.commons.io.IOUtils
* org.apache.commons.lang.text.StrSubstitutor
* org.apache.felix.scr.annotations.Activate
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.ConfigurationPolicy
* org.apache.felix.scr.annotations.Properties
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.PropertyUnbounded
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.Service
* org.apache.jackrabbit.api.JackrabbitSession
* org.apache.jackrabbit.api.security.user.Authorizable
* org.apache.jackrabbit.api.security.user.Group
* org.apache.jackrabbit.api.security.user.User
* org.apache.jackrabbit.api.security.user.UserManager
* org.apache.sling.api.SlingHttpServletRequest
* org.apache.sling.api.resource.LoginException
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ResourceResolverFactory
* org.apache.sling.auth.core.AuthUtil
* org.apache.sling.auth.core.spi.AuthenticationHandler
* org.apache.sling.auth.core.spi.AuthenticationInfo
* org.apache.sling.auth.core.spi.DefaultAuthenticationFeedbackHandler
* org.apache.sling.commons.osgi.OsgiUtil
* org.apache.sling.jcr.api.SlingRepository
* org.osgi.service.component.ComponentContext
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.granite.auth.saml;
import com.adobe.granite.auth.saml.binding.MessageContext;
import com.adobe.granite.auth.saml.binding.PostBinding;
import com.adobe.granite.auth.saml.binding.RequestBinding;
import com.adobe.granite.auth.saml.binding.ResponseBinding;
import com.adobe.granite.auth.saml.configuration.IdpConfiguration;
import com.adobe.granite.auth.saml.configuration.SpConfiguration;
import com.adobe.granite.auth.saml.model.Assertion;
import com.adobe.granite.auth.saml.model.Attribute;
import com.adobe.granite.auth.saml.model.AuthnRequest;
import com.adobe.granite.auth.saml.model.AuthnStatement;
import com.adobe.granite.auth.saml.model.Issuer;
import com.adobe.granite.auth.saml.model.LogoutRequest;
import com.adobe.granite.auth.saml.model.LogoutResponse;
import com.adobe.granite.auth.saml.model.Message;
import com.adobe.granite.auth.saml.model.NameId;
import com.adobe.granite.auth.saml.model.NameIdPolicy;
import com.adobe.granite.auth.saml.model.Response;
import com.adobe.granite.auth.saml.model.Status;
import com.adobe.granite.auth.saml.model.Subject;
import com.adobe.granite.auth.saml.util.SamlReader;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import com.adobe.granite.keystore.KeyStoreNotInitialisedException;
import com.adobe.granite.keystore.KeyStoreService;
import com.day.crx.security.token.TokenUtil;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.jcr.AccessDeniedException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.text.StrSubstitutor;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.auth.core.AuthUtil;
import org.apache.sling.auth.core.spi.AuthenticationHandler;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.apache.sling.auth.core.spi.DefaultAuthenticationFeedbackHandler;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(metatype=1, label="%granite.auth.saml.label", description="%granite.auth.saml.description", policy=ConfigurationPolicy.REQUIRE, configurationFactory=1)
@Service(value={AuthenticationHandler.class}, serviceFactory=1)
@Properties(value={@Property(name="service.description", value={"Adobe Granite SAML Authentication Handler"}, propertyPrivate=1), @Property(name="service.vendor", value={"Adobe"}, propertyPrivate=1), @Property(name="path", value={"/"}, cardinality=100, propertyPrivate=0), @Property(name="service.ranking", intValue={5002}, propertyPrivate=0), @Property(name="authtype", value={"SAML"}, propertyPrivate=1)})
public class SamlAuthenticationHandler
extends DefaultAuthenticationFeedbackHandler
implements AuthenticationHandler {
private static final String DEFAULT_IDP_URL = "";
private static final boolean DEFAULT_IDP_HTTP_REDIRECT = false;
private static final String DEFAULT_SP_ENTITY_ID = "";
private static final String DEFAULT_DEFAULT_REDIRECT_URL = "/";
private static final boolean DEFAULT_USE_ENCRYPTION = true;
private static final String DEFAULT_USER_ID_ATTRIBUTE = "uid";
private static final boolean DEFAULT_CREATE_USER = true;
private static final boolean DEFAULT_ADD_GROUP_MEMBERSHIPS = true;
private static final String DEFAULT_GROUPS_ATTRIBUTE = "groupMembership";
private static final String DEFAULT_NAMEIDFORMAT_ATTRIBUTE = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient";
private static final boolean DEFAULT_HANDLE_LOGOUT = false;
private static final String DEFAULT_IDP_CERT_ALIAS = "";
private static final String DEFAULT_SP_PRIVATE_KEY_ALIAS = "";
private static final String DEFAULT_KEYSTORE_PASSWORD = "";
@Property(value={""})
public static final String OSGI_PROPERTY_IDP_URL = "idpUrl";
@Property(value={""})
public static final String OSGI_PROPERTY_IDP_CERT_ALIAS = "idpCertAlias";
@Property(boolValue={0})
public static final String OSGI_PROPERTY_IDP_HTTP_REDIRECT = "idpHttpRedirect";
@Property(value={""})
public static final String OSGI_PROPERTY_SP_ENTITY_ID = "serviceProviderEntityId";
@Property(value={""})
public static final String OSGI_PROPERTY_SP_PRIVATE_KEY_ALIAS = "spPrivateKeyAlias";
@Property(value={""})
public static final String OSGI_PROPERTY_KEYSTORE_PASSWORD = "keyStorePassword";
@Property(value={"/"})
public static final String OSGI_PROPERTY_DEFAULT_REDIRECT_URL = "defaultRedirectUrl";
@Property(value={"uid"})
public static final String OSGI_PROPERTY_USER_ID_ATTRIBUTE = "userIDAttribute";
@Property(boolValue={1})
public static final String OSGI_PROPERTY_USE_ENCRYPTION = "useEncryption";
@Property(boolValue={1})
public static final String OSGI_PROPERTY_CREATE_USER = "createUser";
@Property(boolValue={1})
public static final String OSGI_PROPERTY_ADD_GROUP_MEMBERSHIPS = "addGroupMemberships";
@Property(value={"groupMembership"})
public static final String OSGI_PROPERTY_GROUPS_ATTRIBUTE = "groupMembershipAttribute";
@Property(unbounded=PropertyUnbounded.ARRAY)
public static final String OSGI_PROPERTY_DEFAULT_GROUPS = "defaultGroups";
@Property(value={"urn:oasis:names:tc:SAML:2.0:nameid-format:transient"})
public static final String OSGI_PROPERTY_NAMEIDFORMAT = "nameIdFormat";
@Property(unbounded=PropertyUnbounded.ARRAY)
public static final String OSGI_PROPERTY_SYNCH_ATTRIBUTES = "synchronizeAttributes";
@Property(boolValue={0})
public static final String OSGI_PROPERTY_HANDLE_LOGOUT = "handleLogout";
@Property
public static final String OSGI_PROPERTY_LOGOUT_URL = "logoutUrl";
static final String AUTH_TYPE = "SAML";
static final String MANAGED_BY_IDP = "rep:managedByIdp";
private static final String LOGIN_SUFFIX = "/saml_login";
private static final String ERROR_HREF_FORMAT = "%s%s.error.html?j_reason=%s";
private static final String ERROR_PAGE_PATH = "/libs/granite/core/content/login";
private static final String UTF_8 = "UTF-8";
private static final String REQUEST_PATH_COOKIE = "saml_request_path";
private static final int COOKIE_MAX_AGE = 300;
private static final String LOGIN_TOKEN_COOKIE = "login-token";
private static final String PROPERTY_SAML_RESPONSE = "samlResponse";
@Reference
private SlingRepository repository;
@Reference
private CryptoSupport cryptoSupport;
@Reference
private ResourceResolverFactory resourceResolverFactory;
@Reference
private KeyStoreService keyStoreService;
private IdpConfiguration idpConfiguration;
private boolean idpHttpRedirect;
private SpConfiguration spConfiguration;
private String defaultRedirectUrl;
private String userIDAttribute;
private String groupsAttribute;
private boolean createUser;
private boolean addGroupMemberships;
private RequestBinding requestBinding;
private ResponseBinding responseBinding;
private String nameIdFormat;
private String[] synchronizeAttributes;
private Set<String> defaultGroups;
private boolean handleLogout;
private String errorTemplate;
private final Logger log;
private SamlReader samlReader;
public SamlAuthenticationHandler() {
this.log = LoggerFactory.getLogger(this.getClass());
PostBinding postBinding = new PostBinding();
this.requestBinding = postBinding;
this.responseBinding = postBinding;
this.idpConfiguration = new IdpConfiguration();
this.spConfiguration = new SpConfiguration();
this.samlReader = new SamlReader();
}
@Activate
public void activate(ComponentContext context) {
this.idpConfiguration.setIdpPostUrl(OsgiUtil.toString(context.getProperties().get("idpUrl"), (String)""));
this.idpHttpRedirect = OsgiUtil.toBoolean(context.getProperties().get("idpHttpRedirect"), (boolean)false);
this.idpConfiguration.setIdpCertAlias(OsgiUtil.toString(context.getProperties().get("idpCertAlias"), (String)""));
this.spConfiguration.setEntityId(OsgiUtil.toString(context.getProperties().get("serviceProviderEntityId"), (String)""));
this.spConfiguration.setUseEncryption(OsgiUtil.toBoolean(context.getProperties().get("useEncryption"), (boolean)true));
this.spConfiguration.setSpPrivateKeyAlias(OsgiUtil.toString(context.getProperties().get("spPrivateKeyAlias"), (String)""));
this.spConfiguration.setKeyStorePassword(OsgiUtil.toString(context.getProperties().get("keyStorePassword"), (String)""));
this.defaultRedirectUrl = OsgiUtil.toString(context.getProperties().get("defaultRedirectUrl"), (String)"/");
this.userIDAttribute = OsgiUtil.toString(context.getProperties().get("userIDAttribute"), (String)"uid");
this.createUser = OsgiUtil.toBoolean(context.getProperties().get("createUser"), (boolean)true);
this.addGroupMemberships = OsgiUtil.toBoolean(context.getProperties().get("addGroupMemberships"), (boolean)true);
this.groupsAttribute = OsgiUtil.toString(context.getProperties().get("groupMembershipAttribute"), (String)"groupMembership");
this.nameIdFormat = OsgiUtil.toString(context.getProperties().get("nameIdFormat"), (String)"urn:oasis:names:tc:SAML:2.0:nameid-format:transient");
this.synchronizeAttributes = OsgiUtil.toStringArray(context.getProperties().get("synchronizeAttributes"), (String[])new String[0]);
this.defaultGroups = this.toStringSet(context.getProperties().get("defaultGroups"), Collections.<String>emptySet());
this.handleLogout = OsgiUtil.toBoolean(context.getProperties().get("handleLogout"), (boolean)false);
this.idpConfiguration.setIdpLogoutPostUrl(OsgiUtil.toString(context.getProperties().get("logoutUrl"), (String)null));
this.errorTemplate = this.loadTemplate("/templates/error.html");
if (this.handleLogout && (this.idpConfiguration.getIdpLogoutPostUrl() == null || this.idpConfiguration.getIdpLogoutPostUrl().length() == 0)) {
this.log.warn("handleLogout set to true, but no logout url provided; logout will be disabled");
}
}
public AuthenticationInfo extractCredentials(HttpServletRequest request, HttpServletResponse response) {
if (this.isDisabled()) {
return null;
}
if (request != null && request.getRequestURI().endsWith("/saml_login")) {
return this.handleLogin(request, response);
}
return null;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
Object failureReason = request.getAttribute("j_reason");
if (failureReason != null) {
String reason = String.valueOf(failureReason);
if (REASON.isA(reason)) {
String href = String.format("%s%s.error.html?j_reason=%s", request.getContextPath(), "/libs/granite/core/content/login", reason);
this.log.info("SAML error with reason: {} detected, redirect user to: {}", (Object[])new String[]{reason, href});
this.redirectErrorPage(response, href);
return false;
}
this.log.warn("Unknown reason found: {}", failureReason);
}
if (this.idpHttpRedirect) {
response.sendRedirect(this.idpConfiguration.getIdpPostUrl());
} else {
ResourceResolver serviceResolver = null;
try {
MessageContext messageContext = new MessageContext(this.idpConfiguration, this.spConfiguration);
messageContext.setMessage(this.createAuthnRequest());
serviceResolver = this.resourceResolverFactory.getServiceResourceResolver(null);
Key privateKey = null;
try {
privateKey = this.spConfiguration.getDecryptionKey(this.keyStoreService.getKeyStore(serviceResolver));
}
catch (KeyStoreNotInitialisedException e) {
this.log.debug("Could not retrieve SP's private key: " + e.getMessage());
}
if (privateKey == null) {
this.log.debug("Private key of SP not provided: Cannot sign Authn request.");
}
this.requestBinding.send(messageContext, response, privateKey);
}
catch (IOException e) {
this.log.warn("Could not send authentication request message", (Throwable)e);
throw new RuntimeException(e);
}
catch (LoginException e) {
this.log.error("Could not get service resolver to retrieve SP's private key.");
}
finally {
if (serviceResolver != null) {
serviceResolver.close();
}
}
}
return true;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
protected void handleLogout(HttpServletRequest request, HttpServletResponse response) {
KeyStore trustStore = null;
KeyStore keyStore = null;
Key privateKey = null;
ResourceResolver serviceResolver = null;
try {
serviceResolver = this.resourceResolverFactory.getServiceResourceResolver(null);
trustStore = this.keyStoreService.getTrustStore(serviceResolver);
keyStore = this.keyStoreService.getKeyStore(serviceResolver);
privateKey = this.spConfiguration.getDecryptionKey(keyStore);
}
catch (LoginException e) {
this.log.warn("Could not access service resource resolver to retrieve SP's private key.");
}
finally {
if (serviceResolver != null) {
serviceResolver.close();
}
}
MessageContext messageContext = new MessageContext(this.idpConfiguration, this.spConfiguration);
MessageContext requestContext = null;
try {
requestContext = this.responseBinding.receive(messageContext, request, trustStore, keyStore);
}
catch (IOException e) {
this.log.error("Could not handle SingleLogout request.", (Throwable)e);
}
if (requestContext == null) {
this.log.error("Could not read LogoutRequest message.");
return;
}
LogoutRequest logoutRequest = (LogoutRequest)requestContext.getMessage();
if (!logoutRequest.isSignatureValid()) {
this.log.error("Received LogoutRequest with invalid signature.");
return;
}
MessageContext responseContext = new MessageContext(this.idpConfiguration, this.spConfiguration);
responseContext.setRelayState(request.getParameter("RelayState").getBytes());
LogoutResponse logoutResponse = this.createLogoutResponse(logoutRequest);
if (privateKey == null) {
this.log.debug("Private key of SP not provided: Cannot sign Logout response.");
}
responseContext.setMessage(logoutResponse);
try {
this.requestBinding.send(responseContext, response, privateKey);
}
catch (IOException e) {
this.log.error("Unable to send LogoutRespond message.", (Throwable)e);
}
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public void dropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
block11 : {
if (this.handleLogout && request instanceof SlingHttpServletRequest) {
this.clearRequestPathCookie(request, response);
this.clearCookie("login-token", request, response);
if (request.getParameter("SAMLRequest") != null) {
this.handleLogout(request, response);
} else {
ResourceResolver serviceResolver = null;
try {
SlingHttpServletRequest slingRequest = (SlingHttpServletRequest)request;
Authorizable user = (Authorizable)slingRequest.getResourceResolver().adaptTo(Authorizable.class);
if (!user.hasProperty("samlResponse")) break block11;
String protectedResponse = user.getProperty("samlResponse")[0].getString();
String decryptedResponse = this.cryptoSupport.unprotect(protectedResponse);
KeyStore trustStore = this.keyStoreService.getTrustStore(((SlingHttpServletRequest)request).getResourceResolver());
Certificate cert = this.idpConfiguration.getCertificate(trustStore);
if (cert != null) {
PublicKey idpPublicKey = cert.getPublicKey();
ByteArrayInputStream stream = new ByteArrayInputStream(decryptedResponse.getBytes("UTF-8"));
Response responseMsg = (Response)this.samlReader.read(stream, null, idpPublicKey);
MessageContext messageContext = new MessageContext(this.idpConfiguration, this.spConfiguration);
messageContext.setMessage(this.createLogoutRequest(responseMsg));
serviceResolver = this.resourceResolverFactory.getServiceResourceResolver(null);
Key privateKey = this.spConfiguration.getDecryptionKey(this.keyStoreService.getKeyStore(serviceResolver));
if (privateKey == null) {
this.log.debug("Private key of SP not provided: Cannot sign Logout request.");
}
this.requestBinding.send(messageContext, response, privateKey);
break block11;
}
this.log.error("Unable to perform SAML logout. Could not read IdP certificate from truststore.");
}
catch (Exception e) {
this.log.error("Unable to perform SAML logout.", (Throwable)e);
}
finally {
if (serviceResolver != null) {
serviceResolver.close();
}
}
}
}
}
}
protected void clearRequestPathCookie(HttpServletRequest request, HttpServletResponse response) {
this.clearCookie("saml_request_path", request, response);
this.clearCookie("anchor_backup", request, response);
}
private void clearCookie(String cookieName, HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
if (!cookie.getName().equals(cookieName)) continue;
cookie.setValue("");
break;
}
}
Cookie cookie = new Cookie(cookieName, "");
cookie.setMaxAge(1);
cookie.setPath("/");
response.addCookie(cookie);
}
public void authenticationFailed(HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
this.clearRequestPathCookie(request, response);
}
public boolean authenticationSucceeded(HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
if (request.getRequestURI().endsWith("/saml_login")) {
try {
String redirectUrl = this.defaultRedirectUrl;
String anchor = null;
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
String temp;
if ("saml_request_path".equals(cookie.getName()) && AuthUtil.isRedirectValid((HttpServletRequest)request, (String)(temp = cookie.getValue()))) {
redirectUrl = temp;
}
if (!"anchor_backup".equals(cookie.getName())) continue;
anchor = cookie.getValue();
}
}
this.clearRequestPathCookie(request, response);
if (anchor != null && anchor.trim().length() > 0) {
redirectUrl = redirectUrl + "#" + anchor;
}
response.sendRedirect(redirectUrl);
}
catch (IOException e) {
this.log.error("Could not read request.", (Throwable)e);
return false;
}
return true;
}
return DefaultAuthenticationFeedbackHandler.handleRedirect((HttpServletRequest)request, (HttpServletResponse)response);
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
protected AuthenticationInfo handleLogin(HttpServletRequest request, HttpServletResponse response) {
KeyStore trustStore;
ResourceResolver serviceResolver;
KeyStore keyStore;
MessageContext messageContext;
block26 : {
messageContext = new MessageContext(this.idpConfiguration, this.spConfiguration);
trustStore = null;
keyStore = null;
serviceResolver = null;
try {
serviceResolver = this.resourceResolverFactory.getServiceResourceResolver(null);
}
catch (LoginException e) {
this.log.error("Could not access service resource resolver to retrieve Key- and TrustStore.", (Object)e.getMessage());
return null;
}
try {
trustStore = this.keyStoreService.getTrustStore(serviceResolver);
}
catch (KeyStoreNotInitialisedException e) {
this.log.error("Could not access TrustStore to get the IdP certificate.", (Object)e.getMessage());
return null;
}
try {
keyStore = this.keyStoreService.getKeyStore(serviceResolver);
}
catch (KeyStoreNotInitialisedException e) {
if (!this.spConfiguration.getUseEncryption()) break block26;
this.log.error("KeyStore uninitialized. Cannot retrieve private key to decrypt assertions.");
return null;
}
}
if (serviceResolver != null) {
serviceResolver.close();
}
MessageContext responseContext = null;
try {
responseContext = this.responseBinding.receive(messageContext, request, trustStore, keyStore);
}
catch (IOException e) {
this.log.error("Fatal failure while parsing the request.", (Throwable)e);
}
if (responseContext == null) {
this.log.error("SAML response parameter was not provided or invalid.");
return null;
}
Response samlResponse = (Response)responseContext.getMessage();
List<Assertion> assertions = samlResponse.getAssertions();
if (assertions.size() > 0) {
Assertion assertion = assertions.get(0);
if (!assertion.isValid(this.spConfiguration)) {
this.log.info("Login failed. SAML token invalid.");
request.setAttribute("j_reason", (Object)REASON.invalid_token);
return AuthenticationInfo.FAIL_AUTH;
}
Authorizable authorizable = null;
Session serviceSession = null;
AuthenticationInfo authInfo = new AuthenticationInfo("SAML");
String username = null;
try {
if (!"".equals(this.userIDAttribute) && assertion.getAttributes().containsKey(this.userIDAttribute)) {
username = assertion.getAttributes().get(this.userIDAttribute).getValue().toString();
}
if ((username == null || "".equals(username)) && assertion.getSubject() != null && assertion.getSubject().getNameId() != null) {
username = assertion.getSubject().getNameId().getValue();
}
if (username == null || "".equals(username)) {
this.log.error("Could not extract username from assertion.");
request.setAttribute("j_reason", (Object)REASON.no_username);
AuthenticationInfo authenticationInfo = AuthenticationInfo.FAIL_AUTH;
return authenticationInfo;
}
serviceSession = this.repository.loginService("", null);
authorizable = this.createOrUpdateCRXUser(serviceSession, username, samlResponse.getRawMessage());
if (authorizable != null) {
if (this.addGroupMemberships) {
Attribute groupsAttributeList = null;
if (assertion.getAttributes().containsKey(this.groupsAttribute)) {
groupsAttributeList = assertion.getAttributes().get(this.groupsAttribute);
}
this.addUserToGroups(serviceSession, authorizable, groupsAttributeList);
}
this.synchronizeAttributes(serviceSession, authorizable, assertion);
}
serviceSession.save();
authInfo = TokenUtil.createCredentials((HttpServletRequest)request, (HttpServletResponse)response, (SlingRepository)this.repository, (String)username, (boolean)true);
}
catch (RepositoryException e) {
this.log.error("User synchronization failed: Could not access repository.", (Throwable)e);
request.setAttribute("j_reason", (Object)REASON.user_sync_failed);
authInfo = AuthenticationInfo.FAIL_AUTH;
}
finally {
if (null != serviceSession) {
serviceSession.logout();
}
}
if (authorizable == null) {
this.log.info("User {} not found", (Object)username);
request.setAttribute("j_reason", (Object)REASON.user_not_found);
return AuthenticationInfo.FAIL_AUTH;
}
authInfo.put("$$auth.info.login$$", new Object());
return authInfo;
}
return null;
}
protected void addUserToGroups(Session serviceSession, Authorizable user, Attribute groupsAttribute) {
try {
UserManager um = ((JackrabbitSession)serviceSession).getUserManager();
if (um == null) {
this.log.error("Group synchronization failed: Could not get user manager.");
return;
}
boolean isAutoSave = um.isAutoSave();
if (isAutoSave) {
um.autoSave(false);
}
HashSet<String> samlGroupIds = new HashSet<String>();
samlGroupIds.addAll(this.defaultGroups);
if (groupsAttribute != null) {
for (Object groupId : groupsAttribute.getListValue()) {
if (groupId == null) continue;
samlGroupIds.add(groupId.toString());
}
}
Iterator mgs = user.declaredMemberOf();
while (mgs.hasNext()) {
Group mg = (Group)mgs.next();
if (!this.isSamlGroup(mg)) continue;
String mgId = mg.getID();
if (samlGroupIds.contains(mgId)) {
samlGroupIds.remove(mgId);
continue;
}
mg.removeMember(user);
}
for (String samlGroupId : samlGroupIds) {
Group group = (Group)um.getAuthorizable(samlGroupId);
if (group == null) continue;
group.addMember(user);
if (this.isSamlGroup(group)) continue;
this.setSamlGroup(serviceSession, group);
}
if (isAutoSave) {
um.autoSave(true);
}
}
catch (AccessDeniedException e) {
this.log.error("Group synchronization failed: Access denied.", (Throwable)e);
}
catch (RepositoryException e) {
this.log.error("Group synchronization failed: Could not access repository.", (Throwable)e);
}
}
protected Authorizable createOrUpdateCRXUser(Session serviceSession, String username, String samlResponseParameter) {
try {
UserManager um = ((JackrabbitSession)serviceSession).getUserManager();
Authorizable authorizable = um.getAuthorizable(username);
if (authorizable == null && this.createUser) {
byte[] key = new byte[16];
try {
this.cryptoSupport.nextRandomBytes(key);
}
catch (CryptoException e) {
this.log.error("cryptoSupport.nextRandomBytes failed", (Throwable)e);
new Random().nextBytes(key);
}
authorizable = um.createUser(username, StringUtils.newStringUtf8((byte[])Base64.encodeBase64((byte[])key)));
}
if (authorizable != null && !authorizable.isGroup()) {
ValueFactory vf = serviceSession.getValueFactory();
try {
authorizable.setProperty("samlResponse", vf.createValue(this.cryptoSupport.protect(samlResponseParameter)));
}
catch (CryptoException e) {
this.log.error("Encryption of samlResponse failed.", (Throwable)e);
}
}
return authorizable;
}
catch (AccessDeniedException e) {
this.log.error("User synchronization failed: Could not get user manager.", (Throwable)e);
}
catch (RepositoryException e) {
this.log.error("User synchronization failed: Could not access repository.", (Throwable)e);
}
return null;
}
protected void synchronizeAttributes(Session serviceSession, Authorizable authorizable, Assertion assertion) {
try {
ValueFactory vf = serviceSession.getValueFactory();
for (String attribute : this.synchronizeAttributes) {
String[] kv = attribute.trim().split("=");
if (kv.length != 2 || !assertion.getAttributes().containsKey(kv[0])) continue;
authorizable.setProperty(kv[1], vf.createValue(assertion.getAttributes().get(kv[0]).getValue().toString()));
}
}
catch (RepositoryException e) {
this.log.error("Attribute synchronization failed.", (Throwable)e);
}
}
protected AuthnRequest createAuthnRequest() {
AuthnRequest authnRequest = new AuthnRequest();
authnRequest.setId("_" + UUID.randomUUID().toString());
authnRequest.setVersion("2.0");
authnRequest.setDestination(this.idpConfiguration.getIdpPostUrl());
authnRequest.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
authnRequest.setIssueInstant(Calendar.getInstance());
Issuer issuer = new Issuer(this.spConfiguration.getEntityId());
authnRequest.setIssuer(issuer);
NameIdPolicy nameIdPolicy = new NameIdPolicy();
nameIdPolicy.setFormat(this.nameIdFormat);
nameIdPolicy.setAllowCreate(true);
authnRequest.setNameIdPolicy(nameIdPolicy);
return authnRequest;
}
protected LogoutRequest createLogoutRequest(Response responseMessage) {
LogoutRequest logoutRequest = new LogoutRequest();
logoutRequest.setIssueInstant(Calendar.getInstance());
logoutRequest.setId("_" + UUID.randomUUID().toString());
logoutRequest.setVersion("2.0");
logoutRequest.setDestination(this.idpConfiguration.getIdpLogoutPostUrl());
logoutRequest.setIssuer(new Issuer(this.spConfiguration.getEntityId()));
logoutRequest.setNameId(responseMessage.getNameId());
logoutRequest.setNameIdFormat(responseMessage.getNameIdFormat());
logoutRequest.setNameQualifier(responseMessage.getNameQualifier());
logoutRequest.setSpNameQualifier(responseMessage.getSpNameQualifier());
for (AuthnStatement authnStatement : responseMessage.getAssertions().get(0).getAuthnStatements()) {
logoutRequest.addSessionIndex(authnStatement.getSessionIndex());
}
return logoutRequest;
}
protected LogoutResponse createLogoutResponse(LogoutRequest logoutRequest) {
LogoutResponse logoutResponse = new LogoutResponse();
logoutResponse.setIssueInstant(Calendar.getInstance());
logoutResponse.setId("_" + UUID.randomUUID().toString());
logoutResponse.setVersion("2.0");
logoutResponse.setDestination(this.idpConfiguration.getIdpLogoutPostUrl());
logoutResponse.setIssuer(new Issuer(this.spConfiguration.getEntityId()));
logoutResponse.setInResponseTo(logoutRequest.getId());
Status status = new Status();
status.setStatusCode("urn:oasis:names:tc:SAML:2.0:status:Success");
logoutResponse.setStatus(status);
return logoutResponse;
}
protected boolean isDisabled() {
return "".equals(this.idpConfiguration.getIdpPostUrl()) || "".equals(this.spConfiguration.getEntityId()) || "".equals(this.idpConfiguration.getIdpCertAlias());
}
private void redirectErrorPage(@Nonnull HttpServletResponse response, @Nonnull String href) throws IOException {
HashMap<String, String> properties = new HashMap<String, String>();
properties.put("href", href);
StrSubstitutor sub = new StrSubstitutor(properties, "{", "}");
String body = sub.replace(this.errorTemplate);
response.setContentType("text/html");
response.addHeader("cache-control", "private, max-age=0, no-cache, no-store");
response.getOutputStream().print(body);
response.flushBuffer();
}
private boolean isSamlGroup(@Nonnull Group group) throws RepositoryException {
Value[] managedByIdP = group.getProperty("rep:managedByIdp");
return managedByIdP != null && managedByIdP.length > 0 && "SAML".equals(managedByIdP[0].getString());
}
private void setSamlGroup(@Nonnull Session serviceSession, @Nonnull Group group) throws RepositoryException {
group.setProperty("rep:managedByIdp", serviceSession.getValueFactory().createValue("SAML"));
}
@Nullable
private Set<String> toStringSet(@Nullable Object propValue, @Nullable Set<String> defaultSet) {
String[] propValues = OsgiUtil.toStringArray((Object)propValue);
return propValues != null ? this.buildSet(propValues) : defaultSet;
}
@Nonnull
private Set<String> buildSet(@Nonnull String[] propValues) {
HashSet<String> values = new HashSet<String>(propValues.length);
for (String propValue : propValues) {
String trimmed;
if (propValue == null || (trimmed = propValue.trim()).length() == 0) continue;
values.add(trimmed);
}
return values;
}
@Nonnull
private String loadTemplate(@Nonnull String resourcePath) {
InputStream resource = this.getClass().getResourceAsStream(resourcePath);
if (resource != null) {
try {
return IOUtils.toString((InputStream)resource, (String)"UTF-8");
}
catch (IOException e) {
this.log.error("I/O error while loading the template: {}", (Object)resourcePath, (Object)e);
}
}
throw new RuntimeException(String.format("Failed to load template: %s", resourcePath));
}
protected void bindRepository(SlingRepository slingRepository) {
this.repository = slingRepository;
}
protected void unbindRepository(SlingRepository slingRepository) {
if (this.repository == slingRepository) {
this.repository = null;
}
}
protected void bindCryptoSupport(CryptoSupport cryptoSupport) {
this.cryptoSupport = cryptoSupport;
}
protected void unbindCryptoSupport(CryptoSupport cryptoSupport) {
if (this.cryptoSupport == cryptoSupport) {
this.cryptoSupport = null;
}
}
protected void bindResourceResolverFactory(ResourceResolverFactory resourceResolverFactory) {
this.resourceResolverFactory = resourceResolverFactory;
}
protected void unbindResourceResolverFactory(ResourceResolverFactory resourceResolverFactory) {
if (this.resourceResolverFactory == resourceResolverFactory) {
this.resourceResolverFactory = null;
}
}
protected void bindKeyStoreService(KeyStoreService keyStoreService) {
this.keyStoreService = keyStoreService;
}
protected void unbindKeyStoreService(KeyStoreService keyStoreService) {
if (this.keyStoreService == keyStoreService) {
this.keyStoreService = null;
}
}
private static enum REASON {
invalid_token,
no_username,
user_sync_failed,
user_not_found;
private REASON() {
}
static boolean isA(@Nonnull String name) {
try {
REASON.valueOf(name);
return true;
}
catch (IllegalArgumentException e) {
return false;
}
}
}
}