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