forked from Shanexpert/Jenkins-saml-SP
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathMoSAMLAddIdp.java
More file actions
1434 lines (1265 loc) · 66.7 KB
/
MoSAMLAddIdp.java
File metadata and controls
1434 lines (1265 loc) · 66.7 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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.miniorange.saml;
import net.sf.json.JSONArray;
import org.apache.commons.io.FileUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Util;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.model.User;
import hudson.security.HudsonPrivateSecurityRealm;
import hudson.security.SecurityRealm;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import jenkins.security.SecurityListener;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.kohsuke.stapler.*;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.apache.commons.io.IOUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hudson.tasks.Mailer;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.metadata.*;
import org.opensaml.saml2.metadata.impl.*;
import org.opensaml.xml.Configuration;
import org.opensaml.xml.io.Marshaller;
import org.opensaml.xml.io.MarshallerFactory;
import org.opensaml.xml.security.credential.UsageType;
import org.opensaml.xml.signature.KeyInfo;
import org.opensaml.xml.signature.X509Certificate;
import org.opensaml.xml.signature.X509Data;
import org.opensaml.xml.signature.impl.KeyInfoBuilder;
import org.opensaml.xml.signature.impl.X509CertificateBuilder;
import org.opensaml.xml.signature.impl.X509DataBuilder;
import org.opensaml.xml.util.XMLHelper;
import org.w3c.dom.Element;
import static jenkins.model.Jenkins.get;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyManagementException;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.conn.ssl.SSLContextBuilder;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.config.Registry;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import java.net.ProxySelector;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class MoSAMLAddIdp extends SecurityRealm {
private static final Logger LOGGER = Logger.getLogger(MoSAMLAddIdp.class.getName());
public static final String MO_SAML_SP_AUTH_URL = "securityRealm/moSamlAuth";
public static final String DEFAULT_CUSTOMER_KEY="16555";
public static final String DEFAULT_API_KEY="fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq";
public static final String AUTH_BASE_URL = "https://auth.miniorange.com/moas";
public static final String NOTIFY_API = AUTH_BASE_URL + "/api/notify/send";
public static final String MO_SAML_JENKINS_LOGIN_ACTION = "securityRealm/moLoginAction";
public static final String MO_SAML_SSO_FORCE_STOP = "securityRealm/moSAMLSingleSignOnForceStop";
public static final String MO_SAML_SP_METADATA_URL = "securityRealm/mospmetadata";
public static final String MO_SAML_SP_CERTIFCATE_DOWNLOAD = "securityRealm/downloadCertificate";
public static final String MO_SAML_SSO_LOGIN_ACTION = "securityRealm/moSamlLogin";
private static final String LOGIN_TEMPLATE_PATH = "/templates/mosaml_login_page_template.html";
private static final String AUTO_REDIRECT_TO_IDP_TEMPLATE_PATH = "/templates/AutoRedirectToIDPTemplate.html";
private static final String REFERER_ATTRIBUTE = MoSAMLAddIdp.class.getName() + ".referer";
private final String idpEntityId;
private final String ssoUrl;
private final String metadataUrl;
private final String metadataFilePath;
private final String publicx509Certificate;
private final String usernameAttribute;
private final String fullnameAttribute;
private final String usernameCaseConversion;
private final Boolean userAttributeUpdate;
private final String emailAttribute;
private final String nameIDFormat;
private final String sslUrl;
private final String loginType;
private final String regexPattern;
private final Boolean enableRegexPattern;
private final Boolean signedRequest;
private final Boolean splitnameAttribute;
private final Boolean userCreate;
private final Boolean forceAuthn;
private final String ssoBindingType;
private final String sloBindingType;
private List<MoAttributeEntry> samlCustomAttributes;
private String newUserGroup;
private String authnContextClass;
@DataBoundConstructor
public MoSAMLAddIdp(String idpEntityId,
String ssoUrl,
String metadataUrl,
String metadataFilePath,
String publicx509Certificate,
String usernameCaseConversion,
String usernameAttribute,
String emailAttribute,
String fullnameAttribute,
String nameIDFormat,
String sslUrl,
String loginType,
String regexPattern,
Boolean enableRegexPattern,
Boolean signedRequest,
Boolean splitnameAttribute,
Boolean userCreate,
Boolean forceAuthn,
String ssoBindingType,
String sloBindingType,
List<MoAttributeEntry> samlCustomAttributes,
Boolean userAttributeUpdate,
String newUserGroup,
String authnContextClass
) throws Exception {
super();
this.metadataUrl = metadataUrl;
this.metadataFilePath = metadataFilePath;
if (!StringUtils.isEmpty(metadataUrl) || !StringUtils.isEmpty(metadataFilePath) ) {
String metadata = (!StringUtils.isEmpty(metadataUrl) ? sendGetRequest(metadataUrl) : getMetadataFromFile(metadataFilePath));
List<String> metadataUrlValues = configureFromMetadata(metadata);
if (metadataUrlValues != null) {
this.idpEntityId = metadataUrlValues.get(0);
this.nameIDFormat = metadataUrlValues.get(1);
this.ssoUrl = metadataUrlValues.get(2);
this.sslUrl = "";
this.publicx509Certificate = metadataUrlValues.get(4);
}
else {
this.idpEntityId = idpEntityId;
this.ssoUrl = ssoUrl;
this.nameIDFormat = nameIDFormat;
this.sslUrl = sslUrl;
this.publicx509Certificate = publicx509Certificate;
}
}
else{
this.idpEntityId = idpEntityId;
this.ssoUrl = ssoUrl;
this.nameIDFormat = nameIDFormat;
this.sslUrl = sslUrl;
this.publicx509Certificate = publicx509Certificate;
}
this.usernameCaseConversion = (usernameCaseConversion != null) ? usernameCaseConversion : "none";
this.usernameAttribute = (usernameAttribute != null && !usernameAttribute.trim().equals("")) ? usernameAttribute : "NameID";
this.emailAttribute = (emailAttribute != null && !emailAttribute.trim().equals("")) ? emailAttribute : "NameID";
this.loginType = (loginType != null) ? loginType : "usernameLogin";
this.regexPattern = regexPattern;
this.enableRegexPattern = (enableRegexPattern != null) ? enableRegexPattern : false;
this.signedRequest = (signedRequest != null) ? signedRequest : false;
this.splitnameAttribute = (splitnameAttribute != null) ? splitnameAttribute : false;
this.userCreate = (userCreate != null) ? userCreate : true;
this.forceAuthn = (forceAuthn != null) ? forceAuthn : false;
this.ssoBindingType = (ssoBindingType != null) ? ssoBindingType : "HttpRedirect";
this.sloBindingType = (sloBindingType != null) ? sloBindingType : "HttpRedirect";
this.samlCustomAttributes = samlCustomAttributes;
this.userAttributeUpdate = (userAttributeUpdate != null) ? userAttributeUpdate : false;
this.fullnameAttribute = fullnameAttribute;
this.newUserGroup= newUserGroup;
this.authnContextClass=(authnContextClass != null) ? authnContextClass : "None";
}
@Override
public String getLoginUrl() {
return "securityRealm/moLogin";
}
@Override
public void doLogout(StaplerRequest req, StaplerResponse rsp) {
try {
LOGGER.fine(" in doLogout");
super.doLogout(req, rsp);
} catch (Exception e) {
LOGGER.fine("error Occurred while generating logout request " + e.getMessage());
}
}
@Override
public String getPostLogOutUrl2(StaplerRequest req, Authentication auth) {
return req.getContextPath() + "/securityRealm/moLogin?from=" + req.getContextPath();
}
public HttpResponse doMoLogin(final StaplerRequest request, final StaplerResponse response, String errorMessage) {
String referer= request.getReferer();
String redirectOnFinish = calculateSafeRedirect(referer);
request.getSession().setAttribute(REFERER_ATTRIBUTE, redirectOnFinish);
return (req, rsp, node) -> {
rsp.setContentType("text/html;charset=UTF-8");
String html = IOUtils.toString(MoSAMLAddIdp.class.getResourceAsStream(LOGIN_TEMPLATE_PATH), "UTF-8");
String baseURL=get().getRootUrl();
if(baseURL.endsWith("/")){
baseURL= baseURL.substring(0,baseURL.length()-1);
}
html = html.replace("$$resURL$$",baseURL);
if (StringUtils.isNotBlank(errorMessage)) {
html = html.replace("<input type=\"hidden\" />", errorMessage);
}
rsp.getWriter().println(html);
};
}
@RequirePOST
public void doMoLoginAction(final StaplerRequest request, final StaplerResponse response) {
String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
String redirectOnFinish = calculateSafeRedirect(referer);
recreateSession(request);
try {
{
String username = request.getParameter("j_username");
username = MoSAMLUtils.sanitizeText(username);
String password = request.getParameter("j_password");
password = MoSAMLUtils.sanitizeText(password);
Boolean isValidUser= Boolean.FALSE ;
String error = StringUtils.EMPTY;
if (StringUtils.isNotBlank(username)) {
final User user_jenkin = User.getById(username, false);
if (user_jenkin != null) {
LOGGER.fine("User exist with username = " + username);
try {
HudsonPrivateSecurityRealm.Details details=user_jenkin.getProperty(HudsonPrivateSecurityRealm.Details.class);
isValidUser= details.isPasswordCorrect(password);
LOGGER.fine("Valid User Password");
} catch (Exception e) {
LOGGER.fine("InValid User Password"+e.getMessage());
isValidUser = Boolean.FALSE;
}
if (isValidUser) {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
request.getSession(true);
MoSAMLUserInfo userInfo = new MoSAMLUserInfo(username, Collections.singleton(AUTHENTICATED_AUTHORITY2));
MoSAMLAuthenticationTokenInfo tokenInfo = new MoSAMLAuthenticationTokenInfo(userInfo);
SecurityContextHolder.getContext().setAuthentication(tokenInfo);
SecurityListener.fireAuthenticated2(userInfo);
SecurityListener.fireLoggedIn(user_jenkin.getId());
response.sendRedirect(redirectOnFinish);
return;
}
}
error = "INVALID USER OR PASSWORD";
}
String errorMessage = StringUtils.EMPTY;
if (StringUtils.isNotBlank(error)) {
errorMessage = "<div class=\"alert alert-danger\">Invalid username or password</div><br>";
}
String html = customLoginTemplate(response, errorMessage);
response.getWriter().println(html);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String calculateSafeRedirect( String referer) {
String redirectURL;
String rootUrl = getBaseUrl();
{
if (referer != null && (referer.startsWith(rootUrl) || Util.isSafeToRedirectTo(referer))) {
redirectURL = referer;
} else {
redirectURL = rootUrl;
}
}
LOGGER.fine("Safe URL redirection: " + redirectURL);
return redirectURL;
}
private String customLoginTemplate(StaplerResponse response, String errorMessage) throws IOException {
response.setContentType("text/html;charset=UTF-8");
String html = IOUtils.toString(MoSAMLAddIdp.class.getResourceAsStream(LOGIN_TEMPLATE_PATH), "UTF-8");
String baseURL=get().getRootUrl();
if(baseURL.endsWith("/")){
baseURL= baseURL.substring(0,baseURL.length()-1);
}
html = html.replace("$$resURL$$",baseURL);
if (StringUtils.isNotBlank(errorMessage)) {
LOGGER.fine(errorMessage);
html = html.replace("<input type=\"hidden\" />", errorMessage);
}
return html;
}
public void doMoSamlLogin(final StaplerRequest request, final StaplerResponse response, @Header("Referer") final String referer) {
recreateSession(request);
String redirectOnFinish = StringUtils.EMPTY;
if(StringUtils.isEmpty(request.getQueryString())){
redirectOnFinish = calculateSafeRedirect(referer);
}
else{
redirectOnFinish = request.getQueryString();
}
LOGGER.fine("relay state " + redirectOnFinish);
request.getSession().setAttribute(REFERER_ATTRIBUTE, redirectOnFinish);
LOGGER.fine("in doMoSamlLogin");
MoSAMLManager moSAMLManager = new MoSAMLManager(getMoSAMLPluginSettings());
moSAMLManager.createAuthnRequestAndRedirect(request, response, redirectOnFinish,getMoSAMLPluginSettings()); }
private String getBaseUrl() {
return get().getRootUrl();
}
private String getErrorUrl() {
return get().getRootUrl() + MO_SAML_JENKINS_LOGIN_ACTION;
}
public String spMetadataURL() {
return get().getRootUrl() + MO_SAML_SP_METADATA_URL;
}
@RequirePOST
public void doMoSAMLSingleSignOnForceStop(final StaplerRequest request, final StaplerResponse response) {
HttpSession session= request.getSession(false);
if(session!=null){
session.invalidate();
}
LOGGER.fine("Enable doMoSAMLSingleSignOnForceStop from doPost");
String username = request.getParameter("username");
username = MoSAMLUtils.sanitizeText(username);
String password = request.getParameter("password");
password = MoSAMLUtils.sanitizeText(password);
LOGGER.fine("Parameters submitted for backdoor: username: "+username+" Password: "+password);
if (StringUtils.isBlank(username) && StringUtils.isBlank(password)) {
sendError(response, HttpServletResponse.SC_UNAUTHORIZED, "Authorization parameters are Missing");
return;
}
final User user_jenkin = User.getById(username, false);
try {
if (user_jenkin != null ) {
HudsonPrivateSecurityRealm.Details details=user_jenkin.getProperty(HudsonPrivateSecurityRealm.Details.class);
Boolean isValidUser= details.isPasswordCorrect(password);
Jenkins j= Jenkins.getInstanceOrNull();
if (j!=null&& isValidUser)
j.setSecurityRealm(new HudsonPrivateSecurityRealm(false, false, null));
JSONObject json = new JSONObject();
JSONObject success = new JSONObject();
success.put("Status", "SUCCESS");
success.put("Message", "Successfully disabled SSO");
json.put("Message", success);
response.setContentType("application/json");
response.setStatus(200);
response.getOutputStream().write(json.toString().getBytes(StandardCharsets.UTF_8));
response.getOutputStream().close();
}
else{
LOGGER.fine("User validation failed.");
sendError(response, HttpServletResponse.SC_UNAUTHORIZED, "UnAuthorize User");
}
}
catch (IOException e)
{
LOGGER.fine(e.getMessage());
}
}
private void sendError(StaplerResponse response, int errorCode, String errorMessage) {
try {
JSONObject json = new JSONObject();
JSONObject error = new JSONObject();
error.put("Status", "ERROR");
error.put("Message", errorMessage);
json.put("error", error);
response.setContentType("application/json");
response.setStatus(errorCode);
response.getOutputStream().write(json.toString().getBytes(StandardCharsets.UTF_8));
response.getOutputStream().close();
} catch (JSONException | IOException e) {
LOGGER.fine("An error occurred while sending json response" + e);
}
}
public void doMospmetadata(final StaplerRequest request, final StaplerResponse response) {
LOGGER.fine("Printing SP Metadata");
HttpSession session=request.getSession(false);
if(session!=null){
MoSAMLPluginSettings moSAMLPluginSettings = getMoSAMLPluginSettings();
String metadata = getMetadata(moSAMLPluginSettings);
LOGGER.fine(metadata);
try {
response.setHeader("Content-Disposition", "attachment; filename=\"sp_metadata.xml\"");
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Pragma", "");
response.setContentType("application/xml");
response.getOutputStream().write(metadata.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
LOGGER.fine("An error occurred while downloading the metadata." + e);
}
}
else{
LOGGER.fine("Invalid Request");
return;
}
}
public void doDownloadCertificate(final StaplerRequest request, final StaplerResponse response) throws Exception {
LOGGER.fine("Downloading SP Certificate.");
try {
MoSAMLPluginSettings moSAMLPluginSettings = getMoSAMLPluginSettings();
String certificate = moSAMLPluginSettings.getPublicSPCertificate();
response.setHeader("Content-Disposition", "attachment; filename=\"sp-certificate.crt\"");
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Pragma", "");
response.setContentType("application/octet-stream");
response.getOutputStream().write(certificate.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
LOGGER.fine("An error occurred while downloading the certificate."+e);
}
}
public String getMetadata(MoSAMLPluginSettings settings) {
LOGGER.fine("Generating SP Metadata.");
MoSAMLUtils.doBootstrap();
EntityDescriptorBuilder builder = new EntityDescriptorBuilder();
SPSSODescriptorBuilder spssoDescriptorBuilder = new SPSSODescriptorBuilder();
KeyDescriptorBuilder keyDescriptorBuilder = new KeyDescriptorBuilder();
KeyInfoBuilder keyInfoBuilder = new KeyInfoBuilder();
X509DataBuilder x509DataBuilder = new X509DataBuilder();
X509CertificateBuilder x509CertificateBuilder = new X509CertificateBuilder();
NameIDFormatBuilder nameIdFormatBuilder = new NameIDFormatBuilder();
AssertionConsumerServiceBuilder assertionConsumerServiceBuilder = new AssertionConsumerServiceBuilder();
SingleLogoutServiceBuilder singleLogOutServiceBuilder = new SingleLogoutServiceBuilder();
OrganizationBuilder organizationBuilder = new OrganizationBuilder();
OrganizationNameBuilder organizationNameBuilder = new OrganizationNameBuilder();
OrganizationDisplayNameBuilder organizationDisplayNameBuilder = new OrganizationDisplayNameBuilder();
OrganizationURLBuilder organizationUrlBuilder = new OrganizationURLBuilder();
ContactPersonBuilder contactPersonBuilder = new ContactPersonBuilder();
GivenNameBuilder givenNameBuilder = new GivenNameBuilder();
EmailAddressBuilder emailAddressBuilder = new EmailAddressBuilder();
EntityDescriptor entityDescriptor = builder.buildObject();
SPSSODescriptor spssoDescriptor = spssoDescriptorBuilder.buildObject();
AssertionConsumerService assertionConsumerService = assertionConsumerServiceBuilder.buildObject();
Organization organization = organizationBuilder.buildObject();
ContactPerson contactPersonTechnical = contactPersonBuilder.buildObject();
ContactPerson contactPersonSupport = contactPersonBuilder.buildObject();
entityDescriptor.setEntityID(settings.getSPEntityID());
spssoDescriptor.setWantAssertionsSigned(true);
spssoDescriptor.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
//signing
if (BooleanUtils.toBoolean(settings.getSignedRequest())) {
spssoDescriptor.setAuthnRequestsSigned(true);
KeyDescriptor signingKeyDescriptor = keyDescriptorBuilder.buildObject();
signingKeyDescriptor.setUse(UsageType.SIGNING);
KeyInfo signingKeyInfo = keyInfoBuilder.buildObject(KeyInfo.DEFAULT_ELEMENT_NAME);
X509Data signingX509Data = x509DataBuilder.buildObject(X509Data.DEFAULT_ELEMENT_NAME);
X509Certificate signingX509Certificate = x509CertificateBuilder
.buildObject(X509Certificate.DEFAULT_ELEMENT_NAME);
String certificate = settings.getPublicSPCertificate();
certificate = MoSAMLUtils.deserializePublicCertificate(certificate);
signingX509Certificate.setValue(certificate);
signingX509Data.getX509Certificates().add(signingX509Certificate);
signingKeyInfo.getX509Datas().add(signingX509Data);
signingKeyDescriptor.setKeyInfo(signingKeyInfo);
spssoDescriptor.getKeyDescriptors().add(signingKeyDescriptor);
}
SingleLogoutService singleLogoutServiceRedir = singleLogOutServiceBuilder.buildObject();
singleLogoutServiceRedir
.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
singleLogoutServiceRedir.setLocation(settings.getspSLOURL());
spssoDescriptor.getSingleLogoutServices().add(singleLogoutServiceRedir);
SingleLogoutService singleLogoutServicePost = singleLogOutServiceBuilder.buildObject();
singleLogoutServicePost.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
singleLogoutServicePost.setLocation(settings.getspSLOURL());
spssoDescriptor.getSingleLogoutServices().add(singleLogoutServicePost);
List<String> nameIds = new ArrayList<>();
nameIds.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
nameIds.add("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress");
nameIds.add("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
nameIds.add("urn:oasis:names:tc:SAML:2.0:nameid-format:transient");
for (String nameId : nameIds) {
NameIDFormat nameIDFormat = nameIdFormatBuilder.buildObject();
nameIDFormat.setFormat(nameId);
spssoDescriptor.getNameIDFormats().add(nameIDFormat);
}
assertionConsumerService.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
assertionConsumerService.setLocation(settings.getSpAcsUrl());
assertionConsumerService.setIndex(1);
spssoDescriptor.getAssertionConsumerServices().add(assertionConsumerService);
entityDescriptor.getRoleDescriptors().add(spssoDescriptor);
OrganizationName organizationName = organizationNameBuilder.buildObject();
organizationName.setName(new LocalizedString(settings.getOrganizationName(), Locale.getDefault().getLanguage()));
organization.getOrganizationNames().add(organizationName);
OrganizationDisplayName organizationDisplayName = organizationDisplayNameBuilder.buildObject();
organizationDisplayName.setName(new LocalizedString(settings.getOrganizationDisplayName(), Locale.getDefault().getLanguage()));
organization.getDisplayNames().add(organizationDisplayName);
OrganizationURL organizationURL = organizationUrlBuilder.buildObject();
organizationURL.setURL(new LocalizedString(settings.getOrganizationUrl(), Locale.getDefault().getLanguage()));
organization.getURLs().add(organizationURL);
entityDescriptor.setOrganization(organization);
contactPersonTechnical.setType(ContactPersonTypeEnumeration.TECHNICAL);
GivenName givenNameTechnical = givenNameBuilder.buildObject();
givenNameTechnical.setName(settings.getTechnicalContactName());
contactPersonTechnical.setGivenName(givenNameTechnical);
EmailAddress emailAddressTechnical = emailAddressBuilder.buildObject();
emailAddressTechnical.setAddress(settings.getTechnicalContactEmail());
contactPersonTechnical.getEmailAddresses().add(emailAddressTechnical);
contactPersonSupport.setType(ContactPersonTypeEnumeration.SUPPORT);
GivenName givenNameSupport = givenNameBuilder.buildObject();
givenNameSupport.setName(settings.getSupportContactName());
contactPersonSupport.setGivenName(givenNameSupport);
EmailAddress emailAddressSupport = emailAddressBuilder.buildObject();
emailAddressSupport.setAddress(settings.getSupportContactEmail());
contactPersonSupport.getEmailAddresses().add(emailAddressSupport);
entityDescriptor.getContactPersons().add(contactPersonTechnical);
entityDescriptor.getContactPersons().add(contactPersonSupport);
try {
MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(entityDescriptor);
Element element = marshaller.marshall(entityDescriptor);
return XMLHelper.nodeToString(element);
} catch (Exception e) {
LOGGER.fine("Marshalling Exception:" + e);
}
return null;
}
private static CloseableHttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException,
KeyManagementException {
HttpClientBuilder builder = HttpClientBuilder.create();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslConnectionFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionFactory)
.register("http", PlainConnectionSocketFactory.INSTANCE)
.build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
//return builder.build();
SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
CloseableHttpClient httpclient = HttpClients.custom().setRoutePlanner(routePlanner).setConnectionManager(ccm)
.build();
return httpclient;
}
public static String getMetadataFromFile(String path) {
String data = StringUtils.EMPTY;
File file = new File(path.trim());
try {
data = FileUtils.readFileToString(file, "UTF-8");
} catch (IOException e) {
LOGGER.fine("Error occurred in reading file " + e);
return StringUtils.EMPTY;
}
LOGGER.fine("data from file is " + data);
return data;
}
public static String sendGetRequest(String url) {
String errorMsg = new String("Did not get metadata");
try {
LOGGER.info("MoHttpUtils sendGetRequest Sending GET request to " + url);
CloseableHttpClient httpClient = getHttpClient();
HttpGet getRequest = new HttpGet(url);
org.apache.http.HttpResponse response = httpClient.execute(getRequest);
LOGGER.info("Response for HTTP Request: " + response.toString() + " and Status Code: " + response
.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200 && response.getEntity() != null) {
LOGGER.info("Response Entity found. Reading Response payload.");
String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
LOGGER.info("Response payload: " + data);
httpClient.close();
return data;
} else {
LOGGER.info("Response Entity NOT found. ");
httpClient.close();
return errorMsg;
}
} catch (Exception e) {
LOGGER.info("error occur "+e);
return errorMsg;
}
}
public static List<String> configureFromMetadata(String metadata) throws Exception {
List<String> metadataUrlValues = new ArrayList<String>();
metadata = metadata.replaceAll("[^\\x20-\\x7e]", "");
MoIDPMetadata idpMetadata = new MoIDPMetadata(metadata);
String idpEntityId = "";
String ssoBinding = "HttpRedirect";
String ssoUrl = "";
String sloBinding = "HttpRedirect";
String sloUrl = "";
String nameIdFormat = "";
try {
idpEntityId = idpMetadata.getEntityId();
nameIdFormat = StringUtils.defaultIfBlank(idpMetadata.nameIdFormat,
"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
if (idpMetadata.getSingleSignOnServices().containsKey(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
ssoBinding = "HttpRedirect";
ssoUrl = idpMetadata.getSingleSignOnServices().get(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
} else {
ssoBinding = "HttpPost";
ssoUrl = idpMetadata.getSingleSignOnServices().get(SAMLConstants.SAML2_POST_BINDING_URI);
}
if (idpMetadata.getSingleLogoutServices().size() > 0) {
if (idpMetadata.getSingleLogoutServices().containsKey(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
sloBinding = "HttpRedirect";
sloUrl = idpMetadata.getSingleLogoutServices().get(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
} else {
sloBinding = "HttpPost";
sloUrl = idpMetadata.getSingleLogoutServices().get(SAMLConstants.SAML2_POST_BINDING_URI);
}
}
metadataUrlValues.add(idpEntityId);
metadataUrlValues.add(nameIdFormat);
metadataUrlValues.add(ssoUrl);
metadataUrlValues.add(sloUrl);
String x509Certificate = idpMetadata.getSigningCertificates().get(0);
metadataUrlValues.add(x509Certificate);
} catch (Exception e) {
LOGGER.fine("Error Occured while updating attributes" + e);
throw new Exception("Can not save IDP configurations", e);
}
return metadataUrlValues;
}
@RequirePOST
public HttpResponse doMoSamlAuth(final StaplerRequest request, final StaplerResponse response) throws IOException {
String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
String redirectUrl = StringUtils.EMPTY;
String relayState = calculateSafeRedirect(request.getParameter(MoSAMLUtils.RELAY_STATE_PARAM));
if(!StringUtils.isEmpty(relayState)){
redirectUrl= URLDecoder.decode(relayState, "UTF-8");
}
LOGGER.fine("Relay state is "+ redirectUrl);
if(StringUtils.isEmpty(redirectUrl)){
redirectUrl = getBaseUrl();
}
recreateSession(request);
LOGGER.fine(" Reading SAML Response");
String username = "";
String email = "";
MoSAMLPluginSettings settings = getMoSAMLPluginSettings();
MoSAMLResponse MoSAMLResponse ;
MoSAMLManager moSAMLManager = new MoSAMLManager(getMoSAMLPluginSettings());
MoSAMLTemplateManager moSAMLTemplateManager = new MoSAMLTemplateManager(getMoSAMLPluginSettings());
try {
MoSAMLResponse = moSAMLManager.readSAMLResponse(request, response,settings);
if (StringUtils.contains(relayState, "testidpconfiguration")) {
LOGGER.fine("Showing Test Configuration Result");
moSAMLTemplateManager.showTestConfigurationResult(MoSAMLResponse, request, response, null);
return null;
}
LOGGER.fine("Not showing test config");
if (MoSAMLResponse.getAttributes().get(settings.getUsernameAttribute()) != null
&& MoSAMLResponse.getAttributes().get(settings.getUsernameAttribute()).length == 1) {
username = MoSAMLResponse.getAttributes().get(settings.getUsernameAttribute())[0];
username = loadUserName(username);
}
if (MoSAMLResponse.getAttributes().get(settings.getEmailAttribute()) != null
&& MoSAMLResponse.getAttributes().get(settings.getEmailAttribute()).length == 1) {
email = MoSAMLResponse.getAttributes().get(settings.getEmailAttribute())[0];
}
LOGGER.fine("Username received: " + username + " email received = " + email);
LOGGER.fine("Login Method for Users is:" + settings.getLoginType());
if (settings.getLoginType().equals("usernameLogin") && StringUtils.isNotBlank(username)) {
LOGGER.fine("User name Login Selected");
username=handleUsernameLogin(username, settings);
User user = User.getById(username, false);
if (user == null && !settings.getUserCreate()) {
LOGGER.fine("User does not exist");
String errorMessage = "<div class=\"alert alert-danger\">User does not Exist</div><br>";
return doMoLogin(request, response, errorMessage);
} else if (user == null && settings.getUserCreate()) {
username=handleUsernameLogin(username, settings);
User newUser = userCreateSAML( username, email, settings, MoSAMLResponse);
if (newUser == null) {
LOGGER.fine("User creation Failed");
String errorMessage = "<div class=\"alert alert-danger\">User creation Failed. Please view logs for more information.<br>";
return doMoLogin(request, response, errorMessage);
} else {
return createSessionAndLoginUser(newUser,request,response, true,settings, redirectUrl);
}
} else {
return createSessionAndLoginUser(user,request,response,false,settings,redirectUrl);
}
} else if(settings.getLoginType().equals("emailLogin") && StringUtils.isNotBlank(email)){
LOGGER.fine("Email Login Selected");
ArrayList<String> usernameList = handleEmailLogin(request, response, email, settings, MoSAMLResponse);
if(usernameList.size() > 1){
LOGGER.fine("Multiple Mail Addresses");
String errorMessage = "<div class=\"alert alert-danger\">More than one user found with this email address.</div><br>";
return doMoLogin(request,response,errorMessage);}
if (usernameList.size()==0 && !settings.getUserCreate()) {
LOGGER.fine("User does not exist and user creation is disabled");
String errorMessage = "<div class=\"alert alert-danger\">User does not Exist</div><br>";
return doMoLogin(request, response, errorMessage);
} else if (usernameList.size()==0 && settings.getUserCreate()) {
User newUser = userCreateSAML(username, email, settings, MoSAMLResponse);
if (newUser == null) {
LOGGER.fine("User creation Failed");
String errorMessage = "<div class=\"alert alert-danger\">User creation Failed.<br>";
return doMoLogin(request, response, errorMessage);
} else {
return createSessionAndLoginUser(newUser,request,response,true,settings,redirectUrl);
}
} else {
User user= User.getById(usernameList.get(0),false);
return createSessionAndLoginUser(user,request,response,false,settings,redirectUrl);
}
}
else {
LOGGER.fine("Invalid login Attribute");
String errorMessage = "<div class=\"alert alert-danger\">Username not received in the SAML Response. Please check your configuration.</div><br>";
return doMoLogin(request, response, errorMessage);
}
} catch (Exception ex) {
LOGGER.fine("Invalid response");
String errorMessage = "<div class=\"alert alert-danger\">Error occurred while reading response.</div><br>";
return doMoLogin(request, response, errorMessage);
}
}
private ArrayList<String> handleEmailLogin(StaplerRequest request, StaplerResponse response, String email, MoSAMLPluginSettings settings, MoSAMLResponse moSAMLResponse) {
ArrayList<String> usernameList= new ArrayList<String>();
try {
Collection<User> users = User.getAll();
for (User user : users) {
String emailAddress = user.getProperty(Mailer.UserProperty.class).getAddress();
if (emailAddress != null&&emailAddress.equals(email)) {
usernameList.add(user.getId());
}
}
} catch (Exception e) {
LOGGER.fine("Error Occurred while searching for user"+e);
return usernameList;
}
return usernameList;
}
private User userCreateSAML( String username, String email, MoSAMLPluginSettings settings, MoSAMLResponse moSAMLResponse) {
User new_user=null;
try {
new_user = User.getById(username, true);
LOGGER.fine("Updating user attributes");
attributeUpdate(settings, new_user, moSAMLResponse,settings.getLoginType());
if(new_user!=null ){
new_user.addProperty(new Mailer.UserProperty(email));
}
} catch (IOException e) {
e.printStackTrace();
return new_user;
}
return new_user;
}
public void attributeUpdate(MoSAMLPluginSettings settings, User user, MoSAMLResponse moSAMLResponse,String loginType) {
try {
if (user != null) {
LOGGER.fine("user is not null");
modifyUserSamlCustomAttributes(user, settings, moSAMLResponse);
}
}catch (Exception e)
{
LOGGER.fine("Error occurred."+e);
}
}
private void modifyUserSamlCustomAttributes(User user, MoSAMLPluginSettings settings, MoSAMLResponse moSAMLResponse) {
LOGGER.fine("Adding custom Attributes");
if (!settings.getSamlCustomAttributes().isEmpty() && user != null) {
MoSAMLuserProperty userProperty = new MoSAMLuserProperty(new ArrayList<>());
Map<String, String[]> responseSAMLAttributes = moSAMLResponse.getAttributes();
for (String name: responseSAMLAttributes.keySet()){
String key = name.toString();
String value = Arrays.toString(responseSAMLAttributes.get(name));
System.out.println(key + " " + value);
}
for (MoAttributeEntry attributeEntry : getSamlCustomAttributes()) {
LOGGER.fine("attributeEntry"+attributeEntry);
if (attributeEntry instanceof MoAttribute) {
MoAttribute attr = (MoAttribute) attributeEntry;
MoSAMLuserProperty.Attribute item = new MoSAMLuserProperty.Attribute(attr.getName(), attr.getDisplayName());
LOGGER.fine(attr.getName()+ attr.getDisplayName()+"sssS");
if (responseSAMLAttributes.containsKey(attr.getName())) {
String AttributeVal = responseSAMLAttributes.get(attr.getName())[0];
LOGGER.fine("AttributeVal"+AttributeVal);
item.setValue(AttributeVal);
} else {
item.setValue("");
}
userProperty.getAttributes().add(item);
}
}
try {
user.addProperty(userProperty);
} catch (IOException e) {
LOGGER.fine("Error Occurred while updating attributes" + e);
}
}
}
@Override
public SecurityComponents createSecurityComponents() {
return new SecurityComponents((AuthenticationManager) authentication -> {
if (authentication instanceof MoSAMLAuthenticationTokenInfo) {
return authentication;
}
throw new BadCredentialsException("Invalid Auth type " + authentication);
});
}
private String handleUsernameLogin(String username, MoSAMLPluginSettings settings) {
String regexPattern = "";
if (StringUtils.isNotBlank(settings.getRegexPattern()) && settings.getEnableRegexPattern()) {
LOGGER.fine("Regex Login for Username");
regexPattern = settings.getRegexPattern();
try {
Pattern pattern = Pattern.compile(StringUtils.trimToEmpty(regexPattern));
Matcher matcher = pattern.matcher(username);
LOGGER.fine(String.valueOf(matcher));
if (matcher.find()) {
username = StringUtils.EMPTY;
if (matcher.groupCount() > 0) {
StringBuffer buf = new StringBuffer();
for (int i = 1; i <= matcher.groupCount(); ++i) {
buf.append(matcher.group(i));
}
username = buf.toString();
} else {
username = matcher.group();
}
}
} catch (Exception e) {
LOGGER.fine("Can't sign in regex pattern exception occured" + e);
return username;
}
}
return username;
}
public HttpResponse createSessionAndLoginUser(User user, StaplerRequest request,StaplerResponse response, Boolean newUserCreated,MoSAMLPluginSettings settings, String redirectUrl){
if (user != null) {
LOGGER.fine("User exists for Username: " + user.getId());
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
session = request.getSession(true);
session.setAttribute("sessionIndex", MoSAMLUtils.generateRandomAlphaNumericKey(16));
session.setAttribute("nameID", user.getId());
UserDetails details = user.getUserDetailsForImpersonation2();
LOGGER.fine("UserDetails"+details);
MoSAMLUserInfo userInfo = new MoSAMLUserInfo(user.getId(), details.getAuthorities());
MoSAMLAuthenticationTokenInfo tokenInfo = new MoSAMLAuthenticationTokenInfo(userInfo);
SecurityContextHolder.getContext().setAuthentication(tokenInfo);
SecurityListener.fireAuthenticated2(userInfo);
SecurityListener.fireLoggedIn(user.getId());
return HttpResponses.redirectTo(redirectUrl);
} else {
LOGGER.fine("User does not exist.");
String errorMessage = "<div class=\"alert alert-danger\">User does not exist..</div><br>";
return doMoLogin(request,response,errorMessage);
}
}
public String getMetadataUrl() {
return metadataUrl;
}
public String getMetadataFilePath() {
return metadataFilePath;
}
public String getIdpEntityId() {
return idpEntityId;
}
public String getSsoUrl() {
return ssoUrl;
}
public String getPublicx509Certificate() {
return publicx509Certificate;
}
public String getUsernameAttribute() {
if (StringUtils.isEmpty(usernameAttribute)) {
return "NameID";
} else {
return usernameAttribute;
}
}
public String getEmailAttribute() {
if (StringUtils.isEmpty(emailAttribute)) {
return "NameID";
} else {
return emailAttribute;
}
}