forked from jenkinsci/oic-auth-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOicSecurityRealm.java
More file actions
1514 lines (1325 loc) · 63.1 KB
/
Copy pathOicSecurityRealm.java
File metadata and controls
1514 lines (1325 loc) · 63.1 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
/*
* The MIT License
*
* Copyright (c) 2016 Michael Bischoff & GeriMedica - www.gerimedica.nl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.oic;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTParser;
import com.nimbusds.oauth2.sdk.GrantType;
import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod;
import com.nimbusds.oauth2.sdk.token.AccessToken;
import com.nimbusds.oauth2.sdk.token.BearerAccessToken;
import com.nimbusds.oauth2.sdk.token.RefreshToken;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Util;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Failure;
import hudson.model.Saveable;
import hudson.model.User;
import hudson.security.ChainedServletFilter2;
import hudson.security.SecurityRealm;
import hudson.tasks.Mailer;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.Secret;
import io.burt.jmespath.Expression;
import io.burt.jmespath.JmesPath;
import io.burt.jmespath.RuntimeConfiguration;
import io.burt.jmespath.jcf.JcfRuntime;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import jenkins.model.IdStrategy;
import jenkins.model.IdStrategyDescriptor;
import jenkins.model.Jenkins;
import jenkins.security.ApiTokenProperty;
import jenkins.security.FIPS140;
import jenkins.security.SecurityListener;
import jenkins.util.SystemProperties;
import org.apache.commons.lang3.StringUtils;
import org.jenkinsci.plugins.oic.properties.AllowedTokenExpirationClockSkew;
import org.jenkinsci.plugins.oic.properties.DisableNonce;
import org.jenkinsci.plugins.oic.properties.DisableTokenVerification;
import org.jenkinsci.plugins.oic.properties.EscapeHatch;
import org.jenkinsci.plugins.oic.properties.LoginQueryParameters;
import org.jenkinsci.plugins.oic.properties.LogoutQueryParameters;
import org.jenkinsci.plugins.oic.properties.Pkce;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.Header;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse2;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.pac4j.core.context.CallContext;
import org.pac4j.core.context.FrameworkParameters;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.credentials.Credentials;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.exception.http.HttpAction;
import org.pac4j.core.exception.http.RedirectionAction;
import org.pac4j.core.http.callback.NoParameterCallbackUrlResolver;
import org.pac4j.core.profile.creator.ProfileCreator;
import org.pac4j.jee.context.JEEContextFactory;
import org.pac4j.jee.context.JEEFrameworkParameters;
import org.pac4j.jee.context.session.JEESessionStoreFactory;
import org.pac4j.jee.http.adapter.JEEHttpActionAdapter;
import org.pac4j.oidc.client.OidcClient;
import org.pac4j.oidc.config.OidcConfiguration;
import org.pac4j.oidc.credentials.authenticator.OidcAuthenticator;
import org.pac4j.oidc.profile.OidcProfile;
import org.pac4j.oidc.redirect.OidcRedirectionActionBuilder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.util.Assert;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Login with OpenID Connect / OAuth 2
*
* @author Michael Bischoff
* @author Steve Arch
*/
public class OicSecurityRealm extends SecurityRealm {
private static final Logger LOGGER = Logger.getLogger(OicSecurityRealm.class.getName());
private IdStrategy userIdStrategy;
private IdStrategy groupIdStrategy;
public static enum TokenAuthMethod {
client_secret_basic(ClientAuthenticationMethod.CLIENT_SECRET_BASIC),
client_secret_post(ClientAuthenticationMethod.CLIENT_SECRET_POST);
private ClientAuthenticationMethod clientAuthMethod;
TokenAuthMethod(ClientAuthenticationMethod clientAuthMethod) {
this.clientAuthMethod = clientAuthMethod;
}
ClientAuthenticationMethod toClientAuthenticationMethod() {
return clientAuthMethod;
}
}
private static final String ID_TOKEN_REQUEST_ATTRIBUTE = "oic-id-token";
private static final String NO_SECRET = "none";
private static final String SESSION_POST_LOGIN_REDIRECT_URL_KEY = "oic-redirect-on-login-url";
private final String clientId;
private final Secret clientSecret;
/** @deprecated see {@link OicServerWellKnownConfiguration#getWellKnownOpenIDConfigurationUrl()} */
@Deprecated
private transient String wellKnownOpenIDConfigurationUrl;
/** @deprecated see {@link OicServerManualConfiguration#getTokenServerUrl()} */
@Deprecated
private transient String tokenServerUrl;
/** @deprecated see {@link OicServerManualConfiguration#getJwksServerUrl()} */
@Deprecated
private transient String jwksServerUrl;
/** @deprecated see {@link OicServerManualConfiguration#getTokenAuthMethod()} */
@Deprecated
private transient TokenAuthMethod tokenAuthMethod;
/** @deprecated see {@link OicServerManualConfiguration#getAuthorizationServerUrl()} */
@Deprecated
private transient String authorizationServerUrl;
/** @deprecated see {@link OicServerManualConfiguration#getUserInfoServerUrl()} */
@Deprecated
private transient String userInfoServerUrl;
private String userNameField = "sub";
private transient Expression<Object> userNameFieldExpr = null;
private String tokenFieldToCheckKey = null;
private transient Expression<Object> tokenFieldToCheckExpr = null;
private String tokenFieldToCheckValue = null;
private String fullNameFieldName = null;
private transient Expression<Object> fullNameFieldExpr = null;
private String emailFieldName = null;
private transient Expression<Object> emailFieldExpr = null;
private String groupsFieldName = null;
private transient Expression<Object> groupsFieldExpr = null;
private transient Expression<Object> avatarFieldExpr = null;
private transient String simpleGroupsFieldName = null;
private transient String nestedGroupFieldName = null;
/** @deprecated see {@link OicServerManualConfiguration#getScopes()} */
@Deprecated
private transient String scopes = null;
private final boolean disableSslVerification;
private boolean logoutFromOpenidProvider = true;
/** @deprecated see {@link OicServerManualConfiguration#getEndSessionUrl()} */
@Deprecated
private transient String endSessionEndpoint = null;
private String postLogoutRedirectUrl;
@Deprecated
private transient boolean escapeHatchEnabled = false;
@Deprecated
private transient String escapeHatchUsername = null;
@Deprecated
private transient Secret escapeHatchSecret = null;
@Deprecated
private transient String escapeHatchGroup = null;
@Deprecated
/** @deprecated with no replacement. See sub classes of {@link OicServerConfiguration} */
private transient String automanualconfigure = null;
@Deprecated
/** @deprecated see {@link OicServerWellKnownConfiguration#isUseRefreshTokens()} */
private transient boolean useRefreshTokens = false;
private OicServerConfiguration serverConfiguration;
/** @deprecated with no replacement. See sub classes of {@link OicServerConfiguration} */
@Deprecated
private String overrideScopes = null;
/** Flag indicating if root url should be taken from config or request
*
* Taking root url from request requires a well configured proxy/ingress
*/
private boolean rootURLFromRequest = false;
/** Flag to send scopes in code token request
*/
private boolean sendScopesInTokenRequest = false;
/**
* Flag to enable PKCE challenge
* @deprecated Use {@link Pkce} property instead.
*/
@Deprecated
private transient boolean pkceEnabled = false;
/**
* Flag to disable JWT signature verification
* @deprecated Use {@link DisableTokenVerification} property instead.
*/
@Deprecated
private transient boolean disableTokenVerification = false;
/**
* Flag to disable nonce security
* @deprecated Use {@link DisableNonce} property instead.
*/
@Deprecated
private transient boolean nonceDisabled = false;
/** Flag to disable token expiration check
*/
private boolean tokenExpirationCheckDisabled = false;
/** Flag to enable traditional Jenkins API token based access (no OicSession needed)
*/
private boolean allowTokenAccessWithoutOicSession = false;
/**
* Additional number of seconds to add to token expiration
* @deprecated Use {@link AllowedTokenExpirationClockSkew} property instead.
*/
@Deprecated
private transient Long allowedTokenExpirationClockSkewSeconds = 60L;
/**
* Flag when set to true will cause enforce nonce checking in the refresh flow.
* https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse states the nonce claim should not be present
* and when faced with a provider that adheres to this if using a nonce, the library attempts to validate the "missing" nonce and fails.
* So this is disabled by default, but if the provider does send the nonce in the claim then we do need to verify it.
* But there is no way to know ahead of time if the server is going to send this or not.
*/
private static boolean checkNonceInRefreshFlow =
SystemProperties.getBoolean(OicSecurityRealm.class.getName() + ".checkNonceInRefreshFlow", false);
/** old field that had an '/' implicitly added at the end,
* transient because we no longer want to have this value stored,
* but it's still needed for backwards compatibility */
@Deprecated
private transient String endSessionUrl;
private DescribableList<OidcProperty, OidcPropertyDescriptor> properties = new DescribableList<>(Saveable.NOOP);
/** Random generator needed for robust random wait
*/
private static final Random RANDOM = new Random();
/** Clock used for token expiration check
*/
private static final Clock CLOCK = Clock.systemUTC();
/** Runtime context to compile JMESPath
*/
private static final JmesPath<Object> JMESPATH = new JcfRuntime(
new RuntimeConfiguration.Builder().withSilentTypeErrors(true).build());
/**
* Resource retriever configured with an appropriate SSL Factory based on {@link #isDisableSslVerification()}
*/
private transient ProxyAwareResourceRetriever proxyAwareResourceRetriever;
/**
* @deprecated Use @{link LoginQueryParameters} property instead.
*/
@Deprecated
private transient List<LoginQueryParameter> loginQueryParameters;
/**
* @deprecated Use @{link LogoutQueryParameters} property instead.
*/
@Deprecated
private transient List<LogoutQueryParameter> logoutQueryParameters;
@DataBoundConstructor
public OicSecurityRealm(
String clientId,
Secret clientSecret,
OicServerConfiguration serverConfiguration,
Boolean disableSslVerification,
IdStrategy userIdStrategy,
IdStrategy groupIdStrategy)
throws IOException, FormException {
// Needed in DataBoundSetter
this.disableSslVerification = Util.fixNull(disableSslVerification, Boolean.FALSE);
if (FIPS140.useCompliantAlgorithms() && this.disableSslVerification) {
throw new FormException(
Messages.OicSecurityRealm_DisableSslVerificationFipsMode(), "disableSslVerification");
}
this.clientId = clientId;
this.clientSecret = clientSecret;
this.serverConfiguration = serverConfiguration;
this.userIdStrategy = userIdStrategy;
this.groupIdStrategy = groupIdStrategy;
this.avatarFieldExpr =
compileJMESPath("picture", "avatar field"); // Default on OIDC spec, part of profile claim
}
@SuppressWarnings("deprecated")
protected Object readResolve() throws ObjectStreamException {
if (properties == null) {
properties = new DescribableList<>(Saveable.NOOP);
}
// Fail if migrating to a FIPS non-compliant config
if (FIPS140.useCompliantAlgorithms() && isDisableSslVerification()) {
throw new IllegalStateException(Messages.OicSecurityRealm_DisableSslVerificationFipsMode());
}
try {
if (nonceDisabled) {
properties.replace(new DisableNonce());
}
if (pkceEnabled) {
properties.replace(new Pkce());
}
if (disableTokenVerification) {
properties.replace(new DisableTokenVerification());
}
if (allowedTokenExpirationClockSkewSeconds != null) {
var value = allowedTokenExpirationClockSkewSeconds.intValue();
if (value != 60) {
properties.replace(new AllowedTokenExpirationClockSkew(value));
}
}
if (loginQueryParameters != null) {
properties.replace(new LoginQueryParameters(loginQueryParameters));
}
if (logoutQueryParameters != null) {
properties.replace(new LogoutQueryParameters(logoutQueryParameters));
}
if (escapeHatchEnabled) {
properties.replace(new EscapeHatch(escapeHatchUsername, escapeHatchGroup, escapeHatchSecret));
}
} catch (IOException e) {
var ose = new InvalidObjectException("Error while migrating properties");
ose.initCause(e);
throw ose;
} catch (FormException e) {
var ose = new InvalidObjectException(e.getFormField() + ": " + e.getMessage());
ose.initCause(e);
throw ose;
}
if (!Strings.isNullOrEmpty(endSessionUrl)) {
this.endSessionEndpoint = endSessionUrl + "/";
}
// backward compatibility with wrong groupsFieldName split
if (Strings.isNullOrEmpty(this.groupsFieldName) && !Strings.isNullOrEmpty(this.simpleGroupsFieldName)) {
String originalGroupFieldName = this.simpleGroupsFieldName;
if (!Strings.isNullOrEmpty(this.nestedGroupFieldName)) {
originalGroupFieldName += "[]." + this.nestedGroupFieldName;
}
this.setGroupsFieldName(originalGroupFieldName);
} else {
this.setGroupsFieldName(this.groupsFieldName);
}
// ensure Field JMESPath are computed
this.avatarFieldExpr =
compileJMESPath("picture", "avatar field"); // Default on OIDC spec, part of profile claim
this.setUserNameField(this.userNameField);
this.setEmailFieldName(this.emailFieldName);
this.setFullNameFieldName(this.fullNameFieldName);
this.setTokenFieldToCheckKey(this.tokenFieldToCheckKey);
try {
if (automanualconfigure != null) {
if ("auto".equals(automanualconfigure)) {
OicServerWellKnownConfiguration conf =
new OicServerWellKnownConfiguration(wellKnownOpenIDConfigurationUrl);
conf.setScopesOverride(this.overrideScopes);
serverConfiguration = conf;
} else {
OicServerManualConfiguration conf = new OicServerManualConfiguration(
/* TODO */ "migrated", tokenServerUrl, authorizationServerUrl);
if (tokenAuthMethod != null) {
conf.setTokenAuthMethod(tokenAuthMethod);
}
conf.setEndSessionUrl(endSessionEndpoint);
conf.setJwksServerUrl(jwksServerUrl);
conf.setScopes(scopes != null ? scopes : "openid email");
conf.setUseRefreshTokens(useRefreshTokens);
conf.setUserInfoServerUrl(userInfoServerUrl);
serverConfiguration = conf;
}
}
} catch (FormException e) {
// FormException does not override toString() so looses info on the fields set and the message may not have
// context
// extract if into a better message until this is fixed.
ObjectStreamException ose = new InvalidObjectException(e.getFormField() + ": " + e.getMessage());
ose.initCause(e);
throw ose;
}
createProxyAwareResourceRetriver();
return this;
}
public String getClientId() {
return clientId;
}
public Secret getClientSecret() {
return clientSecret == null ? Secret.fromString(NO_SECRET) : clientSecret;
}
@Restricted(NoExternalUse.class) // jelly access
public OicServerConfiguration getServerConfiguration() {
return serverConfiguration;
}
public String getUserNameField() {
return userNameField;
}
@Restricted(NoExternalUse.class)
public boolean isMissingIdStrategy() {
return userIdStrategy == null || groupIdStrategy == null;
}
@Override
public IdStrategy getUserIdStrategy() {
if (userIdStrategy != null) {
return userIdStrategy;
} else {
return IdStrategy.CASE_INSENSITIVE;
}
}
public String getTokenFieldToCheckKey() {
return tokenFieldToCheckKey;
}
public String getTokenFieldToCheckValue() {
return tokenFieldToCheckValue;
}
public String getFullNameFieldName() {
return fullNameFieldName;
}
public String getEmailFieldName() {
return emailFieldName;
}
public String getGroupsFieldName() {
return groupsFieldName;
}
@Override
public IdStrategy getGroupIdStrategy() {
if (groupIdStrategy != null) {
return groupIdStrategy;
} else {
return IdStrategy.CASE_INSENSITIVE;
}
}
public boolean isDisableSslVerification() {
return disableSslVerification;
}
public boolean isLogoutFromOpenidProvider() {
return logoutFromOpenidProvider;
}
public String getPostLogoutRedirectUrl() {
return postLogoutRedirectUrl;
}
public boolean isRootURLFromRequest() {
return rootURLFromRequest;
}
public boolean isSendScopesInTokenRequest() {
return sendScopesInTokenRequest;
}
public boolean isTokenExpirationCheckDisabled() {
return tokenExpirationCheckDisabled;
}
public boolean isAllowTokenAccessWithoutOicSession() {
return allowTokenAccessWithoutOicSession;
}
public DescribableList<OidcProperty, OidcPropertyDescriptor> getProperties() {
return properties;
}
@DataBoundSetter
public void setProperties(List<OidcProperty> properties) throws IOException {
this.properties.replaceBy(properties);
}
@PostConstruct
@Restricted(NoExternalUse.class)
public void createProxyAwareResourceRetriver() {
proxyAwareResourceRetriever =
ProxyAwareResourceRetriever.createProxyAwareResourceRetriver(isDisableSslVerification());
}
ProxyAwareResourceRetriever getResourceRetriever() {
return proxyAwareResourceRetriever;
}
private OidcConfiguration buildOidcConfiguration() {
// TODO cache this and use the well known if available.
OidcConfiguration conf = new CustomOidcConfiguration(this.isDisableSslVerification());
conf.setClientId(clientId);
conf.setSecret(clientSecret.getPlainText());
// TODO what do we prefer?
// conf.setPreferredJwsAlgorithm(JWSAlgorithm.HS256);
// set many more as needed...
OIDCProviderMetadata oidcProviderMetadata = serverConfiguration.toProviderMetadata();
if (oidcProviderMetadata.getScopes() != null) {
// auto configuration does not need to supply scopes
conf.setScope(oidcProviderMetadata.getScopes().toString());
}
conf.setResourceRetriever(getResourceRetriever());
return conf;
}
@Restricted(NoExternalUse.class) // exposed for testing only
protected OidcClient buildOidcClient() {
var executions = properties.stream()
.map(p -> p.newExecution(serverConfiguration))
.toList();
OidcConfiguration oidcConfiguration = buildOidcConfiguration();
OidcPropertyDescriptor.all().stream()
.filter(d -> !properties.contains(d))
.forEach(d -> d.getFallbackConfiguration(serverConfiguration, oidcConfiguration));
executions.forEach(execution -> execution.customizeConfiguration(oidcConfiguration));
OidcClient client = new OidcClient(oidcConfiguration);
// add the extra settings for the client...
client.setCallbackUrl(buildOAuthRedirectUrl());
client.setAuthenticator(new OidcAuthenticator(oidcConfiguration, client));
// when building the redirect URL by default pac4j adds the "client_name=DOidcClient" query parameter to the
// redirectURL.
// OPs will reject this for existing clients as the redirect URL is not the same as previously configured
client.setCallbackUrlResolver(new NoParameterCallbackUrlResolver());
executions.forEach(execution -> execution.customizeClient(client));
return client;
}
@DataBoundSetter
public void setUserNameField(String userNameField) {
this.userNameField = Util.fixNull(Util.fixEmptyAndTrim(userNameField), "sub");
this.userNameFieldExpr = compileJMESPath(this.userNameField, "user name field");
}
@DataBoundSetter
public void setTokenFieldToCheckKey(String tokenFieldToCheckKey) {
this.tokenFieldToCheckKey = Util.fixEmptyAndTrim(tokenFieldToCheckKey);
this.tokenFieldToCheckExpr = compileJMESPath(this.tokenFieldToCheckKey, "token field to check");
}
@DataBoundSetter
public void setTokenFieldToCheckValue(String tokenFieldToCheckValue) {
this.tokenFieldToCheckValue = Util.fixEmptyAndTrim(tokenFieldToCheckValue);
}
@DataBoundSetter
public void setFullNameFieldName(String fullNameFieldName) {
this.fullNameFieldName = Util.fixEmptyAndTrim(fullNameFieldName);
this.fullNameFieldExpr = compileJMESPath(this.fullNameFieldName, "full name field");
}
@DataBoundSetter
public void setEmailFieldName(String emailFieldName) {
this.emailFieldName = Util.fixEmptyAndTrim(emailFieldName);
this.emailFieldExpr = compileJMESPath(this.emailFieldName, "email field");
}
protected static Expression<Object> compileJMESPath(String str, String logComment) {
if (str == null) {
return null;
}
try {
Expression<Object> expr = JMESPATH.compile(str);
if (expr == null && logComment != null) {
LOGGER.warning(logComment + " with config '" + str + "' is an invalid JMESPath expression ");
}
return expr;
} catch (RuntimeException e) {
if (logComment != null) {
LOGGER.warning(logComment + " config failed " + e);
}
}
return null;
}
@DataBoundSetter
public void setGroupsFieldName(String groupsFieldName) {
this.groupsFieldName = Util.fixEmptyAndTrim(groupsFieldName);
this.groupsFieldExpr = compileJMESPath(this.groupsFieldName, "groups field");
}
@DataBoundSetter
public void setLogoutFromOpenidProvider(boolean logoutFromOpenidProvider) {
this.logoutFromOpenidProvider = logoutFromOpenidProvider;
}
@DataBoundSetter
public void setPostLogoutRedirectUrl(String postLogoutRedirectUrl) {
this.postLogoutRedirectUrl = Util.fixEmptyAndTrim(postLogoutRedirectUrl);
}
@DataBoundSetter
public void setEscapeHatchSecret(Secret escapeHatchSecret) {
if (escapeHatchSecret != null) {
// ensure escapeHatchSecret is BCrypt hash
String escapeHatchString = Secret.toString(escapeHatchSecret);
final Pattern BCryptPattern = Pattern.compile("\\A\\$[^$]+\\$\\d+\\$[./0-9A-Za-z]{53}");
if (!BCryptPattern.matcher(escapeHatchString).matches()) {
this.escapeHatchSecret = Secret.fromString(BCrypt.hashpw(escapeHatchString, BCrypt.gensalt()));
return;
}
}
this.escapeHatchSecret = escapeHatchSecret;
}
@DataBoundSetter
public void setRootURLFromRequest(boolean rootURLFromRequest) {
this.rootURLFromRequest = rootURLFromRequest;
}
@DataBoundSetter
public void setSendScopesInTokenRequest(boolean sendScopesInTokenRequest) {
this.sendScopesInTokenRequest = sendScopesInTokenRequest;
}
@DataBoundSetter
public void setTokenExpirationCheckDisabled(boolean tokenExpirationCheckDisabled) {
this.tokenExpirationCheckDisabled = tokenExpirationCheckDisabled;
}
@DataBoundSetter
public void setAllowTokenAccessWithoutOicSession(boolean allowTokenAccessWithoutOicSession) {
this.allowTokenAccessWithoutOicSession = allowTokenAccessWithoutOicSession;
}
@Override
public String getLoginUrl() {
// Login begins with our doCommenceLogin(String,String) method
return "securityRealm/commenceLogin";
}
@Override
public String getAuthenticationGatewayUrl() {
return "securityRealm/escapeHatch";
}
@Override
public Filter createFilter(FilterConfig filterConfig) {
return new ChainedServletFilter2(super.createFilter(filterConfig), new Filter() {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (OicSecurityRealm.this.handleTokenExpiration(
(HttpServletRequest) request, (HttpServletResponse) response)) {
chain.doFilter(request, response);
}
}
});
}
/*
* Acegi has this notion that first an {@link Authentication} object is created
* by collecting user information and then the act of authentication is done
* later (by {@link AuthenticationManager}) to verify it. But in case of OpenID,
* we create an {@link Authentication} only after we verified the user identity,
* so {@link AuthenticationManager} becomes no-op.
*/
@Override
public SecurityComponents createSecurityComponents() {
return new SecurityComponents(new AuthenticationManager() {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (authentication instanceof AnonymousAuthenticationToken) return authentication;
for (var property : properties) {
var authenticate = property.authenticate(authentication);
if (authenticate.isPresent()) {
return authenticate.get();
}
}
throw new BadCredentialsException("Unexpected authentication type: " + authentication);
}
});
}
/**
* Validate post-login redirect URL
*
* For security reasons, the login must not redirect outside Jenkins
* realm. For usability reason, the logout page should redirect to
* root url.
*/
protected String getValidRedirectUrl(String url) {
final String rootUrl = getRootUrl();
if (url != null && !url.isEmpty()) {
try {
final String redirectUrl = new URL(new URL(rootUrl), url).toString();
// check redirect url stays within rootUrl
if (redirectUrl.startsWith(rootUrl)) {
// check if redirect is logout page
final String logoutUrl = new URL(new URL(rootUrl), OicLogoutAction.POST_LOGOUT_URL).toString();
if (redirectUrl.startsWith(logoutUrl)) {
return rootUrl;
}
return redirectUrl;
}
} catch (MalformedURLException e) {
// Invalid URL, will return root URL
}
}
return rootUrl;
}
/**
* Handles the securityRealm/commenceLogin resource and sends the user off to the IdP
* @param from the relative URL to the page that the user has just come from
* @param referer the HTTP referer header (where to redirect the user back to after login has finished)
* @throws URISyntaxException if the provided data is invalid
*/
@Restricted(DoNotUse.class) // stapler only
public void doCommenceLogin(@QueryParameter String from, @Header("Referer") final String referer)
throws URISyntaxException {
OidcClient client = buildOidcClient();
// add the extra params for the client...
final String redirectOnFinish = getValidRedirectUrl(from != null ? from : referer);
OidcRedirectionActionBuilder builder = new OidcRedirectionActionBuilder(client);
FrameworkParameters parameters =
new JEEFrameworkParameters(Stapler.getCurrentRequest2(), Stapler.getCurrentResponse2());
WebContext webContext = JEEContextFactory.INSTANCE.newContext(parameters);
SessionStore sessionStore = JEESessionStoreFactory.INSTANCE.newSessionStore(parameters);
CallContext ctx = new CallContext(webContext, sessionStore);
RedirectionAction redirectionAction = builder.getRedirectionAction(ctx).orElseThrow();
// store the redirect url for after the login.
sessionStore.set(webContext, SESSION_POST_LOGIN_REDIRECT_URL_KEY, redirectOnFinish);
JEEHttpActionAdapter.INSTANCE.adapt(redirectionAction, webContext);
}
private boolean failedCheckOfTokenField(JWT idToken) throws ParseException {
if (tokenFieldToCheckKey == null || tokenFieldToCheckValue == null) {
return false;
}
if (idToken == null) {
return true;
}
String value = getStringField(idToken.getJWTClaimsSet().getClaims(), tokenFieldToCheckExpr);
if (value == null) {
return true;
}
return !tokenFieldToCheckValue.equals(value);
}
private void loginAndSetUserData(
String userName, JWT idToken, Map<String, Object> userInfo, OicCredentials credentials)
throws IOException, ParseException {
List<GrantedAuthority> grantedAuthorities = determineAuthorities(idToken, userInfo);
if (LOGGER.isLoggable(Level.FINEST)) {
StringBuilder grantedAuthoritiesAsString = new StringBuilder(userName);
grantedAuthoritiesAsString.append(" (");
for (GrantedAuthority grantedAuthority : grantedAuthorities) {
grantedAuthoritiesAsString.append(" ").append(grantedAuthority.getAuthority());
}
grantedAuthoritiesAsString.append(" )");
LOGGER.finest("GrantedAuthorities:" + grantedAuthoritiesAsString);
}
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(userName, "", grantedAuthorities);
SecurityContextHolder.getContext().setAuthentication(token);
User user = User.get2(token);
if (user == null) {
// should not happen
throw new IOException("Cannot set OIDC property on anonymous user");
}
String email = determineStringField(emailFieldExpr, idToken, userInfo);
if (email != null) {
user.addProperty(new Mailer.UserProperty(email));
}
String fullName = determineStringField(fullNameFieldExpr, idToken, userInfo);
if (fullName != null) {
user.setFullName(fullName);
}
// Set avatar if possible
String avatarUrl = determineStringField(avatarFieldExpr, idToken, userInfo);
OicAvatarProperty oicAvatarProperty;
if (avatarUrl != null) {
LOGGER.finest(() -> "Avatar url is: " + avatarUrl);
OicAvatarProperty.AvatarImage avatarImage = new OicAvatarProperty.AvatarImage(avatarUrl);
oicAvatarProperty = new OicAvatarProperty(avatarImage);
} else {
LOGGER.finest(() -> "No avatar URL found for user " + user.getId() + ". Ensure to remove existing avatar");
oicAvatarProperty = new OicAvatarProperty(null);
}
user.addProperty(oicAvatarProperty);
user.addProperty(credentials);
OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
SecurityListener.fireAuthenticated2(userDetails);
SecurityListener.fireLoggedIn(userName);
}
private String determineStringField(Expression<Object> fieldExpr, JWT idToken, Map<String, Object> userInfo)
throws ParseException {
if (fieldExpr != null) {
if (userInfo != null) {
Object field = fieldExpr.search(userInfo);
if (field != null) {
if (field instanceof String) {
String fieldValue = Util.fixEmptyAndTrim((String) field);
if (fieldValue != null) {
return fieldValue;
}
}
// pac4j OIDC client returns URI for some fields like the "picture" field
if (field instanceof URI) {
return ((URI) field).toASCIIString();
}
}
}
if (idToken != null) {
String fieldValue = Util.fixEmptyAndTrim(
getStringField(idToken.getJWTClaimsSet().getClaims(), fieldExpr));
if (fieldValue != null) {
return fieldValue;
}
}
}
return null;
}
protected String getStringField(Object object, Expression<Object> fieldExpr) {
if (object != null && fieldExpr != null) {
Object value = fieldExpr.search(object);
if ((value != null) && !(value instanceof Map) && !(value instanceof List)) {
return String.valueOf(value);
}
}
return null;
}
private List<GrantedAuthority> determineAuthorities(JWT idToken, Map<String, Object> userInfo)
throws ParseException {
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY2);
if (this.groupsFieldExpr == null) {
if (this.groupsFieldName == null) {
LOGGER.fine("Not adding groups because groupsFieldName is not set.");
} else {
LOGGER.fine("Not adding groups because groupsFieldName is invalid. groupsFieldName=" + groupsFieldName);
}
return grantedAuthorities;
}
Object groupsObject = null;
// userInfo has precedence when available
if (userInfo != null) {
groupsObject = this.groupsFieldExpr.search(userInfo);
}
if (groupsObject == null && idToken != null) {
groupsObject = this.groupsFieldExpr.search(idToken.getJWTClaimsSet().getClaims());
}
if (groupsObject == null) {
LOGGER.warning("idToken and userInfo did not contain group field name: " + this.groupsFieldName);
return grantedAuthorities;
}
List<String> groupNames = ensureString(groupsObject);
if (groupNames.isEmpty()) {
LOGGER.warning("Could not identify groups in " + groupsFieldName + "=" + groupsObject);
return grantedAuthorities;
}
LOGGER.fine("Number of groups in groupNames: " + groupNames.size());
for (String groupName : groupNames) {
LOGGER.fine("Adding group from UserInfo: " + groupName);
grantedAuthorities.add(new SimpleGrantedAuthority(groupName));
}
return grantedAuthorities;
}
/** Ensure group field object returns is string or list of string
*/
private List<String> ensureString(Object field) {
if (field == null) {
LOGGER.warning("userInfo did not contain a valid group field content, got null");
return Collections.emptyList();
} else if (field instanceof String sField) {
// if it's a String, the original value was not a json array.
// We try to convert the string to list based on comma while ignoring whitespaces and square brackets.
// Example value "[demo-user-group, demo-test-group, demo-admin-group]"
String[] rawFields = sField.split("[\\s\\[\\],]");
List<String> result = new ArrayList<>();
for (String rawField : rawFields) {
if (rawField != null && !rawField.isEmpty()) {
result.add(rawField);
}
}
return result;
} else if (field instanceof List) {
List<String> result = new ArrayList<>();
List<Object> groups = (List<Object>) field;
for (Object group : groups) {
if (group instanceof String) {
result.add(group.toString());
} else if (group instanceof Map) {
// if it's a Map, we use the nestedGroupFieldName to grab the groups
Map<String, String> groupMap = (Map<String, String>) group;