1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2021 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15 
16 /*
17  * locate LDAP servers using DNS SRV records.
18  * Location code based on MIT Kerberos KDC location code.
19  */
20 #include "portable.h"
21 
22 #include <stdio.h>
23 
24 #include <ac/stdlib.h>
25 
26 #include <ac/param.h>
27 #include <ac/socket.h>
28 #include <ac/string.h>
29 #include <ac/time.h>
30 
31 #include "ldap-int.h"
32 
33 #ifdef HAVE_ARPA_NAMESER_H
34 #include <arpa/nameser.h>
35 #endif
36 #ifdef HAVE_RESOLV_H
37 #include <resolv.h>
38 #endif
39 
ldap_dn2domain(LDAP_CONST char * dn_in,char ** domainp)40 int ldap_dn2domain(
41 	LDAP_CONST char *dn_in,
42 	char **domainp)
43 {
44 	int i, j;
45 	char *ndomain;
46 	LDAPDN dn = NULL;
47 	LDAPRDN rdn = NULL;
48 	LDAPAVA *ava = NULL;
49 	struct berval domain = BER_BVNULL;
50 	static const struct berval DC = BER_BVC("DC");
51 	static const struct berval DCOID = BER_BVC("0.9.2342.19200300.100.1.25");
52 
53 	assert( dn_in != NULL );
54 	assert( domainp != NULL );
55 
56 	*domainp = NULL;
57 
58 	if ( ldap_str2dn( dn_in, &dn, LDAP_DN_FORMAT_LDAP ) != LDAP_SUCCESS ) {
59 		return -2;
60 	}
61 
62 	if( dn ) for( i=0; dn[i] != NULL; i++ ) {
63 		rdn = dn[i];
64 
65 		for( j=0; rdn[j] != NULL; j++ ) {
66 			ava = rdn[j];
67 
68 			if( rdn[j+1] == NULL &&
69 				(ava->la_flags & LDAP_AVA_STRING) &&
70 				ava->la_value.bv_len &&
71 				( ber_bvstrcasecmp( &ava->la_attr, &DC ) == 0
72 				|| ber_bvcmp( &ava->la_attr, &DCOID ) == 0 ) )
73 			{
74 				if( domain.bv_len == 0 ) {
75 					ndomain = LDAP_REALLOC( domain.bv_val,
76 						ava->la_value.bv_len + 1);
77 
78 					if( ndomain == NULL ) {
79 						goto return_error;
80 					}
81 
82 					domain.bv_val = ndomain;
83 
84 					AC_MEMCPY( domain.bv_val, ava->la_value.bv_val,
85 						ava->la_value.bv_len );
86 
87 					domain.bv_len = ava->la_value.bv_len;
88 					domain.bv_val[domain.bv_len] = '\0';
89 
90 				} else {
91 					ndomain = LDAP_REALLOC( domain.bv_val,
92 						ava->la_value.bv_len + sizeof(".") + domain.bv_len );
93 
94 					if( ndomain == NULL ) {
95 						goto return_error;
96 					}
97 
98 					domain.bv_val = ndomain;
99 					domain.bv_val[domain.bv_len++] = '.';
100 					AC_MEMCPY( &domain.bv_val[domain.bv_len],
101 						ava->la_value.bv_val, ava->la_value.bv_len );
102 					domain.bv_len += ava->la_value.bv_len;
103 					domain.bv_val[domain.bv_len] = '\0';
104 				}
105 			} else {
106 				domain.bv_len = 0;
107 			}
108 		}
109 	}
110 
111 
112 	if( domain.bv_len == 0 && domain.bv_val != NULL ) {
113 		LDAP_FREE( domain.bv_val );
114 		domain.bv_val = NULL;
115 	}
116 
117 	ldap_dnfree( dn );
118 	*domainp = domain.bv_val;
119 	return 0;
120 
121 return_error:
122 	ldap_dnfree( dn );
123 	LDAP_FREE( domain.bv_val );
124 	return -1;
125 }
126 
ldap_domain2dn(LDAP_CONST char * domain_in,char ** dnp)127 int ldap_domain2dn(
128 	LDAP_CONST char *domain_in,
129 	char **dnp)
130 {
131 	char *domain, *s, *tok_r, *dn, *dntmp;
132 	size_t loc;
133 
134 	assert( domain_in != NULL );
135 	assert( dnp != NULL );
136 
137 	domain = LDAP_STRDUP(domain_in);
138 	if (domain == NULL) {
139 		return LDAP_NO_MEMORY;
140 	}
141 	dn = NULL;
142 	loc = 0;
143 
144 	for (s = ldap_pvt_strtok(domain, ".", &tok_r);
145 		s != NULL;
146 		s = ldap_pvt_strtok(NULL, ".", &tok_r))
147 	{
148 		size_t len = strlen(s);
149 
150 		dntmp = (char *) LDAP_REALLOC(dn, loc + sizeof(",dc=") + len );
151 		if (dntmp == NULL) {
152 		    if (dn != NULL)
153 			LDAP_FREE(dn);
154 		    LDAP_FREE(domain);
155 		    return LDAP_NO_MEMORY;
156 		}
157 
158 		dn = dntmp;
159 
160 		if (loc > 0) {
161 		    /* not first time. */
162 		    strcpy(dn + loc, ",");
163 		    loc++;
164 		}
165 		strcpy(dn + loc, "dc=");
166 		loc += sizeof("dc=")-1;
167 
168 		strcpy(dn + loc, s);
169 		loc += len;
170     }
171 
172 	LDAP_FREE(domain);
173 	*dnp = dn;
174 	return LDAP_SUCCESS;
175 }
176 
177 #ifdef HAVE_RES_QUERY
178 #define DNSBUFSIZ (64*1024)
179 #define MAXHOST	254	/* RFC 1034, max length is 253 chars */
180 typedef struct srv_record {
181     u_short priority;
182     u_short weight;
183     u_short port;
184     char hostname[MAXHOST];
185 } srv_record;
186 
187 /* Linear Congruential Generator - we don't need
188  * high quality randomness, and we don't want to
189  * interfere with anyone else's use of srand().
190  *
191  * The PRNG here cycles thru 941,955 numbers.
192  */
193 static float srv_seed;
194 
srv_srand(int seed)195 static void srv_srand(int seed) {
196 	srv_seed = (float)seed / (float)RAND_MAX;
197 }
198 
srv_rand()199 static float srv_rand() {
200 	float val = 9821.0 * srv_seed + .211327;
201 	srv_seed = val - (int)val;
202 	return srv_seed;
203 }
204 
srv_cmp(const void * aa,const void * bb)205 static int srv_cmp(const void *aa, const void *bb){
206 	srv_record *a=(srv_record *)aa;
207 	srv_record *b=(srv_record *)bb;
208 	int i = a->priority - b->priority;
209 	if (i) return i;
210 	return b->weight - a->weight;
211 }
212 
srv_shuffle(srv_record * a,int n)213 static void srv_shuffle(srv_record *a, int n) {
214 	int i, j, total = 0, r, p;
215 
216 	for (i=0; i<n; i++)
217 		total += a[i].weight;
218 
219 	/* Do a shuffle per RFC2782 Page 4 */
220 	for (p=n; p>1; a++, p--) {
221 		if (!total) {
222 			/* all remaining weights are zero,
223 			   do a straight Fisher-Yates shuffle */
224 			j = srv_rand() * p;
225 		} else {
226 			r = srv_rand() * total;
227 			for (j=0; j<p; j++) {
228 				r -= a[j].weight;
229 				if (r < 0) {
230 					total -= a[j].weight;
231 					break;
232 				}
233 			}
234 		}
235 		if (j && j<p) {
236 			srv_record t = a[0];
237 			a[0] = a[j];
238 			a[j] = t;
239 		}
240 	}
241 }
242 #endif /* HAVE_RES_QUERY */
243 
244 /*
245  * Lookup and return LDAP servers for domain (using the DNS
246  * SRV record _ldap._tcp.domain).
247  */
ldap_domain2hostlist(LDAP_CONST char * domain,char ** list)248 int ldap_domain2hostlist(
249 	LDAP_CONST char *domain,
250 	char **list )
251 {
252 #ifdef HAVE_RES_QUERY
253     char *request;
254     char *hostlist = NULL;
255     srv_record *hostent_head=NULL;
256     int i, j;
257     int rc, len, cur = 0;
258     unsigned char reply[DNSBUFSIZ];
259     int hostent_count=0;
260 
261 	assert( domain != NULL );
262 	assert( list != NULL );
263 	if( *domain == '\0' ) {
264 		return LDAP_PARAM_ERROR;
265 	}
266 
267     request = LDAP_MALLOC(strlen(domain) + sizeof("_ldap._tcp."));
268     if (request == NULL) {
269 		return LDAP_NO_MEMORY;
270     }
271     sprintf(request, "_ldap._tcp.%s", domain);
272 
273     LDAP_MUTEX_LOCK(&ldap_int_resolv_mutex);
274 
275     rc = LDAP_UNAVAILABLE;
276 #ifdef NS_HFIXEDSZ
277 	/* Bind 8/9 interface */
278     len = res_query(request, ns_c_in, ns_t_srv, reply, sizeof(reply));
279 #	ifndef T_SRV
280 #		define T_SRV ns_t_srv
281 #	endif
282 #else
283 	/* Bind 4 interface */
284 #	ifndef T_SRV
285 #		define T_SRV 33
286 #	endif
287 
288     len = res_query(request, C_IN, T_SRV, reply, sizeof(reply));
289 #endif
290     if (len >= 0) {
291 	unsigned char *p;
292 	char host[DNSBUFSIZ];
293 	int status;
294 	u_short port, priority, weight;
295 
296 	/* Parse out query */
297 	p = reply;
298 
299 #ifdef NS_HFIXEDSZ
300 	/* Bind 8/9 interface */
301 	p += NS_HFIXEDSZ;
302 #elif defined(HFIXEDSZ)
303 	/* Bind 4 interface w/ HFIXEDSZ */
304 	p += HFIXEDSZ;
305 #else
306 	/* Bind 4 interface w/o HFIXEDSZ */
307 	p += sizeof(HEADER);
308 #endif
309 
310 	status = dn_expand(reply, reply + len, p, host, sizeof(host));
311 	if (status < 0) {
312 	    goto out;
313 	}
314 	p += status;
315 	p += 4;
316 
317 	while (p < reply + len) {
318 	    int type, class, ttl, size;
319 	    status = dn_expand(reply, reply + len, p, host, sizeof(host));
320 	    if (status < 0) {
321 		goto out;
322 	    }
323 	    p += status;
324 	    type = (p[0] << 8) | p[1];
325 	    p += 2;
326 	    class = (p[0] << 8) | p[1];
327 	    p += 2;
328 	    ttl = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
329 	    p += 4;
330 	    size = (p[0] << 8) | p[1];
331 	    p += 2;
332 	    if (type == T_SRV) {
333 		status = dn_expand(reply, reply + len, p + 6, host, sizeof(host));
334 		if (status < 0) {
335 		    goto out;
336 		}
337 
338 		/* Get priority weight and port */
339 		priority = (p[0] << 8) | p[1];
340 		weight = (p[2] << 8) | p[3];
341 		port = (p[4] << 8) | p[5];
342 
343 		if ( port == 0 || host[ 0 ] == '\0' ) {
344 		    goto add_size;
345 		}
346 
347 		hostent_head = (srv_record *) LDAP_REALLOC(hostent_head, (hostent_count+1)*(sizeof(srv_record)));
348 		if(hostent_head==NULL){
349 		    rc=LDAP_NO_MEMORY;
350 		    goto out;
351 		}
352 		hostent_head[hostent_count].priority=priority;
353 		hostent_head[hostent_count].weight=weight;
354 		hostent_head[hostent_count].port=port;
355 		strncpy(hostent_head[hostent_count].hostname, host, MAXHOST-1);
356 		hostent_head[hostent_count].hostname[MAXHOST-1] = '\0';
357 		hostent_count++;
358 	    }
359 add_size:;
360 	    p += size;
361 	}
362 	if (!hostent_head) goto out;
363     qsort(hostent_head, hostent_count, sizeof(srv_record), srv_cmp);
364 
365 	if (!srv_seed)
366 		srv_srand(time(0L));
367 
368 	/* shuffle records of same priority */
369 	j = 0;
370 	priority = hostent_head[0].priority;
371 	for (i=1; i<hostent_count; i++) {
372 		if (hostent_head[i].priority != priority) {
373 			priority = hostent_head[i].priority;
374 			if (i-j > 1)
375 				srv_shuffle(hostent_head+j, i-j);
376 			j = i;
377 		}
378 	}
379 	if (i-j > 1)
380 		srv_shuffle(hostent_head+j, i-j);
381 
382     for(i=0; i<hostent_count; i++){
383 	int buflen;
384         buflen = strlen(hostent_head[i].hostname) + STRLENOF(":65535 ");
385         hostlist = (char *) LDAP_REALLOC(hostlist, cur+buflen+1);
386         if (hostlist == NULL) {
387             rc = LDAP_NO_MEMORY;
388             goto out;
389         }
390         if(cur>0){
391             hostlist[cur++]=' ';
392         }
393         cur += sprintf(&hostlist[cur], "%s:%hu", hostent_head[i].hostname, hostent_head[i].port);
394     }
395     }
396 
397     if (hostlist == NULL) {
398 	/* No LDAP servers found in DNS. */
399 	rc = LDAP_UNAVAILABLE;
400 	goto out;
401     }
402 
403     rc = LDAP_SUCCESS;
404 	*list = hostlist;
405 
406   out:
407     LDAP_MUTEX_UNLOCK(&ldap_int_resolv_mutex);
408 
409     if (request != NULL) {
410 	LDAP_FREE(request);
411     }
412     if (hostent_head != NULL) {
413 	LDAP_FREE(hostent_head);
414     }
415     if (rc != LDAP_SUCCESS && hostlist != NULL) {
416 	LDAP_FREE(hostlist);
417     }
418     return rc;
419 #else
420     return LDAP_NOT_SUPPORTED;
421 #endif /* HAVE_RES_QUERY */
422 }
423