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