1/*	$NetBSD: canohost.c,v 1.5 2011/07/25 03:03:10 christos Exp $	*/
2/* $OpenBSD: canohost.c,v 1.66 2010/01/13 01:20:20 dtucker Exp $ */
3/*
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 *                    All rights reserved
7 * Functions for returning the canonical host name of the remote site.
8 *
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose.  Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
14 */
15
16#include "includes.h"
17__RCSID("$NetBSD: canohost.c,v 1.5 2011/07/25 03:03:10 christos Exp $");
18#include <sys/types.h>
19#include <sys/socket.h>
20
21#include <netinet/in.h>
22
23#include <ctype.h>
24#include <errno.h>
25#include <netdb.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <stdarg.h>
30#include <time.h>
31#include <unistd.h>
32
33#include "xmalloc.h"
34#include "packet.h"
35#include "log.h"
36#include "canohost.h"
37#include "misc.h"
38
39static void check_ip_options(int, char *);
40static char *canonical_host_ip = NULL;
41static int cached_port = -1;
42
43/*
44 * Return the canonical name of the host at the other end of the socket. The
45 * caller should free the returned string with xfree.
46 */
47
48static char *
49get_remote_hostname(int sock, int use_dns)
50{
51	struct sockaddr_storage from;
52	int i;
53	socklen_t fromlen;
54	struct addrinfo hints, *ai, *aitop;
55	char name[NI_MAXHOST], ntop[NI_MAXHOST], ntop2[NI_MAXHOST];
56
57	/* Get IP address of client. */
58	fromlen = sizeof(from);
59	memset(&from, 0, sizeof(from));
60	if (getpeername(sock, (struct sockaddr *)&from, &fromlen) < 0) {
61		debug("getpeername failed: %.100s", strerror(errno));
62		cleanup_exit(255);
63	}
64
65	if (getnameinfo((struct sockaddr *)&from, fromlen, ntop, sizeof(ntop),
66	    NULL, 0, NI_NUMERICHOST) != 0)
67		fatal("get_remote_hostname: getnameinfo NI_NUMERICHOST failed");
68
69	if (from.ss_family == AF_INET)
70		check_ip_options(sock, ntop);
71
72	if (!use_dns)
73		return xstrdup(ntop);
74
75	debug3("Trying to reverse map address %.100s.", ntop);
76	/* Map the IP address to a host name. */
77	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
78	    NULL, 0, NI_NAMEREQD) != 0) {
79		/* Host name not found.  Use ip address. */
80		return xstrdup(ntop);
81	}
82
83	/*
84	 * if reverse lookup result looks like a numeric hostname,
85	 * someone is trying to trick us by PTR record like following:
86	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
87	 */
88	memset(&hints, 0, sizeof(hints));
89	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
90	hints.ai_flags = AI_NUMERICHOST;
91	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
92		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
93		    name, ntop);
94		freeaddrinfo(ai);
95		return xstrdup(ntop);
96	}
97
98	/*
99	 * Convert it to all lowercase (which is expected by the rest
100	 * of this software).
101	 */
102	for (i = 0; name[i]; i++)
103		if (isupper((unsigned char)name[i]))
104			name[i] = (char)tolower((unsigned char)name[i]);
105	/*
106	 * Map it back to an IP address and check that the given
107	 * address actually is an address of this host.  This is
108	 * necessary because anyone with access to a name server can
109	 * define arbitrary names for an IP address. Mapping from
110	 * name to IP address can be trusted better (but can still be
111	 * fooled if the intruder has access to the name server of
112	 * the domain).
113	 */
114	memset(&hints, 0, sizeof(hints));
115	hints.ai_family = from.ss_family;
116	hints.ai_socktype = SOCK_STREAM;
117	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
118		logit("reverse mapping checking getaddrinfo for %.700s "
119		    "[%s] failed - POSSIBLE BREAK-IN ATTEMPT!", name, ntop);
120		return xstrdup(ntop);
121	}
122	/* Look for the address from the list of addresses. */
123	for (ai = aitop; ai; ai = ai->ai_next) {
124		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
125		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
126		    (strcmp(ntop, ntop2) == 0))
127				break;
128	}
129	freeaddrinfo(aitop);
130	/* If we reached the end of the list, the address was not there. */
131	if (!ai) {
132		/* Address not found for the host name. */
133		logit("Address %.100s maps to %.600s, but this does not "
134		    "map back to the address - POSSIBLE BREAK-IN ATTEMPT!",
135		    ntop, name);
136		return xstrdup(ntop);
137	}
138	return xstrdup(name);
139}
140
141/*
142 * If IP options are supported, make sure there are none (log and
143 * disconnect them if any are found).  Basically we are worried about
144 * source routing; it can be used to pretend you are somebody
145 * (ip-address) you are not. That itself may be "almost acceptable"
146 * under certain circumstances, but rhosts autentication is useless
147 * if source routing is accepted. Notice also that if we just dropped
148 * source routing here, the other side could use IP spoofing to do
149 * rest of the interaction and could still bypass security.  So we
150 * exit here if we detect any IP options.
151 */
152/* IPv4 only */
153static void
154check_ip_options(int sock, char *ipaddr)
155{
156	u_char options[200];
157	char text[sizeof(options) * 3 + 1];
158	socklen_t option_size;
159	u_int i;
160	int ipproto;
161	struct protoent *ip;
162
163	if ((ip = getprotobyname("ip")) != NULL)
164		ipproto = ip->p_proto;
165	else
166		ipproto = IPPROTO_IP;
167	option_size = sizeof(options);
168	if (getsockopt(sock, ipproto, IP_OPTIONS, options,
169	    &option_size) >= 0 && option_size != 0) {
170		text[0] = '\0';
171		for (i = 0; i < option_size; i++)
172			snprintf(text + i*3, sizeof(text) - i*3,
173			    " %2.2x", options[i]);
174		fatal("Connection from %.100s with IP options:%.800s",
175		    ipaddr, text);
176	}
177}
178
179/*
180 * Return the canonical name of the host in the other side of the current
181 * connection.  The host name is cached, so it is efficient to call this
182 * several times.
183 */
184
185const char *
186get_canonical_hostname(int use_dns)
187{
188	char *host;
189	static char *canonical_host_name = NULL;
190	static char *remote_ip = NULL;
191
192	/* Check if we have previously retrieved name with same option. */
193	if (use_dns && canonical_host_name != NULL)
194		return canonical_host_name;
195	if (!use_dns && remote_ip != NULL)
196		return remote_ip;
197
198	/* Get the real hostname if socket; otherwise return UNKNOWN. */
199	if (packet_connection_is_on_socket())
200		host = get_remote_hostname(packet_get_connection_in(), use_dns);
201	else
202		host = __UNCONST("UNKNOWN");
203
204	if (use_dns)
205		canonical_host_name = host;
206	else
207		remote_ip = host;
208	return host;
209}
210
211/*
212 * Returns the local/remote IP-address/hostname of socket as a string.
213 * The returned string must be freed.
214 */
215static char *
216get_socket_address(int sock, int remote, int flags)
217{
218	struct sockaddr_storage addr;
219	socklen_t addrlen;
220	char ntop[NI_MAXHOST];
221	int r;
222
223	/* Get IP address of client. */
224	addrlen = sizeof(addr);
225	memset(&addr, 0, sizeof(addr));
226
227	if (remote) {
228		if (getpeername(sock, (struct sockaddr *)&addr, &addrlen)
229		    < 0)
230			return NULL;
231	} else {
232		if (getsockname(sock, (struct sockaddr *)&addr, &addrlen)
233		    < 0)
234			return NULL;
235	}
236	/* Get the address in ascii. */
237	if ((r = getnameinfo((struct sockaddr *)&addr, addrlen, ntop,
238	    sizeof(ntop), NULL, 0, flags)) != 0) {
239		error("get_socket_address: getnameinfo %d failed: %s", flags,
240		    ssh_gai_strerror(r));
241		return NULL;
242	}
243	return xstrdup(ntop);
244}
245
246char *
247get_peer_ipaddr(int sock)
248{
249	char *p;
250
251	if ((p = get_socket_address(sock, 1, NI_NUMERICHOST)) != NULL)
252		return p;
253	return xstrdup("UNKNOWN");
254}
255
256char *
257get_local_ipaddr(int sock)
258{
259	char *p;
260
261	if ((p = get_socket_address(sock, 0, NI_NUMERICHOST)) != NULL)
262		return p;
263	return xstrdup("UNKNOWN");
264}
265
266char *
267get_local_name(int fd)
268{
269	char *host, myname[NI_MAXHOST];
270
271	/* Assume we were passed a socket */
272	if ((host = get_socket_address(fd, 0, NI_NAMEREQD)) != NULL)
273		return host;
274
275	/* Handle the case where we were passed a pipe */
276	if (gethostname(myname, sizeof(myname)) == -1) {
277		verbose("get_local_name: gethostname: %s", strerror(errno));
278	} else {
279		host = xstrdup(myname);
280	}
281
282	return host;
283}
284
285void
286clear_cached_addr(void)
287{
288	if (canonical_host_ip != NULL) {
289		xfree(canonical_host_ip);
290		canonical_host_ip = NULL;
291	}
292	cached_port = -1;
293}
294
295/*
296 * Returns the IP-address of the remote host as a string.  The returned
297 * string must not be freed.
298 */
299
300const char *
301get_remote_ipaddr(void)
302{
303	/* Check whether we have cached the ipaddr. */
304	if (canonical_host_ip == NULL) {
305		if (packet_connection_is_on_socket()) {
306			canonical_host_ip =
307			    get_peer_ipaddr(packet_get_connection_in());
308			if (canonical_host_ip == NULL)
309				cleanup_exit(255);
310		} else {
311			/* If not on socket, return UNKNOWN. */
312			canonical_host_ip = xstrdup("UNKNOWN");
313		}
314	}
315	return canonical_host_ip;
316}
317
318const char *
319get_remote_name_or_ip(u_int utmp_len, int use_dns)
320{
321	static const char *remote = "";
322	if (utmp_len > 0)
323		remote = get_canonical_hostname(use_dns);
324	if (utmp_len == 0 || strlen(remote) > utmp_len)
325		remote = get_remote_ipaddr();
326	return remote;
327}
328
329/* Returns the local/remote port for the socket. */
330
331int
332get_sock_port(int sock, int local)
333{
334	struct sockaddr_storage from;
335	socklen_t fromlen;
336	char strport[NI_MAXSERV];
337	int r;
338
339	/* Get IP address of client. */
340	fromlen = sizeof(from);
341	memset(&from, 0, sizeof(from));
342	if (local) {
343		if (getsockname(sock, (struct sockaddr *)&from, &fromlen) < 0) {
344			error("getsockname failed: %.100s", strerror(errno));
345			return 0;
346		}
347	} else {
348		if (getpeername(sock, (struct sockaddr *)&from, &fromlen) < 0) {
349			debug("getpeername failed: %.100s", strerror(errno));
350			return -1;
351		}
352	}
353	/* Return port number. */
354	if ((r = getnameinfo((struct sockaddr *)&from, fromlen, NULL, 0,
355	    strport, sizeof(strport), NI_NUMERICSERV)) != 0)
356		fatal("get_sock_port: getnameinfo NI_NUMERICSERV failed: %s",
357		    ssh_gai_strerror(r));
358	return atoi(strport);
359}
360
361/* Returns remote/local port number for the current connection. */
362
363static int
364get_port(int local)
365{
366	/*
367	 * If the connection is not a socket, return 65535.  This is
368	 * intentionally chosen to be an unprivileged port number.
369	 */
370	if (!packet_connection_is_on_socket())
371		return 65535;
372
373	/* Get socket and return the port number. */
374	return get_sock_port(packet_get_connection_in(), local);
375}
376
377int
378get_peer_port(int sock)
379{
380	return get_sock_port(sock, 0);
381}
382
383int
384get_remote_port(void)
385{
386	/* Cache to avoid getpeername() on a dead connection */
387	if (cached_port == -1)
388		cached_port = get_port(0);
389
390	return cached_port;
391}
392
393int
394get_local_port(void)
395{
396	return get_port(1);
397}
398