1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  */
24 
25 enum lws_tls_cert_info {
26 	LWS_TLS_CERT_INFO_VALIDITY_FROM,
27 	/**< fills .time with the time_t the cert validity started from */
28 	LWS_TLS_CERT_INFO_VALIDITY_TO,
29 	/**< fills .time with the time_t the cert validity ends at */
30 	LWS_TLS_CERT_INFO_COMMON_NAME,
31 	/**< fills up to len bytes of .ns.name with the cert common name */
32 	LWS_TLS_CERT_INFO_ISSUER_NAME,
33 	/**< fills up to len bytes of .ns.name with the cert issuer name */
34 	LWS_TLS_CERT_INFO_USAGE,
35 	/**< fills verified with a bitfield asserting the valid uses */
36 	LWS_TLS_CERT_INFO_VERIFIED,
37 	/**< fills .verified with a bool representing peer cert validity,
38 	 *   call returns -1 if no cert */
39 	LWS_TLS_CERT_INFO_OPAQUE_PUBLIC_KEY,
40 	/**< the certificate's public key, as an opaque bytestream.  These
41 	 * opaque bytestreams can only be compared with each other using the
42 	 * same tls backend, ie, OpenSSL or mbedTLS.  The different backends
43 	 * produce different, incompatible representations for the same cert.
44 	 */
45 };
46 
47 union lws_tls_cert_info_results {
48 	unsigned int verified;
49 	time_t time;
50 	unsigned int usage;
51 	struct {
52 		int len;
53 		/* KEEP LAST... notice the [64] is only there because
54 		 * name[] is not allowed in a union.  The actual length of
55 		 * name[] is arbitrary and is passed into the api using the
56 		 * len parameter.  Eg
57 		 *
58 		 * char big[1024];
59 		 * union lws_tls_cert_info_results *buf =
60 		 * 	(union lws_tls_cert_info_results *)big;
61 		 *
62 		 * lws_tls_peer_cert_info(wsi, type, buf, sizeof(big) -
63 		 *			  sizeof(*buf) + sizeof(buf->ns.name));
64 		 */
65 		char name[64];
66 	} ns;
67 };
68 
69 struct lws_x509_cert;
70 struct lws_jwk;
71 
72 /**
73  * lws_x509_create() - Allocate an lws_x509_cert object
74  *
75  * \param x509: pointer to lws_x509_cert pointer to be set to allocated object
76  *
77  * Allocates an lws_x509_cert object and set *x509 to point to it.
78  */
79 LWS_VISIBLE LWS_EXTERN int
80 lws_x509_create(struct lws_x509_cert **x509);
81 
82 /**
83  * lws_x509_parse_from_pem() - Read one or more x509 certs in PEM format from memory
84  *
85  * \param x509: pointer to lws_x509_cert object
86  * \param pem: pointer to PEM format content
87  * \param len: length of PEM format content
88  *
89  * Parses PEM certificates in memory into a native x509 representation for the
90  * TLS library.  If there are multiple PEM certs concatenated, they are all
91  * read into the same object and exist as a "chain".
92  *
93  * IMPORTANT for compatibility with mbedtls, the last used byte of \p pem
94  * must be '\0' and the \p len must include it.
95  *
96  * Returns 0 if all went OK.
97  */
98 LWS_VISIBLE LWS_EXTERN int
99 lws_x509_parse_from_pem(struct lws_x509_cert *x509, const void *pem, size_t len);
100 
101 /**
102  * lws_x509_verify() - Validate signing relationship between one or more certs
103  *		       and a trusted CA cert
104  *
105  * \param x509: pointer to lws_x509_cert object, may contain multiple
106  * \param trusted: a single, trusted cert object that we are checking for
107  * \param common_name: NULL, or required CN (Common Name) of \p x509
108  *
109  * Returns 0 if the cert or certs in \p x509 represent a complete chain that is
110  * ultimately signed by the cert in \p trusted.  Returns nonzero if that's not
111  * the case.
112  */
113 LWS_VISIBLE LWS_EXTERN int
114 lws_x509_verify(struct lws_x509_cert *x509, struct lws_x509_cert *trusted,
115 		const char *common_name);
116 
117 /**
118  * lws_x509_public_to_jwk() - Copy the public key out of a cert and into a JWK
119  *
120  * \param jwk: pointer to the jwk to initialize and set to the public key
121  * \param x509: pointer to lws_x509_cert object that has the public key
122  * \param curves: NULL to disallow EC, else a comma-separated list of valid
123  *		  curves using the JWA naming, eg, "P-256,P-384,P-521".
124  * \param rsabits: minimum number of RSA bits required in the cert if RSA
125  *
126  * Returns 0 if JWK was set to the certificate public key correctly and the
127  * curve / the RSA key size was acceptable.  Automatically produces an RSA or
128  * EC JWK depending on what the cert had.
129  */
130 LWS_VISIBLE LWS_EXTERN int
131 lws_x509_public_to_jwk(struct lws_jwk *jwk, struct lws_x509_cert *x509,
132 		       const char *curves, int rsabits);
133 
134 /**
135  * lws_x509_jwk_privkey_pem() - Copy a private key PEM into a jwk that has the
136  *				public part already
137  *
138  * \param jwk: pointer to the jwk to initialize and set to the public key
139  * \param pem: pointer to PEM private key in memory
140  * \param len: length of PEM private key in memory
141  * \param passphrase: NULL or passphrase needed to decrypt private key
142  *
143  * IMPORTANT for compatibility with mbedtls, the last used byte of \p pem
144  * must be '\0' and the \p len must include it.
145  *
146  * Returns 0 if the private key was successfully added to the JWK, else
147  * nonzero if failed.
148  *
149  * The PEM image in memory is zeroed down on both successful and failed exits.
150  * The caller should take care to zero down passphrase if used.
151  */
152 LWS_VISIBLE LWS_EXTERN int
153 lws_x509_jwk_privkey_pem(struct lws_jwk *jwk, void *pem, size_t len,
154 			 const char *passphrase);
155 
156 /**
157  * lws_x509_destroy() - Destroy a previously allocated lws_x509_cert object
158  *
159  * \param x509: pointer to lws_x509_cert pointer
160  *
161  * Deallocates an lws_x509_cert object and sets its pointer to NULL.
162  */
163 LWS_VISIBLE LWS_EXTERN void
164 lws_x509_destroy(struct lws_x509_cert **x509);
165 
166 LWS_VISIBLE LWS_EXTERN int
167 lws_x509_info(struct lws_x509_cert *x509, enum lws_tls_cert_info type,
168 	      union lws_tls_cert_info_results *buf, size_t len);
169 
170 /**
171  * lws_tls_peer_cert_info() - get information from the peer's TLS cert
172  *
173  * \param wsi: the connection to query
174  * \param type: one of LWS_TLS_CERT_INFO_
175  * \param buf: pointer to union to take result
176  * \param len: when result is a string, the true length of buf->ns.name[]
177  *
178  * lws_tls_peer_cert_info() lets you get hold of information from the peer
179  * certificate.
180  *
181  * Return 0 if there is a result in \p buf, or -1 indicating there was no cert
182  * or another problem.
183  *
184  * This function works the same no matter if the TLS backend is OpenSSL or
185  * mbedTLS.
186  */
187 LWS_VISIBLE LWS_EXTERN int
188 lws_tls_peer_cert_info(struct lws *wsi, enum lws_tls_cert_info type,
189 		       union lws_tls_cert_info_results *buf, size_t len);
190 
191 /**
192  * lws_tls_vhost_cert_info() - get information from the vhost's own TLS cert
193  *
194  * \param vhost: the vhost to query
195  * \param type: one of LWS_TLS_CERT_INFO_
196  * \param buf: pointer to union to take result
197  * \param len: when result is a string, the true length of buf->ns.name[]
198  *
199  * lws_tls_vhost_cert_info() lets you get hold of information from the vhost
200  * certificate.
201  *
202  * Return 0 if there is a result in \p buf, or -1 indicating there was no cert
203  * or another problem.
204  *
205  * This function works the same no matter if the TLS backend is OpenSSL or
206  * mbedTLS.
207  */
208 LWS_VISIBLE LWS_EXTERN int
209 lws_tls_vhost_cert_info(struct lws_vhost *vhost, enum lws_tls_cert_info type,
210 		        union lws_tls_cert_info_results *buf, size_t len);
211 
212 /**
213  * lws_tls_acme_sni_cert_create() - creates a temp selfsigned cert
214  *				    and attaches to a vhost
215  *
216  * \param vhost: the vhost to acquire the selfsigned cert
217  * \param san_a: SAN written into the certificate
218  * \param san_b: second SAN written into the certificate
219  *
220  *
221  * Returns 0 if created and attached to the vhost.  Returns -1 if problems and
222  * frees all allocations before returning.
223  *
224  * On success, any allocations are destroyed at vhost destruction automatically.
225  */
226 LWS_VISIBLE LWS_EXTERN int
227 lws_tls_acme_sni_cert_create(struct lws_vhost *vhost, const char *san_a,
228 			     const char *san_b);
229 
230 /**
231  * lws_tls_acme_sni_csr_create() - creates a CSR and related private key PEM
232  *
233  * \param context: lws_context used for random
234  * \param elements: array of LWS_TLS_REQ_ELEMENT_COUNT const char *
235  * \param csr: buffer that will get the b64URL(ASN-1 CSR)
236  * \param csr_len: max length of the csr buffer
237  * \param privkey_pem: pointer to pointer allocated to hold the privkey_pem
238  * \param privkey_len: pointer to size_t set to the length of the privkey_pem
239  *
240  * Creates a CSR according to the information in \p elements, and a private
241  * RSA key used to sign the CSR.
242  *
243  * The outputs are the b64URL(ASN-1 CSR) into csr, and the PEM private key into
244  * privkey_pem.
245  *
246  * Notice that \p elements points to an array of const char *s pointing to the
247  * information listed in the enum above.  If an entry is NULL or an empty
248  * string, the element is set to "none" in the CSR.
249  *
250  * Returns 0 on success or nonzero for failure.
251  */
252 LWS_VISIBLE LWS_EXTERN int
253 lws_tls_acme_sni_csr_create(struct lws_context *context, const char *elements[],
254 			    uint8_t *csr, size_t csr_len, char **privkey_pem,
255 			    size_t *privkey_len);
256 
257 /**
258  * lws_tls_cert_updated() - update every vhost using the given cert path
259  *
260  * \param context: our lws_context
261  * \param certpath: the filepath to the certificate
262  * \param keypath: the filepath to the private key of the certificate
263  * \param mem_cert: copy of the cert in memory
264  * \param len_mem_cert: length of the copy of the cert in memory
265  * \param mem_privkey: copy of the private key in memory
266  * \param len_mem_privkey: length of the copy of the private key in memory
267  *
268  * Checks every vhost to see if it is the using certificate described by the
269  * the given filepaths.  If so, it attempts to update the vhost ssl_ctx to use
270  * the new certificate.
271  *
272  * Returns 0 on success or nonzero for failure.
273  */
274 LWS_VISIBLE LWS_EXTERN int
275 lws_tls_cert_updated(struct lws_context *context, const char *certpath,
276 		     const char *keypath,
277 		     const char *mem_cert, size_t len_mem_cert,
278 		     const char *mem_privkey, size_t len_mem_privkey);
279 
280