1 /*
2  * lws-minimal-secure-streams
3  *
4  * Written in 2010-2020 by Andy Green <andy@warmcat.com>
5  *
6  * This file is made available under the Creative Commons CC0 1.0
7  * Universal Public Domain Dedication.
8  *
9  *
10  * This demonstrates a minimal http client using secure streams api.
11  *
12  * It visits https://warmcat.com/ and receives the html page there.
13  *
14  * This example is built two different ways from the same source... one includes
15  * the policy everything needed to fulfil the stream directly.  The other -client
16  * variant has no policy itself and some other minor init changes, and connects
17  * to the -proxy example to actually get the connection done.
18  *
19  * In the -client build case, the example does not even init the tls libraries
20  * since the proxy part will take care of all that.
21  */
22 
23 #include <libwebsockets.h>
24 #include <string.h>
25 #include <signal.h>
26 
27 /*
28  * uncomment to force network traffic through 127.0.0.1:1080
29  *
30  * On your local machine, you can run a SOCKS5 proxy like this
31  *
32  * $ ssh -N -D 0.0.0.0:1080 localhost -v
33  *
34  * If enabled, this also fetches a remote policy that also
35  * specifies that all traffic should go through the remote
36  * proxy.
37  */
38 // #define VIA_LOCALHOST_SOCKS
39 
40 static int interrupted, bad = 1;
41 static lws_state_notify_link_t nl;
42 
43 /*
44  * If the -proxy app is fulfilling our connection, then we don't need to have
45  * the policy in the client.
46  *
47  * When we build with LWS_SS_USE_SSPC, the apis hook up to a proxy process over
48  * a Unix Domain Socket.  To test that, you need to separately run the
49  * ./lws-minimal-secure-streams-proxy test app on the same machine.
50  */
51 
52 #if !defined(LWS_SS_USE_SSPC)
53 static const char * const default_ss_policy =
54 	"{"
55 	  "\"release\":"			"\"01234567\","
56 	  "\"product\":"			"\"myproduct\","
57 	  "\"schema-version\":"			"1,"
58 #if defined(VIA_LOCALHOST_SOCKS)
59 	  "\"via-socks5\":"                     "\"127.0.0.1:1080\","
60 #endif
61 
62 	  "\"retry\": ["	/* named backoff / retry strategies */
63 		"{\"default\": {"
64 			"\"backoff\": ["	 "1000,"
65 						 "2000,"
66 						 "3000,"
67 						 "5000,"
68 						"10000"
69 				"],"
70 			"\"conceal\":"		"5,"
71 			"\"jitterpc\":"		"20,"
72 			"\"svalidping\":"	"30,"
73 			"\"svalidhup\":"	"35"
74 		"}}"
75 	  "],"
76 	  "\"certs\": [" /* named individual certificates in BASE64 DER */
77 		/*
78 		 * Let's Encrypt certs for warmcat.com / libwebsockets.org
79 		 *
80 		 * We fetch the real policy from there using SS and switch to
81 		 * using that.
82 		 */
83 		"{\"isrg_root_x1\": \"" /* ISRG ROOT X1 */
84 	"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw"
85 	"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh"
86 	"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4"
87 	"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu"
88 	"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY"
89 	"MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc"
90 	"h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+"
91 	"0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U"
92 	"A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW"
93 	"T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH"
94 	"B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC"
95 	"B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv"
96 	"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
143 	"PB0t6JzUA81mSqM3kxl5e+IZwhYAyO0OTg3/fs8HqGTNKd9BqoUwSRBzp06JMg5b"
144 	"rUCGwbCUDI0mxadJ3Bz4WxR6fyNpBK2yAinWEsikxqEt"
145 		"\"}"
146 	  "],"
147 	  "\"trust_stores\": [" /* named cert chains */
148 		"{"
149 			"\"name\": \"le_via_isrg\","
150 			"\"stack\": ["
151 				"\"isrg_root_x1\","
152 				"\"LEX3_isrg_root_x1\""
153 			"]"
154 		"}"
155 	  "],"
156 	  "\"s\": ["
157 		"{\"fetch_policy\": {"
158 			"\"endpoint\":"		"\"warmcat.com\","
159 			"\"port\":"		"443,"
160 			"\"protocol\":"		"\"h1\","
161 			"\"http_method\":"	"\"GET\","
162 #if defined(VIA_LOCALHOST_SOCKS)
163 			"\"http_url\":"		"\"policy/minimal-proxy-socks.json\","
164 #else
165 			"\"http_url\":"		"\"policy/minimal-proxy.json\","
166 #endif
167 			"\"tls\":"		"true,"
168 			"\"opportunistic\":"	"true,"
169 			"\"retry\":"		"\"default\","
170 			"\"tls_trust_store\":"	"\"le_via_isrg\""
171 		"}}"
172 	"}"
173 ;
174 
175 #endif
176 
177 typedef struct myss {
178 	struct lws_ss_handle 		*ss;
179 	void				*opaque_data;
180 	/* ... application specific state ... */
181 	lws_sorted_usec_list_t		sul;
182 } myss_t;
183 
184 static const char *canned_root_token_payload =
185 	"grant_type=refresh_token"
186 	"&refresh_token=Atzr|IwEBIJedGXjDqsU_vMxykqOMg"
187 	"SHfYe3CPcedueWEMWSDMaDnEmiW8RlR1Kns7Cb4B-TOSnqp7ifVsY4BMY2B8tpHfO39XP"
188 	"zfu9HapGjTR458IyHX44FE71pWJkGZ79uVBpljP4sazJuk8XS3Oe_yLnm_DIO6fU1nU3Y"
189 	"0flYmsOiOAQE_gRk_pdlmEtHnpMA-9rLw3mkY5L89Ty9kUygBsiFaYatouROhbsTn8-jW"
190 	"k1zZLUDpT6ICtBXSnrCIg0pUbZevPFhTwdXd6eX-u4rq0W-XaDvPWFO7au-iPb4Zk5eZE"
191 	"iX6sissYrtNmuEXc2uHu7MnQO1hHCaTdIO2CANVumf-PHSD8xseamyh04sLV5JgFzY45S"
192 	"KvKMajiUZuLkMokOx86rjC2Hdkx5DO7G-dbG1ufBDG-N79pFMSs7Ck5pc283IdLoJkCQc"
193 	"AGvTX8o8I29QqkcGou-9TKhOJmpX8As94T61ok0UqqEKPJ7RhfQHHYdCtsdwxgvfVr9qI"
194 	"xL_hDCcTho8opCVX-6QhJHl6SQFlTw13"
195 	"&client_id="
196 		"amzn1.application-oa2-client.4823334c434b4190a2b5a42c07938a2d";
197 
198 /* secure streams payload interface */
199 
200 static int
myss_rx(void * userobj,const uint8_t * buf,size_t len,int flags)201 myss_rx(void *userobj, const uint8_t *buf, size_t len, int flags)
202 {
203 //	myss_t *m = (myss_t *)userobj;
204 
205 	lwsl_user("%s: len %d, flags: %d\n", __func__, (int)len, flags);
206 	lwsl_hexdump_info(buf, len);
207 
208 	/*
209 	 * If we received the whole message, for our example it means
210 	 * we are done.
211 	 */
212 	if (flags & LWSSS_FLAG_EOM) {
213 		bad = 0;
214 		interrupted = 1;
215 	}
216 
217 	return 0;
218 }
219 
220 static int
myss_tx(void * userobj,lws_ss_tx_ordinal_t ord,uint8_t * buf,size_t * len,int * flags)221 myss_tx(void *userobj, lws_ss_tx_ordinal_t ord, uint8_t *buf, size_t *len,
222 	int *flags)
223 {
224 	//myss_t *m = (myss_t *)userobj;
225 
226 	return 0;
227 }
228 
229 static int
myss_state(void * userobj,void * sh,lws_ss_constate_t state,lws_ss_tx_ordinal_t ack)230 myss_state(void *userobj, void *sh, lws_ss_constate_t state,
231 	   lws_ss_tx_ordinal_t ack)
232 {
233 	myss_t *m = (myss_t *)userobj;
234 
235 	lwsl_user("%s: %s, ord 0x%x\n", __func__, lws_ss_state_name(state),
236 		  (unsigned int)ack);
237 
238 	switch (state) {
239 	case LWSSSCS_CREATING:
240 		lws_ss_set_metadata(m->ss, "uptag", "myuptag123", 10);
241 		lws_ss_set_metadata(m->ss, "ctype", "myctype", 7);
242 		lws_ss_client_connect(m->ss);
243 		break;
244 	case LWSSSCS_ALL_RETRIES_FAILED:
245 		/* if we're out of retries, we want to close the app and FAIL */
246 		interrupted = 1;
247 		break;
248 	case LWSSSCS_QOS_ACK_REMOTE:
249 		lwsl_notice("%s: LWSSSCS_QOS_ACK_REMOTE\n", __func__);
250 		break;
251 	default:
252 		break;
253 	}
254 
255 	return 0;
256 }
257 
258 static int
app_system_state_nf(lws_state_manager_t * mgr,lws_state_notify_link_t * link,int current,int target)259 app_system_state_nf(lws_state_manager_t *mgr, lws_state_notify_link_t *link,
260 		    int current, int target)
261 {
262 	struct lws_context *context = lws_system_context_from_system_mgr(mgr);
263 	lws_system_blob_t *ab = lws_system_get_blob(context,
264 				LWS_SYSBLOB_TYPE_AUTH, 1 /* AUTH_IDX_ROOT */);
265 	size_t size;
266 
267 	/*
268 	 * For the things we care about, let's notice if we are trying to get
269 	 * past them when we haven't solved them yet, and make the system
270 	 * state wait while we trigger the dependent action.
271 	 */
272 	switch (target) {
273 	case LWS_SYSTATE_REGISTERED:
274 		size = lws_system_blob_get_size(ab);
275 		if (size)
276 			break;
277 
278 		/* let's register our canned root token so auth can use it */
279 		lws_system_blob_direct_set(ab,
280 				(const uint8_t *)canned_root_token_payload,
281 				strlen(canned_root_token_payload));
282 		break;
283 
284 	case LWS_SYSTATE_OPERATIONAL:
285 		if (current == LWS_SYSTATE_OPERATIONAL) {
286 			lws_ss_info_t ssi;
287 
288 			/* We're making an outgoing secure stream ourselves */
289 
290 			memset(&ssi, 0, sizeof(ssi));
291 			ssi.handle_offset = offsetof(myss_t, ss);
292 			ssi.opaque_user_data_offset = offsetof(myss_t,
293 							       opaque_data);
294 			ssi.rx = myss_rx;
295 			ssi.tx = myss_tx;
296 			ssi.state = myss_state;
297 			ssi.user_alloc = sizeof(myss_t);
298 			ssi.streamtype = "mintest";
299 
300 			if (lws_ss_create(context, 0, &ssi, NULL, NULL,
301 					  NULL, NULL)) {
302 				lwsl_err("%s: failed to create secure stream\n",
303 					 __func__);
304 				return -1;
305 			}
306 		}
307 		break;
308 	}
309 
310 	return 0;
311 }
312 
313 static lws_state_notify_link_t * const app_notifier_list[] = {
314 	&nl, NULL
315 };
316 
317 static void
sigint_handler(int sig)318 sigint_handler(int sig)
319 {
320 	interrupted = 1;
321 }
322 
main(int argc,const char ** argv)323 int main(int argc, const char **argv)
324 {
325 	struct lws_context_creation_info info;
326 	struct lws_context *context;
327 	int n = 0;
328 
329 	signal(SIGINT, sigint_handler);
330 
331 	memset(&info, 0, sizeof info);
332 	lws_cmdline_option_handle_builtin(argc, argv, &info);
333 
334 	lwsl_user("LWS secure streams test client [-d<verb>]\n");
335 
336 	info.fd_limit_per_thread = 1 + 6 + 1;
337 	info.port = CONTEXT_PORT_NO_LISTEN;
338 #if defined(LWS_SS_USE_SSPC)
339 	info.protocols = lws_sspc_protocols;
340 	{
341 		const char *p;
342 
343 		/* connect to ssproxy via UDS by default, else via
344 		 * tcp connection to this port */
345 		if ((p = lws_cmdline_option(argc, argv, "-p")))
346 			info.ss_proxy_port = atoi(p);
347 
348 		/* UDS "proxy.ss.lws" in abstract namespace, else this socket
349 		 * path; when -p given this can specify the network interface
350 		 * to bind to */
351 		if ((p = lws_cmdline_option(argc, argv, "-i")))
352 			info.ss_proxy_bind = p;
353 
354 		/* if -p given, -a specifies the proxy address to connect to */
355 		if ((p = lws_cmdline_option(argc, argv, "-a")))
356 			info.ss_proxy_address = p;
357 	}
358 #else
359 	info.pss_policies_json = default_ss_policy;
360 	info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
361 		       LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
362 #endif
363 #if defined(LWS_WITH_DETAILED_LATENCY)
364 	info.detailed_latency_cb = lws_det_lat_plot_cb;
365 	info.detailed_latency_filepath = "/tmp/lws-latency-ssproxy";
366 #endif
367 
368 	/* integrate us with lws system state management when context created */
369 
370 	nl.name = "app";
371 	nl.notify_cb = app_system_state_nf;
372 	info.register_notifier_list = app_notifier_list;
373 
374 	/* create the context */
375 
376 	context = lws_create_context(&info);
377 	if (!context) {
378 		lwsl_err("lws init failed\n");
379 		return 1;
380 	}
381 
382 	/*
383 	 * Set the related lws_system blobs
384 	 *
385 	 * ...direct_set() sets a pointer, so the thing pointed to has to have
386 	 * a suitable lifetime, eg, something that already exists on the heap or
387 	 * a const string in .rodata like this
388 	 */
389 
390 	lws_system_blob_direct_set(lws_system_get_blob(context,
391 				   LWS_SYSBLOB_TYPE_DEVICE_SERIAL, 0),
392 				   (const uint8_t *)"SN12345678", 10);
393 	lws_system_blob_direct_set(lws_system_get_blob(context,
394 				   LWS_SYSBLOB_TYPE_DEVICE_FW_VERSION, 0),
395 				   (const uint8_t *)"v0.01", 5);
396 
397 	/*
398 	 * ..._heap_append() appends to a buflist kind of arrangement on heap,
399 	 * just one block is fine, otherwise it will concatenate the fragments
400 	 * in the order they were appended (and take care of freeing them at
401 	 * context destroy time). ..._heap_empty() is also available to remove
402 	 * everything that was already allocated.
403 	 *
404 	 * Here we use _heap_append() just so it's tested as well as direct set.
405 	 */
406 
407 	lws_system_blob_heap_append(lws_system_get_blob(context,
408 				    LWS_SYSBLOB_TYPE_DEVICE_TYPE, 0),
409 				   (const uint8_t *)"spacerocket", 11);
410 
411 	/* the event loop */
412 
413 	while (n >= 0 && !interrupted)
414 		n = lws_service(context, 0);
415 
416 	lws_context_destroy(context);
417 
418 	lwsl_user("Completed: %s\n", bad ? "failed" : "OK");
419 
420 	return bad;
421 }
422