xref: /netbsd-src/crypto/external/bsd/openssh/dist/sshbuf.h (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*	$NetBSD: sshbuf.h,v 1.15 2020/12/04 18:42:50 christos Exp $	*/
2 /*	$OpenBSD: sshbuf.h,v 1.23 2020/06/22 05:54:10 djm Exp $	*/
3 
4 /*
5  * Copyright (c) 2011 Damien Miller
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #ifndef _SSHBUF_H
21 #define _SSHBUF_H
22 
23 #include <sys/types.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 
27 #ifdef WITH_OPENSSL
28 #include <openssl/bn.h>
29 #include <openssl/ec.h>
30 #include <openssl/ecdsa.h>
31 #else /* OPENSSL */
32 #define BIGNUM		void
33 #define EC_KEY		void
34 #define EC_GROUP	void
35 #define EC_POINT	void
36 #endif /* WITH_OPENSSL */
37 
38 /* move the following to a more appropriate place and name */
39 #define BUFFER_MAX_LEN_HPN	0x4000000	/* 64MB */
40 
41 #define SSHBUF_SIZE_MAX		0x8000000	/* Hard maximum size */
42 #define SSHBUF_REFS_MAX		0x100000	/* Max child buffers */
43 #define SSHBUF_MAX_BIGNUM	(16384 / 8)	/* Max bignum *bytes* */
44 #define SSHBUF_MAX_ECPOINT	((528 * 2 / 8) + 1) /* Max EC point *bytes* */
45 
46 /*
47  * NB. do not depend on the internals of this. It will be made opaque
48  * one day.
49  */
50 struct sshbuf {
51 	u_char *d;		/* Data */
52 	const u_char *cd;	/* Const data */
53 	size_t off;		/* First available byte is buf->d + buf->off */
54 	size_t size;		/* Last byte is buf->d + buf->size - 1 */
55 	size_t max_size;	/* Maximum size of buffer */
56 	size_t alloc;		/* Total bytes allocated to buf->d */
57 	int readonly;		/* Refers to external, const data */
58 	int dont_free;		/* Kludge to support sshbuf_init */
59 	u_int refcount;		/* Tracks self and number of child buffers */
60 	struct sshbuf *parent;	/* If child, pointer to parent */
61 };
62 
63 /*
64  * Create a new sshbuf buffer.
65  * Returns pointer to buffer on success, or NULL on allocation failure.
66  */
67 struct sshbuf *sshbuf_new(void);
68 
69 /*
70  * Create a new, read-only sshbuf buffer from existing data.
71  * Returns pointer to buffer on success, or NULL on allocation failure.
72  */
73 struct sshbuf *sshbuf_from(const void *blob, size_t len);
74 
75 /*
76  * Create a new, read-only sshbuf buffer from the contents of an existing
77  * buffer. The contents of "buf" must not change in the lifetime of the
78  * resultant buffer.
79  * Returns pointer to buffer on success, or NULL on allocation failure.
80  */
81 struct sshbuf *sshbuf_fromb(struct sshbuf *buf);
82 
83 /*
84  * Create a new, read-only sshbuf buffer from the contents of a string in
85  * an existing buffer (the string is consumed in the process).
86  * The contents of "buf" must not change in the lifetime of the resultant
87  * buffer.
88  * Returns pointer to buffer on success, or NULL on allocation failure.
89  */
90 int	sshbuf_froms(struct sshbuf *buf, struct sshbuf **bufp);
91 
92 /*
93  * Clear and free buf
94  */
95 void	sshbuf_free(struct sshbuf *buf);
96 
97 /*
98  * Reset buf, clearing its contents. NB. max_size is preserved.
99  */
100 void	sshbuf_reset(struct sshbuf *buf);
101 
102 /*
103  * Return the maximum size of buf
104  */
105 size_t	sshbuf_max_size(const struct sshbuf *buf);
106 
107 /*
108  * Set the maximum size of buf
109  * Returns 0 on success, or a negative SSH_ERR_* error code on failure.
110  */
111 int	sshbuf_set_max_size(struct sshbuf *buf, size_t max_size);
112 
113 /*
114  * Returns the length of data in buf
115  */
116 size_t	sshbuf_len(const struct sshbuf *buf);
117 
118 /*
119  * Returns number of bytes left in buffer before hitting max_size.
120  */
121 size_t	sshbuf_avail(const struct sshbuf *buf);
122 
123 /*
124  * Returns a read-only pointer to the start of the data in buf
125  */
126 const u_char *sshbuf_ptr(const struct sshbuf *buf);
127 
128 /*
129  * Returns a mutable pointer to the start of the data in buf, or
130  * NULL if the buffer is read-only.
131  */
132 u_char *sshbuf_mutable_ptr(const struct sshbuf *buf);
133 
134 /*
135  * Check whether a reservation of size len will succeed in buf
136  * Safer to use than direct comparisons again sshbuf_avail as it copes
137  * with unsigned overflows correctly.
138  * Returns 0 on success, or a negative SSH_ERR_* error code on failure.
139  */
140 int	sshbuf_check_reserve(const struct sshbuf *buf, size_t len);
141 
142 /*
143  * Preallocates len additional bytes in buf.
144  * Useful for cases where the caller knows how many bytes will ultimately be
145  * required to avoid realloc in the buffer code.
146  * Returns 0 on success, or a negative SSH_ERR_* error code on failure.
147  */
148 int	sshbuf_allocate(struct sshbuf *buf, size_t len);
149 
150 /*
151  * Reserve len bytes in buf.
152  * Returns 0 on success and a pointer to the first reserved byte via the
153  * optional dpp parameter or a negative SSH_ERR_* error code on failure.
154  */
155 int	sshbuf_reserve(struct sshbuf *buf, size_t len, u_char **dpp);
156 
157 /*
158  * Consume len bytes from the start of buf
159  * Returns 0 on success, or a negative SSH_ERR_* error code on failure.
160  */
161 int	sshbuf_consume(struct sshbuf *buf, size_t len);
162 
163 /*
164  * Consume len bytes from the end of buf
165  * Returns 0 on success, or a negative SSH_ERR_* error code on failure.
166  */
167 int	sshbuf_consume_end(struct sshbuf *buf, size_t len);
168 
169 /* Extract or deposit some bytes */
170 int	sshbuf_get(struct sshbuf *buf, void *v, size_t len);
171 int	sshbuf_put(struct sshbuf *buf, const void *v, size_t len);
172 int	sshbuf_putb(struct sshbuf *buf, const struct sshbuf *v);
173 
174 /* Append using a printf(3) format */
175 int	sshbuf_putf(struct sshbuf *buf, const char *fmt, ...)
176 	    __attribute__((format(printf, 2, 3)));
177 int	sshbuf_putfv(struct sshbuf *buf, const char *fmt, va_list ap)
178 	    __printflike(2, 0);
179 
180 /* Functions to extract or store big-endian words of various sizes */
181 int	sshbuf_get_u64(struct sshbuf *buf, u_int64_t *valp);
182 int	sshbuf_get_u32(struct sshbuf *buf, u_int32_t *valp);
183 int	sshbuf_get_u16(struct sshbuf *buf, u_int16_t *valp);
184 int	sshbuf_get_u8(struct sshbuf *buf, u_char *valp);
185 int	sshbuf_put_u64(struct sshbuf *buf, u_int64_t val);
186 int	sshbuf_put_u32(struct sshbuf *buf, u_int32_t val);
187 int	sshbuf_put_u16(struct sshbuf *buf, u_int16_t val);
188 int	sshbuf_put_u8(struct sshbuf *buf, u_char val);
189 
190 /* Functions to peek at the contents of a buffer without modifying it. */
191 int	sshbuf_peek_u64(const struct sshbuf *buf, size_t offset,
192     u_int64_t *valp);
193 int	sshbuf_peek_u32(const struct sshbuf *buf, size_t offset,
194     u_int32_t *valp);
195 int	sshbuf_peek_u16(const struct sshbuf *buf, size_t offset,
196     u_int16_t *valp);
197 int	sshbuf_peek_u8(const struct sshbuf *buf, size_t offset,
198     u_char *valp);
199 
200 /*
201  * Functions to poke values into an existing buffer (e.g. a length header
202  * to a packet). The destination bytes must already exist in the buffer.
203  */
204 int sshbuf_poke_u64(struct sshbuf *buf, size_t offset, u_int64_t val);
205 int sshbuf_poke_u32(struct sshbuf *buf, size_t offset, u_int32_t val);
206 int sshbuf_poke_u16(struct sshbuf *buf, size_t offset, u_int16_t val);
207 int sshbuf_poke_u8(struct sshbuf *buf, size_t offset, u_char val);
208 int sshbuf_poke(struct sshbuf *buf, size_t offset, void *v, size_t len);
209 
210 /*
211  * Functions to extract or store SSH wire encoded strings (u32 len || data)
212  * The "cstring" variants admit no \0 characters in the string contents.
213  * Caller must free *valp.
214  */
215 int	sshbuf_get_string(struct sshbuf *buf, u_char **valp, size_t *lenp);
216 int	sshbuf_get_cstring(struct sshbuf *buf, char **valp, size_t *lenp);
217 int	sshbuf_get_stringb(struct sshbuf *buf, struct sshbuf *v);
218 int	sshbuf_put_string(struct sshbuf *buf, const void *v, size_t len);
219 int	sshbuf_put_cstring(struct sshbuf *buf, const char *v);
220 int	sshbuf_put_stringb(struct sshbuf *buf, const struct sshbuf *v);
221 
222 /*
223  * "Direct" variant of sshbuf_get_string, returns pointer into the sshbuf to
224  * avoid an malloc+memcpy. The pointer is guaranteed to be valid until the
225  * next sshbuf-modifying function call. Caller does not free.
226  */
227 int	sshbuf_get_string_direct(struct sshbuf *buf, const u_char **valp,
228 	    size_t *lenp);
229 
230 /* Skip past a string */
231 #define sshbuf_skip_string(buf) sshbuf_get_string_direct(buf, NULL, NULL)
232 
233 /* Another variant: "peeks" into the buffer without modifying it */
234 int	sshbuf_peek_string_direct(const struct sshbuf *buf, const u_char **valp,
235 	    size_t *lenp);
236 
237 /*
238  * Functions to extract or store SSH wire encoded bignums and elliptic
239  * curve points.
240  */
241 int	sshbuf_get_bignum2(struct sshbuf *buf, BIGNUM **valp);
242 int	sshbuf_get_bignum2_bytes_direct(struct sshbuf *buf,
243 	    const u_char **valp, size_t *lenp);
244 int	sshbuf_put_bignum2(struct sshbuf *buf, const BIGNUM *v);
245 int	sshbuf_put_bignum2_bytes(struct sshbuf *buf, const void *v, size_t len);
246 int	sshbuf_get_ec(struct sshbuf *buf, EC_POINT *v, const EC_GROUP *g);
247 int	sshbuf_get_eckey(struct sshbuf *buf, EC_KEY *v);
248 int	sshbuf_put_ec(struct sshbuf *buf, const EC_POINT *v, const EC_GROUP *g);
249 int	sshbuf_put_eckey(struct sshbuf *buf, const EC_KEY *v);
250 
251 /* Dump the contents of the buffer in a human-readable format */
252 void	sshbuf_dump(const struct sshbuf *buf, FILE *f);
253 
254 /* Dump specified memory in a human-readable format */
255 void	sshbuf_dump_data(const void *s, size_t len, FILE *f);
256 
257 /* Return the hexadecimal representation of the contents of the buffer */
258 char	*sshbuf_dtob16(struct sshbuf *buf);
259 
260 /* Encode the contents of the buffer as base64 */
261 char	*sshbuf_dtob64_string(const struct sshbuf *buf, int wrap);
262 int	sshbuf_dtob64(const struct sshbuf *d, struct sshbuf *b64, int wrap);
263 /* RFC4648 "base64url" encoding variant */
264 int	sshbuf_dtourlb64(const struct sshbuf *d, struct sshbuf *b64, int wrap);
265 
266 /* Decode base64 data and append it to the buffer */
267 int	sshbuf_b64tod(struct sshbuf *buf, const char *b64);
268 
269 /*
270  * Tests whether the buffer contains the specified byte sequence at the
271  * specified offset. Returns 0 on successful match, or a ssherr.h code
272  * otherwise. SSH_ERR_INVALID_FORMAT indicates sufficient bytes were
273  * present but the buffer contents did not match those supplied. Zero-
274  * length comparisons are not allowed.
275  *
276  * If sufficient data is present to make a comparison, then it is
277  * performed with timing independent of the value of the data. If
278  * insufficient data is present then the comparison is not attempted at
279  * all.
280  */
281 int	sshbuf_cmp(const struct sshbuf *b, size_t offset,
282     const void *s, size_t len);
283 
284 /*
285  * Searches the buffer for the specified string. Returns 0 on success
286  * and updates *offsetp with the offset of the first match, relative to
287  * the start of the buffer. Otherwise sshbuf_find will return a ssherr.h
288  * error code. SSH_ERR_INVALID_FORMAT indicates sufficient bytes were
289  * present in the buffer for a match to be possible but none was found.
290  * Searches for zero-length data are not allowed.
291  */
292 int
293 sshbuf_find(const struct sshbuf *b, size_t start_offset,
294     const void *s, size_t len, size_t *offsetp);
295 
296 /*
297  * Duplicate the contents of a buffer to a string (caller to free).
298  * Returns NULL on buffer error, or if the buffer contains a premature
299  * nul character.
300  */
301 char *sshbuf_dup_string(struct sshbuf *buf);
302 
303 /*
304  * Fill a buffer from a file descriptor or filename. Both allocate the
305  * buffer for the caller.
306  */
307 int sshbuf_load_fd(int, struct sshbuf **)
308     __attribute__((__nonnull__ (2)));
309 int sshbuf_load_file(const char *, struct sshbuf **)
310     __attribute__((__nonnull__ (2)));
311 
312 /*
313  * Write a buffer to a path, creating/truncating as needed (mode 0644,
314  * subject to umask). The buffer contents are not modified.
315  */
316 int sshbuf_write_file(const char *path, struct sshbuf *buf)
317     __attribute__((__nonnull__ (2)));
318 
319 /* Macros for decoding/encoding integers */
320 #define PEEK_U64(p) \
321 	(((u_int64_t)(((const u_char *)(p))[0]) << 56) | \
322 	 ((u_int64_t)(((const u_char *)(p))[1]) << 48) | \
323 	 ((u_int64_t)(((const u_char *)(p))[2]) << 40) | \
324 	 ((u_int64_t)(((const u_char *)(p))[3]) << 32) | \
325 	 ((u_int64_t)(((const u_char *)(p))[4]) << 24) | \
326 	 ((u_int64_t)(((const u_char *)(p))[5]) << 16) | \
327 	 ((u_int64_t)(((const u_char *)(p))[6]) << 8) | \
328 	  (u_int64_t)(((const u_char *)(p))[7]))
329 #define PEEK_U32(p) \
330 	(((u_int32_t)(((const u_char *)(p))[0]) << 24) | \
331 	 ((u_int32_t)(((const u_char *)(p))[1]) << 16) | \
332 	 ((u_int32_t)(((const u_char *)(p))[2]) << 8) | \
333 	  (u_int32_t)(((const u_char *)(p))[3]))
334 #define PEEK_U16(p) \
335 	(((u_int16_t)(((const u_char *)(p))[0]) << 8) | \
336 	  (u_int16_t)(((const u_char *)(p))[1]))
337 
338 #define POKE_U64(p, v) \
339 	do { \
340 		const u_int64_t __v = (v); \
341 		((u_char *)(p))[0] = (__v >> 56) & 0xff; \
342 		((u_char *)(p))[1] = (__v >> 48) & 0xff; \
343 		((u_char *)(p))[2] = (__v >> 40) & 0xff; \
344 		((u_char *)(p))[3] = (__v >> 32) & 0xff; \
345 		((u_char *)(p))[4] = (__v >> 24) & 0xff; \
346 		((u_char *)(p))[5] = (__v >> 16) & 0xff; \
347 		((u_char *)(p))[6] = (__v >> 8) & 0xff; \
348 		((u_char *)(p))[7] = __v & 0xff; \
349 	} while (0)
350 #define POKE_U32(p, v) \
351 	do { \
352 		const u_int32_t __v = (v); \
353 		((u_char *)(p))[0] = (__v >> 24) & 0xff; \
354 		((u_char *)(p))[1] = (__v >> 16) & 0xff; \
355 		((u_char *)(p))[2] = (__v >> 8) & 0xff; \
356 		((u_char *)(p))[3] = __v & 0xff; \
357 	} while (0)
358 #define POKE_U16(p, v) \
359 	do { \
360 		const u_int16_t __v = (v); \
361 		((u_char *)(p))[0] = (__v >> 8) & 0xff; \
362 		((u_char *)(p))[1] = __v & 0xff; \
363 	} while (0)
364 
365 /* Internal definitions follow. Exposed for regress tests */
366 #ifdef SSHBUF_INTERNAL
367 
368 /*
369  * Return the allocation size of buf
370  */
371 size_t	sshbuf_alloc(const struct sshbuf *buf);
372 
373 /*
374  * Increment the reference count of buf.
375  */
376 int	sshbuf_set_parent(struct sshbuf *child, struct sshbuf *parent);
377 
378 /*
379  * Return the parent buffer of buf, or NULL if it has no parent.
380  */
381 const struct sshbuf *sshbuf_parent(const struct sshbuf *buf);
382 
383 /*
384  * Return the reference count of buf
385  */
386 u_int	sshbuf_refcount(const struct sshbuf *buf);
387 
388 # define SSHBUF_SIZE_INIT	256		/* Initial allocation */
389 # define SSHBUF_SIZE_INC	256		/* Preferred increment length */
390 # define SSHBUF_PACK_MIN	8192		/* Minimim packable offset */
391 
392 /* # define SSHBUF_ABORT abort */
393 /* # define SSHBUF_DEBUG */
394 
395 # ifndef SSHBUF_ABORT
396 #  define SSHBUF_ABORT()
397 # endif
398 
399 # ifdef SSHBUF_DEBUG
400 #  define SSHBUF_TELL(what) do { \
401 		printf("%s:%d %s: %s size %zu alloc %zu off %zu max %zu\n", \
402 		    __FILE__, __LINE__, __func__, what, \
403 		    buf->size, buf->alloc, buf->off, buf->max_size); \
404 		fflush(stdout); \
405 	} while (0)
406 #  define SSHBUF_DBG(x) do { \
407 		printf("%s:%d %s: ", __FILE__, __LINE__, __func__); \
408 		printf x; \
409 		printf("\n"); \
410 		fflush(stdout); \
411 	} while (0)
412 # else
413 #  define SSHBUF_TELL(what)
414 #  define SSHBUF_DBG(x)
415 # endif
416 #endif /* SSHBUF_INTERNAL */
417 
418 #endif /* _SSHBUF_H */
419