summaryrefslogtreecommitdiffstats
path: root/src/lib/krb5/os/hst_realm.c
blob: 9836378642795fc84dee0e5b2c1eca8ce5f76ce2 (plain)
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
/*
 * lib/krb5/os/hst_realm.c
 *
 * Copyright 1990,1991,2002 by the Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * Export of this software from the United States of America may
 *   require a specific license from the United States Government.
 *   It is the responsibility of any person or organization contemplating
 *   export to obtain such a license before exporting.
 * 
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of M.I.T. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  Furthermore if you modify this software you must label
 * your software as modified software and not distribute it in such a
 * fashion that it might be confused with the original M.I.T. software.
 * M.I.T. makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 * 
 *
 * krb5_get_host_realm()
 */


/*
 Figures out the Kerberos realm names for host, filling in a
 pointer to an argv[] style list of names, terminated with a null pointer.
 
 If host is NULL, the local host's realms are determined.

 If there are no known realms for the host, the filled-in pointer is set
 to NULL.

 The pointer array and strings pointed to are all in allocated storage,
 and should be freed by the caller when finished.

 returns system errors
*/

/*
 * Implementation notes:
 *
 * this implementation only provides one realm per host, using the same
 * mapping file used in kerberos v4.

 * Given a fully-qualified domain-style primary host name,
 * return the name of the Kerberos realm for the host.
 * If the hostname contains no discernable domain, or an error occurs,
 * return the local realm name, as supplied by krb5_get_default_realm().
 * If the hostname contains a domain, but no translation is found,
 * the hostname's domain is converted to upper-case and returned.
 *
 * The format of each line of the translation file is:
 * domain_name kerberos_realm
 * -or-
 * host_name kerberos_realm
 *
 * domain_name should be of the form .XXX.YYY (e.g. .LCS.MIT.EDU)
 * host names should be in the usual form (e.g. FOO.BAR.BAZ)
 */


#include "k5-int.h"
#include "os-proto.h"
#include <ctype.h>
#include <stdio.h>
#ifdef HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif

#include "fake-addrinfo.h"

#ifdef KRB5_DNS_LOOKUP

#include "dnsglue.h"
/*
 * Try to look up a TXT record pointing to a Kerberos realm
 */

krb5_error_code
krb5_try_realm_txt_rr(const char *prefix, const char *name, char **realm)
{
    krb5_error_code retval = KRB5_ERR_HOST_REALM_UNKNOWN;
    const unsigned char *p, *base;
    char host[MAXDNAME], *h;
    int ret, rdlen, len;
    struct krb5int_dns_state *ds = NULL;

    /*
     * Form our query, and send it via DNS
     */

    if (name == NULL || name[0] == '\0') {
	if (strlen (prefix) >= sizeof(host)-1)
	    return KRB5_ERR_HOST_REALM_UNKNOWN;
        strcpy(host,prefix);
    } else {
        if ( strlen(prefix) + strlen(name) + 3 > MAXDNAME )
            return KRB5_ERR_HOST_REALM_UNKNOWN;
        if (snprintf(host, sizeof(host), "%s.%s", prefix, name) >= sizeof(host))
	    return KRB5_ERR_HOST_REALM_UNKNOWN;

        /* Realm names don't (normally) end with ".", but if the query
           doesn't end with "." and doesn't get an answer as is, the
           resolv code will try appending the local domain.  Since the
           realm names are absolutes, let's stop that.  

           But only if a name has been specified.  If we are performing
           a search on the prefix alone then the intention is to allow
           the local domain or domain search lists to be expanded.
        */

        h = host + strlen (host);
        if ((h > host) && (h[-1] != '.') && ((h - host + 1) < sizeof(host)))
            strcpy (h, ".");
    }
    ret = krb5int_dns_init(&ds, host, C_IN, T_TXT);
    if (ret < 0)
	goto errout;

    ret = krb5int_dns_nextans(ds, &base, &rdlen);
    if (ret < 0 || base == NULL)
	goto errout;

    p = base;
    if (!INCR_OK(base, rdlen, p, 1))
	goto errout;
    len = *p++;
    *realm = malloc((size_t)len + 1);
    if (*realm == NULL) {
	retval = ENOMEM;
	goto errout;
    }
    strncpy(*realm, (const char *)p, (size_t)len);
    (*realm)[len] = '\0';
    /* Avoid a common error. */
    if ( (*realm)[len-1] == '.' )
	(*realm)[len-1] = '\0';
    retval = 0;

errout:
    if (ds != NULL) {
	krb5int_dns_fini(ds);
	ds = NULL;
    }
    return retval;
}
#else /* KRB5_DNS_LOOKUP */
#ifndef MAXDNAME
#define MAXDNAME (16 * MAXHOSTNAMELEN)
#endif /* MAXDNAME */
#endif /* KRB5_DNS_LOOKUP */

krb5_error_code krb5int_translate_gai_error (int);

