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. */
55 /* To call clock_gettime() directly */
56 #include <sys/syscall.h>
59 #ifdef HAVE_MACH_MACH_TIME_H
60 #include <mach/mach_time.h>
61 #include <mach/mach.h>
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
,
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
;
86 #ifndef DISABLE_SYSLOG
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
, ...) {
99 va_start(param
, format
);
100 _dropbear_exit(EXIT_SUCCESS
, format
, param
);
105 void dropbear_exit(const char* format
, ...) {
109 va_start(param
, format
);
110 _dropbear_exit(EXIT_FAILURE
, format
, param
);
114 static void generic_dropbear_exit(int exitcode
, const char* format
,
119 snprintf(fmtbuf
, sizeof(fmtbuf
), "Exited: %s", format
);
121 _dropbear_log(LOG_INFO
, fmtbuf
, param
);
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
,
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
, ...) {
146 va_start(param
, format
);
147 _dropbear_log(priority
, format
, param
);
153 void dropbear_trace(const char* format
, ...) {
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");
170 void dropbear_trace2(const char* format
, ...) {
171 static int trace_env
= -1;
175 if (trace_env
== -1) {
176 trace_env
= getenv("DROPBEAR_TRACE2") ? 1 : 0;
179 if (!(debug_trace
&& trace_env
)) {
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");
191 #endif /* DEBUG_TRACE */
193 void set_sock_nodelay(int sock
) {
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
)));
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
)));
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)",
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
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
;
254 struct linger linger
;
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 */
269 TRACE(("dropbear_listen: local loopback"))
271 if (address
[0] == '\0') {
272 TRACE(("dropbear_listen: all interfaces"))
275 hints
.ai_flags
= AI_PASSIVE
;
277 err
= getaddrinfo(address
, port
, &hints
, &res0
);
280 if (errstring
!= NULL
&& *errstring
== NULL
) {
282 len
= 20 + strlen(gai_strerror(err
));
283 *errstring
= (char*)m_malloc(len
);
284 snprintf(*errstring
, len
, "Error resolving: %s", gai_strerror(err
));
290 TRACE(("leave dropbear_listen: failed resolving"))
296 for (res
= res0
; res
!= NULL
&& nsock
< sockcount
;
297 res
= res
->ai_next
) {
300 socks
[nsock
] = socket(res
->ai_family
, res
->ai_socktype
,
303 sock
= socks
[nsock
]; /* For clarity */
307 TRACE(("socket() failed"))
311 /* Various useful socket options */
313 /* set to reuse, quick timeout */
314 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &val
, sizeof(val
));
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
) {
322 if (setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
,
323 &on
, sizeof(on
)) == -1) {
324 dropbear_log(LOG_WARNING
, "Couldn't set IPV6_V6ONLY");
329 set_sock_nodelay(sock
);
331 if (bind(sock
, res
->ai_addr
, res
->ai_addrlen
) < 0) {
334 TRACE(("bind(%s) failed", port
))
338 if (listen(sock
, DROPBEAR_LISTEN_BACKLOG
) < 0) {
341 TRACE(("listen() failed"))
345 *maxfd
= MAX(*maxfd
, sock
);
356 if (errstring
!= NULL
&& *errstring
== NULL
) {
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
)))
366 TRACE(("leave dropbear_listen: success, %d socks bound", 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
;
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);
381 TRACE(("Failed to open unix socket"))
384 if (connect(fd
, (struct sockaddr
*)&addr
, sizeof(addr
)) < 0) {
385 TRACE(("Failed to connect to '%s' socket", path
))
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 */
398 int connect_remote(const char* remotehost
, const char* remoteport
,
399 int nonblocking
, char ** errstring
) {
401 struct addrinfo
*res0
= NULL
, *res
= NULL
, hints
;
405 TRACE(("enter connect_remote"))
407 if (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
);
417 if (errstring
!= NULL
&& *errstring
== NULL
) {
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
)))
430 for (res
= res0
; res
; res
= res
->ai_next
) {
432 sock
= socket(res
->ai_family
, res
->ai_socktype
, res
->ai_protocol
);
439 setnonblocking(sock
);
442 if (connect(sock
, res
->ai_addr
, res
->ai_addrlen
) < 0) {
443 if (errno
== EINPROGRESS
&& nonblocking
) {
444 TRACE(("Connect in progress"))
457 if (sock
< 0 && !(errno
== EINPROGRESS
&& nonblocking
)) {
459 if (errstring
!= NULL
&& *errstring
== NULL
) {
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
)))
468 set_sock_nodelay(sock
);
472 if (sock
> 0 && errstring
!= NULL
&& *errstring
!= NULL
) {
476 TRACE(("leave connect_remote: sock %d\n", 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
) {
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
;
513 return DROPBEAR_FAILURE
;
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");
537 close(outfds
[FDOUT
]);
541 close(errfds
[FDOUT
]);
546 return DROPBEAR_FAILURE
;
550 close(outfds
[FDOUT
]);
552 setnonblocking(outfds
[FDIN
]);
553 setnonblocking(infds
[FDOUT
]);
556 close(errfds
[FDOUT
]);
557 setnonblocking(errfds
[FDIN
]);
564 *ret_writefd
= infds
[FDOUT
];
565 *ret_readfd
= outfds
[FDIN
];
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
) {
578 char * baseshell
= NULL
;
581 baseshell
= basename(usershell
);
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
);
594 argv
[2] = (char*)cmd
;
597 /* construct a shell of the form "-bash" etc */
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
++) {
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
;
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
,
643 char host
[NI_MAXHOST
+1], serv
[NI_MAXSERV
+1];
647 int flags
= NI_NUMERICSERV
| NI_NUMERICHOST
;
649 #ifndef DO_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
);
667 if (addr
->ss_family
== AF_INET6
) {
668 len
= sizeof(struct sockaddr_in6
);
673 ret
= getnameinfo((struct sockaddr
*)addr
, len
, host
, sizeof(host
)-1,
674 serv
, sizeof(serv
)-1, flags
);
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);
684 /* if we can't do a numeric lookup, something's gone terribly wrong */
685 dropbear_exit("Failed lookup: %s", gai_strerror(ret
));
690 *ret_host
= m_strdup(host
);
693 *ret_port
= m_strdup(serv
);
698 void printhex(const char * label
, const unsigned char * buf
, int len
) {
702 fprintf(stderr
, "%s\n", label
);
703 for (i
= 0; i
< len
; i
++) {
704 fprintf(stderr
, "%02x", buf
[i
]);
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
);
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
728 char * stripcontrol(const char * text
) {
735 ret
= m_malloc(len
+1);
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') {
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
) {
758 int ret
= DROPBEAR_FAILURE
;
760 fd
= open(filename
, O_RDONLY
);
767 maxlen
= buf
->size
- buf
->pos
;
768 len
= read(fd
, buf_getwriteptr(buf
, maxlen
), maxlen
);
770 if (errno
== EINTR
|| errno
== EAGAIN
) {
775 buf_incrwritepos(buf
, len
);
776 } while (len
< maxlen
&& len
> 0);
778 ret
= DROPBEAR_SUCCESS
;
787 /* get a line from the file into buffer in the style expected for an
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
) {
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') {
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 */
817 /* if we didn't read anything before EOF or error, exit */
818 if (c
== EOF
&& line
->pos
== 0) {
819 return DROPBEAR_FAILURE
;
822 return DROPBEAR_SUCCESS
;
828 /* make sure that the socket closes */
829 void m_close(int 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
) {
851 dropbear_exit("m_malloc failed");
853 ret
= calloc(1, size
);
855 dropbear_exit("m_malloc failed");
861 void * m_strdup(const char * str
) {
866 dropbear_exit("m_strdup failed");
871 void * m_realloc(void* ptr
, size_t size
) {
876 dropbear_exit("m_realloc failed");
878 ret
= realloc(ptr
, size
);
880 dropbear_exit("m_realloc failed");
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
889 void m_burn(void *data
, unsigned int len
) {
890 volatile char *p
= data
;
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"))
910 dropbear_exit("Couldn't set nonblocking");
913 TRACE(("leave setnonblocking"))
916 void disallow_core() {
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
) {
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
)
932 return DROPBEAR_FAILURE
;
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]);
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
;
961 for (i
= 0; i
< n
; i
++)
963 c
|= (xa
[i
] ^ xb
[i
]);
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
974 static clockid_t
get_linux_clock_source() {
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
;
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) {
999 if (syscall(SYS_clock_gettime
, clock_source
, &ts
) != 0) {
1000 /* Intermittent clock failures should not happen */
1001 dropbear_exit("Clock broke");
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
1015 #endif /* osx mach_absolute_time */
1017 /* Fallback for everything else - this will sometimes go backwards */