1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
5  * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
6  * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * a) Redistributions of source code must retain the above copyright notice,
12  *    this list of conditions and the following disclaimer.
13  *
14  * b) Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the distribution.
17  *
18  * c) Neither the name of Cisco Systems, Inc. nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
32  * THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #if defined(__FreeBSD__) && !defined(__Userspace__)
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD: head/sys/netinet/sctp_auth.c 365071 2020-09-01 21:19:14Z mjg $");
38 #endif
39 
40 #include <netinet/sctp_os.h>
41 #include <netinet/sctp.h>
42 #include <netinet/sctp_header.h>
43 #include <netinet/sctp_pcb.h>
44 #include <netinet/sctp_var.h>
45 #include <netinet/sctp_sysctl.h>
46 #include <netinet/sctputil.h>
47 #include <netinet/sctp_indata.h>
48 #include <netinet/sctp_output.h>
49 #include <netinet/sctp_auth.h>
50 
51 #ifdef SCTP_DEBUG
52 #define SCTP_AUTH_DEBUG		(SCTP_BASE_SYSCTL(sctp_debug_on) & SCTP_DEBUG_AUTH1)
53 #define SCTP_AUTH_DEBUG2	(SCTP_BASE_SYSCTL(sctp_debug_on) & SCTP_DEBUG_AUTH2)
54 #endif /* SCTP_DEBUG */
55 
56 void
sctp_clear_chunklist(sctp_auth_chklist_t * chklist)57 sctp_clear_chunklist(sctp_auth_chklist_t *chklist)
58 {
59 	memset(chklist, 0, sizeof(*chklist));
60 	/* chklist->num_chunks = 0; */
61 }
62 
63 sctp_auth_chklist_t *
sctp_alloc_chunklist(void)64 sctp_alloc_chunklist(void)
65 {
66 	sctp_auth_chklist_t *chklist;
67 
68 	SCTP_MALLOC(chklist, sctp_auth_chklist_t *, sizeof(*chklist),
69 		    SCTP_M_AUTH_CL);
70 	if (chklist == NULL) {
71 		SCTPDBG(SCTP_DEBUG_AUTH1, "sctp_alloc_chunklist: failed to get memory!\n");
72 	} else {
73 		sctp_clear_chunklist(chklist);
74 	}
75 	return (chklist);
76 }
77 
78 void
sctp_free_chunklist(sctp_auth_chklist_t * list)79 sctp_free_chunklist(sctp_auth_chklist_t *list)
80 {
81 	if (list != NULL)
82 		SCTP_FREE(list, SCTP_M_AUTH_CL);
83 }
84 
85 sctp_auth_chklist_t *
sctp_copy_chunklist(sctp_auth_chklist_t * list)86 sctp_copy_chunklist(sctp_auth_chklist_t *list)
87 {
88 	sctp_auth_chklist_t *new_list;
89 
90 	if (list == NULL)
91 		return (NULL);
92 
93 	/* get a new list */
94 	new_list = sctp_alloc_chunklist();
95 	if (new_list == NULL)
96 		return (NULL);
97 	/* copy it */
98 	memcpy(new_list, list, sizeof(*new_list));
99 
100 	return (new_list);
101 }
102 
103 /*
104  * add a chunk to the required chunks list
105  */
106 int
sctp_auth_add_chunk(uint8_t chunk,sctp_auth_chklist_t * list)107 sctp_auth_add_chunk(uint8_t chunk, sctp_auth_chklist_t *list)
108 {
109 	if (list == NULL)
110 		return (-1);
111 
112 	/* is chunk restricted? */
113 	if ((chunk == SCTP_INITIATION) ||
114 	    (chunk == SCTP_INITIATION_ACK) ||
115 	    (chunk == SCTP_SHUTDOWN_COMPLETE) ||
116 	    (chunk == SCTP_AUTHENTICATION)) {
117 		return (-1);
118 	}
119 	if (list->chunks[chunk] == 0) {
120 		list->chunks[chunk] = 1;
121 		list->num_chunks++;
122 		SCTPDBG(SCTP_DEBUG_AUTH1,
123 			"SCTP: added chunk %u (0x%02x) to Auth list\n",
124 			chunk, chunk);
125 	}
126 	return (0);
127 }
128 
129 /*
130  * delete a chunk from the required chunks list
131  */
132 int
sctp_auth_delete_chunk(uint8_t chunk,sctp_auth_chklist_t * list)133 sctp_auth_delete_chunk(uint8_t chunk, sctp_auth_chklist_t *list)
134 {
135 	if (list == NULL)
136 		return (-1);
137 
138 	if (list->chunks[chunk] == 1) {
139 		list->chunks[chunk] = 0;
140 		list->num_chunks--;
141 		SCTPDBG(SCTP_DEBUG_AUTH1,
142 			"SCTP: deleted chunk %u (0x%02x) from Auth list\n",
143 			chunk, chunk);
144 	}
145 	return (0);
146 }
147 
148 size_t
sctp_auth_get_chklist_size(const sctp_auth_chklist_t * list)149 sctp_auth_get_chklist_size(const sctp_auth_chklist_t *list)
150 {
151 	if (list == NULL)
152 		return (0);
153 	else
154 		return (list->num_chunks);
155 }
156 
157 /*
158  * return the current number and list of required chunks caller must
159  * guarantee ptr has space for up to 256 bytes
160  */
161 int
sctp_serialize_auth_chunks(const sctp_auth_chklist_t * list,uint8_t * ptr)162 sctp_serialize_auth_chunks(const sctp_auth_chklist_t *list, uint8_t *ptr)
163 {
164 	int i, count = 0;
165 
166 	if (list == NULL)
167 		return (0);
168 
169 	for (i = 0; i < 256; i++) {
170 		if (list->chunks[i] != 0) {
171 			*ptr++ = i;
172 			count++;
173 		}
174 	}
175 	return (count);
176 }
177 
178 int
sctp_pack_auth_chunks(const sctp_auth_chklist_t * list,uint8_t * ptr)179 sctp_pack_auth_chunks(const sctp_auth_chklist_t *list, uint8_t *ptr)
180 {
181 	int i, size = 0;
182 
183 	if (list == NULL)
184 		return (0);
185 
186 	if (list->num_chunks <= 32) {
187 		/* just list them, one byte each */
188 		for (i = 0; i < 256; i++) {
189 			if (list->chunks[i] != 0) {
190 				*ptr++ = i;
191 				size++;
192 			}
193 		}
194 	} else {
195 		int index, offset;
196 
197 		/* pack into a 32 byte bitfield */
198 		for (i = 0; i < 256; i++) {
199 			if (list->chunks[i] != 0) {
200 				index = i / 8;
201 				offset = i % 8;
202 				ptr[index] |= (1 << offset);
203 			}
204 		}
205 		size = 32;
206 	}
207 	return (size);
208 }
209 
210 int
sctp_unpack_auth_chunks(const uint8_t * ptr,uint8_t num_chunks,sctp_auth_chklist_t * list)211 sctp_unpack_auth_chunks(const uint8_t *ptr, uint8_t num_chunks,
212     sctp_auth_chklist_t *list)
213 {
214 	int i;
215 	int size;
216 
217 	if (list == NULL)
218 		return (0);
219 
220 	if (num_chunks <= 32) {
221 		/* just pull them, one byte each */
222 		for (i = 0; i < num_chunks; i++) {
223 			(void)sctp_auth_add_chunk(*ptr++, list);
224 		}
225 		size = num_chunks;
226 	} else {
227 		int index, offset;
228 
229 		/* unpack from a 32 byte bitfield */
230 		for (index = 0; index < 32; index++) {
231 			for (offset = 0; offset < 8; offset++) {
232 				if (ptr[index] & (1 << offset)) {
233 					(void)sctp_auth_add_chunk((index * 8) + offset, list);
234 				}
235 			}
236 		}
237 		size = 32;
238 	}
239 	return (size);
240 }
241 
242 /*
243  * allocate structure space for a key of length keylen
244  */
245 sctp_key_t *
sctp_alloc_key(uint32_t keylen)246 sctp_alloc_key(uint32_t keylen)
247 {
248 	sctp_key_t *new_key;
249 
250 	SCTP_MALLOC(new_key, sctp_key_t *, sizeof(*new_key) + keylen,
251 		    SCTP_M_AUTH_KY);
252 	if (new_key == NULL) {
253 		/* out of memory */
254 		return (NULL);
255 	}
256 	new_key->keylen = keylen;
257 	return (new_key);
258 }
259 
260 void
sctp_free_key(sctp_key_t * key)261 sctp_free_key(sctp_key_t *key)
262 {
263 	if (key != NULL)
264 		SCTP_FREE(key,SCTP_M_AUTH_KY);
265 }
266 
267 void
sctp_print_key(sctp_key_t * key,const char * str)268 sctp_print_key(sctp_key_t *key, const char *str)
269 {
270 	uint32_t i;
271 
272 	if (key == NULL) {
273 		SCTP_PRINTF("%s: [Null key]\n", str);
274 		return;
275 	}
276 	SCTP_PRINTF("%s: len %u, ", str, key->keylen);
277 	if (key->keylen) {
278 		for (i = 0; i < key->keylen; i++)
279 			SCTP_PRINTF("%02x", key->key[i]);
280 		SCTP_PRINTF("\n");
281 	} else {
282 		SCTP_PRINTF("[Null key]\n");
283 	}
284 }
285 
286 void
sctp_show_key(sctp_key_t * key,const char * str)287 sctp_show_key(sctp_key_t *key, const char *str)
288 {
289 	uint32_t i;
290 
291 	if (key == NULL) {
292 		SCTP_PRINTF("%s: [Null key]\n", str);
293 		return;
294 	}
295 	SCTP_PRINTF("%s: len %u, ", str, key->keylen);
296 	if (key->keylen) {
297 		for (i = 0; i < key->keylen; i++)
298 			SCTP_PRINTF("%02x", key->key[i]);
299 		SCTP_PRINTF("\n");
300 	} else {
301 		SCTP_PRINTF("[Null key]\n");
302 	}
303 }
304 
305 static uint32_t
sctp_get_keylen(sctp_key_t * key)306 sctp_get_keylen(sctp_key_t *key)
307 {
308 	if (key != NULL)
309 		return (key->keylen);
310 	else
311 		return (0);
312 }
313 
314 /*
315  * generate a new random key of length 'keylen'
316  */
317 sctp_key_t *
sctp_generate_random_key(uint32_t keylen)318 sctp_generate_random_key(uint32_t keylen)
319 {
320 	sctp_key_t *new_key;
321 
322 	new_key = sctp_alloc_key(keylen);
323 	if (new_key == NULL) {
324 		/* out of memory */
325 		return (NULL);
326 	}
327 	SCTP_READ_RANDOM(new_key->key, keylen);
328 	new_key->keylen = keylen;
329 	return (new_key);
330 }
331 
332 sctp_key_t *
sctp_set_key(uint8_t * key,uint32_t keylen)333 sctp_set_key(uint8_t *key, uint32_t keylen)
334 {
335 	sctp_key_t *new_key;
336 
337 	new_key = sctp_alloc_key(keylen);
338 	if (new_key == NULL) {
339 		/* out of memory */
340 		return (NULL);
341 	}
342 	memcpy(new_key->key, key, keylen);
343 	return (new_key);
344 }
345 
346 /*-
347  * given two keys of variable size, compute which key is "larger/smaller"
348  * returns:  1 if key1 > key2
349  *          -1 if key1 < key2
350  *           0 if key1 = key2
351  */
352 static int
sctp_compare_key(sctp_key_t * key1,sctp_key_t * key2)353 sctp_compare_key(sctp_key_t *key1, sctp_key_t *key2)
354 {
355 	uint32_t maxlen;
356 	uint32_t i;
357 	uint32_t key1len, key2len;
358 	uint8_t *key_1, *key_2;
359 	uint8_t val1, val2;
360 
361 	/* sanity/length check */
362 	key1len = sctp_get_keylen(key1);
363 	key2len = sctp_get_keylen(key2);
364 	if ((key1len == 0) && (key2len == 0))
365 		return (0);
366 	else if (key1len == 0)
367 		return (-1);
368 	else if (key2len == 0)
369 		return (1);
370 
371 	if (key1len < key2len) {
372 		maxlen = key2len;
373 	} else {
374 		maxlen = key1len;
375 	}
376 	key_1 = key1->key;
377 	key_2 = key2->key;
378 	/* check for numeric equality */
379 	for (i = 0; i < maxlen; i++) {
380 		/* left-pad with zeros */
381 		val1 = (i < (maxlen - key1len)) ? 0 : *(key_1++);
382 		val2 = (i < (maxlen - key2len)) ? 0 : *(key_2++);
383 		if (val1 > val2) {
384 			return (1);
385 		} else if (val1 < val2) {
386 			return (-1);
387 		}
388 	}
389 	/* keys are equal value, so check lengths */
390 	if (key1len == key2len)
391 		return (0);
392 	else if (key1len < key2len)
393 		return (-1);
394 	else
395 		return (1);
396 }
397 
398 /*
399  * generate the concatenated keying material based on the two keys and the
400  * shared key (if available). draft-ietf-tsvwg-auth specifies the specific
401  * order for concatenation
402  */
403 sctp_key_t *
sctp_compute_hashkey(sctp_key_t * key1,sctp_key_t * key2,sctp_key_t * shared)404 sctp_compute_hashkey(sctp_key_t *key1, sctp_key_t *key2, sctp_key_t *shared)
405 {
406 	uint32_t keylen;
407 	sctp_key_t *new_key;
408 	uint8_t *key_ptr;
409 
410 	keylen = sctp_get_keylen(key1) + sctp_get_keylen(key2) +
411 	    sctp_get_keylen(shared);
412 
413 	if (keylen > 0) {
414 		/* get space for the new key */
415 		new_key = sctp_alloc_key(keylen);
416 		if (new_key == NULL) {
417 			/* out of memory */
418 			return (NULL);
419 		}
420 		new_key->keylen = keylen;
421 		key_ptr = new_key->key;
422 	} else {
423 		/* all keys empty/null?! */
424 		return (NULL);
425 	}
426 
427 	/* concatenate the keys */
428 	if (sctp_compare_key(key1, key2) <= 0) {
429 		/* key is shared + key1 + key2 */
430 		if (sctp_get_keylen(shared)) {
431 			memcpy(key_ptr, shared->key, shared->keylen);
432 			key_ptr += shared->keylen;
433 		}
434 		if (sctp_get_keylen(key1)) {
435 			memcpy(key_ptr, key1->key, key1->keylen);
436 			key_ptr += key1->keylen;
437 		}
438 		if (sctp_get_keylen(key2)) {
439 			memcpy(key_ptr, key2->key, key2->keylen);
440 		}
441 	} else {
442 		/* key is shared + key2 + key1 */
443 		if (sctp_get_keylen(shared)) {
444 			memcpy(key_ptr, shared->key, shared->keylen);
445 			key_ptr += shared->keylen;
446 		}
447 		if (sctp_get_keylen(key2)) {
448 			memcpy(key_ptr, key2->key, key2->keylen);
449 			key_ptr += key2->keylen;
450 		}
451 		if (sctp_get_keylen(key1)) {
452 			memcpy(key_ptr, key1->key, key1->keylen);
453 		}
454 	}
455 	return (new_key);
456 }
457 
458 sctp_sharedkey_t *
sctp_alloc_sharedkey(void)459 sctp_alloc_sharedkey(void)
460 {
461 	sctp_sharedkey_t *new_key;
462 
463 	SCTP_MALLOC(new_key, sctp_sharedkey_t *, sizeof(*new_key),
464 		    SCTP_M_AUTH_KY);
465 	if (new_key == NULL) {
466 		/* out of memory */
467 		return (NULL);
468 	}
469 	new_key->keyid = 0;
470 	new_key->key = NULL;
471 	new_key->refcount = 1;
472 	new_key->deactivated = 0;
473 	return (new_key);
474 }
475 
476 void
sctp_free_sharedkey(sctp_sharedkey_t * skey)477 sctp_free_sharedkey(sctp_sharedkey_t *skey)
478 {
479 	if (skey == NULL)
480 		return;
481 
482 	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&skey->refcount)) {
483 		if (skey->key != NULL)
484 			sctp_free_key(skey->key);
485 		SCTP_FREE(skey, SCTP_M_AUTH_KY);
486 	}
487 }
488 
489 sctp_sharedkey_t *
sctp_find_sharedkey(struct sctp_keyhead * shared_keys,uint16_t key_id)490 sctp_find_sharedkey(struct sctp_keyhead *shared_keys, uint16_t key_id)
491 {
492 	sctp_sharedkey_t *skey;
493 
494 	LIST_FOREACH(skey, shared_keys, next) {
495 		if (skey->keyid == key_id)
496 			return (skey);
497 	}
498 	return (NULL);
499 }
500 
501 int
sctp_insert_sharedkey(struct sctp_keyhead * shared_keys,sctp_sharedkey_t * new_skey)502 sctp_insert_sharedkey(struct sctp_keyhead *shared_keys,
503 		      sctp_sharedkey_t *new_skey)
504 {
505 	sctp_sharedkey_t *skey;
506 
507 	if ((shared_keys == NULL) || (new_skey == NULL))
508 		return (EINVAL);
509 
510 	/* insert into an empty list? */
511 	if (LIST_EMPTY(shared_keys)) {
512 		LIST_INSERT_HEAD(shared_keys, new_skey, next);
513 		return (0);
514 	}
515 	/* insert into the existing list, ordered by key id */
516 	LIST_FOREACH(skey, shared_keys, next) {
517 		if (new_skey->keyid < skey->keyid) {
518 			/* insert it before here */
519 			LIST_INSERT_BEFORE(skey, new_skey, next);
520 			return (0);
521 		} else if (new_skey->keyid == skey->keyid) {
522 			/* replace the existing key */
523 			/* verify this key *can* be replaced */
524 			if ((skey->deactivated) || (skey->refcount > 1)) {
525 				SCTPDBG(SCTP_DEBUG_AUTH1,
526 					"can't replace shared key id %u\n",
527 					new_skey->keyid);
528 				return (EBUSY);
529 			}
530 			SCTPDBG(SCTP_DEBUG_AUTH1,
531 				"replacing shared key id %u\n",
532 				new_skey->keyid);
533 			LIST_INSERT_BEFORE(skey, new_skey, next);
534 			LIST_REMOVE(skey, next);
535 			sctp_free_sharedkey(skey);
536 			return (0);
537 		}
538 		if (LIST_NEXT(skey, next) == NULL) {
539 			/* belongs at the end of the list */
540 			LIST_INSERT_AFTER(skey, new_skey, next);
541 			return (0);
542 		}
543 	}
544 	/* shouldn't reach here */
545 	return (EINVAL);
546 }
547 
548 void
sctp_auth_key_acquire(struct sctp_tcb * stcb,uint16_t key_id)549 sctp_auth_key_acquire(struct sctp_tcb *stcb, uint16_t key_id)
550 {
551 	sctp_sharedkey_t *skey;
552 
553 	/* find the shared key */
554 	skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, key_id);
555 
556 	/* bump the ref count */
557 	if (skey) {
558 		atomic_add_int(&skey->refcount, 1);
559 		SCTPDBG(SCTP_DEBUG_AUTH2,
560 			"%s: stcb %p key %u refcount acquire to %d\n",
561 			__func__, (void *)stcb, key_id, skey->refcount);
562 	}
563 }
564 
565 void
sctp_auth_key_release(struct sctp_tcb * stcb,uint16_t key_id,int so_locked)566 sctp_auth_key_release(struct sctp_tcb *stcb, uint16_t key_id, int so_locked)
567 {
568 	sctp_sharedkey_t *skey;
569 
570 	/* find the shared key */
571 	skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, key_id);
572 
573 	/* decrement the ref count */
574 	if (skey) {
575 		SCTPDBG(SCTP_DEBUG_AUTH2,
576 			"%s: stcb %p key %u refcount release to %d\n",
577 			__func__, (void *)stcb, key_id, skey->refcount);
578 
579 		/* see if a notification should be generated */
580 		if ((skey->refcount <= 2) && (skey->deactivated)) {
581 			/* notify ULP that key is no longer used */
582 			sctp_ulp_notify(SCTP_NOTIFY_AUTH_FREE_KEY, stcb,
583 					key_id, 0, so_locked);
584 			SCTPDBG(SCTP_DEBUG_AUTH2,
585 				"%s: stcb %p key %u no longer used, %d\n",
586 				__func__, (void *)stcb, key_id, skey->refcount);
587 		}
588 		sctp_free_sharedkey(skey);
589 	}
590 }
591 
592 static sctp_sharedkey_t *
sctp_copy_sharedkey(const sctp_sharedkey_t * skey)593 sctp_copy_sharedkey(const sctp_sharedkey_t *skey)
594 {
595 	sctp_sharedkey_t *new_skey;
596 
597 	if (skey == NULL)
598 		return (NULL);
599 	new_skey = sctp_alloc_sharedkey();
600 	if (new_skey == NULL)
601 		return (NULL);
602 	if (skey->key != NULL)
603 		new_skey->key = sctp_set_key(skey->key->key, skey->key->keylen);
604 	else
605 		new_skey->key = NULL;
606 	new_skey->keyid = skey->keyid;
607 	return (new_skey);
608 }
609 
610 int
sctp_copy_skeylist(const struct sctp_keyhead * src,struct sctp_keyhead * dest)611 sctp_copy_skeylist(const struct sctp_keyhead *src, struct sctp_keyhead *dest)
612 {
613 	sctp_sharedkey_t *skey, *new_skey;
614 	int count = 0;
615 
616 	if ((src == NULL) || (dest == NULL))
617 		return (0);
618 	LIST_FOREACH(skey, src, next) {
619 		new_skey = sctp_copy_sharedkey(skey);
620 		if (new_skey != NULL) {
621 			if (sctp_insert_sharedkey(dest, new_skey)) {
622 				sctp_free_sharedkey(new_skey);
623 			} else {
624 				count++;
625 			}
626 		}
627 	}
628 	return (count);
629 }
630 
631 sctp_hmaclist_t *
sctp_alloc_hmaclist(uint16_t num_hmacs)632 sctp_alloc_hmaclist(uint16_t num_hmacs)
633 {
634 	sctp_hmaclist_t *new_list;
635 	int alloc_size;
636 
637 	alloc_size = sizeof(*new_list) + num_hmacs * sizeof(new_list->hmac[0]);
638 	SCTP_MALLOC(new_list, sctp_hmaclist_t *, alloc_size,
639 		    SCTP_M_AUTH_HL);
640 	if (new_list == NULL) {
641 		/* out of memory */
642 		return (NULL);
643 	}
644 	new_list->max_algo = num_hmacs;
645 	new_list->num_algo = 0;
646 	return (new_list);
647 }
648 
649 void
sctp_free_hmaclist(sctp_hmaclist_t * list)650 sctp_free_hmaclist(sctp_hmaclist_t *list)
651 {
652 	if (list != NULL) {
653 		SCTP_FREE(list,SCTP_M_AUTH_HL);
654 	}
655 }
656 
657 int
sctp_auth_add_hmacid(sctp_hmaclist_t * list,uint16_t hmac_id)658 sctp_auth_add_hmacid(sctp_hmaclist_t *list, uint16_t hmac_id)
659 {
660 	int i;
661 	if (list == NULL)
662 		return (-1);
663 	if (list->num_algo == list->max_algo) {
664 		SCTPDBG(SCTP_DEBUG_AUTH1,
665 			"SCTP: HMAC id list full, ignoring add %u\n", hmac_id);
666 		return (-1);
667 	}
668 #if defined(SCTP_SUPPORT_HMAC_SHA256)
669 	if ((hmac_id != SCTP_AUTH_HMAC_ID_SHA1) &&
670 	    (hmac_id != SCTP_AUTH_HMAC_ID_SHA256)) {
671 #else
672 	if (hmac_id != SCTP_AUTH_HMAC_ID_SHA1) {
673 #endif
674 		return (-1);
675 	}
676 	/* Now is it already in the list */
677 	for (i = 0; i < list->num_algo; i++) {
678 		if (list->hmac[i] == hmac_id) {
679 			/* already in list */
680 			return (-1);
681 		}
682 	}
683 	SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: add HMAC id %u to list\n", hmac_id);
684 	list->hmac[list->num_algo++] = hmac_id;
685 	return (0);
686 }
687 
688 sctp_hmaclist_t *
689 sctp_copy_hmaclist(sctp_hmaclist_t *list)
690 {
691 	sctp_hmaclist_t *new_list;
692 	int i;
693 
694 	if (list == NULL)
695 		return (NULL);
696 	/* get a new list */
697 	new_list = sctp_alloc_hmaclist(list->max_algo);
698 	if (new_list == NULL)
699 		return (NULL);
700 	/* copy it */
701 	new_list->max_algo = list->max_algo;
702 	new_list->num_algo = list->num_algo;
703 	for (i = 0; i < list->num_algo; i++)
704 		new_list->hmac[i] = list->hmac[i];
705 	return (new_list);
706 }
707 
708 sctp_hmaclist_t *
709 sctp_default_supported_hmaclist(void)
710 {
711 	sctp_hmaclist_t *new_list;
712 
713 #if defined(SCTP_SUPPORT_HMAC_SHA256)
714 	new_list = sctp_alloc_hmaclist(2);
715 #else
716 	new_list = sctp_alloc_hmaclist(1);
717 #endif
718 	if (new_list == NULL)
719 		return (NULL);
720 #if defined(SCTP_SUPPORT_HMAC_SHA256)
721 	/* We prefer SHA256, so list it first */
722 	(void)sctp_auth_add_hmacid(new_list, SCTP_AUTH_HMAC_ID_SHA256);
723 #endif
724 	(void)sctp_auth_add_hmacid(new_list, SCTP_AUTH_HMAC_ID_SHA1);
725 	return (new_list);
726 }
727 
728 /*-
729  * HMAC algos are listed in priority/preference order
730  * find the best HMAC id to use for the peer based on local support
731  */
732 uint16_t
733 sctp_negotiate_hmacid(sctp_hmaclist_t *peer, sctp_hmaclist_t *local)
734 {
735 	int i, j;
736 
737 	if ((local == NULL) || (peer == NULL))
738 		return (SCTP_AUTH_HMAC_ID_RSVD);
739 
740 	for (i = 0; i < peer->num_algo; i++) {
741 		for (j = 0; j < local->num_algo; j++) {
742 			if (peer->hmac[i] == local->hmac[j]) {
743 				/* found the "best" one */
744 				SCTPDBG(SCTP_DEBUG_AUTH1,
745 					"SCTP: negotiated peer HMAC id %u\n",
746 					peer->hmac[i]);
747 				return (peer->hmac[i]);
748 			}
749 		}
750 	}
751 	/* didn't find one! */
752 	return (SCTP_AUTH_HMAC_ID_RSVD);
753 }
754 
755 /*-
756  * serialize the HMAC algo list and return space used
757  * caller must guarantee ptr has appropriate space
758  */
759 int
760 sctp_serialize_hmaclist(sctp_hmaclist_t *list, uint8_t *ptr)
761 {
762 	int i;
763 	uint16_t hmac_id;
764 
765 	if (list == NULL)
766 		return (0);
767 
768 	for (i = 0; i < list->num_algo; i++) {
769 		hmac_id = htons(list->hmac[i]);
770 		memcpy(ptr, &hmac_id, sizeof(hmac_id));
771 		ptr += sizeof(hmac_id);
772 	}
773 	return (list->num_algo * sizeof(hmac_id));
774 }
775 
776 int
777 sctp_verify_hmac_param (struct sctp_auth_hmac_algo *hmacs, uint32_t num_hmacs)
778 {
779 	uint32_t i;
780 
781 	for (i = 0; i < num_hmacs; i++) {
782 		if (ntohs(hmacs->hmac_ids[i]) == SCTP_AUTH_HMAC_ID_SHA1) {
783 			return (0);
784 		}
785 	}
786 	return (-1);
787 }
788 
789 sctp_authinfo_t *
790 sctp_alloc_authinfo(void)
791 {
792 	sctp_authinfo_t *new_authinfo;
793 
794 	SCTP_MALLOC(new_authinfo, sctp_authinfo_t *, sizeof(*new_authinfo),
795 		    SCTP_M_AUTH_IF);
796 
797 	if (new_authinfo == NULL) {
798 		/* out of memory */
799 		return (NULL);
800 	}
801 	memset(new_authinfo, 0, sizeof(*new_authinfo));
802 	return (new_authinfo);
803 }
804 
805 void
806 sctp_free_authinfo(sctp_authinfo_t *authinfo)
807 {
808 	if (authinfo == NULL)
809 		return;
810 
811 	if (authinfo->random != NULL)
812 		sctp_free_key(authinfo->random);
813 	if (authinfo->peer_random != NULL)
814 		sctp_free_key(authinfo->peer_random);
815 	if (authinfo->assoc_key != NULL)
816 		sctp_free_key(authinfo->assoc_key);
817 	if (authinfo->recv_key != NULL)
818 		sctp_free_key(authinfo->recv_key);
819 
820 	/* We are NOT dynamically allocating authinfo's right now... */
821 	/* SCTP_FREE(authinfo, SCTP_M_AUTH_??); */
822 }
823 
824 uint32_t
825 sctp_get_auth_chunk_len(uint16_t hmac_algo)
826 {
827 	int size;
828 
829 	size = sizeof(struct sctp_auth_chunk) + sctp_get_hmac_digest_len(hmac_algo);
830 	return (SCTP_SIZE32(size));
831 }
832 
833 uint32_t
834 sctp_get_hmac_digest_len(uint16_t hmac_algo)
835 {
836 	switch (hmac_algo) {
837 	case SCTP_AUTH_HMAC_ID_SHA1:
838 		return (SCTP_AUTH_DIGEST_LEN_SHA1);
839 #if defined(SCTP_SUPPORT_HMAC_SHA256)
840 	case SCTP_AUTH_HMAC_ID_SHA256:
841 		return (SCTP_AUTH_DIGEST_LEN_SHA256);
842 #endif
843 	default:
844 		/* unknown HMAC algorithm: can't do anything */
845 		return (0);
846 	} /* end switch */
847 }
848 
849 static inline int
850 sctp_get_hmac_block_len(uint16_t hmac_algo)
851 {
852 	switch (hmac_algo) {
853 	case SCTP_AUTH_HMAC_ID_SHA1:
854 		return (64);
855 #if defined(SCTP_SUPPORT_HMAC_SHA256)
856 	case SCTP_AUTH_HMAC_ID_SHA256:
857 		return (64);
858 #endif
859 	case SCTP_AUTH_HMAC_ID_RSVD:
860 	default:
861 		/* unknown HMAC algorithm: can't do anything */
862 		return (0);
863 	} /* end switch */
864 }
865 
866 #if defined(__Userspace__)
867 /* __Userspace__ SHA1_Init is defined in libcrypto.a (libssl-dev on Ubuntu) */
868 #endif
869 static void
870 sctp_hmac_init(uint16_t hmac_algo, sctp_hash_context_t *ctx)
871 {
872 	switch (hmac_algo) {
873 	case SCTP_AUTH_HMAC_ID_SHA1:
874 		SCTP_SHA1_INIT(&ctx->sha1);
875 		break;
876 #if defined(SCTP_SUPPORT_HMAC_SHA256)
877 	case SCTP_AUTH_HMAC_ID_SHA256:
878 		SCTP_SHA256_INIT(&ctx->sha256);
879 		break;
880 #endif
881 	case SCTP_AUTH_HMAC_ID_RSVD:
882 	default:
883 		/* unknown HMAC algorithm: can't do anything */
884 		return;
885 	} /* end switch */
886 }
887 
888 static void
889 sctp_hmac_update(uint16_t hmac_algo, sctp_hash_context_t *ctx,
890     uint8_t *text, uint32_t textlen)
891 {
892 	switch (hmac_algo) {
893 	case SCTP_AUTH_HMAC_ID_SHA1:
894 		SCTP_SHA1_UPDATE(&ctx->sha1, text, textlen);
895 		break;
896 #if defined(SCTP_SUPPORT_HMAC_SHA256)
897 	case SCTP_AUTH_HMAC_ID_SHA256:
898 		SCTP_SHA256_UPDATE(&ctx->sha256, text, textlen);
899 		break;
900 #endif
901 	case SCTP_AUTH_HMAC_ID_RSVD:
902 	default:
903 		/* unknown HMAC algorithm: can't do anything */
904 		return;
905 	} /* end switch */
906 }
907 
908 static void
909 sctp_hmac_final(uint16_t hmac_algo, sctp_hash_context_t *ctx,
910     uint8_t *digest)
911 {
912 	switch (hmac_algo) {
913 	case SCTP_AUTH_HMAC_ID_SHA1:
914 		SCTP_SHA1_FINAL(digest, &ctx->sha1);
915 		break;
916 #if defined(SCTP_SUPPORT_HMAC_SHA256)
917 	case SCTP_AUTH_HMAC_ID_SHA256:
918 		SCTP_SHA256_FINAL(digest, &ctx->sha256);
919 		break;
920 #endif
921 	case SCTP_AUTH_HMAC_ID_RSVD:
922 	default:
923 		/* unknown HMAC algorithm: can't do anything */
924 		return;
925 	} /* end switch */
926 }
927 
928 /*-
929  * Keyed-Hashing for Message Authentication: FIPS 198 (RFC 2104)
930  *
931  * Compute the HMAC digest using the desired hash key, text, and HMAC
932  * algorithm.  Resulting digest is placed in 'digest' and digest length
933  * is returned, if the HMAC was performed.
934  *
935  * WARNING: it is up to the caller to supply sufficient space to hold the
936  * resultant digest.
937  */
938 uint32_t
939 sctp_hmac(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
940     uint8_t *text, uint32_t textlen, uint8_t *digest)
941 {
942 	uint32_t digestlen;
943 	uint32_t blocklen;
944 	sctp_hash_context_t ctx;
945 	uint8_t ipad[128], opad[128];	/* keyed hash inner/outer pads */
946 	uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
947 	uint32_t i;
948 
949 	/* sanity check the material and length */
950 	if ((key == NULL) || (keylen == 0) || (text == NULL) ||
951 	    (textlen == 0) || (digest == NULL)) {
952 		/* can't do HMAC with empty key or text or digest store */
953 		return (0);
954 	}
955 	/* validate the hmac algo and get the digest length */
956 	digestlen = sctp_get_hmac_digest_len(hmac_algo);
957 	if (digestlen == 0)
958 		return (0);
959 
960 	/* hash the key if it is longer than the hash block size */
961 	blocklen = sctp_get_hmac_block_len(hmac_algo);
962 	if (keylen > blocklen) {
963 		sctp_hmac_init(hmac_algo, &ctx);
964 		sctp_hmac_update(hmac_algo, &ctx, key, keylen);
965 		sctp_hmac_final(hmac_algo, &ctx, temp);
966 		/* set the hashed key as the key */
967 		keylen = digestlen;
968 		key = temp;
969 	}
970 	/* initialize the inner/outer pads with the key and "append" zeroes */
971 	memset(ipad, 0, blocklen);
972 	memset(opad, 0, blocklen);
973 	memcpy(ipad, key, keylen);
974 	memcpy(opad, key, keylen);
975 
976 	/* XOR the key with ipad and opad values */
977 	for (i = 0; i < blocklen; i++) {
978 		ipad[i] ^= 0x36;
979 		opad[i] ^= 0x5c;
980 	}
981 
982 	/* perform inner hash */
983 	sctp_hmac_init(hmac_algo, &ctx);
984 	sctp_hmac_update(hmac_algo, &ctx, ipad, blocklen);
985 	sctp_hmac_update(hmac_algo, &ctx, text, textlen);
986 	sctp_hmac_final(hmac_algo, &ctx, temp);
987 
988 	/* perform outer hash */
989 	sctp_hmac_init(hmac_algo, &ctx);
990 	sctp_hmac_update(hmac_algo, &ctx, opad, blocklen);
991 	sctp_hmac_update(hmac_algo, &ctx, temp, digestlen);
992 	sctp_hmac_final(hmac_algo, &ctx, digest);
993 
994 	return (digestlen);
995 }
996 
997 /* mbuf version */
998 uint32_t
999 sctp_hmac_m(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
1000     struct mbuf *m, uint32_t m_offset, uint8_t *digest, uint32_t trailer)
1001 {
1002 	uint32_t digestlen;
1003 	uint32_t blocklen;
1004 	sctp_hash_context_t ctx;
1005 	uint8_t ipad[128], opad[128];	/* keyed hash inner/outer pads */
1006 	uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
1007 	uint32_t i;
1008 	struct mbuf *m_tmp;
1009 
1010 	/* sanity check the material and length */
1011 	if ((key == NULL) || (keylen == 0) || (m == NULL) || (digest == NULL)) {
1012 		/* can't do HMAC with empty key or text or digest store */
1013 		return (0);
1014 	}
1015 	/* validate the hmac algo and get the digest length */
1016 	digestlen = sctp_get_hmac_digest_len(hmac_algo);
1017 	if (digestlen == 0)
1018 		return (0);
1019 
1020 	/* hash the key if it is longer than the hash block size */
1021 	blocklen = sctp_get_hmac_block_len(hmac_algo);
1022 	if (keylen > blocklen) {
1023 		sctp_hmac_init(hmac_algo, &ctx);
1024 		sctp_hmac_update(hmac_algo, &ctx, key, keylen);
1025 		sctp_hmac_final(hmac_algo, &ctx, temp);
1026 		/* set the hashed key as the key */
1027 		keylen = digestlen;
1028 		key = temp;
1029 	}
1030 	/* initialize the inner/outer pads with the key and "append" zeroes */
1031 	memset(ipad, 0, blocklen);
1032 	memset(opad, 0, blocklen);
1033 	memcpy(ipad, key, keylen);
1034 	memcpy(opad, key, keylen);
1035 
1036 	/* XOR the key with ipad and opad values */
1037 	for (i = 0; i < blocklen; i++) {
1038 		ipad[i] ^= 0x36;
1039 		opad[i] ^= 0x5c;
1040 	}
1041 
1042 	/* perform inner hash */
1043 	sctp_hmac_init(hmac_algo, &ctx);
1044 	sctp_hmac_update(hmac_algo, &ctx, ipad, blocklen);
1045 	/* find the correct starting mbuf and offset (get start of text) */
1046 	m_tmp = m;
1047 	while ((m_tmp != NULL) && (m_offset >= (uint32_t) SCTP_BUF_LEN(m_tmp))) {
1048 		m_offset -= SCTP_BUF_LEN(m_tmp);
1049 		m_tmp = SCTP_BUF_NEXT(m_tmp);
1050 	}
1051 	/* now use the rest of the mbuf chain for the text */
1052 	while (m_tmp != NULL) {
1053 		if ((SCTP_BUF_NEXT(m_tmp) == NULL) && trailer) {
1054 			sctp_hmac_update(hmac_algo, &ctx, mtod(m_tmp, uint8_t *) + m_offset,
1055 					 SCTP_BUF_LEN(m_tmp) - (trailer+m_offset));
1056 		} else {
1057 			sctp_hmac_update(hmac_algo, &ctx, mtod(m_tmp, uint8_t *) + m_offset,
1058 					 SCTP_BUF_LEN(m_tmp) - m_offset);
1059 		}
1060 
1061 		/* clear the offset since it's only for the first mbuf */
1062 		m_offset = 0;
1063 		m_tmp = SCTP_BUF_NEXT(m_tmp);
1064 	}
1065 	sctp_hmac_final(hmac_algo, &ctx, temp);
1066 
1067 	/* perform outer hash */
1068 	sctp_hmac_init(hmac_algo, &ctx);
1069 	sctp_hmac_update(hmac_algo, &ctx, opad, blocklen);
1070 	sctp_hmac_update(hmac_algo, &ctx, temp, digestlen);
1071 	sctp_hmac_final(hmac_algo, &ctx, digest);
1072 
1073 	return (digestlen);
1074 }
1075 
1076 /*
1077  * computes the requested HMAC using a key struct (which may be modified if
1078  * the keylen exceeds the HMAC block len).
1079  */
1080 uint32_t
1081 sctp_compute_hmac(uint16_t hmac_algo, sctp_key_t *key, uint8_t *text,
1082     uint32_t textlen, uint8_t *digest)
1083 {
1084 	uint32_t digestlen;
1085 	uint32_t blocklen;
1086 	sctp_hash_context_t ctx;
1087 	uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
1088 
1089 	/* sanity check */
1090 	if ((key == NULL) || (text == NULL) || (textlen == 0) ||
1091 	    (digest == NULL)) {
1092 		/* can't do HMAC with empty key or text or digest store */
1093 		return (0);
1094 	}
1095 	/* validate the hmac algo and get the digest length */
1096 	digestlen = sctp_get_hmac_digest_len(hmac_algo);
1097 	if (digestlen == 0)
1098 		return (0);
1099 
1100 	/* hash the key if it is longer than the hash block size */
1101 	blocklen = sctp_get_hmac_block_len(hmac_algo);
1102 	if (key->keylen > blocklen) {
1103 		sctp_hmac_init(hmac_algo, &ctx);
1104 		sctp_hmac_update(hmac_algo, &ctx, key->key, key->keylen);
1105 		sctp_hmac_final(hmac_algo, &ctx, temp);
1106 		/* save the hashed key as the new key */
1107 		key->keylen = digestlen;
1108 		memcpy(key->key, temp, key->keylen);
1109 	}
1110 	return (sctp_hmac(hmac_algo, key->key, key->keylen, text, textlen,
1111 	    digest));
1112 }
1113 
1114 /* mbuf version */
1115 uint32_t
1116 sctp_compute_hmac_m(uint16_t hmac_algo, sctp_key_t *key, struct mbuf *m,
1117     uint32_t m_offset, uint8_t *digest)
1118 {
1119 	uint32_t digestlen;
1120 	uint32_t blocklen;
1121 	sctp_hash_context_t ctx;
1122 	uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
1123 
1124 	/* sanity check */
1125 	if ((key == NULL) || (m == NULL) || (digest == NULL)) {
1126 		/* can't do HMAC with empty key or text or digest store */
1127 		return (0);
1128 	}
1129 	/* validate the hmac algo and get the digest length */
1130 	digestlen = sctp_get_hmac_digest_len(hmac_algo);
1131 	if (digestlen == 0)
1132 		return (0);
1133 
1134 	/* hash the key if it is longer than the hash block size */
1135 	blocklen = sctp_get_hmac_block_len(hmac_algo);
1136 	if (key->keylen > blocklen) {
1137 		sctp_hmac_init(hmac_algo, &ctx);
1138 		sctp_hmac_update(hmac_algo, &ctx, key->key, key->keylen);
1139 		sctp_hmac_final(hmac_algo, &ctx, temp);
1140 		/* save the hashed key as the new key */
1141 		key->keylen = digestlen;
1142 		memcpy(key->key, temp, key->keylen);
1143 	}
1144 	return (sctp_hmac_m(hmac_algo, key->key, key->keylen, m, m_offset, digest, 0));
1145 }
1146 
1147 int
1148 sctp_auth_is_supported_hmac(sctp_hmaclist_t *list, uint16_t id)
1149 {
1150 	int i;
1151 
1152 	if ((list == NULL) || (id == SCTP_AUTH_HMAC_ID_RSVD))
1153 		return (0);
1154 
1155 	for (i = 0; i < list->num_algo; i++)
1156 		if (list->hmac[i] == id)
1157 			return (1);
1158 
1159 	/* not in the list */
1160 	return (0);
1161 }
1162 
1163 /*-
1164  * clear any cached key(s) if they match the given key id on an association.
1165  * the cached key(s) will be recomputed and re-cached at next use.
1166  * ASSUMES TCB_LOCK is already held
1167  */
1168 void
1169 sctp_clear_cachedkeys(struct sctp_tcb *stcb, uint16_t keyid)
1170 {
1171 	if (stcb == NULL)
1172 		return;
1173 
1174 	if (keyid == stcb->asoc.authinfo.assoc_keyid) {
1175 		sctp_free_key(stcb->asoc.authinfo.assoc_key);
1176 		stcb->asoc.authinfo.assoc_key = NULL;
1177 	}
1178 	if (keyid == stcb->asoc.authinfo.recv_keyid) {
1179 		sctp_free_key(stcb->asoc.authinfo.recv_key);
1180 		stcb->asoc.authinfo.recv_key = NULL;
1181 	}
1182 }
1183 
1184 /*-
1185  * clear any cached key(s) if they match the given key id for all assocs on
1186  * an endpoint.
1187  * ASSUMES INP_WLOCK is already held
1188  */
1189 void
1190 sctp_clear_cachedkeys_ep(struct sctp_inpcb *inp, uint16_t keyid)
1191 {
1192 	struct sctp_tcb *stcb;
1193 
1194 	if (inp == NULL)
1195 		return;
1196 
1197 	/* clear the cached keys on all assocs on this instance */
1198 	LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
1199 		SCTP_TCB_LOCK(stcb);
1200 		sctp_clear_cachedkeys(stcb, keyid);
1201 		SCTP_TCB_UNLOCK(stcb);
1202 	}
1203 }
1204 
1205 /*-
1206  * delete a shared key from an association
1207  * ASSUMES TCB_LOCK is already held
1208  */
1209 int
1210 sctp_delete_sharedkey(struct sctp_tcb *stcb, uint16_t keyid)
1211 {
1212 	sctp_sharedkey_t *skey;
1213 
1214 	if (stcb == NULL)
1215 		return (-1);
1216 
1217 	/* is the keyid the assoc active sending key */
1218 	if (keyid == stcb->asoc.authinfo.active_keyid)
1219 		return (-1);
1220 
1221 	/* does the key exist? */
1222 	skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
1223 	if (skey == NULL)
1224 		return (-1);
1225 
1226 	/* are there other refcount holders on the key? */
1227 	if (skey->refcount > 1)
1228 		return (-1);
1229 
1230 	/* remove it */
1231 	LIST_REMOVE(skey, next);
1232 	sctp_free_sharedkey(skey);	/* frees skey->key as well */
1233 
1234 	/* clear any cached keys */
1235 	sctp_clear_cachedkeys(stcb, keyid);
1236 	return (0);
1237 }
1238 
1239 /*-
1240  * deletes a shared key from the endpoint
1241  * ASSUMES INP_WLOCK is already held
1242  */
1243 int
1244 sctp_delete_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid)
1245 {
1246 	sctp_sharedkey_t *skey;
1247 
1248 	if (inp == NULL)
1249 		return (-1);
1250 
1251 	/* is the keyid the active sending key on the endpoint */
1252 	if (keyid == inp->sctp_ep.default_keyid)
1253 		return (-1);
1254 
1255 	/* does the key exist? */
1256 	skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
1257 	if (skey == NULL)
1258 		return (-1);
1259 
1260 	/* endpoint keys are not refcounted */
1261 
1262 	/* remove it */
1263 	LIST_REMOVE(skey, next);
1264 	sctp_free_sharedkey(skey);	/* frees skey->key as well */
1265 
1266 	/* clear any cached keys */
1267 	sctp_clear_cachedkeys_ep(inp, keyid);
1268 	return (0);
1269 }
1270 
1271 /*-
1272  * set the active key on an association
1273  * ASSUMES TCB_LOCK is already held
1274  */
1275 int
1276 sctp_auth_setactivekey(struct sctp_tcb *stcb, uint16_t keyid)
1277 {
1278 	sctp_sharedkey_t *skey = NULL;
1279 
1280 	/* find the key on the assoc */
1281 	skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
1282 	if (skey == NULL) {
1283 		/* that key doesn't exist */
1284 		return (-1);
1285 	}
1286 	if ((skey->deactivated) && (skey->refcount > 1)) {
1287 		/* can't reactivate a deactivated key with other refcounts */
1288 		return (-1);
1289 	}
1290 
1291 	/* set the (new) active key */
1292 	stcb->asoc.authinfo.active_keyid = keyid;
1293 	/* reset the deactivated flag */
1294 	skey->deactivated = 0;
1295 
1296 	return (0);
1297 }
1298 
1299 /*-
1300  * set the active key on an endpoint
1301  * ASSUMES INP_WLOCK is already held
1302  */
1303 int
1304 sctp_auth_setactivekey_ep(struct sctp_inpcb *inp, uint16_t keyid)
1305 {
1306 	sctp_sharedkey_t *skey;
1307 
1308 	/* find the key */
1309 	skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
1310 	if (skey == NULL) {
1311 		/* that key doesn't exist */
1312 		return (-1);
1313 	}
1314 	inp->sctp_ep.default_keyid = keyid;
1315 	return (0);
1316 }
1317 
1318 /*-
1319  * deactivates a shared key from the association
1320  * ASSUMES INP_WLOCK is already held
1321  */
1322 int
1323 sctp_deact_sharedkey(struct sctp_tcb *stcb, uint16_t keyid)
1324 {
1325 	sctp_sharedkey_t *skey;
1326 
1327 	if (stcb == NULL)
1328 		return (-1);
1329 
1330 	/* is the keyid the assoc active sending key */
1331 	if (keyid == stcb->asoc.authinfo.active_keyid)
1332 		return (-1);
1333 
1334 	/* does the key exist? */
1335 	skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
1336 	if (skey == NULL)
1337 		return (-1);
1338 
1339 	/* are there other refcount holders on the key? */
1340 	if (skey->refcount == 1) {
1341 		/* no other users, send a notification for this key */
1342 		sctp_ulp_notify(SCTP_NOTIFY_AUTH_FREE_KEY, stcb, keyid, 0,
1343 				SCTP_SO_LOCKED);
1344 	}
1345 
1346 	/* mark the key as deactivated */
1347 	skey->deactivated = 1;
1348 
1349 	return (0);
1350 }
1351 
1352 /*-
1353  * deactivates a shared key from the endpoint
1354  * ASSUMES INP_WLOCK is already held
1355  */
1356 int
1357 sctp_deact_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid)
1358 {
1359 	sctp_sharedkey_t *skey;
1360 
1361 	if (inp == NULL)
1362 		return (-1);
1363 
1364 	/* is the keyid the active sending key on the endpoint */
1365 	if (keyid == inp->sctp_ep.default_keyid)
1366 		return (-1);
1367 
1368 	/* does the key exist? */
1369 	skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
1370 	if (skey == NULL)
1371 		return (-1);
1372 
1373 	/* endpoint keys are not refcounted */
1374 
1375 	/* remove it */
1376 	LIST_REMOVE(skey, next);
1377 	sctp_free_sharedkey(skey);	/* frees skey->key as well */
1378 
1379 	return (0);
1380 }
1381 
1382 /*
1383  * get local authentication parameters from cookie (from INIT-ACK)
1384  */
1385 void
1386 sctp_auth_get_cookie_params(struct sctp_tcb *stcb, struct mbuf *m,
1387     uint32_t offset, uint32_t length)
1388 {
1389 	struct sctp_paramhdr *phdr, tmp_param;
1390 	uint16_t plen, ptype;
1391 	uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
1392 	struct sctp_auth_random *p_random = NULL;
1393 	uint16_t random_len = 0;
1394 	uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
1395 	struct sctp_auth_hmac_algo *hmacs = NULL;
1396 	uint16_t hmacs_len = 0;
1397 	uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
1398 	struct sctp_auth_chunk_list *chunks = NULL;
1399 	uint16_t num_chunks = 0;
1400 	sctp_key_t *new_key;
1401 	uint32_t keylen;
1402 
1403 	/* convert to upper bound */
1404 	length += offset;
1405 
1406 	phdr = (struct sctp_paramhdr *)sctp_m_getptr(m, offset,
1407 	    sizeof(struct sctp_paramhdr), (uint8_t *)&tmp_param);
1408 	while (phdr != NULL) {
1409 		ptype = ntohs(phdr->param_type);
1410 		plen = ntohs(phdr->param_length);
1411 
1412 		if ((plen < sizeof(struct sctp_paramhdr)) ||
1413 		    (offset + plen > length))
1414 			break;
1415 
1416 		if (ptype == SCTP_RANDOM) {
1417 			if (plen > sizeof(random_store))
1418 				break;
1419 			phdr = sctp_get_next_param(m, offset,
1420 			    (struct sctp_paramhdr *)random_store, plen);
1421 			if (phdr == NULL)
1422 				return;
1423 			/* save the random and length for the key */
1424 			p_random = (struct sctp_auth_random *)phdr;
1425 			random_len = plen - sizeof(*p_random);
1426 		} else if (ptype == SCTP_HMAC_LIST) {
1427 			uint16_t num_hmacs;
1428 			uint16_t i;
1429 
1430 			if (plen > sizeof(hmacs_store))
1431 				break;
1432 			phdr = sctp_get_next_param(m, offset,
1433 			    (struct sctp_paramhdr *)hmacs_store, plen);
1434 			if (phdr == NULL)
1435 				return;
1436 			/* save the hmacs list and num for the key */
1437 			hmacs = (struct sctp_auth_hmac_algo *)phdr;
1438 			hmacs_len = plen - sizeof(*hmacs);
1439 			num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
1440 			if (stcb->asoc.local_hmacs != NULL)
1441 				sctp_free_hmaclist(stcb->asoc.local_hmacs);
1442 			stcb->asoc.local_hmacs = sctp_alloc_hmaclist(num_hmacs);
1443 			if (stcb->asoc.local_hmacs != NULL) {
1444 				for (i = 0; i < num_hmacs; i++) {
1445 					(void)sctp_auth_add_hmacid(stcb->asoc.local_hmacs,
1446 					    ntohs(hmacs->hmac_ids[i]));
1447 				}
1448 			}
1449 		} else if (ptype == SCTP_CHUNK_LIST) {
1450 			int i;
1451 
1452 			if (plen > sizeof(chunks_store))
1453 				break;
1454 			phdr = sctp_get_next_param(m, offset,
1455 			    (struct sctp_paramhdr *)chunks_store, plen);
1456 			if (phdr == NULL)
1457 				return;
1458 			chunks = (struct sctp_auth_chunk_list *)phdr;
1459 			num_chunks = plen - sizeof(*chunks);
1460 			/* save chunks list and num for the key */
1461 			if (stcb->asoc.local_auth_chunks != NULL)
1462 				sctp_clear_chunklist(stcb->asoc.local_auth_chunks);
1463 			else
1464 				stcb->asoc.local_auth_chunks = sctp_alloc_chunklist();
1465 			for (i = 0; i < num_chunks; i++) {
1466 				(void)sctp_auth_add_chunk(chunks->chunk_types[i],
1467 				    stcb->asoc.local_auth_chunks);
1468 			}
1469 		}
1470 		/* get next parameter */
1471 		offset += SCTP_SIZE32(plen);
1472 		if (offset + sizeof(struct sctp_paramhdr) > length)
1473 			break;
1474 		phdr = (struct sctp_paramhdr *)sctp_m_getptr(m, offset, sizeof(struct sctp_paramhdr),
1475 		    (uint8_t *)&tmp_param);
1476 	}
1477 	/* concatenate the full random key */
1478 	keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
1479 	if (chunks != NULL) {
1480 		keylen += sizeof(*chunks) + num_chunks;
1481 	}
1482 	new_key = sctp_alloc_key(keylen);
1483 	if (new_key != NULL) {
1484 		/* copy in the RANDOM */
1485 		if (p_random != NULL) {
1486 			keylen = sizeof(*p_random) + random_len;
1487 			memcpy(new_key->key, p_random, keylen);
1488 		} else {
1489 			keylen = 0;
1490 		}
1491 		/* append in the AUTH chunks */
1492 		if (chunks != NULL) {
1493 			memcpy(new_key->key + keylen, chunks,
1494 			       sizeof(*chunks) + num_chunks);
1495 			keylen += sizeof(*chunks) + num_chunks;
1496 		}
1497 		/* append in the HMACs */
1498 		if (hmacs != NULL) {
1499 			memcpy(new_key->key + keylen, hmacs,
1500 			       sizeof(*hmacs) + hmacs_len);
1501 		}
1502 	}
1503 	if (stcb->asoc.authinfo.random != NULL)
1504 		sctp_free_key(stcb->asoc.authinfo.random);
1505 	stcb->asoc.authinfo.random = new_key;
1506 	stcb->asoc.authinfo.random_len = random_len;
1507 	sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
1508 	sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);
1509 
1510 	/* negotiate what HMAC to use for the peer */
1511 	stcb->asoc.peer_hmac_id = sctp_negotiate_hmacid(stcb->asoc.peer_hmacs,
1512 	    stcb->asoc.local_hmacs);
1513 
1514 	/* copy defaults from the endpoint */
1515 	/* FIX ME: put in cookie? */
1516 	stcb->asoc.authinfo.active_keyid = stcb->sctp_ep->sctp_ep.default_keyid;
1517 	/* copy out the shared key list (by reference) from the endpoint */
1518 	(void)sctp_copy_skeylist(&stcb->sctp_ep->sctp_ep.shared_keys,
1519 				 &stcb->asoc.shared_keys);
1520 }
1521 
1522 /*
1523  * compute and fill in the HMAC digest for a packet
1524  */
1525 void
1526 sctp_fill_hmac_digest_m(struct mbuf *m, uint32_t auth_offset,
1527     struct sctp_auth_chunk *auth, struct sctp_tcb *stcb, uint16_t keyid)
1528 {
1529 	uint32_t digestlen;
1530 	sctp_sharedkey_t *skey;
1531 	sctp_key_t *key;
1532 
1533 	if ((stcb == NULL) || (auth == NULL))
1534 		return;
1535 
1536 	/* zero the digest + chunk padding */
1537 	digestlen = sctp_get_hmac_digest_len(stcb->asoc.peer_hmac_id);
1538 	memset(auth->hmac, 0, SCTP_SIZE32(digestlen));
1539 
1540 	/* is the desired key cached? */
1541 	if ((keyid != stcb->asoc.authinfo.assoc_keyid) ||
1542 	    (stcb->asoc.authinfo.assoc_key == NULL)) {
1543 		if (stcb->asoc.authinfo.assoc_key != NULL) {
1544 			/* free the old cached key */
1545 			sctp_free_key(stcb->asoc.authinfo.assoc_key);
1546 		}
1547 		skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
1548 		/* the only way skey is NULL is if null key id 0 is used */
1549 		if (skey != NULL)
1550 			key = skey->key;
1551 		else
1552 			key = NULL;
1553 		/* compute a new assoc key and cache it */
1554 		stcb->asoc.authinfo.assoc_key =
1555 		    sctp_compute_hashkey(stcb->asoc.authinfo.random,
1556 					 stcb->asoc.authinfo.peer_random, key);
1557 		stcb->asoc.authinfo.assoc_keyid = keyid;
1558 		SCTPDBG(SCTP_DEBUG_AUTH1, "caching key id %u\n",
1559 			stcb->asoc.authinfo.assoc_keyid);
1560 #ifdef SCTP_DEBUG
1561 		if (SCTP_AUTH_DEBUG)
1562 			sctp_print_key(stcb->asoc.authinfo.assoc_key,
1563 				       "Assoc Key");
1564 #endif
1565 	}
1566 
1567 	/* set in the active key id */
1568 	auth->shared_key_id = htons(keyid);
1569 
1570 	/* compute and fill in the digest */
1571 	(void)sctp_compute_hmac_m(stcb->asoc.peer_hmac_id, stcb->asoc.authinfo.assoc_key,
1572 				  m, auth_offset, auth->hmac);
1573 }
1574 
1575 static void
1576 sctp_zero_m(struct mbuf *m, uint32_t m_offset, uint32_t size)
1577 {
1578 	struct mbuf *m_tmp;
1579 	uint8_t *data;
1580 
1581 	/* sanity check */
1582 	if (m == NULL)
1583 		return;
1584 
1585 	/* find the correct starting mbuf and offset (get start position) */
1586 	m_tmp = m;
1587 	while ((m_tmp != NULL) && (m_offset >= (uint32_t) SCTP_BUF_LEN(m_tmp))) {
1588 		m_offset -= SCTP_BUF_LEN(m_tmp);
1589 		m_tmp = SCTP_BUF_NEXT(m_tmp);
1590 	}
1591 	/* now use the rest of the mbuf chain */
1592 	while ((m_tmp != NULL) && (size > 0)) {
1593 		data = mtod(m_tmp, uint8_t *) + m_offset;
1594 		if (size > (uint32_t)(SCTP_BUF_LEN(m_tmp) - m_offset)) {
1595 			memset(data, 0, SCTP_BUF_LEN(m_tmp) - m_offset);
1596 			size -= SCTP_BUF_LEN(m_tmp) - m_offset;
1597 		} else {
1598 			memset(data, 0, size);
1599 			size = 0;
1600 		}
1601 		/* clear the offset since it's only for the first mbuf */
1602 		m_offset = 0;
1603 		m_tmp = SCTP_BUF_NEXT(m_tmp);
1604 	}
1605 }
1606 
1607 /*-
1608  * process the incoming Authentication chunk
1609  * return codes:
1610  *   -1 on any authentication error
1611  *    0 on authentication verification
1612  */
1613 int
1614 sctp_handle_auth(struct sctp_tcb *stcb, struct sctp_auth_chunk *auth,
1615     struct mbuf *m, uint32_t offset)
1616 {
1617 	uint16_t chunklen;
1618 	uint16_t shared_key_id;
1619 	uint16_t hmac_id;
1620 	sctp_sharedkey_t *skey;
1621 	uint32_t digestlen;
1622 	uint8_t digest[SCTP_AUTH_DIGEST_LEN_MAX];
1623 	uint8_t computed_digest[SCTP_AUTH_DIGEST_LEN_MAX];
1624 
1625 	/* auth is checked for NULL by caller */
1626 	chunklen = ntohs(auth->ch.chunk_length);
1627 	if (chunklen < sizeof(*auth)) {
1628 		SCTP_STAT_INCR(sctps_recvauthfailed);
1629 		return (-1);
1630 	}
1631 	SCTP_STAT_INCR(sctps_recvauth);
1632 
1633 	/* get the auth params */
1634 	shared_key_id = ntohs(auth->shared_key_id);
1635 	hmac_id = ntohs(auth->hmac_id);
1636 	SCTPDBG(SCTP_DEBUG_AUTH1,
1637 		"SCTP AUTH Chunk: shared key %u, HMAC id %u\n",
1638 		shared_key_id, hmac_id);
1639 
1640 #if defined(__Userspace__) && defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
1641 	return (0);
1642 #endif
1643 	/* is the indicated HMAC supported? */
1644 	if (!sctp_auth_is_supported_hmac(stcb->asoc.local_hmacs, hmac_id)) {
1645 		struct mbuf *op_err;
1646 		struct sctp_error_auth_invalid_hmac *cause;
1647 
1648 		SCTP_STAT_INCR(sctps_recvivalhmacid);
1649 		SCTPDBG(SCTP_DEBUG_AUTH1,
1650 			"SCTP Auth: unsupported HMAC id %u\n",
1651 			hmac_id);
1652 		/*
1653 		 * report this in an Error Chunk: Unsupported HMAC
1654 		 * Identifier
1655 		 */
1656 		op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_error_auth_invalid_hmac),
1657 		                               0, M_NOWAIT, 1, MT_HEADER);
1658 		if (op_err != NULL) {
1659 			/* pre-reserve some space */
1660 			SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
1661 			/* fill in the error */
1662 			cause = mtod(op_err, struct sctp_error_auth_invalid_hmac *);
1663 			cause->cause.code = htons(SCTP_CAUSE_UNSUPPORTED_HMACID);
1664 			cause->cause.length = htons(sizeof(struct sctp_error_auth_invalid_hmac));
1665 			cause->hmac_id = ntohs(hmac_id);
1666 			SCTP_BUF_LEN(op_err) = sizeof(struct sctp_error_auth_invalid_hmac);
1667 			/* queue it */
1668 			sctp_queue_op_err(stcb, op_err);
1669 		}
1670 		return (-1);
1671 	}
1672 	/* get the indicated shared key, if available */
1673 	if ((stcb->asoc.authinfo.recv_key == NULL) ||
1674 	    (stcb->asoc.authinfo.recv_keyid != shared_key_id)) {
1675 		/* find the shared key on the assoc first */
1676 		skey = sctp_find_sharedkey(&stcb->asoc.shared_keys,
1677 					   shared_key_id);
1678 		/* if the shared key isn't found, discard the chunk */
1679 		if (skey == NULL) {
1680 			SCTP_STAT_INCR(sctps_recvivalkeyid);
1681 			SCTPDBG(SCTP_DEBUG_AUTH1,
1682 				"SCTP Auth: unknown key id %u\n",
1683 				shared_key_id);
1684 			return (-1);
1685 		}
1686 		/* generate a notification if this is a new key id */
1687 		if (stcb->asoc.authinfo.recv_keyid != shared_key_id)
1688 			/*
1689 			 * sctp_ulp_notify(SCTP_NOTIFY_AUTH_NEW_KEY, stcb,
1690 			 * shared_key_id, (void
1691 			 * *)stcb->asoc.authinfo.recv_keyid);
1692 			 */
1693 			sctp_notify_authentication(stcb, SCTP_AUTH_NEW_KEY,
1694 			    shared_key_id, stcb->asoc.authinfo.recv_keyid,
1695 			    SCTP_SO_NOT_LOCKED);
1696 		/* compute a new recv assoc key and cache it */
1697 		if (stcb->asoc.authinfo.recv_key != NULL)
1698 			sctp_free_key(stcb->asoc.authinfo.recv_key);
1699 		stcb->asoc.authinfo.recv_key =
1700 		    sctp_compute_hashkey(stcb->asoc.authinfo.random,
1701 		    stcb->asoc.authinfo.peer_random, skey->key);
1702 		stcb->asoc.authinfo.recv_keyid = shared_key_id;
1703 #ifdef SCTP_DEBUG
1704 		if (SCTP_AUTH_DEBUG)
1705 			sctp_print_key(stcb->asoc.authinfo.recv_key, "Recv Key");
1706 #endif
1707 	}
1708 	/* validate the digest length */
1709 	digestlen = sctp_get_hmac_digest_len(hmac_id);
1710 	if (chunklen < (sizeof(*auth) + digestlen)) {
1711 		/* invalid digest length */
1712 		SCTP_STAT_INCR(sctps_recvauthfailed);
1713 		SCTPDBG(SCTP_DEBUG_AUTH1,
1714 			"SCTP Auth: chunk too short for HMAC\n");
1715 		return (-1);
1716 	}
1717 	/* save a copy of the digest, zero the pseudo header, and validate */
1718 	memcpy(digest, auth->hmac, digestlen);
1719 	sctp_zero_m(m, offset + sizeof(*auth), SCTP_SIZE32(digestlen));
1720 	(void)sctp_compute_hmac_m(hmac_id, stcb->asoc.authinfo.recv_key,
1721 	    m, offset, computed_digest);
1722 
1723 	/* compare the computed digest with the one in the AUTH chunk */
1724 	if (timingsafe_bcmp(digest, computed_digest, digestlen) != 0) {
1725 		SCTP_STAT_INCR(sctps_recvauthfailed);
1726 		SCTPDBG(SCTP_DEBUG_AUTH1,
1727 			"SCTP Auth: HMAC digest check failed\n");
1728 		return (-1);
1729 	}
1730 	return (0);
1731 }
1732 
1733 /*
1734  * Generate NOTIFICATION
1735  */
1736 void
1737 sctp_notify_authentication(struct sctp_tcb *stcb, uint32_t indication,
1738 			   uint16_t keyid, uint16_t alt_keyid, int so_locked)
1739 {
1740 	struct mbuf *m_notify;
1741 	struct sctp_authkey_event *auth;
1742 	struct sctp_queued_to_read *control;
1743 
1744 	if ((stcb == NULL) ||
1745 	   (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
1746 	   (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
1747 	   (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET)
1748 		) {
1749 		/* If the socket is gone we are out of here */
1750 		return;
1751 	}
1752 
1753 	if (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_AUTHEVNT))
1754 		/* event not enabled */
1755 		return;
1756 
1757 	m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_authkey_event),
1758 					  0, M_NOWAIT, 1, MT_HEADER);
1759 	if (m_notify == NULL)
1760 		/* no space left */
1761 		return;
1762 
1763 	SCTP_BUF_LEN(m_notify) = 0;
1764 	auth = mtod(m_notify, struct sctp_authkey_event *);
1765 	memset(auth, 0, sizeof(struct sctp_authkey_event));
1766 	auth->auth_type = SCTP_AUTHENTICATION_EVENT;
1767 	auth->auth_flags = 0;
1768 	auth->auth_length = sizeof(*auth);
1769 	auth->auth_keynumber = keyid;
1770 	auth->auth_altkeynumber = alt_keyid;
1771 	auth->auth_indication = indication;
1772 	auth->auth_assoc_id = sctp_get_associd(stcb);
1773 
1774 	SCTP_BUF_LEN(m_notify) = sizeof(*auth);
1775 	SCTP_BUF_NEXT(m_notify) = NULL;
1776 
1777 	/* append to socket */
1778 	control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
1779 	    0, 0, stcb->asoc.context, 0, 0, 0, m_notify);
1780 	if (control == NULL) {
1781 		/* no memory */
1782 		sctp_m_freem(m_notify);
1783 		return;
1784 	}
1785 	control->length = SCTP_BUF_LEN(m_notify);
1786 	control->spec_flags = M_NOTIFICATION;
1787 	/* not that we need this */
1788 	control->tail_mbuf = m_notify;
1789 	sctp_add_to_readq(stcb->sctp_ep, stcb, control,
1790 	    &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, so_locked);
1791 }
1792 
1793 /*-
1794  * validates the AUTHentication related parameters in an INIT/INIT-ACK
1795  * Note: currently only used for INIT as INIT-ACK is handled inline
1796  * with sctp_load_addresses_from_init()
1797  */
1798 int
1799 sctp_validate_init_auth_params(struct mbuf *m, int offset, int limit)
1800 {
1801 	struct sctp_paramhdr *phdr, param_buf;
1802 	uint16_t ptype, plen;
1803 	int peer_supports_asconf = 0;
1804 	int peer_supports_auth = 0;
1805 	int got_random = 0, got_hmacs = 0, got_chklist = 0;
1806 	uint8_t saw_asconf = 0;
1807 	uint8_t saw_asconf_ack = 0;
1808 
1809 	/* go through each of the params. */
1810 	phdr = sctp_get_next_param(m, offset, &param_buf, sizeof(param_buf));
1811 	while (phdr) {
1812 		ptype = ntohs(phdr->param_type);
1813 		plen = ntohs(phdr->param_length);
1814 
1815 		if (offset + plen > limit) {
1816 			break;
1817 		}
1818 		if (plen < sizeof(struct sctp_paramhdr)) {
1819 			break;
1820 		}
1821 		if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
1822 			/* A supported extension chunk */
1823 			struct sctp_supported_chunk_types_param *pr_supported;
1824 			uint8_t local_store[SCTP_SMALL_CHUNK_STORE];
1825 			int num_ent, i;
1826 
1827 			if (plen > sizeof(local_store)) {
1828 				break;
1829 			}
1830 			phdr = sctp_get_next_param(m, offset,
1831 			                           (struct sctp_paramhdr *)&local_store,
1832 			                           plen);
1833 			if (phdr == NULL) {
1834 				return (-1);
1835 			}
1836 			pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
1837 			num_ent = plen - sizeof(struct sctp_paramhdr);
1838 			for (i = 0; i < num_ent; i++) {
1839 				switch (pr_supported->chunk_types[i]) {
1840 				case SCTP_ASCONF:
1841 				case SCTP_ASCONF_ACK:
1842 					peer_supports_asconf = 1;
1843 					break;
1844 				default:
1845 					/* one we don't care about */
1846 					break;
1847 				}
1848 			}
1849 		} else if (ptype == SCTP_RANDOM) {
1850 			/* enforce the random length */
1851 			if (plen != (sizeof(struct sctp_auth_random) +
1852 				     SCTP_AUTH_RANDOM_SIZE_REQUIRED)) {
1853 				SCTPDBG(SCTP_DEBUG_AUTH1,
1854 					"SCTP: invalid RANDOM len\n");
1855 				return (-1);
1856 			}
1857 			got_random = 1;
1858 		} else if (ptype == SCTP_HMAC_LIST) {
1859 			struct sctp_auth_hmac_algo *hmacs;
1860 			uint8_t store[SCTP_PARAM_BUFFER_SIZE];
1861 			int num_hmacs;
1862 
1863 			if (plen > sizeof(store)) {
1864 				break;
1865 			}
1866 			phdr = sctp_get_next_param(m, offset,
1867 			                           (struct sctp_paramhdr *)store,
1868 			                           plen);
1869 			if (phdr == NULL) {
1870 				return (-1);
1871 			}
1872 			hmacs = (struct sctp_auth_hmac_algo *)phdr;
1873 			num_hmacs = (plen - sizeof(*hmacs)) / sizeof(hmacs->hmac_ids[0]);
1874 			/* validate the hmac list */
1875 			if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
1876 				SCTPDBG(SCTP_DEBUG_AUTH1,
1877 					"SCTP: invalid HMAC param\n");
1878 				return (-1);
1879 			}
1880 			got_hmacs = 1;
1881 		} else if (ptype == SCTP_CHUNK_LIST) {
1882 			struct sctp_auth_chunk_list *chunks;
1883 			uint8_t chunks_store[SCTP_SMALL_CHUNK_STORE];
1884 			int i, num_chunks;
1885 
1886 			if (plen > sizeof(chunks_store)) {
1887 				break;
1888 			}
1889 			phdr = sctp_get_next_param(m, offset,
1890 						   (struct sctp_paramhdr *)chunks_store,
1891 						   plen);
1892 			if (phdr == NULL) {
1893 				return (-1);
1894 			}
1895 			/*-
1896 			 * Flip through the list and mark that the
1897 			 * peer supports asconf/asconf_ack.
1898 			 */
1899 			chunks = (struct sctp_auth_chunk_list *)phdr;
1900 			num_chunks = plen - sizeof(*chunks);
1901 			for (i = 0; i < num_chunks; i++) {
1902 				/* record asconf/asconf-ack if listed */
1903 				if (chunks->chunk_types[i] == SCTP_ASCONF)
1904 					saw_asconf = 1;
1905 				if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
1906 					saw_asconf_ack = 1;
1907 			}
1908 			if (num_chunks)
1909 				got_chklist = 1;
1910 		}
1911 
1912 		offset += SCTP_SIZE32(plen);
1913 		if (offset >= limit) {
1914 			break;
1915 		}
1916 		phdr = sctp_get_next_param(m, offset, &param_buf,
1917 		    sizeof(param_buf));
1918 	}
1919 	/* validate authentication required parameters */
1920 	if (got_random && got_hmacs) {
1921 		peer_supports_auth = 1;
1922 	} else {
1923 		peer_supports_auth = 0;
1924 	}
1925 	if (!peer_supports_auth && got_chklist) {
1926 		SCTPDBG(SCTP_DEBUG_AUTH1,
1927 			"SCTP: peer sent chunk list w/o AUTH\n");
1928 		return (-1);
1929 	}
1930 	if (peer_supports_asconf && !peer_supports_auth) {
1931 		SCTPDBG(SCTP_DEBUG_AUTH1,
1932 			"SCTP: peer supports ASCONF but not AUTH\n");
1933 		return (-1);
1934 	} else if ((peer_supports_asconf) && (peer_supports_auth) &&
1935 		   ((saw_asconf == 0) || (saw_asconf_ack == 0))) {
1936 		return (-2);
1937 	}
1938 	return (0);
1939 }
1940 
1941 void
1942 sctp_initialize_auth_params(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
1943 {
1944 	uint16_t chunks_len = 0;
1945 	uint16_t hmacs_len = 0;
1946 	uint16_t random_len = SCTP_AUTH_RANDOM_SIZE_DEFAULT;
1947 	sctp_key_t *new_key;
1948 	uint16_t keylen;
1949 
1950 	/* initialize hmac list from endpoint */
1951 	stcb->asoc.local_hmacs = sctp_copy_hmaclist(inp->sctp_ep.local_hmacs);
1952 	if (stcb->asoc.local_hmacs != NULL) {
1953 		hmacs_len = stcb->asoc.local_hmacs->num_algo *
1954 		    sizeof(stcb->asoc.local_hmacs->hmac[0]);
1955 	}
1956 	/* initialize auth chunks list from endpoint */
1957 	stcb->asoc.local_auth_chunks =
1958 	    sctp_copy_chunklist(inp->sctp_ep.local_auth_chunks);
1959 	if (stcb->asoc.local_auth_chunks != NULL) {
1960 		int i;
1961 		for (i = 0; i < 256; i++) {
1962 			if (stcb->asoc.local_auth_chunks->chunks[i])
1963 				chunks_len++;
1964 		}
1965 	}
1966 	/* copy defaults from the endpoint */
1967 	stcb->asoc.authinfo.active_keyid = inp->sctp_ep.default_keyid;
1968 
1969 	/* copy out the shared key list (by reference) from the endpoint */
1970 	(void)sctp_copy_skeylist(&inp->sctp_ep.shared_keys,
1971 				 &stcb->asoc.shared_keys);
1972 
1973 	/* now set the concatenated key (random + chunks + hmacs) */
1974 	/* key includes parameter headers */
1975 	keylen = (3 * sizeof(struct sctp_paramhdr)) + random_len + chunks_len +
1976 	    hmacs_len;
1977 	new_key = sctp_alloc_key(keylen);
1978 	if (new_key != NULL) {
1979 		struct sctp_paramhdr *ph;
1980 		int plen;
1981 		/* generate and copy in the RANDOM */
1982 		ph = (struct sctp_paramhdr *)new_key->key;
1983 		ph->param_type = htons(SCTP_RANDOM);
1984 		plen = sizeof(*ph) + random_len;
1985 		ph->param_length = htons(plen);
1986 		SCTP_READ_RANDOM(new_key->key + sizeof(*ph), random_len);
1987 		keylen = plen;
1988 
1989 		/* append in the AUTH chunks */
1990 		/* NOTE: currently we always have chunks to list */
1991 		ph = (struct sctp_paramhdr *)(new_key->key + keylen);
1992 		ph->param_type = htons(SCTP_CHUNK_LIST);
1993 		plen = sizeof(*ph) + chunks_len;
1994 		ph->param_length = htons(plen);
1995 		keylen += sizeof(*ph);
1996 		if (stcb->asoc.local_auth_chunks) {
1997 			int i;
1998 			for (i = 0; i < 256; i++) {
1999 				if (stcb->asoc.local_auth_chunks->chunks[i])
2000 					new_key->key[keylen++] = i;
2001 			}
2002 		}
2003 
2004 		/* append in the HMACs */
2005 		ph = (struct sctp_paramhdr *)(new_key->key + keylen);
2006 		ph->param_type = htons(SCTP_HMAC_LIST);
2007 		plen = sizeof(*ph) + hmacs_len;
2008 		ph->param_length = htons(plen);
2009 		keylen += sizeof(*ph);
2010 		(void)sctp_serialize_hmaclist(stcb->asoc.local_hmacs,
2011 					new_key->key + keylen);
2012 	}
2013 	if (stcb->asoc.authinfo.random != NULL)
2014 	    sctp_free_key(stcb->asoc.authinfo.random);
2015 	stcb->asoc.authinfo.random = new_key;
2016 	stcb->asoc.authinfo.random_len = random_len;
2017 }
2018 
2019 
2020 #ifdef SCTP_HMAC_TEST
2021 /*
2022  * HMAC and key concatenation tests
2023  */
2024 static void
2025 sctp_print_digest(uint8_t *digest, uint32_t digestlen, const char *str)
2026 {
2027 	uint32_t i;
2028 
2029 	SCTP_PRINTF("\n%s: 0x", str);
2030 	if (digest == NULL)
2031 		return;
2032 
2033 	for (i = 0; i < digestlen; i++)
2034 		SCTP_PRINTF("%02x", digest[i]);
2035 }
2036 
2037 static int
2038 sctp_test_hmac(const char *str, uint16_t hmac_id, uint8_t *key,
2039     uint32_t keylen, uint8_t *text, uint32_t textlen,
2040     uint8_t *digest, uint32_t digestlen)
2041 {
2042 	uint8_t computed_digest[SCTP_AUTH_DIGEST_LEN_MAX];
2043 
2044 	SCTP_PRINTF("\n%s:", str);
2045 	sctp_hmac(hmac_id, key, keylen, text, textlen, computed_digest);
2046 	sctp_print_digest(digest, digestlen, "Expected digest");
2047 	sctp_print_digest(computed_digest, digestlen, "Computed digest");
2048 	if (memcmp(digest, computed_digest, digestlen) != 0) {
2049 		SCTP_PRINTF("\nFAILED");
2050 		return (-1);
2051 	} else {
2052 		SCTP_PRINTF("\nPASSED");
2053 		return (0);
2054 	}
2055 }
2056 
2057 
2058 /*
2059  * RFC 2202: HMAC-SHA1 test cases
2060  */
2061 void
2062 sctp_test_hmac_sha1(void)
2063 {
2064 	uint8_t *digest;
2065 	uint8_t key[128];
2066 	uint32_t keylen;
2067 	uint8_t text[128];
2068 	uint32_t textlen;
2069 	uint32_t digestlen = 20;
2070 	int failed = 0;
2071 
2072 	/*-
2073 	 * test_case =     1
2074 	 * key =           0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
2075 	 * key_len =       20
2076 	 * data =          "Hi There"
2077 	 * data_len =      8
2078 	 * digest =        0xb617318655057264e28bc0b6fb378c8ef146be00
2079 	 */
2080 	keylen = 20;
2081 	memset(key, 0x0b, keylen);
2082 	textlen = 8;
2083 	strcpy(text, "Hi There");
2084 	digest = "\xb6\x17\x31\x86\x55\x05\x72\x64\xe2\x8b\xc0\xb6\xfb\x37\x8c\x8e\xf1\x46\xbe\x00";
2085 	if (sctp_test_hmac("SHA1 test case 1", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
2086 	    text, textlen, digest, digestlen) < 0)
2087 		failed++;
2088 
2089 	/*-
2090 	 * test_case =     2
2091 	 * key =           "Jefe"
2092 	 * key_len =       4
2093 	 * data =          "what do ya want for nothing?"
2094 	 * data_len =      28
2095 	 * digest =        0xeffcdf6ae5eb2fa2d27416d5f184df9c259a7c79
2096 	 */
2097 	keylen = 4;
2098 	strcpy(key, "Jefe");
2099 	textlen = 28;
2100 	strcpy(text, "what do ya want for nothing?");
2101 	digest = "\xef\xfc\xdf\x6a\xe5\xeb\x2f\xa2\xd2\x74\x16\xd5\xf1\x84\xdf\x9c\x25\x9a\x7c\x79";
2102 	if (sctp_test_hmac("SHA1 test case 2", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
2103 	    text, textlen, digest, digestlen) < 0)
2104 		failed++;
2105 
2106 	/*-
2107 	 * test_case =     3
2108 	 * key =           0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
2109 	 * key_len =       20
2110 	 * data =          0xdd repeated 50 times
2111 	 * data_len =      50
2112 	 * digest =        0x125d7342b9ac11cd91a39af48aa17b4f63f175d3
2113 	 */
2114 	keylen = 20;
2115 	memset(key, 0xaa, keylen);
2116 	textlen = 50;
2117 	memset(text, 0xdd, textlen);
2118 	digest = "\x12\x5d\x73\x42\xb9\xac\x11\xcd\x91\xa3\x9a\xf4\x8a\xa1\x7b\x4f\x63\xf1\x75\xd3";
2119 	if (sctp_test_hmac("SHA1 test case 3", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
2120 	    text, textlen, digest, digestlen) < 0)
2121 		failed++;
2122 
2123 	/*-
2124 	 * test_case =     4
2125 	 * key =           0x0102030405060708090a0b0c0d0e0f10111213141516171819
2126 	 * key_len =       25
2127 	 * data =          0xcd repeated 50 times
2128 	 * data_len =      50
2129 	 * digest =        0x4c9007f4026250c6bc8414f9bf50c86c2d7235da
2130 	 */
2131 	keylen = 25;
2132 	memcpy(key, "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", keylen);
2133 	textlen = 50;
2134 	memset(text, 0xcd, textlen);
2135 	digest = "\x4c\x90\x07\xf4\x02\x62\x50\xc6\xbc\x84\x14\xf9\xbf\x50\xc8\x6c\x2d\x72\x35\xda";
2136 	if (sctp_test_hmac("SHA1 test case 4", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
2137 	    text, textlen, digest, digestlen) < 0)
2138 		failed++;
2139 
2140 	/*-
2141 	 * test_case =     5
2142 	 * key =           0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
2143 	 * key_len =       20
2144 	 * data =          "Test With Truncation"
2145 	 * data_len =      20
2146 	 * digest =        0x4c1a03424b55e07fe7f27be1d58bb9324a9a5a04
2147 	 * digest-96 =     0x4c1a03424b55e07fe7f27be1
2148 	 */
2149 	keylen = 20;
2150 	memset(key, 0x0c, keylen);
2151 	textlen = 20;
2152 	strcpy(text, "Test With Truncation");
2153 	digest = "\x4c\x1a\x03\x42\x4b\x55\xe0\x7f\xe7\xf2\x7b\xe1\xd5\x8b\xb9\x32\x4a\x9a\x5a\x04";
2154 	if (sctp_test_hmac("SHA1 test case 5", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
2155 	    text, textlen, digest, digestlen) < 0)
2156 		failed++;
2157 
2158 	/*-
2159 	 * test_case =     6
2160 	 * key =           0xaa repeated 80 times
2161 	 * key_len =       80
2162 	 * data =          "Test Using Larger Than Block-Size Key - Hash Key First"
2163 	 * data_len =      54
2164 	 * digest =        0xaa4ae5e15272d00e95705637ce8a3b55ed402112
2165 	 */
2166 	keylen = 80;
2167 	memset(key, 0xaa, keylen);
2168 	textlen = 54;
2169 	strcpy(text, "Test Using Larger Than Block-Size Key - Hash Key First");
2170 	digest = "\xaa\x4a\xe5\xe1\x52\x72\xd0\x0e\x95\x70\x56\x37\xce\x8a\x3b\x55\xed\x40\x21\x12";
2171 	if (sctp_test_hmac("SHA1 test case 6", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
2172 	    text, textlen, digest, digestlen) < 0)
2173 		failed++;
2174 
2175 	/*-
2176 	 * test_case =     7
2177 	 * key =           0xaa repeated 80 times
2178 	 * key_len =       80
2179 	 * data =          "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"
2180 	 * data_len =      73
2181 	 * digest =        0xe8e99d0f45237d786d6bbaa7965c7808bbff1a91
2182 	 */
2183 	keylen = 80;
2184 	memset(key, 0xaa, keylen);
2185 	textlen = 73;
2186 	strcpy(text, "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data");
2187 	digest = "\xe8\xe9\x9d\x0f\x45\x23\x7d\x78\x6d\x6b\xba\xa7\x96\x5c\x78\x08\xbb\xff\x1a\x91";
2188 	if (sctp_test_hmac("SHA1 test case 7", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
2189 	    text, textlen, digest, digestlen) < 0)
2190 		failed++;
2191 
2192 	/* done with all tests */
2193 	if (failed)
2194 		SCTP_PRINTF("\nSHA1 test results: %d cases failed", failed);
2195 	else
2196 		SCTP_PRINTF("\nSHA1 test results: all test cases passed");
2197 }
2198 
2199 /*
2200  * test assoc key concatenation
2201  */
2202 static int
2203 sctp_test_key_concatenation(sctp_key_t *key1, sctp_key_t *key2,
2204     sctp_key_t *expected_key)
2205 {
2206 	sctp_key_t *key;
2207 	int ret_val;
2208 
2209 	sctp_show_key(key1, "\nkey1");
2210 	sctp_show_key(key2, "\nkey2");
2211 	key = sctp_compute_hashkey(key1, key2, NULL);
2212 	sctp_show_key(expected_key, "\nExpected");
2213 	sctp_show_key(key, "\nComputed");
2214 	if (memcmp(key, expected_key, expected_key->keylen) != 0) {
2215 		SCTP_PRINTF("\nFAILED");
2216 		ret_val = -1;
2217 	} else {
2218 		SCTP_PRINTF("\nPASSED");
2219 		ret_val = 0;
2220 	}
2221 	sctp_free_key(key1);
2222 	sctp_free_key(key2);
2223 	sctp_free_key(expected_key);
2224 	sctp_free_key(key);
2225 	return (ret_val);
2226 }
2227 
2228 
2229 void
2230 sctp_test_authkey(void)
2231 {
2232 	sctp_key_t *key1, *key2, *expected_key;
2233 	int failed = 0;
2234 
2235 	/* test case 1 */
2236 	key1 = sctp_set_key("\x01\x01\x01\x01", 4);
2237 	key2 = sctp_set_key("\x01\x02\x03\x04", 4);
2238 	expected_key = sctp_set_key("\x01\x01\x01\x01\x01\x02\x03\x04", 8);
2239 	if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
2240 		failed++;
2241 
2242 	/* test case 2 */
2243 	key1 = sctp_set_key("\x00\x00\x00\x01", 4);
2244 	key2 = sctp_set_key("\x02", 1);
2245 	expected_key = sctp_set_key("\x00\x00\x00\x01\x02", 5);
2246 	if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
2247 		failed++;
2248 
2249 	/* test case 3 */
2250 	key1 = sctp_set_key("\x01", 1);
2251 	key2 = sctp_set_key("\x00\x00\x00\x02", 4);
2252 	expected_key = sctp_set_key("\x01\x00\x00\x00\x02", 5);
2253 	if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
2254 		failed++;
2255 
2256 	/* test case 4 */
2257 	key1 = sctp_set_key("\x00\x00\x00\x01", 4);
2258 	key2 = sctp_set_key("\x01", 1);
2259 	expected_key = sctp_set_key("\x01\x00\x00\x00\x01", 5);
2260 	if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
2261 		failed++;
2262 
2263 	/* test case 5 */
2264 	key1 = sctp_set_key("\x01", 1);
2265 	key2 = sctp_set_key("\x00\x00\x00\x01", 4);
2266 	expected_key = sctp_set_key("\x01\x00\x00\x00\x01", 5);
2267 	if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
2268 		failed++;
2269 
2270 	/* test case 6 */
2271 	key1 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07", 11);
2272 	key2 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 11);
2273 	expected_key = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 22);
2274 	if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
2275 		failed++;
2276 
2277 	/* test case 7 */
2278 	key1 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 11);
2279 	key2 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07", 11);
2280 	expected_key = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 22);
2281 	if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
2282 		failed++;
2283 
2284 	/* done with all tests */
2285 	if (failed)
2286 		SCTP_PRINTF("\nKey concatenation test results: %d cases failed", failed);
2287 	else
2288 		SCTP_PRINTF("\nKey concatenation test results: all test cases passed");
2289 }
2290 
2291 
2292 #if defined(STANDALONE_HMAC_TEST)
2293 int
2294 main(void)
2295 {
2296 	sctp_test_hmac_sha1();
2297 	sctp_test_authkey();
2298 }
2299 
2300 #endif /* STANDALONE_HMAC_TEST */
2301 
2302 #endif /* SCTP_HMAC_TEST */
2303