-
Notifications
You must be signed in to change notification settings - Fork 21
/
PAMSecurityRealm.java
211 lines (190 loc) · 8.08 KB
/
PAMSecurityRealm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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 hudson.Extension;
import hudson.Functions;
import hudson.Util;
import hudson.model.Descriptor;
import hudson.security.pam.Messages;
import hudson.util.FormValidation;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import jenkins.model.IdStrategy;
import jenkins.model.Jenkins;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.jvnet.libpam.PAM;
import org.jvnet.libpam.PAMException;
import org.jvnet.libpam.UnixUser;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.springframework.dao.DataAccessException;
import java.io.File;
import java.util.Set;
import java.util.logging.Logger;
/**
* {@link SecurityRealm} that uses Unix PAM authentication.
*
* @author Kohsuke Kawaguchi
* @since 1.282
*/
public class PAMSecurityRealm extends AbstractPasswordBasedSecurityRealm {
private static final Logger LOGGER = Logger.getLogger(PAMSecurityRealm.class.getName());
public final String serviceName;
@DataBoundConstructor
public PAMSecurityRealm(String serviceName) {
serviceName = Util.fixEmptyAndTrim(serviceName);
if (serviceName == null) {
serviceName = "sshd"; // use sshd as the default
}
this.serviceName = serviceName;
}
@Override
protected synchronized UserDetails authenticate(String username, String password) throws AuthenticationException {
try {
UnixUser u = new PAM(serviceName).authenticate(username, password);
// I never understood why Acegi insists on keeping the password...
return new User(username, "", true, true, true, true, toAuthorities(u));
} catch (PAMException e) {
throw new BadCredentialsException(e.getMessage(), e);
}
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
if (!UnixUser.exists(username)) {
throw new UsernameNotFoundException("No such Unix user: " + username);
}
try {
UnixUser u = new UnixUser(username);
// return some dummy instance
return new User(username, "", true, true, true, true, toAuthorities(u));
} catch (PAMException e) {
throw new UsernameNotFoundException("Failed to load information about Unix user: " + username, e);
}
}
private static GrantedAuthority[] toAuthorities(UnixUser u) {
Set<String> groups = u.getGroups();
GrantedAuthority[] authorities = new GrantedAuthority[groups.size() + 1];
int i = 0;
for (String group : groups) {
authorities[i++] = new GrantedAuthorityImpl(group);
}
authorities[i] = AUTHENTICATED_AUTHORITY;
return authorities;
}
@Override
public GroupDetails loadGroupByGroupname(String groupName) throws UsernameNotFoundException, DataAccessException {
String group = groupName.startsWith("@") ? groupName.substring(1) : groupName;
try {
FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByGroupName(groupName);
} catch (IOException e) {
throw new UsernameNotFoundException(group);
} catch (UnsupportedOperationException e) {
throw new UsernameNotFoundException("Unable to generate the lookup service to load " + group);
}
return new GroupDetails() {
@Override
public String getName() {
return group;
}
};
}
/**
* {@inheritDoc}
*
* @since 1.2
*/
@Override
public IdStrategy getUserIdStrategy() {
return DescriptorImpl.STRATEGY;
}
/**
* {@inheritDoc}
*
* @since 1.2
*/
@Override
public IdStrategy getGroupIdStrategy() {
return DescriptorImpl.STRATEGY;
}
public static final class DescriptorImpl extends Descriptor<SecurityRealm> {
public String getDisplayName() {
return Messages.PAMSecurityRealm_DisplayName();
}
/**
* NSS/PAM databases are case sensitive... unless running OS-X (think different™)
*
* @since 1.2
*/
private static final IdStrategy STRATEGY =
Util.fixNull(System.getProperty("os.name")).contains("OS X")
? IdStrategy.CASE_INSENSITIVE
: new IdStrategy.CaseSensitive();
@RequirePOST
public FormValidation doTest() {
Jenkins jenkins = Jenkins.get();
if (!jenkins.hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.ok();
}
File s = new File("/etc/shadow");
if (s.exists() && !s.canRead()) {
// it looks like shadow password is in use, but we don't have read access
LOGGER.fine("/etc/shadow exists but not readable");
String shadowOwner = null;
String shadowGroup = null;
PosixFileAttributes fileAttributes = null;
try {
fileAttributes = Files.readAttributes(s.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
shadowOwner = fileAttributes.owner().getName();
shadowGroup = fileAttributes.group().getName();
} catch (IOException e) {
return FormValidation.error(Messages.PAMSecurityRealm_ReadPermission());
} catch (UnsupportedOperationException e) {
return FormValidation.error(Messages.PAMSecurityRealm_UnsupportedOperation());
}
String user = System.getProperty("user.name") != null ? Messages.PAMSecurityRealm_User(System.getProperty("user.name")) : Messages.PAMSecurityRealm_CurrentUser();
if (fileAttributes.permissions().contains(PosixFilePermission.GROUP_READ)) {
// the file is readable to group. Jenkins should be in the right group, then
return FormValidation.error(Messages.PAMSecurityRealm_BelongToGroup(user, shadowGroup));
} else {
return FormValidation.error(Messages.PAMSecurityRealm_RunAsUserOrBelongToGroupAndChmod(shadowOwner, user, shadowGroup));
}
}
return FormValidation.ok(Messages.PAMSecurityRealm_Success());
}
}
@Extension
public static DescriptorImpl install() {
return Functions.isWindows() ? null : new DescriptorImpl();
}
}