dropbear: update to 2015.67
[tomato.git] / release / src / router / dropbear / dbutil.c
blobae7313207e4fce467e2581136c0662e0ce336fd3
1 /*
2 * Dropbear - a SSH2 server
3 *
4 * Copyright (c) 2002,2003 Matt Johnston
5 * All rights reserved.
6 *
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
23 * SOFTWARE.
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
31 * are met:
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. */
51 #include "config.h"
53 #ifdef __linux__
54 #define _GNU_SOURCE
55 /* To call clock_gettime() directly */
56 #include <sys/syscall.h>
57 #endif /* __linux */
59 #ifdef HAVE_MACH_MACH_TIME_H
60 #include <mach/mach_time.h>
61 #include <mach/mach.h>
62 #endif
64 #include "includes.h"
65 #include "dbutil.h"
66 #include "buffer.h"
67 #include "session.h"
68 #include "atomicio.h"
70 #define MAX_FMT 100
72 static void generic_dropbear_exit(int exitcode, const char* format,
73 va_list param) ATTRIB_NORETURN;
74 static void generic_dropbear_log(int priority, const char* format,
75 va_list param);
77 void (*_dropbear_exit)(int exitcode, const char* format, va_list param) ATTRIB_NORETURN
78 = generic_dropbear_exit;
79 void (*_dropbear_log)(int priority, const char* format, va_list param)
80 = generic_dropbear_log;
82 #ifdef DEBUG_TRACE
83 int debug_trace = 0;
84 #endif
86 #ifndef DISABLE_SYSLOG
87 void startsyslog() {
89 openlog(PROGNAME, LOG_PID, LOG_AUTHPRIV);
92 #endif /* DISABLE_SYSLOG */
94 /* the "format" string must be <= 100 characters */
95 void dropbear_close(const char* format, ...) {
97 va_list param;
99 va_start(param, format);
100 _dropbear_exit(EXIT_SUCCESS, format, param);
101 va_end(param);
105 void dropbear_exit(const char* format, ...) {
107 va_list param;
109 va_start(param, format);
110 _dropbear_exit(EXIT_FAILURE, format, param);
111 va_end(param);
114 static void generic_dropbear_exit(int exitcode, const char* format,
115 va_list param) {
117 char fmtbuf[300];
119 snprintf(fmtbuf, sizeof(fmtbuf), "Exited: %s", format);
121 _dropbear_log(LOG_INFO, fmtbuf, param);
123 exit(exitcode);
126 void fail_assert(const char* expr, const char* file, int line) {
127 dropbear_exit("Failed assertion (%s:%d): `%s'", file, line, expr);
130 static void generic_dropbear_log(int UNUSED(priority), const char* format,
131 va_list param) {
133 char printbuf[1024];
135 vsnprintf(printbuf, sizeof(printbuf), format, param);
137 fprintf(stderr, "%s\n", printbuf);
141 /* this is what can be called to write arbitrary log messages */
142 void dropbear_log(int priority, const char* format, ...) {
144 va_list param;
146 va_start(param, format);
147 _dropbear_log(priority, format, param);
148 va_end(param);
152 #ifdef DEBUG_TRACE
153 void dropbear_trace(const char* format, ...) {
154 va_list param;
155 struct timeval tv;
157 if (!debug_trace) {
158 return;
161 gettimeofday(&tv, NULL);
163 va_start(param, format);
164 fprintf(stderr, "TRACE (%d) %d.%d: ", getpid(), (int)tv.tv_sec, (int)tv.tv_usec);
165 vfprintf(stderr, format, param);
166 fprintf(stderr, "\n");
167 va_end(param);
170 void dropbear_trace2(const char* format, ...) {
171 static int trace_env = -1;
172 va_list param;
173 struct timeval tv;
175 if (trace_env == -1) {
176 trace_env = getenv("DROPBEAR_TRACE2") ? 1 : 0;
179 if (!(debug_trace && trace_env)) {
180 return;
183 gettimeofday(&tv, NULL);
185 va_start(param, format);
186 fprintf(stderr, "TRACE2 (%d) %d.%d: ", getpid(), (int)tv.tv_sec, (int)tv.tv_usec);
187 vfprintf(stderr, format, param);
188 fprintf(stderr, "\n");
189 va_end(param);
191 #endif /* DEBUG_TRACE */
193 void set_sock_nodelay(int sock) {
194 int val;
196 /* disable nagle */
197 val = 1;
198 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void*)&val, sizeof(val));
201 void set_sock_priority(int sock, enum dropbear_prio prio) {
203 int iptos_val = 0, so_prio_val = 0, rc;
205 /* Don't log ENOTSOCK errors so that this can harmlessly be called
206 * on a client '-J' proxy pipe */
208 /* set the TOS bit for either ipv4 or ipv6 */
209 #ifdef IPTOS_LOWDELAY
210 if (prio == DROPBEAR_PRIO_LOWDELAY) {
211 iptos_val = IPTOS_LOWDELAY;
212 } else if (prio == DROPBEAR_PRIO_BULK) {
213 iptos_val = IPTOS_THROUGHPUT;
215 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
216 rc = setsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, (void*)&iptos_val, sizeof(iptos_val));
217 if (rc < 0 && errno != ENOTSOCK) {
218 TRACE(("Couldn't set IPV6_TCLASS (%s)", strerror(errno)));
220 #endif
221 rc = setsockopt(sock, IPPROTO_IP, IP_TOS, (void*)&iptos_val, sizeof(iptos_val));
222 if (rc < 0 && errno != ENOTSOCK) {
223 TRACE(("Couldn't set IP_TOS (%s)", strerror(errno)));
225 #endif
227 #ifdef SO_PRIORITY
228 if (prio == DROPBEAR_PRIO_LOWDELAY) {
229 so_prio_val = TC_PRIO_INTERACTIVE;
230 } else if (prio == DROPBEAR_PRIO_BULK) {
231 so_prio_val = TC_PRIO_BULK;
233 /* linux specific, sets QoS class. see tc-prio(8) */
234 rc = setsockopt(sock, SOL_SOCKET, SO_PRIORITY, (void*) &so_prio_val, sizeof(so_prio_val));
235 if (rc < 0 && errno != ENOTSOCK)
236 dropbear_log(LOG_WARNING, "Couldn't set SO_PRIORITY (%s)",
237 strerror(errno));
238 #endif
242 /* Listen on address:port.
243 * Special cases are address of "" listening on everything,
244 * and address of NULL listening on localhost only.
245 * Returns the number of sockets bound on success, or -1 on failure. On
246 * failure, if errstring wasn't NULL, it'll be a newly malloced error
247 * string.*/
248 int dropbear_listen(const char* address, const char* port,
249 int *socks, unsigned int sockcount, char **errstring, int *maxfd) {
251 struct addrinfo hints, *res = NULL, *res0 = NULL;
252 int err;
253 unsigned int nsock;
254 struct linger linger;
255 int val;
256 int sock;
258 TRACE(("enter dropbear_listen"))
260 memset(&hints, 0, sizeof(hints));
261 hints.ai_family = AF_UNSPEC; /* TODO: let them flag v4 only etc */
262 hints.ai_socktype = SOCK_STREAM;
264 /* for calling getaddrinfo:
265 address == NULL and !AI_PASSIVE: local loopback
266 address == NULL and AI_PASSIVE: all interfaces
267 address != NULL: whatever the address says */
268 if (!address) {
269 TRACE(("dropbear_listen: local loopback"))
270 } else {
271 if (address[0] == '\0') {
272 TRACE(("dropbear_listen: all interfaces"))
273 address = NULL;
275 hints.ai_flags = AI_PASSIVE;
277 err = getaddrinfo(address, port, &hints, &res0);
279 if (err) {
280 if (errstring != NULL && *errstring == NULL) {
281 int len;
282 len = 20 + strlen(gai_strerror(err));
283 *errstring = (char*)m_malloc(len);
284 snprintf(*errstring, len, "Error resolving: %s", gai_strerror(err));
286 if (res0) {
287 freeaddrinfo(res0);
288 res0 = NULL;
290 TRACE(("leave dropbear_listen: failed resolving"))
291 return -1;
295 nsock = 0;
296 for (res = res0; res != NULL && nsock < sockcount;
297 res = res->ai_next) {
299 /* Get a socket */
300 socks[nsock] = socket(res->ai_family, res->ai_socktype,
301 res->ai_protocol);
303 sock = socks[nsock]; /* For clarity */
305 if (sock < 0) {
306 err = errno;
307 TRACE(("socket() failed"))
308 continue;
311 /* Various useful socket options */
312 val = 1;
313 /* set to reuse, quick timeout */
314 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &val, sizeof(val));
315 linger.l_onoff = 1;
316 linger.l_linger = 5;
317 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void*)&linger, sizeof(linger));
319 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
320 if (res->ai_family == AF_INET6) {
321 int on = 1;
322 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
323 &on, sizeof(on)) == -1) {
324 dropbear_log(LOG_WARNING, "Couldn't set IPV6_V6ONLY");
327 #endif
329 set_sock_nodelay(sock);
331 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
332 err = errno;
333 close(sock);
334 TRACE(("bind(%s) failed", port))
335 continue;
338 if (listen(sock, DROPBEAR_LISTEN_BACKLOG) < 0) {
339 err = errno;
340 close(sock);
341 TRACE(("listen() failed"))
342 continue;
345 *maxfd = MAX(*maxfd, sock);
347 nsock++;
350 if (res0) {
351 freeaddrinfo(res0);
352 res0 = NULL;
355 if (nsock == 0) {
356 if (errstring != NULL && *errstring == NULL) {
357 int len;
358 len = 20 + strlen(strerror(err));
359 *errstring = (char*)m_malloc(len);
360 snprintf(*errstring, len, "Error listening: %s", strerror(err));
362 TRACE(("leave dropbear_listen: failure, %s", strerror(err)))
363 return -1;
366 TRACE(("leave dropbear_listen: success, %d socks bound", nsock))
367 return nsock;
370 /* Connect to a given unix socket. The socket is blocking */
371 #ifdef ENABLE_CONNECT_UNIX
372 int connect_unix(const char* path) {
373 struct sockaddr_un addr;
374 int fd = -1;
376 memset((void*)&addr, 0x0, sizeof(addr));
377 addr.sun_family = AF_UNIX;
378 strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
379 fd = socket(PF_UNIX, SOCK_STREAM, 0);
380 if (fd < 0) {
381 TRACE(("Failed to open unix socket"))
382 return -1;
384 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
385 TRACE(("Failed to connect to '%s' socket", path))
386 m_close(fd);
387 return -1;
389 return fd;
391 #endif
393 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will
394 * return immediately if nonblocking is set. On failure, if errstring
395 * wasn't null, it will be a newly malloced error message */
397 /* TODO: maxfd */
398 int connect_remote(const char* remotehost, const char* remoteport,
399 int nonblocking, char ** errstring) {
401 struct addrinfo *res0 = NULL, *res = NULL, hints;
402 int sock;
403 int err;
405 TRACE(("enter connect_remote"))
407 if (errstring != NULL) {
408 *errstring = NULL;
411 memset(&hints, 0, sizeof(hints));
412 hints.ai_socktype = SOCK_STREAM;
413 hints.ai_family = PF_UNSPEC;
415 err = getaddrinfo(remotehost, remoteport, &hints, &res0);
416 if (err) {
417 if (errstring != NULL && *errstring == NULL) {
418 int len;
419 len = 100 + strlen(gai_strerror(err));
420 *errstring = (char*)m_malloc(len);
421 snprintf(*errstring, len, "Error resolving '%s' port '%s'. %s",
422 remotehost, remoteport, gai_strerror(err));
424 TRACE(("Error resolving: %s", gai_strerror(err)))
425 return -1;
428 sock = -1;
429 err = EADDRNOTAVAIL;
430 for (res = res0; res; res = res->ai_next) {
432 sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
433 if (sock < 0) {
434 err = errno;
435 continue;
438 if (nonblocking) {
439 setnonblocking(sock);
442 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
443 if (errno == EINPROGRESS && nonblocking) {
444 TRACE(("Connect in progress"))
445 break;
446 } else {
447 err = errno;
448 close(sock);
449 sock = -1;
450 continue;
454 break; /* Success */
457 if (sock < 0 && !(errno == EINPROGRESS && nonblocking)) {
458 /* Failed */
459 if (errstring != NULL && *errstring == NULL) {
460 int len;
461 len = 20 + strlen(strerror(err));
462 *errstring = (char*)m_malloc(len);
463 snprintf(*errstring, len, "Error connecting: %s", strerror(err));
465 TRACE(("Error connecting: %s", strerror(err)))
466 } else {
467 /* Success */
468 set_sock_nodelay(sock);
471 freeaddrinfo(res0);
472 if (sock > 0 && errstring != NULL && *errstring != NULL) {
473 m_free(*errstring);
476 TRACE(("leave connect_remote: sock %d\n", sock))
477 return sock;
480 /* Sets up a pipe for a, returning three non-blocking file descriptors
481 * and the pid. exec_fn is the function that will actually execute the child process,
482 * it will be run after the child has fork()ed, and is passed exec_data.
483 * If ret_errfd == NULL then stderr will not be captured.
484 * ret_pid can be passed as NULL to discard the pid. */
485 int spawn_command(void(*exec_fn)(void *user_data), void *exec_data,
486 int *ret_writefd, int *ret_readfd, int *ret_errfd, pid_t *ret_pid) {
487 int infds[2];
488 int outfds[2];
489 int errfds[2];
490 pid_t pid;
492 const int FDIN = 0;
493 const int FDOUT = 1;
495 /* redirect stdin/stdout/stderr */
496 if (pipe(infds) != 0) {
497 return DROPBEAR_FAILURE;
499 if (pipe(outfds) != 0) {
500 return DROPBEAR_FAILURE;
502 if (ret_errfd && pipe(errfds) != 0) {
503 return DROPBEAR_FAILURE;
506 #ifdef USE_VFORK
507 pid = vfork();
508 #else
509 pid = fork();
510 #endif
512 if (pid < 0) {
513 return DROPBEAR_FAILURE;
516 if (!pid) {
517 /* child */
519 TRACE(("back to normal sigchld"))
520 /* Revert to normal sigchld handling */
521 if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
522 dropbear_exit("signal() error");
525 /* redirect stdin/stdout */
527 if ((dup2(infds[FDIN], STDIN_FILENO) < 0) ||
528 (dup2(outfds[FDOUT], STDOUT_FILENO) < 0) ||
529 (ret_errfd && dup2(errfds[FDOUT], STDERR_FILENO) < 0)) {
530 TRACE(("leave noptycommand: error redirecting FDs"))
531 dropbear_exit("Child dup2() failure");
534 close(infds[FDOUT]);
535 close(infds[FDIN]);
536 close(outfds[FDIN]);
537 close(outfds[FDOUT]);
538 if (ret_errfd)
540 close(errfds[FDIN]);
541 close(errfds[FDOUT]);
544 exec_fn(exec_data);
545 /* not reached */
546 return DROPBEAR_FAILURE;
547 } else {
548 /* parent */
549 close(infds[FDIN]);
550 close(outfds[FDOUT]);
552 setnonblocking(outfds[FDIN]);
553 setnonblocking(infds[FDOUT]);
555 if (ret_errfd) {
556 close(errfds[FDOUT]);
557 setnonblocking(errfds[FDIN]);
560 if (ret_pid) {
561 *ret_pid = pid;
564 *ret_writefd = infds[FDOUT];
565 *ret_readfd = outfds[FDIN];
566 if (ret_errfd) {
567 *ret_errfd = errfds[FDIN];
569 return DROPBEAR_SUCCESS;
573 /* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
574 * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
576 void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell) {
577 char * argv[4];
578 char * baseshell = NULL;
579 unsigned int i;
581 baseshell = basename(usershell);
583 if (cmd != NULL) {
584 argv[0] = baseshell;
585 } else {
586 /* a login shell should be "-bash" for "/bin/bash" etc */
587 int len = strlen(baseshell) + 2; /* 2 for "-" */
588 argv[0] = (char*)m_malloc(len);
589 snprintf(argv[0], len, "-%s", baseshell);
592 if (cmd != NULL) {
593 argv[1] = "-c";
594 argv[2] = (char*)cmd;
595 argv[3] = NULL;
596 } else {
597 /* construct a shell of the form "-bash" etc */
598 argv[1] = NULL;
601 /* Re-enable SIGPIPE for the executed process */
602 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR) {
603 dropbear_exit("signal() error");
606 /* close file descriptors except stdin/stdout/stderr
607 * Need to be sure FDs are closed here to avoid reading files as root */
608 for (i = 3; i <= maxfd; i++) {
609 m_close(i);
612 execv(usershell, argv);
615 void get_socket_address(int fd, char **local_host, char **local_port,
616 char **remote_host, char **remote_port, int host_lookup)
618 struct sockaddr_storage addr;
619 socklen_t addrlen;
621 if (local_host || local_port) {
622 addrlen = sizeof(addr);
623 if (getsockname(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
624 dropbear_exit("Failed socket address: %s", strerror(errno));
626 getaddrstring(&addr, local_host, local_port, host_lookup);
628 if (remote_host || remote_port) {
629 addrlen = sizeof(addr);
630 if (getpeername(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
631 dropbear_exit("Failed socket address: %s", strerror(errno));
633 getaddrstring(&addr, remote_host, remote_port, host_lookup);
637 /* Return a string representation of the socket address passed. The return
638 * value is allocated with malloc() */
639 void getaddrstring(struct sockaddr_storage* addr,
640 char **ret_host, char **ret_port,
641 int host_lookup) {
643 char host[NI_MAXHOST+1], serv[NI_MAXSERV+1];
644 unsigned int len;
645 int ret;
647 int flags = NI_NUMERICSERV | NI_NUMERICHOST;
649 #ifndef DO_HOST_LOOKUP
650 host_lookup = 0;
651 #endif
653 if (host_lookup) {
654 flags = NI_NUMERICSERV;
657 len = sizeof(struct sockaddr_storage);
658 /* Some platforms such as Solaris 8 require that len is the length
659 * of the specific structure. Some older linux systems (glibc 2.1.3
660 * such as debian potato) have sockaddr_storage.__ss_family instead
661 * but we'll ignore them */
662 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
663 if (addr->ss_family == AF_INET) {
664 len = sizeof(struct sockaddr_in);
666 #ifdef AF_INET6
667 if (addr->ss_family == AF_INET6) {
668 len = sizeof(struct sockaddr_in6);
670 #endif
671 #endif
673 ret = getnameinfo((struct sockaddr*)addr, len, host, sizeof(host)-1,
674 serv, sizeof(serv)-1, flags);
676 if (ret != 0) {
677 if (host_lookup) {
678 /* On some systems (Darwin does it) we get EINTR from getnameinfo
679 * somehow. Eew. So we'll just return the IP, since that doesn't seem
680 * to exhibit that behaviour. */
681 getaddrstring(addr, ret_host, ret_port, 0);
682 return;
683 } else {
684 /* if we can't do a numeric lookup, something's gone terribly wrong */
685 dropbear_exit("Failed lookup: %s", gai_strerror(ret));
689 if (ret_host) {
690 *ret_host = m_strdup(host);
692 if (ret_port) {
693 *ret_port = m_strdup(serv);
697 #ifdef DEBUG_TRACE
698 void printhex(const char * label, const unsigned char * buf, int len) {
700 int i;
702 fprintf(stderr, "%s\n", label);
703 for (i = 0; i < len; i++) {
704 fprintf(stderr, "%02x", buf[i]);
705 if (i % 16 == 15) {
706 fprintf(stderr, "\n");
708 else if (i % 2 == 1) {
709 fprintf(stderr, " ");
712 fprintf(stderr, "\n");
715 void printmpint(const char *label, mp_int *mp) {
716 buffer *buf = buf_new(1000);
717 buf_putmpint(buf, mp);
718 printhex(label, buf->data, buf->len);
719 buf_free(buf);
722 #endif
724 /* Strip all control characters from text (a null-terminated string), except
725 * for '\n', '\r' and '\t'.
726 * The result returned is a newly allocated string, this must be free()d after
727 * use */
728 char * stripcontrol(const char * text) {
730 char * ret;
731 int len, pos;
732 int i;
734 len = strlen(text);
735 ret = m_malloc(len+1);
737 pos = 0;
738 for (i = 0; i < len; i++) {
739 if ((text[i] <= '~' && text[i] >= ' ') /* normal printable range */
740 || text[i] == '\n' || text[i] == '\r' || text[i] == '\t') {
741 ret[pos] = text[i];
742 pos++;
745 ret[pos] = 0x0;
746 return ret;
750 /* reads the contents of filename into the buffer buf, from the current
751 * position, either to the end of the file, or the buffer being full.
752 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
753 int buf_readfile(buffer* buf, const char* filename) {
755 int fd = -1;
756 int len;
757 int maxlen;
758 int ret = DROPBEAR_FAILURE;
760 fd = open(filename, O_RDONLY);
762 if (fd < 0) {
763 goto out;
766 do {
767 maxlen = buf->size - buf->pos;
768 len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
769 if (len < 0) {
770 if (errno == EINTR || errno == EAGAIN) {
771 continue;
773 goto out;
775 buf_incrwritepos(buf, len);
776 } while (len < maxlen && len > 0);
778 ret = DROPBEAR_SUCCESS;
780 out:
781 if (fd >= 0) {
782 m_close(fd);
784 return ret;
787 /* get a line from the file into buffer in the style expected for an
788 * authkeys file.
789 * Will return DROPBEAR_SUCCESS if data is read, or DROPBEAR_FAILURE on EOF.*/
790 /* Only used for ~/.ssh/known_hosts and ~/.ssh/authorized_keys */
791 #if defined(DROPBEAR_CLIENT) || defined(ENABLE_SVR_PUBKEY_AUTH)
792 int buf_getline(buffer * line, FILE * authfile) {
794 int c = EOF;
796 buf_setpos(line, 0);
797 buf_setlen(line, 0);
799 while (line->pos < line->size) {
801 c = fgetc(authfile); /*getc() is weird with some uClibc systems*/
802 if (c == EOF || c == '\n' || c == '\r') {
803 goto out;
806 buf_putbyte(line, (unsigned char)c);
809 TRACE(("leave getauthline: line too long"))
810 /* We return success, but the line length will be zeroed - ie we just
811 * ignore that line */
812 buf_setlen(line, 0);
814 out:
817 /* if we didn't read anything before EOF or error, exit */
818 if (c == EOF && line->pos == 0) {
819 return DROPBEAR_FAILURE;
820 } else {
821 buf_setpos(line, 0);
822 return DROPBEAR_SUCCESS;
826 #endif
828 /* make sure that the socket closes */
829 void m_close(int fd) {
831 if (fd == -1) {
832 return;
835 int val;
836 do {
837 val = close(fd);
838 } while (val < 0 && errno == EINTR);
840 if (val < 0 && errno != EBADF) {
841 /* Linux says EIO can happen */
842 dropbear_exit("Error closing fd %d, %s", fd, strerror(errno));
846 void * m_malloc(size_t size) {
848 void* ret;
850 if (size == 0) {
851 dropbear_exit("m_malloc failed");
853 ret = calloc(1, size);
854 if (ret == NULL) {
855 dropbear_exit("m_malloc failed");
857 return ret;
861 void * m_strdup(const char * str) {
862 char* ret;
864 ret = strdup(str);
865 if (ret == NULL) {
866 dropbear_exit("m_strdup failed");
868 return ret;
871 void * m_realloc(void* ptr, size_t size) {
873 void *ret;
875 if (size == 0) {
876 dropbear_exit("m_realloc failed");
878 ret = realloc(ptr, size);
879 if (ret == NULL) {
880 dropbear_exit("m_realloc failed");
882 return ret;
885 /* Clear the data, based on the method in David Wheeler's
886 * "Secure Programming for Linux and Unix HOWTO" */
887 /* Beware of calling this from within dbutil.c - things might get
888 * optimised away */
889 void m_burn(void *data, unsigned int len) {
890 volatile char *p = data;
892 if (data == NULL)
893 return;
894 while (len--) {
895 *p++ = 0x0;
900 void setnonblocking(int fd) {
902 TRACE(("setnonblocking: %d", fd))
904 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
905 if (errno == ENODEV) {
906 /* Some devices (like /dev/null redirected in)
907 * can't be set to non-blocking */
908 TRACE(("ignoring ENODEV for setnonblocking"))
909 } else {
910 dropbear_exit("Couldn't set nonblocking");
913 TRACE(("leave setnonblocking"))
916 void disallow_core() {
917 struct rlimit lim;
918 lim.rlim_cur = lim.rlim_max = 0;
919 setrlimit(RLIMIT_CORE, &lim);
922 /* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
923 int m_str_to_uint(const char* str, unsigned int *val) {
924 unsigned long l;
925 errno = 0;
926 l = strtoul(str, NULL, 10);
927 /* The c99 spec doesn't actually seem to define EINVAL, but most platforms
928 * I've looked at mention it in their manpage */
929 if ((l == 0 && errno == EINVAL)
930 || (l == ULONG_MAX && errno == ERANGE)
931 || (l > UINT_MAX)) {
932 return DROPBEAR_FAILURE;
933 } else {
934 *val = l;
935 return DROPBEAR_SUCCESS;
939 /* Returns malloced path. Only expands ~ in first character */
940 char * expand_tilde(const char *inpath) {
941 struct passwd *pw = NULL;
942 if (inpath[0] == '~') {
943 pw = getpwuid(getuid());
944 if (pw && pw->pw_dir) {
945 int len = strlen(inpath) + strlen(pw->pw_dir) + 1;
946 char *buf = m_malloc(len);
947 snprintf(buf, len, "%s/%s", pw->pw_dir, &inpath[1]);
948 return buf;
952 /* Fallback */
953 return m_strdup(inpath);
956 int constant_time_memcmp(const void* a, const void *b, size_t n)
958 const char *xa = a, *xb = b;
959 uint8_t c = 0;
960 size_t i;
961 for (i = 0; i < n; i++)
963 c |= (xa[i] ^ xb[i]);
965 return c;
968 #if defined(__linux__) && defined(SYS_clock_gettime)
969 /* CLOCK_MONOTONIC_COARSE was added in Linux 2.6.32 but took a while to
970 reach userspace include headers */
971 #ifndef CLOCK_MONOTONIC_COARSE
972 #define CLOCK_MONOTONIC_COARSE 6
973 #endif
974 static clockid_t get_linux_clock_source() {
975 struct timespec ts;
976 if (syscall(SYS_clock_gettime, CLOCK_MONOTONIC_COARSE, &ts) == 0) {
977 return CLOCK_MONOTONIC_COARSE;
980 if (syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts) == 0) {
981 return CLOCK_MONOTONIC;
983 return -1;
985 #endif
987 time_t monotonic_now() {
988 #if defined(__linux__) && defined(SYS_clock_gettime)
989 static clockid_t clock_source = -2;
991 if (clock_source == -2) {
992 /* First run, find out which one works.
993 -1 will fall back to time() */
994 clock_source = get_linux_clock_source();
997 if (clock_source >= 0) {
998 struct timespec ts;
999 if (syscall(SYS_clock_gettime, clock_source, &ts) != 0) {
1000 /* Intermittent clock failures should not happen */
1001 dropbear_exit("Clock broke");
1003 return ts.tv_sec;
1005 #endif /* linux clock_gettime */
1007 #if defined(HAVE_MACH_ABSOLUTE_TIME)
1008 /* OS X, see https://developer.apple.com/library/mac/qa/qa1398/_index.html */
1009 static mach_timebase_info_data_t timebase_info;
1010 if (timebase_info.denom == 0) {
1011 mach_timebase_info(&timebase_info);
1013 return mach_absolute_time() * timebase_info.numer / timebase_info.denom
1014 / 1e9;
1015 #endif /* osx mach_absolute_time */
1017 /* Fallback for everything else - this will sometimes go backwards */
1018 return time(NULL);