static krb5_error_code
krb5int_get_fq_hostname (char *buf, size_t bufsize, const char *name)
{
    struct addrinfo *ai, hints;
    int err;

    memset (&hints, 0, sizeof (hints));
    hints.ai_flags = AI_CANONNAME;
    err = getaddrinfo (name, 0, &hints, &ai);
    if (err)
	return krb5int_translate_gai_error (err);
    if (ai->ai_canonname == 0)
	return KRB5_EAI_FAIL;
    strncpy (buf, ai->ai_canonname, bufsize);
    buf[bufsize-1] = 0;
    freeaddrinfo (ai);
    return 0;
}

/* Get the local host name, try to make it fully-qualified.
   Always return a null-terminated string.
   Might return an error if gethostname fails.  */
krb5_error_code
krb5int_get_fq_local_hostname (char *buf, size_t bufsiz)
{
    buf[0] = 0;
    if (gethostname (buf, bufsiz) == -1)
	return SOCKET_ERRNO;
    buf[bufsiz - 1] = 0;
    return krb5int_get_fq_hostname (buf, bufsiz, buf);
}

krb5_error_code KRB5_CALLCONV
krb5_get_host_realm(krb5_context context, const char *host, char ***realmsp)
{
    char **retrealms;
    char *realm, *cp, *temp_realm;
    krb5_error_code retval;
    char local_host[MAXDNAME+1];

#ifdef DEBUG_REFERRALS
    printf("get_host_realm(host:%s) called\n",host);
#endif

    krb5int_clean_hostname(context, host, local_host, sizeof local_host);

    /*
       Search for the best match for the host or domain.
       Example: Given a host a.b.c.d, try to match on:
         1) A.B.C.D
	 2) .B.C.D
	 3) B.C.D
	 4) .C.D
	 5) C.D
	 6) .D
	 7) D
     */

    cp = local_host;
#ifdef DEBUG_REFERRALS
    printf("  local_host: %s\n",local_host);
#endif
    realm = (char *)NULL;
    temp_realm = 0;
    while (cp) {
#ifdef DEBUG_REFERRALS
        printf("  trying to look up %s in the domain_realm map\n",cp);
#endif
	retval = profile_get_string(context->profile, "domain_realm", cp,
				    0, (char *)NULL, &temp_realm);
	if (retval)
	    return retval;
	if (temp_realm != (char *)NULL)
	    break;	/* Match found */

	/* Setup for another test */
	if (*cp == '.') {
	    cp++;
	} else {
	    cp = strchr(cp, '.');
	}
    }
#ifdef DEBUG_REFERRALS
    printf("  done searching the domain_realm map\n");
#endif
    if (temp_realm) {
#ifdef DEBUG_REFERRALS
    printf("  temp_realm is %s\n",temp_realm);
#endif
        realm = malloc(strlen(temp_realm) + 1);
        if (!realm) {
            profile_release_string(temp_realm);
            return ENOMEM;
        }
        strcpy(realm, temp_realm);
        profile_release_string(temp_realm);
    }

    if (realm == (char *)NULL) {
        if (!(cp = (char *)malloc(strlen(KRB5_REFERRAL_REALM)+1)))
	    return ENOMEM;
	strcpy(cp, KRB5_REFERRAL_REALM);
	realm = cp;
    }
    
    if (!(retrealms = (char **)calloc(2, sizeof(*retrealms)))) {
	if (realm != (char *)NULL)
	    free(realm);
	return ENOMEM;
    }

    retrealms[0] = realm;
    retrealms[1] = 0;
    
    *realmsp = retrealms;
    return 0;
}

#if defined(_WIN32) && !defined(__CYGWIN32__)
# ifndef EAFNOSUPPORT
#  define EAFNOSUPPORT WSAEAFNOSUPPORT
# endif
#endif

krb5_error_code
krb5int_translate_gai_error (int num)
{
    switch (num) {
#ifdef EAI_ADDRFAMILY
    case EAI_ADDRFAMILY:
	return EAFNOSUPPORT;
#endif
    case EAI_AGAIN:
	return EAGAIN;
    case EAI_BADFLAGS:
	return EINVAL;
    case EAI_FAIL:
	return KRB5_EAI_FAIL;
    case EAI_FAMILY:
	return EAFNOSUPPORT;
    case EAI_MEMORY:
	return ENOMEM;
#if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME
    case EAI_NODATA:
	return KRB5_EAI_NODATA;
#endif
    case EAI_NONAME:
	return KRB5_EAI_NONAME;
#if defined(EAI_OVERFLOW)
    case EAI_OVERFLOW:
	return EINVAL;		/* XXX */
#endif
    case EAI_SERVICE:
	return KRB5_EAI_SERVICE;
    case EAI_SOCKTYPE:
	return EINVAL;
#ifdef EAI_SYSTEM
    case EAI_SYSTEM:
	return errno;
#endif
    }
    abort ();
    return -1;
}


/*
 * Ganked from krb5_get_host_realm; handles determining a fallback realm
 * to try in the case where referrals have failed and it's time to go
 * look at TXT records or make a DNS-based assumption.
 */

