/
ActiveDirectorySecurityRealm.java
686 lines (605 loc) · 32 KB
/
ActiveDirectorySecurityRealm.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
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
/*
* The MIT License
*
* Copyright (c) 2008-2014, Kohsuke Kawaguchi, CloudBees, Inc., and contributors
*
* 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.plugins.active_directory;
import static hudson.Util.fixEmpty;
import static hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.toDC;
import com4j.typelibs.ado20.ClassFactory;
import groovy.lang.Binding;
import hudson.Extension;
import hudson.Functions;
import hudson.Util;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.security.AbstractPasswordBasedSecurityRealm;
import hudson.security.AuthorizationStrategy;
import hudson.security.GroupDetails;
import hudson.security.SecurityRealm;
import hudson.security.TokenBasedRememberMeServices2;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.ListBoxModel.Option;
import hudson.util.Secret;
import hudson.util.spring.BeanBuilder;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.StartTlsRequest;
import javax.naming.ldap.StartTlsResponse;
import javax.net.ssl.SSLSocketFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.springframework.dao.DataAccessException;
import org.springframework.web.context.WebApplicationContext;
import com.sun.jndi.ldap.LdapCtxFactory;
/**
* {@link SecurityRealm} that talks to Active Directory.
*
* @author Kohsuke Kawaguchi
*/
public class ActiveDirectorySecurityRealm extends AbstractPasswordBasedSecurityRealm {
/**
* Active directory domain name to authenticate against.
*
* <p>
* When this plugin is used on Windows, this field is null, and we use ADSI
* and ADO through com4j to perform authentication.
*
* <p>
* OTOH, when this plugin runs on non-Windows, this field must be non-null,
* and we'll use LDAP for authentication.
*/
public final String domain;
/**
* Active directory site (which specifies the physical concentration of the
* servers), if any. If the value is non-null, we'll only contact servers in
* this site.
*
* <p>
* On Windows, I'm assuming ADSI takes care of everything automatically.
*/
public final String site;
/**
* If non-null, use this name and password to bind to LDAP to obtain the DN
* of the user trying to login. This is unnecessary in a single-domain mode,
* where we can just bind with the user name and password provided during
* the login, but in a forest mode, without some known credential, we cannot
* figure out which domain in the forest the user belongs to.
*/
public final String bindName;
public final Secret bindPassword;
/**
* If non-null, Jenkins will try to connect at this server at the first priority, before falling back to
* discovered DNS servers.
*/
public final String server;
private GroupLookupStrategy groupLookupStrategy;
/**
* If true, Jenkins ignores Active Directory groups that are not being used by the active Authorization Strategy.
* This can significantly improve performance in environments with a large number of groups
* but a small number of corresponding rules defined by the Authorization Strategy.
* Groups are considered as used if they are returned by {@link AuthorizationStrategy#getGroups()}.
*/
public final boolean removeIrrelevantGroups;
public ActiveDirectorySecurityRealm(String domain, String site, String bindName, String bindPassword, String server) {
this(domain,site,bindName,bindPassword,server,GroupLookupStrategy.AUTO,false);
}
public ActiveDirectorySecurityRealm(String domain, String site, String bindName, String bindPassword, String server, GroupLookupStrategy groupLookupStrategy) {
this(domain,site,bindName,bindPassword,server,groupLookupStrategy,false);
}
@DataBoundConstructor
public ActiveDirectorySecurityRealm(String domain, String site, String bindName,
String bindPassword, String server, GroupLookupStrategy groupLookupStrategy, boolean removeIrrelevantGroups) {
this.domain = fixEmpty(domain);
this.site = fixEmpty(site);
this.bindName = fixEmpty(bindName);
this.bindPassword = Secret.fromString(fixEmpty(bindPassword));
this.groupLookupStrategy = groupLookupStrategy;
this.removeIrrelevantGroups = removeIrrelevantGroups;
// append default port if not specified
server = fixEmpty(server);
if (server != null) {
if (!server.contains(":")) server += ":3268";
}
this.server = server;
}
public GroupLookupStrategy getGroupLookupStrategy() {
if (groupLookupStrategy==null) return GroupLookupStrategy.AUTO;
return groupLookupStrategy;
}
public SecurityComponents createSecurityComponents() {
BeanBuilder builder = new BeanBuilder(getClass().getClassLoader());
Binding binding = new Binding();
binding.setVariable("realm", this);
builder.parse(getClass().getResourceAsStream("ActiveDirectory.groovy"), binding);
WebApplicationContext context = builder.createApplicationContext();
final AbstractActiveDirectoryAuthenticationProvider adp = findBean(AbstractActiveDirectoryAuthenticationProvider.class, context);
final UserDetailsService uds = findBean(UserDetailsService.class, context);
TokenBasedRememberMeServices2 rms = new TokenBasedRememberMeServices2() {
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
try {
return super.autoLogin(request, response);
} catch (Exception e) {// TODO: this check is made redundant with 1.556, but needed with earlier versions
cancelCookie(request, response, "Failed to handle remember-me cookie: "+Functions.printThrowable(e));
return null;
}
}
};
rms.setUserDetailsService(uds);
rms.setKey(Hudson.getInstance().getSecretKey());
rms.setParameter("remember_me"); // this is the form field name in login.jelly
return new SecurityComponents( findBean(AuthenticationManager.class, context), uds, rms);
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/**
* Authentication test.
*/
public void doAuthTest(StaplerRequest req, StaplerResponse rsp, @QueryParameter String username, @QueryParameter String password) throws IOException, ServletException {
// require the administrator permission since this is full of debug info.
Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
StringWriter out = new StringWriter();
PrintWriter pw = new PrintWriter(out);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
UserDetailsService uds = getAuthenticationProvider();
if (uds instanceof ActiveDirectoryUnixAuthenticationProvider) {
ActiveDirectoryUnixAuthenticationProvider p = (ActiveDirectoryUnixAuthenticationProvider) uds;
DescriptorImpl descriptor = getDescriptor();
for (String domainName : domain.split(",")) {
try {
pw.println("Domain="+domainName+" site="+site);
List<SocketInfo> ldapServers = descriptor.obtainLDAPServer(domainName, site, server);
pw.println("List of domain controllers: "+ldapServers);
for (SocketInfo ldapServer : ldapServers) {
pw.println("Trying a domain controller at "+ldapServer);
try {
UserDetails d = p.retrieveUser(username, password, domainName, Collections.singletonList(ldapServer));
pw.println("Authenticated as "+d);
} catch (AuthenticationException e) {
e.printStackTrace(pw);
}
}
} catch (NamingException e) {
pw.println("Failing to resolve domain controllers");
e.printStackTrace(pw);
}
}
} else {
pw.println("Using Windows ADSI. No diagnostics available.");
}
} catch (Exception e) {
e.printStackTrace(pw);
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
req.setAttribute("output", out.toString());
req.getView(this, "test.jelly").forward(req, rsp);
}
@Extension
public static final class DescriptorImpl extends Descriptor<SecurityRealm> {
public String getDisplayName() {
return Messages.DisplayName();
}
@Override
public String getHelpFile() {
return "/plugin/active-directory/help/realm.html";
}
/**
* If true, we can do ADSI/COM based look up that's far more reliable.
* False if we need to do the authentication in pure Java via
* {@link ActiveDirectoryUnixAuthenticationProvider}
*/
public boolean canDoNativeAuth() {
if (!Functions.isWindows()) return false;
try {
ClassFactory.createConnection().dispose();
return true;
} catch (Throwable t) {
if (!WARNED) {
LOGGER.log(Level.INFO,"COM4J isn't working. Falling back to non-native authentication",t);
WARNED = true;
}
return false;
}
}
public ListBoxModel doFillGroupLookupStrategyItems() {
ListBoxModel model = new ListBoxModel();
for (GroupLookupStrategy e : GroupLookupStrategy.values()) {
model.add(e.getDisplayName(),e.name());
}
return model;
}
private static boolean WARNED = false;
public FormValidation doValidate(@QueryParameter(fixEmpty = true) String domain, @QueryParameter(fixEmpty = true) String site, @QueryParameter(fixEmpty = true) String bindName,
@QueryParameter(fixEmpty = true) String bindPassword, @QueryParameter(fixEmpty = true) String server) throws IOException, ServletException, NamingException {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
Functions.checkPermission(Hudson.ADMINISTER);
domain = Util.fixEmptyAndTrim(domain);
if (canDoNativeAuth() && domain==null) {
// this check must be identical to that of ActiveDirectory.groovy
try {
// make sure we can connect via ADSI
new ActiveDirectoryAuthenticationProvider();
return FormValidation.ok("OK");
} catch (Exception e) {
return FormValidation.error(e, "Failed to contact Active Directory");
}
}
if (domain==null) {// no value given yet
return FormValidation.error("No domain name set");
}
Secret password = Secret.fromString(bindPassword);
if (bindName!=null && password==null)
return FormValidation.error("DN is specified but not password");
String[] names = domain.split(",");
for (String name : names) {
if (!name.endsWith("."))
name += '.';
DirContext ictx;
// first test the sanity of the domain name itself
try {
LOGGER.fine("Attempting to resolve "+name+" to NS record");
ictx = createDNSLookupContext();
Attributes attributes = ictx.getAttributes(name, new String[] { "NS" });
Attribute ns = attributes.get("NS");
if (ns==null) {
LOGGER.fine("Attempting to resolve "+name+" to A record");
attributes = ictx.getAttributes(name, new String[] { "A" });
Attribute a = attributes.get("A");
if (a==null)
throw new NamingException(name+" doesn't look like a domain name");
}
LOGGER.log(Level.FINE, "{0} resolved to {1}", new Object[] {name, ns});
} catch (NamingException e) {
LOGGER.log(Level.WARNING, "Failed to resolve "+name+" to A record", e);
return FormValidation.error(e, name+" doesn't look like a valid domain name");
}
// then look for the LDAP server
List<SocketInfo> servers;
try {
servers = obtainLDAPServer(ictx, name, site, server);
} catch (NamingException e) {
String msg = site==null ? "No LDAP server was found in "+name : "No LDAP server was found in the "+site+" site of "+name;
LOGGER.log(Level.WARNING, msg, e);
return FormValidation.error(e, msg);
}
if (bindName!=null) {
// make sure the bind actually works
try {
DirContext context = bind(bindName, Secret.toString(password), servers);
try {
// actually do a search to make sure the credential is valid
new LDAPSearchBuilder(context, toDC(name)).searchOne("(objectClass=user)");
} finally {
context.close();
}
} catch (BadCredentialsException e) {
return FormValidation.error(e, "Bad bind username or password");
} catch (javax.naming.AuthenticationException e) {
return FormValidation.error(e, "Bad bind username or password");
} catch (Exception e) {
return FormValidation.error(e, e.getMessage());
}
} else {
// just some connection test
// try to connect to LDAP port to make sure this machine has LDAP service
IOException error = null;
for (SocketInfo si : servers) {
try {
si.connect().close();
break; // looks good
} catch (IOException e) {
LOGGER.log(Level.FINE, "Failed to connect to "+si, e);
error = e;
// try the next server in the list
}
}
if (error!=null) {
LOGGER.log(Level.WARNING, "Failed to connect to "+servers, error);
return FormValidation.error(error, "Failed to connect to "+servers);
}
}
}
// looks good
return FormValidation.ok("Success");
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
}
/**
* Binds to the server using the specified username/password.
* <p>
* In a real deployment, often there are servers that don't respond or
* otherwise broken, so try all the servers.
*/
public DirContext bind(String principalName, String password, List<SocketInfo> ldapServers) {
// in a AD forest, it'd be mighty nice to be able to login as "joe"
// as opposed to "joe@europe",
// but the bind operation doesn't appear to allow me to do so.
Hashtable<String, String> props = new Hashtable<String, String>();
props.put(Context.REFERRAL, "follow");
props.put("java.naming.ldap.attributes.binary","tokenGroups objectSid");
props.put("java.naming.ldap.factory.socket",TrustAllSocketFactory.class.getName());
NamingException error = null;
for (SocketInfo ldapServer : ldapServers) {
try {
LdapContext context = bind(principalName, password, ldapServer, props);
LOGGER.fine("Bound to " + ldapServer);
return context;
} catch (javax.naming.AuthenticationException e) {
// if the authentication failed (as opposed to a communication problem with the server),
// don't retry, because if this is because of a wrong password, we can end up locking
// the user out by causing multiple failed attempts.
// error code 49 (LdapClient.LDAP_INVALID_CREDENTIALS) maps to this exception in LdapCtx.mapErrorCode
// see http://confluence.atlassian.com/display/CONFKB/LDAP+Error+Code+49 and http://www-01.ibm.com/support/docview.wss?uid=swg21290631
// for subcodes within this error.
// it seems like we can be clever about checking subcode to decide if we retry or not,
// but I'm erring on the safe side as I'm not sure how reliable the code is, and maybe
// servers can be configured to hide the distinction between "no such user" and "bad password"
// to reveal what user names are available.
LOGGER.log(Level.WARNING, "Failed to authenticate while binding to "+ldapServer, e);
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
} catch (NamingException e) {
LOGGER.log(Level.WARNING, "Failed to bind to "+ldapServer, e);
error = e; // retry
}
}
// if all the attempts failed
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password", error);
}
private void customizeLdapProperty(Hashtable<String, String> props, String propName) {
String prop = System.getProperty(propName, null);
if (prop != null) {
props.put(propName, prop);
}
}
/** Lookups for hardcoded LDAP properties if they are specified as System properties and uses them */
private void customizeLdapProperties(Hashtable<String, String> props) {
customizeLdapProperty(props, "com.sun.jndi.ldap.connect.timeout");
customizeLdapProperty(props, "com.sun.jndi.ldap.read.timeout");
}
private LdapContext bind(String principalName, String password, SocketInfo server, Hashtable<String, String> props) throws NamingException {
String ldapUrl = (FORCE_LDAPS?"ldaps://":"ldap://") + server + '/';
String oldName = Thread.currentThread().getName();
Thread.currentThread().setName("Connecting to "+ldapUrl+" : "+oldName);
LOGGER.fine("Connecting to " + ldapUrl);
try {
props.put(Context.PROVIDER_URL, ldapUrl);
props.put("java.naming.ldap.version", "3");
customizeLdapProperties(props);
LdapContext context = (LdapContext)LdapCtxFactory.getLdapCtxInstance(ldapUrl, props);
if (!FORCE_LDAPS) {
// try to upgrade to TLS if we can, but failing to do so isn't fatal
// see http://download.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html
try {
StartTlsResponse rsp = (StartTlsResponse)context.extendedOperation(new StartTlsRequest());
rsp.negotiate((SSLSocketFactory)TrustAllSocketFactory.getDefault());
LOGGER.fine("Connection upgraded to TLS");
} catch (NamingException e) {
LOGGER.log(Level.FINE, "Failed to start TLS. Authentication will be done via plain-text LDAP", e);
context.removeFromEnvironment("java.naming.ldap.factory.socket");
} catch (IOException e) {
LOGGER.log(Level.FINE, "Failed to start TLS. Authentication will be done via plain-text LDAP", e);
context.removeFromEnvironment("java.naming.ldap.factory.socket");
}
}
if (principalName==null || password==null || password.equals("")) {
// anonymous bind. LDAP uses empty password as a signal to anonymous bind (RFC 2829 5.1),
// which means it can never be the actual user password.
context.addToEnvironment(Context.SECURITY_AUTHENTICATION, "none");
LOGGER.fine("Binding anonymously to "+ldapUrl);
} else {
// authenticate after upgrading to TLS, so that the credential won't go in clear text
context.addToEnvironment(Context.SECURITY_PRINCIPAL, principalName);
context.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
LOGGER.fine("Binding as "+principalName+" to "+ldapUrl);
}
// this is supposed to cause the LDAP bind operation with the server,
// but I notice that AD may still accept this and yet fail to search later,
// when I tried anonymous bind.
// if I do specify a wrong credential, this seems to fail.
context.reconnect(null);
return context; // worked
} finally {
Thread.currentThread().setName(oldName);
}
}
/**
* Creates {@link DirContext} for accesssing DNS.
*/
public DirContext createDNSLookupContext() throws NamingException {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
env.put("java.naming.provider.url", "dns:");
return new InitialDirContext(env);
}
public List<SocketInfo> obtainLDAPServer(String domainName, String site, String preferredServer) throws NamingException {
return obtainLDAPServer(createDNSLookupContext(), domainName, site, preferredServer);
}
// domain name prefixes
// see http://technet.microsoft.com/en-us/library/cc759550(WS.10).aspx
private static final List<String> CANDIDATES = Arrays.asList("_gc._tcp.","_ldap._tcp.");
/**
* Use DNS and obtains the LDAP servers that we should try.
*
* @param preferredServers
* If non-null, these servers are reported instead of doing the discovery.
* In previous versions, this was simply added on top of the auto-discovered list, but this option
* is useful when you have many domain controllers (because a single mistyped password can cause
* an authentication attempt with every listed server, which can lock the user out!) This also
* puts this feature in alignment with {@link #DOMAIN_CONTROLLERS}, which seems to indicate that
* there are users who prefer this behaviour.
*
* @return A list with at least one item.
*/
public List<SocketInfo> obtainLDAPServer(DirContext ictx, String domainName, String site, String preferredServers) throws NamingException {
List<SocketInfo> result = new ArrayList<SocketInfo>();
if (preferredServers==null)
preferredServers = DOMAIN_CONTROLLERS;
if (preferredServers!=null) {
for (String token : preferredServers.split(",")) {
result.add(new SocketInfo(token.trim()));
}
return result;
}
String ldapServer = null;
Attribute a = null;
NamingException failure = null;
// try global catalog if it exists first, then the particular domain
for (String candidate : CANDIDATES) {
ldapServer = candidate+(site!=null ? site+"._sites." : "")+domainName;
LOGGER.fine("Attempting to resolve "+ldapServer+" to SRV record");
try {
Attributes attributes = ictx.getAttributes(ldapServer, new String[] { "SRV" });
a = attributes.get("SRV");
if (a!=null)
break;
} catch (NamingException e) {
// failed retrieval. try next option.
failure = e;
} catch (NumberFormatException x) {
failure = (NamingException) new NamingException("JDK IPv6 bug encountered").initCause(x);
}
}
if (a!=null) {
// discover servers
class PrioritizedSocketInfo implements Comparable<PrioritizedSocketInfo> {
SocketInfo socket;
int priority;
PrioritizedSocketInfo(SocketInfo socket, int priority) {
this.socket = socket;
this.priority = priority;
}
public int compareTo(PrioritizedSocketInfo that) {
return that.priority-this.priority; // sort them so that bigger priority comes first
}
}
List<PrioritizedSocketInfo> plist = new ArrayList<PrioritizedSocketInfo>();
for (NamingEnumeration ne = a.getAll(); ne.hasMoreElements();) {
String record = ne.next().toString();
LOGGER.fine("SRV record found: "+record);
String[] fields = record.split(" ");
// fields[1]: weight
// fields[2]: port
// fields[3]: target host name
String hostName = fields[3];
// cut off trailing ".". JENKINS-2647
if (hostName.endsWith("."))
hostName = hostName.substring(0, hostName.length()-1);
int port = Integer.parseInt(fields[2]);
if (FORCE_LDAPS) {
// map to LDAPS ports. I don't think there's any SRV records specifically for LDAPS.
// I think Microsoft considers LDAP+TLS the way to go, or else there should have been
// separate SRV entries.
if (port==389) port=636;
if (port==3268) port=3269;
}
int p = Integer.parseInt(fields[0]);
plist.add(new PrioritizedSocketInfo(new SocketInfo(hostName, port),p));
}
Collections.sort(plist);
for (PrioritizedSocketInfo psi : plist)
result.add(psi.socket);
}
if (result.isEmpty()) {
NamingException x = new NamingException("No SRV record found for " + ldapServer);
if (failure!=null) x.initCause(failure);
throw x;
}
LOGGER.fine(ldapServer+" resolved to "+result);
return result;
}
}
@Override
public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
return getAuthenticationProvider().loadGroupByGroupname(groupname);
}
/**
* Interface that actually talks to Active Directory.
*/
public AbstractActiveDirectoryAuthenticationProvider getAuthenticationProvider() {
return (AbstractActiveDirectoryAuthenticationProvider)getSecurityComponents().userDetails;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
// delegate to one of our ActiveDirectory(Unix)?AuthenticationProvider
return getAuthenticationProvider().loadUserByUsername(username);
}
@Override
protected UserDetails authenticate(String username, String password) throws AuthenticationException {
return getAuthenticationProvider().retrieveUser(username,new UsernamePasswordAuthenticationToken(username,password));
}
private static final Logger LOGGER = Logger.getLogger(ActiveDirectorySecurityRealm.class.getName());
/**
* If non-null, this value specifies the domain controllers and overrides all the lookups.
*
* The format is "host:port,host:port,..."
*
* @deprecated as of 1.28
* Use the UI field.
*/
public static String DOMAIN_CONTROLLERS = System.getProperty(ActiveDirectorySecurityRealm.class.getName()+".domainControllers");
/**
* Instead of LDAP+TLS upgrade, start right away with LDAPS.
* For the time being I'm trying not to expose this to users. I don't see why any AD shouldn't support
* TLS upgrade if it's got the certificate.
*
* One legitimate use case is when the domain controller is Windows 2000, which doesn't support TLS
* (according to http://support.microsoft.com/kb/321051).
*/
public static boolean FORCE_LDAPS = Boolean.getBoolean(ActiveDirectorySecurityRealm.class.getName()+".forceLdaps");
}