1 /* $OpenBSD: sshbuf-misc.c,v 1.6 2016/05/02 08:49:03 djm Exp $ */
3 * Copyright (c) 2011 Damien Miller
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
35 #define SSHBUF_INTERNAL
39 sshbuf_dump_data(const void *s, size_t len, FILE *f)
42 const u_char *p = (const u_char *)s;
44 for (i = 0; i < len; i += 16) {
45 fprintf(f, "%.4zu: ", i);
46 for (j = i; j < i + 16; j++) {
48 fprintf(f, "%02x ", p[j]);
53 for (j = i; j < i + 16; j++) {
55 if (isascii(p[j]) && isprint(p[j]))
56 fprintf(f, "%c", p[j]);
66 sshbuf_dump(struct sshbuf *buf, FILE *f)
68 fprintf(f, "buffer %p len = %zu\n", buf, sshbuf_len(buf));
69 sshbuf_dump_data(sshbuf_ptr(buf), sshbuf_len(buf), f);
73 sshbuf_dtob16(struct sshbuf *buf)
75 size_t i, j, len = sshbuf_len(buf);
76 const u_char *p = sshbuf_ptr(buf);
78 const char hex[] = "0123456789abcdef";
82 if (SIZE_MAX / 2 <= len || (ret = malloc(len * 2 + 1)) == NULL)
84 for (i = j = 0; i < len; i++) {
85 ret[j++] = hex[(p[i] >> 4) & 0xf];
86 ret[j++] = hex[p[i] & 0xf];
93 sshbuf_dtob64(struct sshbuf *buf)
95 size_t len = sshbuf_len(buf), plen;
96 const u_char *p = sshbuf_ptr(buf);
102 plen = ((len + 2) / 3) * 4 + 1;
103 if (SIZE_MAX / 2 <= len || (ret = malloc(plen)) == NULL)
105 if ((r = b64_ntop(p, len, ret, plen)) == -1) {
106 explicit_bzero(ret, plen);
114 sshbuf_b64tod(struct sshbuf *buf, const char *b64)
116 size_t plen = strlen(b64);
122 if ((p = malloc(plen)) == NULL)
123 return SSH_ERR_ALLOC_FAIL;
124 if ((nlen = b64_pton(b64, p, plen)) < 0) {
125 explicit_bzero(p, plen);
127 return SSH_ERR_INVALID_FORMAT;
129 if ((r = sshbuf_put(buf, p, nlen)) < 0) {
130 explicit_bzero(p, plen);
134 explicit_bzero(p, plen);
140 sshbuf_dup_string(struct sshbuf *buf)
142 const u_char *p = NULL, *s = sshbuf_ptr(buf);
143 size_t l = sshbuf_len(buf);
146 if (s == NULL || l > SIZE_MAX)
148 /* accept a nul only as the last character in the buffer */
149 if (l > 0 && (p = memchr(s, '\0', l)) != NULL) {
152 l--; /* the nul is put back below */
154 if ((r = malloc(l + 1)) == NULL)