krb5_error_code KRB5_CALLCONV
krb5_get_fallback_host_realm(krb5_context context, krb5_data *hdata, char ***realmsp)
{
    char **retrealms;
    char *default_realm, *realm, *cp, *temp_realm;
    krb5_error_code retval;
    char local_host[MAXDNAME+1], host[MAXDNAME+1];

    /* Convert what we hope is a hostname to a string. */
    memcpy(host, hdata->data, hdata->length);
    host[hdata->length]=0;

#ifdef DEBUG_REFERRALS
    printf("get_fallback_host_realm(host >%s<) called\n",host);
#endif

    krb5int_clean_hostname(context, host, local_host, sizeof local_host);

    /* Scan hostname for DNS realm, and save as last-ditch realm
       assumption. */
    cp = local_host;
#ifdef DEBUG_REFERRALS
    printf("  local_host: %s\n",local_host);
#endif
    realm = default_realm = (char *)NULL;
    temp_realm = 0;
    while (cp && !default_realm) {
	if (*cp == '.') {
	    cp++;
	    if (default_realm == (char *)NULL) {
		/* If nothing else works, use the host's domain */
		default_realm = cp;
	    }
	} else {
	    cp = strchr(cp, '.');
	}
    }
#ifdef DEBUG_REFERRALS
    printf("  done finding DNS-based default realm: >%s<\n",default_realm);
#endif

#ifdef KRB5_DNS_LOOKUP
    if (realm == (char *)NULL) {
        int use_dns = _krb5_use_dns_realm(context);
        if ( use_dns ) {
            /*
             * Since this didn't appear in our config file, try looking
             * it up via DNS.  Look for a TXT records of the form:
             *
             * _kerberos.<hostname>
             *
             */
            cp = local_host;
            do {
                retval = krb5_try_realm_txt_rr("_kerberos", cp, &realm);
                cp = strchr(cp,'.');
                if (cp) 
                    cp++;
            } while (retval && cp && cp[0]);
        }
    }
#endif /* KRB5_DNS_LOOKUP */

      
    if (realm == (char *)NULL) {
        if (default_realm != (char *)NULL) {
            /* We are defaulting to the realm of the host */
            if (!(cp = (char *)malloc(strlen(default_realm)+1)))
                return ENOMEM;
            strcpy(cp, default_realm);
            realm = cp;

            /* Assume the realm name is upper case */
            for (cp = realm; *cp; cp++)
                if (islower((int) (*cp)))
                    *cp = toupper((int) *cp);
        } else {    
            /* We are defaulting to the local realm */
            retval = krb5_get_default_realm(context, &realm);
            if (retval) {
                return retval;
            }
        }
    }
    if (!(retrealms = (char **)calloc(2, sizeof(*retrealms)))) {
	if (realm != (char *)NULL)
	    free(realm);
	return ENOMEM;
    }

    retrealms[0] = realm;
    retrealms[1] = 0;
    
    *realmsp = retrealms;
    return 0;
}

/*
 * Common code for krb5_get_host_realm and krb5_get_fallback_host_realm
 * to do basic sanity checks on supplied hostname.
 */
krb5_error_code KRB5_CALLCONV
krb5int_clean_hostname(krb5_context context, const char *host, char *local_host, size_t lhsize)
{
    char *cp;
    krb5_error_code retval;
    int l;

    local_host[0]=0;
#ifdef DEBUG_REFERRALS
    printf("krb5int_clean_hostname called: host<%s>, local_host<%s>, size %d\n",host,local_host,lhsize);
#endif
    if (host) {
	/* Filter out numeric addresses if the caller utterly failed to
	   convert them to names.  */
	/* IPv4 - dotted quads only */
	if (strspn(host, "01234567890.") == strlen(host)) {
	    /* All numbers and dots... if it's three dots, it's an
	       IP address, and we reject it.  But "12345" could be
	       a local hostname, couldn't it?  We'll just assume
	       that a name with three dots is not meant to be an
	       all-numeric hostname three all-numeric domains down
	       from the current domain.  */
	    int ndots = 0;
	    const char *p;
	    for (p = host; *p; p++)
		if (*p == '.')
		    ndots++;
	    if (ndots == 3)
		return KRB5_ERR_NUMERIC_REALM;
	}
	if (strchr(host, ':'))
	    /* IPv6 numeric address form?  Bye bye.  */
	    return KRB5_ERR_NUMERIC_REALM;

	/* Should probably error out if strlen(host) > MAXDNAME.  */
	strncpy(local_host, host, lhsize);
	local_host[lhsize - 1] = '\0';
    } else {
        retval = krb5int_get_fq_local_hostname (local_host, lhsize);
	if (retval)
	    return retval;
    }

    /* fold to lowercase */
    for (cp = local_host; *cp; cp++) {
	if (isupper((unsigned char) (*cp)))
	    *cp = tolower((unsigned char) *cp);
    }
    l = strlen(local_host);
    /* strip off trailing dot */
    if (l && local_host[l-1] == '.')
	    local_host[l-1] = 0;

#ifdef DEBUG_REFERRALS
    printf("krb5int_clean_hostname ending: host<%s>, local_host<%s>, size %d\n",host,local_host,lhsize);
#endif
    return 0;
}