-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
Expand file tree
/
Copy pathHudsonPrivateSecurityRealm.java
More file actions
1188 lines (1030 loc) · 46.5 KB
/
HudsonPrivateSecurityRealm.java
File metadata and controls
1188 lines (1030 loc) · 46.5 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) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, David Calavera, Seiji Sogabe
*
* 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 hudson.security;
import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Util;
import hudson.model.Descriptor;
import hudson.model.ManagementLink;
import hudson.model.ModelObject;
import hudson.model.User;
import hudson.model.UserProperty;
import hudson.model.UserPropertyDescriptor;
import hudson.model.userproperty.UserPropertyCategory;
import hudson.security.FederatedLoginService.FederatedIdentity;
import hudson.security.captcha.CaptchaSupport;
import hudson.util.FormValidation;
import hudson.util.PluginServletFilter;
import hudson.util.Protector;
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 jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import jenkins.model.Jenkins;
import jenkins.security.FIPS140;
import jenkins.security.SecurityListener;
import jenkins.security.seed.UserSeedProperty;
import jenkins.util.SystemProperties;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.CompatibleFilter;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
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.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.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* {@link SecurityRealm} that performs authentication by looking up {@link User}.
*
* <p>
* Implements {@link AccessControlled} to satisfy view rendering, but in reality the access control
* is done against the {@link jenkins.model.Jenkins} object.
*
* @author Kohsuke Kawaguchi
*/
public class HudsonPrivateSecurityRealm extends AbstractPasswordBasedSecurityRealm implements ModelObject, AccessControlled {
private static final int FIPS_PASSWORD_LENGTH = 14;
private static /* not final */ String ID_REGEX = System.getProperty(HudsonPrivateSecurityRealm.class.getName() + ".ID_REGEX");
/**
* Default REGEX for the user ID check in case the ID_REGEX is not set
* It allows A-Za-z0-9 + "_-"
* in Java {@code \w} is equivalent to {@code [A-Za-z0-9_]} (take care of "_")
*/
private static final String DEFAULT_ID_REGEX = "^[\\w-]+$";
/**
* If true, sign up is not allowed.
* <p>
* This is a negative switch so that the default value 'false' remains compatible with older installations.
*/
private final boolean disableSignup;
/**
* If true, captcha will be enabled.
*/
private final boolean enableCaptcha;
@Deprecated
public HudsonPrivateSecurityRealm(boolean allowsSignup) {
this(allowsSignup, false, (CaptchaSupport) null);
}
@DataBoundConstructor
public HudsonPrivateSecurityRealm(boolean allowsSignup, boolean enableCaptcha, CaptchaSupport captchaSupport) {
this.disableSignup = !allowsSignup;
this.enableCaptcha = enableCaptcha;
setCaptchaSupport(captchaSupport);
if (!allowsSignup && !hasSomeUser()) {
// if Hudson is newly set up with the security realm and there's no user account created yet,
// insert a filter that asks the user to create one
try {
PluginServletFilter.addFilter(CREATE_FIRST_USER_FILTER);
} catch (ServletException e) {
throw new AssertionError(e); // never happen because our Filter.init is no-op
}
}
}
@Override
public boolean allowsSignup() {
return !disableSignup;
}
@Restricted(NoExternalUse.class) // Jelly
public boolean getAllowsSignup() {
return allowsSignup();
}
/**
* Checks if captcha is enabled on user signup.
*
* @return true if captcha is enabled on signup.
*/
public boolean isEnableCaptcha() {
return enableCaptcha;
}
/**
* Computes if this Hudson has some user accounts configured.
*
* <p>
* This is used to check for the initial
*/
private static boolean hasSomeUser() {
for (User u : User.getAll())
if (u.getProperty(Details.class) != null)
return true;
return false;
}
/**
* This implementation doesn't support groups.
*/
@Override
public GroupDetails loadGroupByGroupname2(String groupname, boolean fetchMembers) throws UsernameNotFoundException {
throw new UsernameNotFoundException(groupname);
}
@Override
public UserDetails loadUserByUsername2(String username) throws UsernameNotFoundException {
return load(username).asUserDetails();
}
@Restricted(NoExternalUse.class)
public Details load(String username) throws UsernameNotFoundException {
User u = User.getById(username, false);
Details p = u != null ? u.getProperty(Details.class) : null;
if (p == null)
throw new UsernameNotFoundException("Password is not set: " + username);
if (p.getUser() == null)
throw new AssertionError();
return p;
}
@Override
protected UserDetails authenticate2(String username, String password) throws AuthenticationException {
Details u;
try {
u = load(username);
} catch (UsernameNotFoundException ex) {
// Waste time to prevent timing attacks distinguishing existing and non-existing user
PASSWORD_ENCODER.matches(password, ENCODED_INVALID_USER_PASSWORD);
throw ex;
}
if (!u.isPasswordCorrect(password)) {
throw new BadCredentialsException("Bad credentials");
}
return u.asUserDetails();
}
/**
* Show the sign up page with the data from the identity.
*/
@Override
public HttpResponse commenceSignup(final FederatedIdentity identity) {
// store the identity in the session so that we can use this later
Stapler.getCurrentRequest2().getSession().setAttribute(FEDERATED_IDENTITY_SESSION_KEY, identity);
return new ForwardToView(this, "signupWithFederatedIdentity.jelly") {
@Override
public void generateResponse(StaplerRequest2 req, StaplerResponse2 rsp, Object node) throws IOException, ServletException {
SignupInfo si = new SignupInfo(identity);
si.errorMessage = Messages.HudsonPrivateSecurityRealm_WouldYouLikeToSignUp(identity.getPronoun(), identity.getIdentifier());
req.setAttribute("data", si);
super.generateResponse(req, rsp, node);
}
};
}
/**
* Creates an account and associates that with the given identity. Used in conjunction
* with {@link #commenceSignup}.
*/
@RequirePOST
public User doCreateAccountWithFederatedIdentity(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
User u = _doCreateAccount(req, rsp, "signupWithFederatedIdentity.jelly");
if (u != null)
((FederatedIdentity) req.getSession().getAttribute(FEDERATED_IDENTITY_SESSION_KEY)).addTo(u);
return u;
}
private static final String FEDERATED_IDENTITY_SESSION_KEY = HudsonPrivateSecurityRealm.class.getName() + ".federatedIdentity";
/**
* Creates an user account. Used for self-registration.
*/
@RequirePOST
public User doCreateAccount(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
return _doCreateAccount(req, rsp, "signup.jelly");
}
private User _doCreateAccount(StaplerRequest2 req, StaplerResponse2 rsp, String formView) throws ServletException, IOException {
if (!allowsSignup())
throw HttpResponses.errorWithoutStack(SC_UNAUTHORIZED, "User sign up is prohibited");
boolean firstUser = !hasSomeUser();
User u = createAccount(req, rsp, enableCaptcha, formView);
if (u != null) {
if (firstUser)
tryToMakeAdmin(u); // the first user should be admin, or else there's a risk of lock out
loginAndTakeBack(req, rsp, u);
}
return u;
}
/**
* Lets the current user silently login as the given user and report back accordingly.
*/
private void loginAndTakeBack(StaplerRequest2 req, StaplerResponse2 rsp, User u) throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session != null) {
// avoid session fixation
session.invalidate();
}
req.getSession(true);
// ... and let him login
Authentication a = new UsernamePasswordAuthenticationToken(u.getId(), req.getParameter("password1"));
a = this.getSecurityComponents().manager2.authenticate(a);
SecurityContextHolder.getContext().setAuthentication(a);
SecurityListener.fireLoggedIn(u.getId());
// then back to top
req.getView(this, "success.jelly").forward(req, rsp);
}
/**
* Creates a user account. Used by admins.
*
* This version behaves differently from {@link #doCreateAccount(StaplerRequest2, StaplerResponse2)} in that
* this is someone creating another user.
*/
@RequirePOST
public void doCreateAccountByAdmin(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
createAccountByAdmin(req, rsp, "addUser.jelly", "."); // send the user back to the listing page on success
}
/**
* Creates a user account. Requires {@link Jenkins#ADMINISTER}
*/
@Restricted(NoExternalUse.class)
public User createAccountByAdmin(StaplerRequest2 req, StaplerResponse2 rsp, String addUserView, String successView) throws IOException, ServletException {
checkPermission(Jenkins.ADMINISTER);
User u = createAccount(req, rsp, false, addUserView);
if (u != null && successView != null) {
rsp.sendRedirect(successView);
}
return u;
}
/**
* Creates a user account. Intended to be called from the setup wizard.
* Note that this method does not check whether it is actually called from
* the setup wizard. This requires the {@link Jenkins#ADMINISTER} permission.
*
* @param req the request to retrieve input data from
* @return the created user account, never null
* @throws AccountCreationFailedException if account creation failed due to invalid form input
*/
@Restricted(NoExternalUse.class)
public User createAccountFromSetupWizard(StaplerRequest2 req) throws IOException, AccountCreationFailedException {
checkPermission(Jenkins.ADMINISTER);
SignupInfo si = validateAccountCreationForm(req, false);
if (!si.errors.isEmpty()) {
String messages = getErrorMessages(si);
throw new AccountCreationFailedException(messages);
} else {
return createAccount(si);
}
}
private String getErrorMessages(SignupInfo si) {
StringBuilder messages = new StringBuilder();
for (String message : si.errors.values()) {
messages.append(message).append(" | ");
}
return messages.toString();
}
/**
* Creates a first admin user account.
*
* <p>
* This can be run by anyone, but only to create the very first user account.
*/
@RequirePOST
public synchronized void doCreateFirstAccount(StaplerRequest2 req, StaplerResponse2 rsp)
throws IOException, ServletException {
if (hasSomeUser()) {
rsp.sendError(SC_UNAUTHORIZED, "First user was already created");
return;
}
User u = createAccount(req, rsp, false, "firstUser.jelly");
if (u != null) {
tryToMakeAdmin(u);
loginAndTakeBack(req, rsp, u);
}
}
/**
* Try to make this user a super-user
*/
private void tryToMakeAdmin(User u) {
AuthorizationStrategy as = Jenkins.get().getAuthorizationStrategy();
for (PermissionAdder adder : ExtensionList.lookup(PermissionAdder.class)) {
if (adder.add(as, u, Jenkins.ADMINISTER)) {
return;
}
}
}
/**
* @param req the request to get the form data from (is also used for redirection)
* @param rsp the response to use for forwarding if the creation fails
* @param validateCaptcha whether to attempt to validate a captcha in the request
* @param formView the view to redirect to if creation fails
*
* @return
* null if failed. The browser is already redirected to retry by the time this method returns.
* a valid {@link User} object if the user creation was successful.
*/
private User createAccount(StaplerRequest2 req, StaplerResponse2 rsp, boolean validateCaptcha, String formView) throws ServletException, IOException {
SignupInfo si = validateAccountCreationForm(req, validateCaptcha);
if (!si.errors.isEmpty()) {
// failed. ask the user to try again.
req.getView(this, formView).forward(req, rsp);
return null;
}
return createAccount(si);
}
/**
* @param req the request to process
* @param validateCaptcha whether to attempt to validate a captcha in the request
*
* @return a {@link SignupInfo#SignupInfo(StaplerRequest2) SignupInfo from given request}, with {@link
* SignupInfo#errors} containing errors (keyed by field name), if any of the supported fields are invalid
*/
@SuppressFBWarnings(value = "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", justification = "written to by Stapler")
private SignupInfo validateAccountCreationForm(StaplerRequest2 req, boolean validateCaptcha) {
// form field validation
// this pattern needs to be generalized and moved to stapler
SignupInfo si = new SignupInfo(req);
if (validateCaptcha && !validateCaptcha(si.captcha)) {
si.errors.put("captcha", Messages.HudsonPrivateSecurityRealm_CreateAccount_TextNotMatchWordInImage());
}
if (si.username == null || si.username.isEmpty()) {
si.errors.put("username", Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameRequired());
} else if (!containsOnlyAcceptableCharacters(si.username)) {
if (ID_REGEX == null) {
si.errors.put("username", Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameInvalidCharacters());
} else {
si.errors.put("username", Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameInvalidCharactersCustom(ID_REGEX));
}
} else {
// do not create the user - we just want to check if the user already exists but is not a "login" user.
User user = User.getById(si.username, false);
if (null != user)
// Allow sign up. SCM people has no such property.
if (user.getProperty(Details.class) != null)
si.errors.put("username", Messages.HudsonPrivateSecurityRealm_CreateAccount_UserNameAlreadyTaken());
}
if (si.password1 != null && !si.password1.equals(si.password2)) {
si.errors.put("password1", Messages.HudsonPrivateSecurityRealm_CreateAccount_PasswordNotMatch());
}
if (!(si.password1 != null && !si.password1.isEmpty())) {
si.errors.put("password1", Messages.HudsonPrivateSecurityRealm_CreateAccount_PasswordRequired());
}
try {
PASSWORD_HASH_ENCODER.encode2(si.password1);
} catch (RuntimeException ex) {
si.errors.put("password1", ex.getMessage());
}
if (si.fullname == null || si.fullname.isEmpty()) {
si.fullname = si.username;
}
if (isMailerPluginPresent() && (si.email == null || !si.email.contains("@"))) {
si.errors.put("email", Messages.HudsonPrivateSecurityRealm_CreateAccount_InvalidEmailAddress());
}
if (!User.isIdOrFullnameAllowed(si.username)) {
si.errors.put("username", hudson.model.Messages.User_IllegalUsername(si.username));
}
if (!User.isIdOrFullnameAllowed(si.fullname)) {
si.errors.put("fullname", hudson.model.Messages.User_IllegalFullname(si.fullname));
}
req.setAttribute("data", si); // for error messages in the view
return si;
}
/**
* Creates a new account from a valid signup info. A signup info is valid if its {@link SignupInfo#errors}
* field is empty.
*
* @param si the valid signup info to create an account from
* @return a valid {@link User} object created from given signup info
* @throws IllegalArgumentException if an invalid signup info is passed
*/
private User createAccount(SignupInfo si) throws IOException {
if (!si.errors.isEmpty()) {
String messages = getErrorMessages(si);
throw new IllegalArgumentException("invalid signup info passed to createAccount(si): " + messages);
}
// register the user
User user = createAccount(si.username, si.password1);
user.setFullName(si.fullname);
if (isMailerPluginPresent()) {
try {
// legacy hack. mail support has moved out to a separate plugin
Class<?> up = Jenkins.get().pluginManager.uberClassLoader.loadClass("hudson.tasks.Mailer$UserProperty");
Constructor<?> c = up.getDeclaredConstructor(String.class);
user.addProperty((UserProperty) c.newInstance(si.email));
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
user.save();
return user;
}
private boolean containsOnlyAcceptableCharacters(@NonNull String value) {
return value.matches(Objects.requireNonNullElse(ID_REGEX, DEFAULT_ID_REGEX));
}
@Restricted(NoExternalUse.class) // _entryForm.jelly and signup.jelly
public boolean isMailerPluginPresent() {
try {
// mail support has moved to a separate plugin
return null != Jenkins.get().pluginManager.uberClassLoader.loadClass("hudson.tasks.Mailer$UserProperty");
} catch (ClassNotFoundException e) {
LOGGER.finer("Mailer plugin not present");
}
return false;
}
/**
* Creates a new user account by registering a password to the user.
*/
public User createAccount(String userName, String password) throws IOException {
User user = User.getById(userName, true);
user.addProperty(Details.fromPlainPassword(password));
SecurityListener.fireUserCreated(user.getId());
return user;
}
/**
* Creates a new user account by registering a Hashed password with the user.
*
* @param userName The user's name
* @param hashedPassword A hashed password, must begin with {@code getPasswordHeader()}
* @see #getPasswordHeader()
*/
public User createAccountWithHashedPassword(String userName, String hashedPassword) throws IOException {
if (!PASSWORD_ENCODER.isPasswordHashed(hashedPassword)) {
final String message;
if (hashedPassword == null) {
message = "The hashed password cannot be null";
} else if (hashedPassword.startsWith(getPasswordHeader())) {
message = "The hashed password was hashed with the correct algorithm, but the format was not correct";
} else {
message = "The hashed password was hashed with an incorrect algorithm. Jenkins is expecting " + getPasswordHeader();
}
throw new IllegalArgumentException(message);
}
User user = User.getById(userName, true);
user.addProperty(Details.fromHashedPassword(hashedPassword));
SecurityListener.fireUserCreated(user.getId());
return user;
}
/**
* This is used primarily when the object is listed in the breadcrumb, in the user management screen.
*/
@Override
public String getDisplayName() {
return Messages.HudsonPrivateSecurityRealm_DisplayName();
}
@Override
public ACL getACL() {
return Jenkins.get().getACL();
}
@Override
public void checkPermission(Permission permission) {
Jenkins.get().checkPermission(permission);
}
@Override
public boolean hasPermission(Permission permission) {
return Jenkins.get().hasPermission(permission);
}
/**
* All users who can login to the system.
*/
public List<User> getAllUsers() {
List<User> r = new ArrayList<>();
for (User u : User.getAll()) {
if (u.getProperty(Details.class) != null)
r.add(u);
}
Collections.sort(r);
return r;
}
/**
* This is to map users under the security realm URL.
* This in turn helps us set up the right navigation breadcrumb.
*/
@Restricted(NoExternalUse.class)
public User getUser(String id) {
return User.getById(id, User.ALLOW_USER_CREATION_VIA_URL && hasPermission(Jenkins.ADMINISTER));
}
// TODO
private static final Collection<? extends GrantedAuthority> TEST_AUTHORITY = Set.of(AUTHENTICATED_AUTHORITY2);
public static final class SignupInfo {
public String username, password1, password2, fullname, email, captcha;
/**
* To display a general error message, set it here.
*
*/
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", justification = "read by Stapler")
public String errorMessage;
/**
* Add field-specific error messages here.
* Keys are field names (e.g. {@code password2}), values are the messages.
*/
// TODO i18n?
public HashMap<String, String> errors = new HashMap<>();
public SignupInfo() {
}
public SignupInfo(StaplerRequest2 req) {
req.bindParameters(this);
}
public SignupInfo(FederatedIdentity i) {
this.username = i.getNickname();
this.fullname = i.getFullName();
this.email = i.getEmailAddress();
}
}
/**
* {@link UserProperty} that provides the {@link UserDetails} view of the User object.
*
* <p>
* When a {@link User} object has this property on it, it means the user is configured
* for log-in.
*
* <p>
* When a {@link User} object is re-configured via the UI, the password
* is sent to the hidden input field by using {@link Protector}, so that
* the same password can be retained but without leaking information to the browser.
*/
public static final class Details extends UserProperty {
/**
* Hashed password.
*/
private /*almost final*/ String passwordHash;
/**
* @deprecated Scrambled password.
* Field kept here to load old (pre 1.283) user records,
* but now marked transient so field is no longer saved.
*/
@Deprecated
private transient String password;
private Details(String passwordHash) {
this.passwordHash = passwordHash;
}
static Details fromHashedPassword(String hashed) {
return new Details(hashed);
}
static Details fromPlainPassword(String rawPassword) {
return new Details(PASSWORD_ENCODER.encode(rawPassword));
}
/**
* @since 2.266
*/
public Collection<? extends GrantedAuthority> getAuthorities2() {
// TODO
return TEST_AUTHORITY;
}
/**
* @deprecated use {@link #getAuthorities2}
*/
@Deprecated
public org.acegisecurity.GrantedAuthority[] getAuthorities() {
return org.acegisecurity.GrantedAuthority.fromSpring(getAuthorities2());
}
public String getPassword() {
return passwordHash;
}
public boolean isPasswordCorrect(String candidate) {
return PASSWORD_ENCODER.matches(candidate, getPassword());
}
public String getProtectedPassword() {
// put session Id in it to prevent a replay attack.
return Protector.protect(Stapler.getCurrentRequest2().getSession().getId() + ':' + getPassword());
}
public String getUsername() {
return user.getId();
}
/*package*/ User getUser() {
return user;
}
public boolean isAccountNonExpired() {
return true;
}
public boolean isAccountNonLocked() {
return true;
}
public boolean isCredentialsNonExpired() {
return true;
}
public boolean isEnabled() {
return true;
}
UserDetails asUserDetails() {
return new UserDetailsImpl(getAuthorities2(), getPassword(), getUsername(), isAccountNonExpired(), isAccountNonLocked(), isCredentialsNonExpired(), isEnabled());
}
private static final class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;
private final Collection<? extends GrantedAuthority> authorities;
private final String password;
private final String username;
private final boolean accountNonExpired;
private final boolean accountNonLocked;
private final boolean credentialsNonExpired;
private final boolean enabled;
UserDetailsImpl(Collection<? extends GrantedAuthority> authorities, String password, String username, boolean accountNonExpired, boolean accountNonLocked, boolean credentialsNonExpired, boolean enabled) {
this.authorities = authorities;
this.password = password;
this.username = username;
this.accountNonExpired = accountNonExpired;
this.accountNonLocked = accountNonLocked;
this.credentialsNonExpired = credentialsNonExpired;
this.enabled = enabled;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public boolean equals(Object o) {
return o instanceof UserDetailsImpl && ((UserDetailsImpl) o).getUsername().equals(getUsername());
}
@Override
public int hashCode() {
return getUsername().hashCode();
}
}
@Extension @Symbol("password")
public static final class DescriptorImpl extends UserPropertyDescriptor {
@NonNull
@Override
public String getDisplayName() {
return Messages.HudsonPrivateSecurityRealm_Details_DisplayName();
}
@Override
public Details newInstance(StaplerRequest2 req, JSONObject formData) throws FormException {
if (req == null) {
// Should never happen, see newInstance() Javadoc
throw new FormException("Stapler request is missing in the call", "staplerRequest");
}
String pwd = Util.fixEmpty(req.getParameter("user.password"));
String pwd2 = Util.fixEmpty(req.getParameter("user.password2"));
if (pwd == null || pwd2 == null) {
// one of the fields is empty
throw new FormException("Please confirm the password by typing it twice", "user.password2");
}
// will be null if it wasn't encrypted
String data = Protector.unprotect(pwd);
String data2 = Protector.unprotect(pwd2);
if (data == null != (data2 == null)) {
// Require that both values are protected or unprotected; do not allow user to change just one text field
throw new FormException("Please confirm the password by typing it twice", "user.password2");
}
if (data != null /* && data2 != null */ && !MessageDigest.isEqual(data.getBytes(StandardCharsets.UTF_8), data2.getBytes(StandardCharsets.UTF_8))) {
// passwords are different encrypted values
throw new FormException("Please confirm the password by typing it twice", "user.password2");
}
if (data == null /* && data2 == null */ && !pwd.equals(pwd2)) {
// passwords are different plain values
throw new FormException("Please confirm the password by typing it twice", "user.password2");
}
if (data != null) {
String prefix = Stapler.getCurrentRequest2().getSession().getId() + ':';
if (data.startsWith(prefix)) {
// The password is not being changed
return Details.fromHashedPassword(data.substring(prefix.length()));
}
}
// The password is being changed
try {
PASSWORD_HASH_ENCODER.encode2(pwd);
} catch (RuntimeException ex) {
throw new FormException(ex.getMessage(), "user.password");
}
User user = Util.getNearestAncestorOfTypeOrThrow(req, User.class);
// the UserSeedProperty is not touched by the configure page
UserSeedProperty userSeedProperty = user.getProperty(UserSeedProperty.class);
if (userSeedProperty != null) {
userSeedProperty.renewSeed();
}
return Details.fromPlainPassword(Util.fixNull(pwd));
}
@Override
public boolean isEnabled() {
// this feature is only when HudsonPrivateSecurityRealm is enabled
return Jenkins.get().getSecurityRealm() instanceof HudsonPrivateSecurityRealm;
}
@Override
public UserProperty newInstance(User user) {
return null;
}
@Override
public @NonNull UserPropertyCategory getUserPropertyCategory() {
return UserPropertyCategory.get(UserPropertyCategory.Security.class);
}
}
}
/**
* Displays "manage users" link in the system config if {@link HudsonPrivateSecurityRealm}
* is in effect.
*/
@Extension @Symbol("localUsers")
public static final class ManageUserLinks extends ManagementLink {
@Override
public String getIconFileName() {
if (Jenkins.get().getSecurityRealm() instanceof HudsonPrivateSecurityRealm)
return "symbol-people";
else
return null; // not applicable now
}
@Override
public String getUrlName() {
return "securityRealm/";
}
@Override
public String getDisplayName() {
return Messages.HudsonPrivateSecurityRealm_ManageUserLinks_DisplayName();
}
@Override
public String getDescription() {
return Messages.HudsonPrivateSecurityRealm_ManageUserLinks_Description();
}
@NonNull
@Override
public Category getCategory() {
return Category.SECURITY;
}
}
/**
* {@link PasswordHashEncoder} that uses jBCrypt.
*/
static class JBCryptEncoder extends BCryptPasswordEncoder implements PasswordHashEncoder {
// in jBCrypt the maximum is 30, which takes ~22h with laptop late-2017
// and for 18, it's "only" 20s
@Restricted(NoExternalUse.class)
private static int MAXIMUM_BCRYPT_LOG_ROUND = SystemProperties.getInteger(HudsonPrivateSecurityRealm.class.getName() + ".maximumBCryptLogRound", 18);
private static final Pattern BCRYPT_PATTERN = Pattern.compile("^\\$2a\\$([0-9]{2})\\$.{53}$");
@Override
public String encode2(CharSequence rawPassword) {
try {
return encode(rawPassword);
} catch (IllegalArgumentException ex) {
if (ex.getMessage().equals("password cannot be more than 72 bytes")) {
if (rawPassword.toString().matches("\\A\\p{ASCII}+\\z")) {
throw new IllegalArgumentException(Messages.HudsonPrivateSecurityRealm_CreateAccount_BCrypt_PasswordTooLong_ASCII());
}
throw new IllegalArgumentException(Messages.HudsonPrivateSecurityRealm_CreateAccount_BCrypt_PasswordTooLong());
}
throw ex;
}
}
/**
* Returns true if the supplied hash looks like a bcrypt encoded hash value, based off of the
* implementation defined in jBCrypt and <a href="https://en.wikipedia.org/wiki/Bcrypt">the Wikipedia page</a>.
*
*/
@Override
public boolean isHashValid(String hash) {
Matcher matcher = BCRYPT_PATTERN.matcher(hash);
if (matcher.matches()) {
String logNumOfRound = matcher.group(1);
// no number format exception due to the expression
int logNumOfRoundInt = Integer.parseInt(logNumOfRound);
if (logNumOfRoundInt > 0 && logNumOfRoundInt <= MAXIMUM_BCRYPT_LOG_ROUND) {
return true;
}
}
return false;
}
}
static class PBKDF2PasswordEncoder implements PasswordHashEncoder {
private static final String STRING_SEPARATION = ":";
private static final int KEY_LENGTH_BITS = 512;
private static final int SALT_LENGTH_BYTES = 16;
// https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2
// ~230ms on an Intel i7-10875H CPU (JBCryptEncoder is ~57ms)
private static final int ITTERATIONS = 210_000;
private static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA512";
private volatile SecureRandom random; // defer construction until we need to use it to not delay startup in the case of lack of entropy.
// $PBDKF2 is already checked before we get here.
// $algorithm(HMACSHA512) : rounds : salt_in_hex $ mac_in_hex
private static final Pattern PBKDF2_PATTERN =
Pattern.compile("^\\$HMACSHA512\\:" + ITTERATIONS + "\\:[a-f0-9]{" + (SALT_LENGTH_BYTES * 2) + "}\\$[a-f0-9]{" + ((KEY_LENGTH_BITS / 8) * 2) + "}$");
@Override
public String encode(CharSequence rawPassword) {
if (rawPassword.length() < FIPS_PASSWORD_LENGTH) {
throw new IllegalArgumentException(Messages.HudsonPrivateSecurityRealm_CreateAccount_FIPS_PasswordLengthInvalid());
}
try {
return generatePasswordHashWithPBKDF2(rawPassword);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new RuntimeException("Unable to generate password with PBKDF2WithHmacSHA512", e);
}
}
@Override