2 * Dropbear - a SSH2 server
4 * Copyright (c) 2002,2003 Matt Johnston
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 * strlcat() is copyright as follows:
26 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
27 * All rights reserved.
29 * Redistribution and use in source and binary forms, with or without
30 * modification, are permitted provided that the following conditions
32 * 1. Redistributions of source code must retain the above copyright
33 * notice, this list of conditions and the following disclaimer.
34 * 2. Redistributions in binary form must reproduce the above copyright
35 * notice, this list of conditions and the following disclaimer in the
36 * documentation and/or other materials provided with the distribution.
37 * 3. The name of the author may not be used to endorse or promote products
38 * derived from this software without specific prior written permission.
40 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
41 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
42 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
43 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
44 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
45 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
46 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
47 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
48 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
49 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
59 static void generic_dropbear_exit(int exitcode
, const char* format
,
61 static void generic_dropbear_log(int priority
, const char* format
,
64 void (*_dropbear_exit
)(int exitcode
, const char* format
, va_list param
)
65 = generic_dropbear_exit
;
66 void (*_dropbear_log
)(int priority
, const char* format
, va_list param
)
67 = generic_dropbear_log
;
73 #ifndef DISABLE_SYSLOG
76 openlog(PROGNAME
, LOG_PID
, LOG_AUTHPRIV
);
79 #endif /* DISABLE_SYSLOG */
81 /* the "format" string must be <= 100 characters */
82 void dropbear_close(const char* format
, ...) {
86 va_start(param
, format
);
87 _dropbear_exit(EXIT_SUCCESS
, format
, param
);
92 void dropbear_exit(const char* format
, ...) {
96 va_start(param
, format
);
97 _dropbear_exit(EXIT_FAILURE
, format
, param
);
101 static void generic_dropbear_exit(int exitcode
, const char* format
,
106 snprintf(fmtbuf
, sizeof(fmtbuf
), "Exited: %s", format
);
108 _dropbear_log(LOG_INFO
, fmtbuf
, param
);
113 void fail_assert(const char* expr
, const char* file
, int line
) {
114 dropbear_exit("Failed assertion (%s:%d): `%s'", file
, line
, expr
);
117 static void generic_dropbear_log(int UNUSED(priority
), const char* format
,
122 vsnprintf(printbuf
, sizeof(printbuf
), format
, param
);
124 fprintf(stderr
, "%s\n", printbuf
);
128 /* this is what can be called to write arbitrary log messages */
129 void dropbear_log(int priority
, const char* format
, ...) {
133 va_start(param
, format
);
134 _dropbear_log(priority
, format
, param
);
140 void dropbear_trace(const char* format
, ...) {
148 va_start(param
, format
);
149 fprintf(stderr
, "TRACE (%d): ", getpid());
150 vfprintf(stderr
, format
, param
);
151 fprintf(stderr
, "\n");
154 #endif /* DEBUG_TRACE */
156 static void set_sock_priority(int sock
) {
162 setsockopt(sock
, IPPROTO_TCP
, TCP_NODELAY
, (void*)&val
, sizeof(val
));
164 /* set the TOS bit for either ipv4 or ipv6 */
165 #ifdef IPTOS_LOWDELAY
166 val
= IPTOS_LOWDELAY
;
167 #if defined(IPPROTO_IPV6) && defined(TCONFIG_IPV6)
168 setsockopt(sock
, IPPROTO_IPV6
, IPV6_TCLASS
, (void*)&val
, sizeof(val
));
170 setsockopt(sock
, IPPROTO_IP
, IP_TOS
, (void*)&val
, sizeof(val
));
174 /* linux specific, sets QoS class.
175 * 6 looks to be optimal for interactive traffic (see tc-prio(8) ). */
177 setsockopt(sock
, SOL_SOCKET
, SO_PRIORITY
, (void*) &val
, sizeof(val
));
182 /* Listen on address:port.
183 * Special cases are address of "" listening on everything,
184 * and address of NULL listening on localhost only.
185 * Returns the number of sockets bound on success, or -1 on failure. On
186 * failure, if errstring wasn't NULL, it'll be a newly malloced error
188 int dropbear_listen(const char* address
, const char* port
,
189 int *socks
, unsigned int sockcount
, char **errstring
, int *maxfd
) {
191 struct addrinfo hints
, *res
= NULL
, *res0
= NULL
;
194 struct linger linger
;
198 TRACE(("enter dropbear_listen"))
200 memset(&hints
, 0, sizeof(hints
));
201 hints
.ai_family
= AF_UNSPEC
; /* TODO: let them flag v4 only etc */
202 hints
.ai_socktype
= SOCK_STREAM
;
204 /* for calling getaddrinfo:
205 address == NULL and !AI_PASSIVE: local loopback
206 address == NULL and AI_PASSIVE: all interfaces
207 address != NULL: whatever the address says */
209 TRACE(("dropbear_listen: local loopback"))
211 if (address
[0] == '\0') {
212 TRACE(("dropbear_listen: all interfaces"))
215 hints
.ai_flags
= AI_PASSIVE
;
217 err
= getaddrinfo(address
, port
, &hints
, &res0
);
220 if (errstring
!= NULL
&& *errstring
== NULL
) {
222 len
= 20 + strlen(gai_strerror(err
));
223 *errstring
= (char*)m_malloc(len
);
224 snprintf(*errstring
, len
, "Error resolving: %s", gai_strerror(err
));
230 TRACE(("leave dropbear_listen: failed resolving"))
236 for (res
= res0
; res
!= NULL
&& nsock
< sockcount
;
237 res
= res
->ai_next
) {
240 socks
[nsock
] = socket(res
->ai_family
, res
->ai_socktype
,
243 sock
= socks
[nsock
]; /* For clarity */
247 TRACE(("socket() failed"))
251 /* Various useful socket options */
253 /* set to reuse, quick timeout */
254 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &val
, sizeof(val
));
257 setsockopt(sock
, SOL_SOCKET
, SO_LINGER
, (void*)&linger
, sizeof(linger
));
259 set_sock_priority(sock
);
261 if (bind(sock
, res
->ai_addr
, res
->ai_addrlen
) < 0) {
264 TRACE(("bind(%s) failed", port
))
268 if (listen(sock
, 20) < 0) {
271 TRACE(("listen() failed"))
275 *maxfd
= MAX(*maxfd
, sock
);
286 if (errstring
!= NULL
&& *errstring
== NULL
) {
288 len
= 20 + strlen(strerror(err
));
289 *errstring
= (char*)m_malloc(len
);
290 snprintf(*errstring
, len
, "Error listening: %s", strerror(err
));
292 TRACE(("leave dropbear_listen: failure, %s", strerror(err
)))
296 TRACE(("leave dropbear_listen: success, %d socks bound", nsock
))
300 /* Connect to a given unix socket. The socket is blocking */
301 #ifdef ENABLE_CONNECT_UNIX
302 int connect_unix(const char* path
) {
303 struct sockaddr_un addr
;
306 memset((void*)&addr
, 0x0, sizeof(addr
));
307 addr
.sun_family
= AF_UNIX
;
308 strlcpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
309 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
311 TRACE(("Failed to open unix socket"))
314 if (connect(fd
, (struct sockaddr
*)&addr
, sizeof(addr
)) < 0) {
315 TRACE(("Failed to connect to '%s' socket", path
))
322 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will
323 * return immediately if nonblocking is set. On failure, if errstring
324 * wasn't null, it will be a newly malloced error message */
327 int connect_remote(const char* remotehost
, const char* remoteport
,
328 int nonblocking
, char ** errstring
) {
330 struct addrinfo
*res0
= NULL
, *res
= NULL
, hints
;
334 TRACE(("enter connect_remote"))
336 if (errstring
!= NULL
) {
340 memset(&hints
, 0, sizeof(hints
));
341 hints
.ai_socktype
= SOCK_STREAM
;
342 hints
.ai_family
= PF_UNSPEC
;
344 err
= getaddrinfo(remotehost
, remoteport
, &hints
, &res0
);
346 if (errstring
!= NULL
&& *errstring
== NULL
) {
348 len
= 100 + strlen(gai_strerror(err
));
349 *errstring
= (char*)m_malloc(len
);
350 snprintf(*errstring
, len
, "Error resolving '%s' port '%s'. %s",
351 remotehost
, remoteport
, gai_strerror(err
));
353 TRACE(("Error resolving: %s", gai_strerror(err
)))
359 for (res
= res0
; res
; res
= res
->ai_next
) {
361 sock
= socket(res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
);
368 setnonblocking(sock
);
371 if (connect(sock
, res
->ai_addr
, res
->ai_addrlen
) < 0) {
372 if (errno
== EINPROGRESS
&& nonblocking
) {
373 TRACE(("Connect in progress"))
386 if (sock
< 0 && !(errno
== EINPROGRESS
&& nonblocking
)) {
388 if (errstring
!= NULL
&& *errstring
== NULL
) {
390 len
= 20 + strlen(strerror(err
));
391 *errstring
= (char*)m_malloc(len
);
392 snprintf(*errstring
, len
, "Error connecting: %s", strerror(err
));
394 TRACE(("Error connecting: %s", strerror(err
)))
397 set_sock_priority(sock
);
401 if (sock
> 0 && errstring
!= NULL
&& *errstring
!= NULL
) {
405 TRACE(("leave connect_remote: sock %d\n", sock
))
409 /* Sets up a pipe for a, returning three non-blocking file descriptors
410 * and the pid. exec_fn is the function that will actually execute the child process,
411 * it will be run after the child has fork()ed, and is passed exec_data.
412 * If ret_errfd == NULL then stderr will not be captured.
413 * ret_pid can be passed as NULL to discard the pid. */
414 int spawn_command(void(*exec_fn
)(void *user_data
), void *exec_data
,
415 int *ret_writefd
, int *ret_readfd
, int *ret_errfd
, pid_t
*ret_pid
) {
424 /* redirect stdin/stdout/stderr */
425 if (pipe(infds
) != 0) {
426 return DROPBEAR_FAILURE
;
428 if (pipe(outfds
) != 0) {
429 return DROPBEAR_FAILURE
;
431 if (ret_errfd
&& pipe(errfds
) != 0) {
432 return DROPBEAR_FAILURE
;
442 return DROPBEAR_FAILURE
;
448 TRACE(("back to normal sigchld"))
449 /* Revert to normal sigchld handling */
450 if (signal(SIGCHLD
, SIG_DFL
) == SIG_ERR
) {
451 dropbear_exit("signal() error");
454 /* redirect stdin/stdout */
456 if ((dup2(infds
[FDIN
], STDIN_FILENO
) < 0) ||
457 (dup2(outfds
[FDOUT
], STDOUT_FILENO
) < 0) ||
458 (ret_errfd
&& dup2(errfds
[FDOUT
], STDERR_FILENO
) < 0)) {
459 TRACE(("leave noptycommand: error redirecting FDs"))
460 dropbear_exit("Child dup2() failure");
466 close(outfds
[FDOUT
]);
470 close(errfds
[FDOUT
]);
475 return DROPBEAR_FAILURE
;
479 close(outfds
[FDOUT
]);
481 setnonblocking(outfds
[FDIN
]);
482 setnonblocking(infds
[FDOUT
]);
485 close(errfds
[FDOUT
]);
486 setnonblocking(errfds
[FDIN
]);
493 *ret_writefd
= infds
[FDOUT
];
494 *ret_readfd
= outfds
[FDIN
];
496 *ret_errfd
= errfds
[FDIN
];
498 return DROPBEAR_SUCCESS
;
502 /* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
503 * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
505 void run_shell_command(const char* cmd
, unsigned int maxfd
, char* usershell
) {
507 char * baseshell
= NULL
;
510 baseshell
= basename(usershell
);
515 /* a login shell should be "-bash" for "/bin/bash" etc */
516 int len
= strlen(baseshell
) + 2; /* 2 for "-" */
517 argv
[0] = (char*)m_malloc(len
);
518 snprintf(argv
[0], len
, "-%s", baseshell
);
523 argv
[2] = (char*)cmd
;
526 /* construct a shell of the form "-bash" etc */
530 /* Re-enable SIGPIPE for the executed process */
531 if (signal(SIGPIPE
, SIG_DFL
) == SIG_ERR
) {
532 dropbear_exit("signal() error");
535 /* close file descriptors except stdin/stdout/stderr
536 * Need to be sure FDs are closed here to avoid reading files as root */
537 for (i
= 3; i
<= maxfd
; i
++) {
541 execv(usershell
, argv
);
544 void get_socket_address(int fd
, char **local_host
, char **local_port
,
545 char **remote_host
, char **remote_port
, int host_lookup
)
547 struct sockaddr_storage addr
;
550 if (local_host
|| local_port
) {
551 addrlen
= sizeof(addr
);
552 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
) < 0) {
553 dropbear_exit("Failed socket address: %s", strerror(errno
));
555 getaddrstring(&addr
, local_host
, local_port
, host_lookup
);
557 if (remote_host
|| remote_port
) {
558 addrlen
= sizeof(addr
);
559 if (getpeername(fd
, (struct sockaddr
*)&addr
, &addrlen
) < 0) {
560 dropbear_exit("Failed socket address: %s", strerror(errno
));
562 getaddrstring(&addr
, remote_host
, remote_port
, host_lookup
);
566 /* Return a string representation of the socket address passed. The return
567 * value is allocated with malloc() */
568 void getaddrstring(struct sockaddr_storage
* addr
,
569 char **ret_host
, char **ret_port
,
572 char host
[NI_MAXHOST
+1], serv
[NI_MAXSERV
+1];
576 int flags
= NI_NUMERICSERV
| NI_NUMERICHOST
;
578 #ifndef DO_HOST_LOOKUP
583 flags
= NI_NUMERICSERV
;
586 len
= sizeof(struct sockaddr_storage
);
587 /* Some platforms such as Solaris 8 require that len is the length
588 * of the specific structure. Some older linux systems (glibc 2.1.3
589 * such as debian potato) have sockaddr_storage.__ss_family instead
590 * but we'll ignore them */
591 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
592 if (addr
->ss_family
== AF_INET
) {
593 len
= sizeof(struct sockaddr_in
);
596 if (addr
->ss_family
== AF_INET6
) {
597 len
= sizeof(struct sockaddr_in6
);
602 ret
= getnameinfo((struct sockaddr
*)addr
, len
, host
, sizeof(host
)-1,
603 serv
, sizeof(serv
)-1, flags
);
607 /* On some systems (Darwin does it) we get EINTR from getnameinfo
608 * somehow. Eew. So we'll just return the IP, since that doesn't seem
609 * to exhibit that behaviour. */
610 getaddrstring(addr
, ret_host
, ret_port
, 0);
613 /* if we can't do a numeric lookup, something's gone terribly wrong */
614 dropbear_exit("Failed lookup: %s", gai_strerror(ret
));
619 *ret_host
= m_strdup(host
);
622 *ret_port
= m_strdup(serv
);
627 void printhex(const char * label
, const unsigned char * buf
, int len
) {
631 fprintf(stderr
, "%s\n", label
);
632 for (i
= 0; i
< len
; i
++) {
633 fprintf(stderr
, "%02x", buf
[i
]);
635 fprintf(stderr
, "\n");
637 else if (i
% 2 == 1) {
638 fprintf(stderr
, " ");
641 fprintf(stderr
, "\n");
645 /* Strip all control characters from text (a null-terminated string), except
646 * for '\n', '\r' and '\t'.
647 * The result returned is a newly allocated string, this must be free()d after
649 char * stripcontrol(const char * text
) {
656 ret
= m_malloc(len
+1);
659 for (i
= 0; i
< len
; i
++) {
660 if ((text
[i
] <= '~' && text
[i
] >= ' ') /* normal printable range */
661 || text
[i
] == '\n' || text
[i
] == '\r' || text
[i
] == '\t') {
671 /* reads the contents of filename into the buffer buf, from the current
672 * position, either to the end of the file, or the buffer being full.
673 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
674 int buf_readfile(buffer
* buf
, const char* filename
) {
679 int ret
= DROPBEAR_FAILURE
;
681 fd
= open(filename
, O_RDONLY
);
688 maxlen
= buf
->size
- buf
->pos
;
689 len
= read(fd
, buf_getwriteptr(buf
, maxlen
), maxlen
);
691 if (errno
== EINTR
|| errno
== EAGAIN
) {
696 buf_incrwritepos(buf
, len
);
697 } while (len
< maxlen
&& len
> 0);
699 ret
= DROPBEAR_SUCCESS
;
708 /* get a line from the file into buffer in the style expected for an
710 * Will return DROPBEAR_SUCCESS if data is read, or DROPBEAR_FAILURE on EOF.*/
711 /* Only used for ~/.ssh/known_hosts and ~/.ssh/authorized_keys */
712 #if defined(DROPBEAR_CLIENT) || defined(ENABLE_SVR_PUBKEY_AUTH)
713 int buf_getline(buffer
* line
, FILE * authfile
) {
717 TRACE(("enter buf_getline"))
722 while (line
->pos
< line
->size
) {
724 c
= fgetc(authfile
); /*getc() is weird with some uClibc systems*/
725 if (c
== EOF
|| c
== '\n' || c
== '\r') {
729 buf_putbyte(line
, (unsigned char)c
);
732 TRACE(("leave getauthline: line too long"))
733 /* We return success, but the line length will be zeroed - ie we just
734 * ignore that line */
740 /* if we didn't read anything before EOF or error, exit */
741 if (c
== EOF
&& line
->pos
== 0) {
742 TRACE(("leave buf_getline: failure"))
743 return DROPBEAR_FAILURE
;
745 TRACE(("leave buf_getline: success"))
747 return DROPBEAR_SUCCESS
;
753 /* make sure that the socket closes */
754 void m_close(int fd
) {
759 } while (val
< 0 && errno
== EINTR
);
761 if (val
< 0 && errno
!= EBADF
) {
762 /* Linux says EIO can happen */
763 dropbear_exit("Error closing fd %d, %s", fd
, strerror(errno
));
767 void * m_malloc(size_t size
) {
772 dropbear_exit("m_malloc failed");
774 ret
= calloc(1, size
);
776 dropbear_exit("m_malloc failed");
782 void * m_strdup(const char * str
) {
787 dropbear_exit("m_strdup failed");
792 void __m_free(void* ptr
) {
798 void * m_realloc(void* ptr
, size_t size
) {
803 dropbear_exit("m_realloc failed");
805 ret
= realloc(ptr
, size
);
807 dropbear_exit("m_realloc failed");
812 /* Clear the data, based on the method in David Wheeler's
813 * "Secure Programming for Linux and Unix HOWTO" */
814 /* Beware of calling this from within dbutil.c - things might get
816 void m_burn(void *data
, unsigned int len
) {
817 volatile char *p
= data
;
827 void setnonblocking(int fd
) {
829 TRACE(("setnonblocking: %d", fd
))
831 if (fcntl(fd
, F_SETFL
, O_NONBLOCK
) < 0) {
832 if (errno
== ENODEV
) {
833 /* Some devices (like /dev/null redirected in)
834 * can't be set to non-blocking */
835 TRACE(("ignoring ENODEV for setnonblocking"))
837 dropbear_exit("Couldn't set nonblocking");
840 TRACE(("leave setnonblocking"))
843 void disallow_core() {
845 lim
.rlim_cur
= lim
.rlim_max
= 0;
846 setrlimit(RLIMIT_CORE
, &lim
);
849 /* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
850 int m_str_to_uint(const char* str
, unsigned int *val
) {
852 *val
= strtoul(str
, NULL
, 10);
853 /* The c99 spec doesn't actually seem to define EINVAL, but most platforms
854 * I've looked at mention it in their manpage */
855 if ((*val
== 0 && errno
== EINVAL
)
856 || (*val
== ULONG_MAX
&& errno
== ERANGE
)) {
857 return DROPBEAR_FAILURE
;
859 return DROPBEAR_SUCCESS
;