xref: /freebsd/contrib/bearssl/tools/brssl.h (revision 95ee2897e98f5d444f26ed2334cc7c439f9c16c6)
1 /*
2  * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 
25 #ifndef BRSSL_H__
26 #define BRSSL_H__
27 
28 #ifndef _STANDALONE
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdint.h>
33 
34 #elif !defined(STAND_H)
35 #include <stand.h>
36 #endif
37 
38 #include "bearssl.h"
39 
40 /*
41  * malloc() wrapper:
42  * -- If len is 0, then NULL is returned.
43  * -- If len is non-zero, and allocation fails, then an error message is
44  *    printed and the process exits with an error code.
45  */
46 void *xmalloc(size_t len);
47 
48 /*
49  * free() wrapper, meant to release blocks allocated with xmalloc().
50  */
51 void xfree(void *buf);
52 
53 /*
54  * Duplicate a character string into a newly allocated block.
55  */
56 char *xstrdup(const void *src);
57 
58 /*
59  * Allocate a new block with the provided length, filled with a copy
60  * of exactly that many bytes starting at address 'src'.
61  */
62 void *xblobdup(const void *src, size_t len);
63 
64 /*
65  * Duplicate a public key, into newly allocated blocks. The returned
66  * key must be later on released with xfreepkey().
67  */
68 br_x509_pkey *xpkeydup(const br_x509_pkey *pk);
69 
70 /*
71  * Release a public key that was allocated with xpkeydup(). If pk is NULL,
72  * this function does nothing.
73  */
74 void xfreepkey(br_x509_pkey *pk);
75 
76 /*
77  * Macros for growable arrays.
78  */
79 
80 /*
81  * Make a structure type for a vector of 'type'.
82  */
83 #define VECTOR(type)   struct { \
84 		type *buf; \
85 		size_t ptr, len; \
86 	}
87 
88 /*
89  * Constant initialiser for a vector.
90  */
91 #define VEC_INIT   { 0, 0, 0 }
92 
93 /*
94  * Clear a vector.
95  */
96 #define VEC_CLEAR(vec)   do { \
97 		xfree((vec).buf); \
98 		(vec).buf = NULL; \
99 		(vec).ptr = 0; \
100 		(vec).len = 0; \
101 	} while (0)
102 
103 /*
104  * Clear a vector, first calling the provided function on each vector
105  * element.
106  */
107 #define VEC_CLEAREXT(vec, fun)   do { \
108 		size_t vec_tmp; \
109 		for (vec_tmp = 0; vec_tmp < (vec).ptr; vec_tmp ++) { \
110 			(fun)(&(vec).buf[vec_tmp]); \
111 		} \
112 		VEC_CLEAR(vec); \
113 	} while (0)
114 
115 /*
116  * Add a value at the end of a vector.
117  */
118 #define VEC_ADD(vec, x)   do { \
119 		(vec).buf = vector_expand((vec).buf, sizeof *((vec).buf), \
120 			&(vec).ptr, &(vec).len, 1); \
121 		(vec).buf[(vec).ptr ++] = (x); \
122 	} while (0)
123 
124 /*
125  * Add several values at the end of a vector.
126  */
127 #define VEC_ADDMANY(vec, xp, num)   do { \
128 		size_t vec_num = (num); \
129 		(vec).buf = vector_expand((vec).buf, sizeof *((vec).buf), \
130 			&(vec).ptr, &(vec).len, vec_num); \
131 		memcpy((vec).buf + (vec).ptr, \
132 			(xp), vec_num * sizeof *((vec).buf)); \
133 		(vec).ptr += vec_num; \
134 	} while (0)
135 
136 /*
137  * Access a vector element by index. This is a lvalue, and can be modified.
138  */
139 #define VEC_ELT(vec, idx)   ((vec).buf[idx])
140 
141 /*
142  * Get current vector length.
143  */
144 #define VEC_LEN(vec)   ((vec).ptr)
145 
146 /*
147  * Copy all vector elements into a newly allocated block.
148  */
149 #define VEC_TOARRAY(vec)    xblobdup((vec).buf, sizeof *((vec).buf) * (vec).ptr)
150 
151 /*
152  * Internal function used to handle memory allocations for vectors.
153  */
154 void *vector_expand(void *buf,
155 	size_t esize, size_t *ptr, size_t *len, size_t extra);
156 
157 /*
158  * Type for a vector of bytes.
159  */
160 typedef VECTOR(unsigned char) bvector;
161 
162 /*
163  * Compare two strings for equality; returned value is 1 if the strings
164  * are to be considered equal, 0 otherwise. Comparison is case-insensitive
165  * (ASCII letters only) and skips some characters (all whitespace, defined
166  * as ASCII codes 0 to 32 inclusive, and also '-', '_', '.', '/', '+' and
167  * ':').
168  */
169 int eqstr(const char *s1, const char *s2);
170 
171 /*
172  * Convert a string to a positive integer (size_t). Returned value is
173  * (size_t)-1 on error. On error, an explicit error message is printed.
174  */
175 size_t parse_size(const char *s);
176 
177 /*
178  * Structure for a known protocol version.
179  */
180 typedef struct {
181 	const char *name;
182 	unsigned version;
183 	const char *comment;
184 } protocol_version;
185 
186 /*
187  * Known protocol versions. Last element has a NULL name.
188  */
189 extern const protocol_version protocol_versions[];
190 
191 /*
192  * Parse a version name. If the name is not recognized, then an error
193  * message is printed, and 0 is returned.
194  */
195 unsigned parse_version(const char *name, size_t len);
196 
197 /*
198  * Type for a known hash function.
199  */
200 typedef struct {
201 	const char *name;
202 	const br_hash_class *hclass;
203 	const char *comment;
204 } hash_function;
205 
206 /*
207  * Known hash functions. Last element has a NULL name.
208  */
209 extern const hash_function hash_functions[];
210 
211 /*
212  * Parse hash function names. This function expects a comma-separated
213  * list of names, and returns a bit mask corresponding to the matched
214  * names. If one of the name does not match, or the list is empty, then
215  * an error message is printed, and 0 is returned.
216  */
217 unsigned parse_hash_functions(const char *arg);
218 
219 /*
220  * Get a curve name (by ID). If the curve ID is not known, this returns
221  * NULL.
222  */
223 const char *get_curve_name(int id);
224 
225 /*
226  * Get a curve name (by ID). The name is written in the provided buffer
227  * (zero-terminated). If the curve ID is not known, the name is
228  * "unknown (***)" where "***" is the decimal value of the identifier.
229  * If the name does not fit in the provided buffer, then dst[0] is set
230  * to 0 (unless len is 0, in which case nothing is written), and -1 is
231  * returned. Otherwise, the name is written in dst[] (with a terminating
232  * 0), and this function returns 0.
233  */
234 int get_curve_name_ext(int id, char *dst, size_t len);
235 
236 /*
237  * Type for a known cipher suite.
238  */
239 typedef struct {
240 	const char *name;
241 	uint16_t suite;
242 	unsigned req;
243 	const char *comment;
244 } cipher_suite;
245 
246 /*
247  * Known cipher suites. Last element has a NULL name.
248  */
249 extern const cipher_suite cipher_suites[];
250 
251 /*
252  * Flags for cipher suite requirements.
253  */
254 #define REQ_TLS12          0x0001   /* suite needs TLS 1.2 */
255 #define REQ_SHA1           0x0002   /* suite needs SHA-1 */
256 #define REQ_SHA256         0x0004   /* suite needs SHA-256 */
257 #define REQ_SHA384         0x0008   /* suite needs SHA-384 */
258 #define REQ_AESCBC         0x0010   /* suite needs AES/CBC encryption */
259 #define REQ_AESGCM         0x0020   /* suite needs AES/GCM encryption */
260 #define REQ_AESCCM         0x0040   /* suite needs AES/CCM encryption */
261 #define REQ_CHAPOL         0x0080   /* suite needs ChaCha20+Poly1305 */
262 #define REQ_3DESCBC        0x0100   /* suite needs 3DES/CBC encryption */
263 #define REQ_RSAKEYX        0x0200   /* suite uses RSA key exchange */
264 #define REQ_ECDHE_RSA      0x0400   /* suite uses ECDHE_RSA key exchange */
265 #define REQ_ECDHE_ECDSA    0x0800   /* suite uses ECDHE_ECDSA key exchange */
266 #define REQ_ECDH           0x1000   /* suite uses static ECDH key exchange */
267 
268 /*
269  * Parse a list of cipher suite names. The names are comma-separated. If
270  * one of the name is not recognised, or the list is empty, then an
271  * appropriate error message is printed, and NULL is returned.
272  * The returned array is allocated with xmalloc() and must be released
273  * by the caller. That array is terminated with a dummy entry whose 'name'
274  * field is NULL. The number of entries (not counting the dummy entry)
275  * is also written into '*num'.
276  */
277 cipher_suite *parse_suites(const char *arg, size_t *num);
278 
279 /*
280  * Get the name of a cipher suite. Returned value is NULL if the suite is
281  * not recognized.
282  */
283 const char *get_suite_name(unsigned suite);
284 
285 /*
286  * Get the name of a cipher suite. The name is written in the provided
287  * buffer; if the suite is not recognised, then the name is
288  * "unknown (0x****)" where "****" is the hexadecimal value of the suite.
289  * If the name does not fit in the provided buffer, then dst[0] is set
290  * to 0 (unless len is 0, in which case nothing is written), and -1 is
291  * returned. Otherwise, the name is written in dst[] (with a terminating
292  * 0), and this function returns 0.
293  */
294 int get_suite_name_ext(unsigned suite, char *dst, size_t len);
295 
296 /*
297  * Tell whether a cipher suite uses ECDHE key exchange.
298  */
299 int uses_ecdhe(unsigned suite);
300 
301 /*
302  * Print out all known names (for protocol versions, cipher suites...).
303  */
304 void list_names(void);
305 
306 /*
307  * Print out all known elliptic curve names.
308  */
309 void list_curves(void);
310 
311 /*
312  * Get the symbolic name for an elliptic curve (by ID).
313  */
314 const char *ec_curve_name(int curve);
315 
316 /*
317  * Get a curve by symbolic name. If the name is not recognized, -1 is
318  * returned.
319  */
320 int get_curve_by_name(const char *str);
321 
322 /*
323  * Get the symbolic name for a hash function name (by ID).
324  */
325 const char *hash_function_name(int id);
326 
327 /*
328  * Read a file completely. The returned block is allocated with xmalloc()
329  * and must be released by the caller.
330  * If the file cannot be found or read completely, or is empty, then an
331  * appropriate error message is written, and NULL is returned.
332  */
333 unsigned char *read_file(const char *fname, size_t *len);
334 
335 /*
336  * Write a file completely. This returns 0 on success, -1 on error. On
337  * error, an appropriate error message is printed.
338  */
339 int write_file(const char *fname, const void *data, size_t len);
340 
341 /*
342  * This function returns non-zero if the provided buffer "looks like"
343  * a DER-encoded ASN.1 object (criteria: it has the tag for a SEQUENCE
344  * with a definite length that matches the total object length).
345  */
346 int looks_like_DER(const unsigned char *buf, size_t len);
347 
348 /*
349  * Type for a named blob (the 'name' is a normalised PEM header name).
350  */
351 typedef struct {
352 	char *name;
353 	unsigned char *data;
354 	size_t data_len;
355 } pem_object;
356 
357 /*
358  * Release the contents of a named blob (buffer and name).
359  */
360 void free_pem_object_contents(pem_object *po);
361 
362 /*
363  * Decode a buffer as a PEM file, and return all objects. On error, NULL
364  * is returned and an error message is printed. Absence of any object
365  * is an error.
366  *
367  * The returned array is terminated by a dummy object whose 'name' is
368  * NULL. The number of objects (not counting the dummy terminator) is
369  * written in '*num'.
370  */
371 pem_object *decode_pem(const void *src, size_t len, size_t *num);
372 
373 /*
374  * Get the certificate(s) from a file. This accepts both a single
375  * DER-encoded certificate, and a text file that contains
376  * PEM-encoded certificates (and possibly other objects, which are
377  * then ignored).
378  *
379  * On decoding error, or if the file turns out to contain no certificate
380  * at all, then an error message is printed and NULL is returned.
381  *
382  * The returned array, and all referenced buffers, are allocated with
383  * xmalloc() and must be released by the caller. The returned array
384  * ends with a dummy entry whose 'data' field is NULL.
385  * The number of decoded certificates (not counting the dummy entry)
386  * is written into '*num'.
387  */
388 br_x509_certificate *read_certificates(const char *fname, size_t *num);
389 
390 /*
391  * Release certificates. This releases all certificate data arrays,
392  * and the whole array as well.
393  */
394 void free_certificates(br_x509_certificate *certs, size_t num);
395 
396 /*
397  * Interpret a certificate as a trust anchor. The trust anchor is
398  * newly allocated with xmalloc() and the caller must release it.
399  * On decoding error, an error message is printed, and this function
400  * returns NULL.
401  */
402 br_x509_trust_anchor *certificate_to_trust_anchor(br_x509_certificate *xc);
403 
404 /*
405  * Type for a vector of trust anchors.
406  */
407 typedef VECTOR(br_x509_trust_anchor) anchor_list;
408 
409 /*
410  * Release contents for a trust anchor (assuming they were dynamically
411  * allocated with xmalloc()). The structure itself is NOT released.
412  */
413 void free_ta_contents(br_x509_trust_anchor *ta);
414 
415 /*
416  * Decode certificates from a file and interpret them as trust anchors.
417  * The trust anchors are added to the provided list. The number of found
418  * anchors is returned; on error, 0 is returned (finding no anchor at
419  * all is considered an error). An appropriate error message is displayed.
420  */
421 size_t read_trust_anchors(anchor_list *dst, const char *fname);
422 
423 /*
424  * Get the "signer key type" for the certificate (key type of the
425  * issuing CA). On error, this prints a message on stderr, and returns 0.
426  */
427 int get_cert_signer_algo(br_x509_certificate *xc);
428 
429 /*
430  * Special "no anchor" X.509 validator that wraps around another X.509
431  * validator and turns "not trusted" error codes into success. This is
432  * by definition insecure, but convenient for debug purposes.
433  */
434 typedef struct {
435 	const br_x509_class *vtable;
436 	const br_x509_class **inner;
437 } x509_noanchor_context;
438 extern const br_x509_class x509_noanchor_vtable;
439 
440 /*
441  * Initialise a "no anchor" X.509 validator.
442  */
443 void x509_noanchor_init(x509_noanchor_context *xwc,
444 	const br_x509_class **inner);
445 
446 /*
447  * Aggregate type for a private key.
448  */
449 typedef struct {
450 	int key_type;  /* BR_KEYTYPE_RSA or BR_KEYTYPE_EC */
451 	union {
452 		br_rsa_private_key rsa;
453 		br_ec_private_key ec;
454 	} key;
455 } private_key;
456 
457 /*
458  * Decode a private key from a file. On error, this prints an error
459  * message and returns NULL.
460  */
461 private_key *read_private_key(const char *fname);
462 
463 /*
464  * Free a private key.
465  */
466 void free_private_key(private_key *sk);
467 
468 /*
469  * Get the encoded OID for a given hash function (to use with PKCS#1
470  * signatures). If the hash function ID is 0 (for MD5+SHA-1), or if
471  * the ID is not one of the SHA-* functions (SHA-1, SHA-224, SHA-256,
472  * SHA-384, SHA-512), then this function returns NULL.
473  */
474 const unsigned char *get_hash_oid(int id);
475 
476 /*
477  * Get a hash implementation by ID. This returns NULL if the hash
478  * implementation is not available.
479  */
480 const br_hash_class *get_hash_impl(int id);
481 
482 /*
483  * Find the symbolic name and the description for an error. If 'err' is
484  * recognised then the error symbolic name is returned; if 'comment' is
485  * not NULL then '*comment' is then set to a descriptive human-readable
486  * message. If the error code 'err' is not recognised, then '*comment' is
487  * untouched and this function returns NULL.
488  */
489 const char *find_error_name(int err, const char **comment);
490 
491 /*
492  * Find the symbolic name for an algorithm implementation. Provided
493  * pointer should be a pointer to a vtable or to a function, where
494  * appropriate. If not recognised, then the string "UNKNOWN" is returned.
495  *
496  * If 'long_name' is non-zero, then the returned name recalls the
497  * algorithm type as well; otherwise, only the core implementation name
498  * is returned (e.g. the long name could be 'aes_big_cbcenc' while the
499  * short name is 'big').
500  */
501 const char *get_algo_name(const void *algo, int long_name);
502 
503 /*
504  * Run a SSL engine, with a socket connected to the peer, and using
505  * stdin/stdout to exchange application data. The socket must be a
506  * non-blocking descriptor.
507  *
508  * To help with Win32 compatibility, the socket descriptor is provided
509  * as an "unsigned long" value.
510  *
511  * Returned value:
512  *    0        SSL connection closed successfully
513  *    x > 0    SSL error "x"
514  *   -1        early socket close
515  *   -2        stdout was closed, or something failed badly
516  */
517 int run_ssl_engine(br_ssl_engine_context *eng,
518 	unsigned long fd, unsigned flags);
519 
520 #define RUN_ENGINE_VERBOSE     0x0001  /* enable verbose messages */
521 #define RUN_ENGINE_TRACE       0x0002  /* hex dump of records */
522 
523 /*
524  * Do the "client" command. Returned value is 0 on success, -1 on failure.
525  * Command-line arguments start _after_ the command name.
526  */
527 int do_client(int argc, char *argv[]);
528 
529 /*
530  * Do the "server" command. Returned value is 0 on success, -1 on failure.
531  * Command-line arguments start _after_ the command name.
532  */
533 int do_server(int argc, char *argv[]);
534 
535 /*
536  * Do the "verify" command. Returned value is 0 on success, -1 on failure.
537  * Command-line arguments start _after_ the command name.
538  */
539 int do_verify(int argc, char *argv[]);
540 
541 /*
542  * Do the "skey" command. Returned value is 0 on success, -1 on failure.
543  * Command-line arguments start _after_ the command name.
544  */
545 int do_skey(int argc, char *argv[]);
546 
547 /*
548  * Do the "ta" command. Returned value is 0 on success, -1 on failure.
549  * Command-line arguments start _after_ the command name.
550  */
551 int do_ta(int argc, char *argv[]);
552 
553 /*
554  * Do the "chain" command. Returned value is 0 on success, -1 on failure.
555  * Command-line arguments start _after_ the command name.
556  */
557 int do_chain(int argc, char *argv[]);
558 
559 /*
560  * Do the "twrch" command. Returned value is 0 on success, -1 on failure
561  * (processing or arguments), or a non-zero exit code. Command-line
562  * arguments start _after_ the command name.
563  */
564 int do_twrch(int argc, char *argv[]);
565 
566 /*
567  * Do the "impl" command. Returned value is 0 on success, -1 on failure.
568  * Command-line arguments start _after_ the command name.
569  */
570 int do_impl(int argc, char *argv[]);
571 
572 #endif
573