Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
/*	$NetBSD: portalgo.c,v 1.15 2022/11/04 09:01:53 ozaki-r Exp $	*/

/*
 * Copyright 2011 Vlad Balan
 *
 * Written by Vlad Balan for the NetBSD Foundation.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

/*
 * see:
 *	RFC 6056 Recommendations for Transport-Protocol Port Randomization
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: portalgo.c,v 1.15 2022/11/04 09:01:53 ozaki-r Exp $");

#ifdef _KERNEL_OPT
#include "opt_inet.h"
#endif

#include <sys/param.h>
#include <sys/errno.h>
#include <sys/kauth.h>
#include <sys/uidinfo.h>
#include <sys/md5.h>
#include <sys/cprng.h>
#include <sys/bitops.h>

#include <net/if.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/in_var.h>
#include <netinet/ip_var.h>

#ifdef INET6
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#include <netinet6/in6_pcb.h>
#endif

#include <netinet/tcp_vtw.h>

#include "portalgo.h"

#define NPROTO 2
#define PORTALGO_TCP 0
#define PORTALGO_UDP 1

#define NAF 2
#define PORTALGO_IPV4 0
#define PORTALGO_IPV6 1

#define NRANGES 2
#define PORTALGO_LOWPORT 0
#define PORTALGO_HIGHPORT 1

#if PORTALGO_DEBUG
static bool portalgo_debug = true;
#define DPRINTF if (portalgo_debug) printf
#else
#define DPRINTF while (/*CONSTCOND*/0) printf
#endif

#ifndef PORTALGO_INET4_DEFAULT
#define PORTALGO_INET4_DEFAULT PORTALGO_BSD
#endif
#ifndef PORTALGO_INET6_DEFAULT
#define PORTALGO_INET6_DEFAULT PORTALGO_BSD
#endif

typedef __BITMAP_TYPE(, uint32_t, 0x10000) bitmap;
#ifdef INET
static int inet4_portalgo = PORTALGO_INET4_DEFAULT;
static bitmap inet4_reserve;
#endif
#ifdef INET6
static int inet6_portalgo = PORTALGO_INET6_DEFAULT;
static bitmap inet6_reserve;
#endif

typedef struct {
	const char *name;
	int (*func)(int, uint16_t *, struct inpcb *, kauth_cred_t);
} portalgo_algorithm_t;

static int algo_bsd(int, uint16_t *, struct inpcb *, kauth_cred_t);
static int algo_random_start(int, uint16_t *, struct inpcb *, kauth_cred_t);
static int algo_random_pick(int, uint16_t *, struct inpcb *, kauth_cred_t);
static int algo_hash(int, uint16_t *, struct inpcb *, kauth_cred_t);
static int algo_doublehash(int, uint16_t *, struct inpcb *, kauth_cred_t);
static int algo_randinc(int, uint16_t *, struct inpcb *, kauth_cred_t);

static const portalgo_algorithm_t algos[] = {
	{
		.name = "bsd",
		.func = algo_bsd
	},
	{
		.name = "random_start",
		.func = algo_random_start
	},
	{
		.name = "random_pick",
		.func = algo_random_pick
	},
	{
		.name = "hash",
		.func = algo_hash
	},
	{
		.name = "doublehash",
		.func = algo_doublehash
	},
	{
		.name = "randinc",
		.func = algo_randinc
	}
};

#define NALGOS __arraycount(algos)

static uint16_t portalgo_next_ephemeral[NPROTO][NAF][NRANGES][NALGOS];

/*
 * Access the pcb and copy the values of the last port and the ends of
 * the port range.
 */
static int
pcb_getports(struct inpcb *inp, uint16_t *lastport,
    uint16_t *mymin, uint16_t *mymax, uint16_t **pnext_ephemeral, int algo)
{
	struct inpcbtable * const table = inp->inp_table;
	struct socket *so;
	int portalgo_proto;
	int portalgo_af;
	int portalgo_range;

	so = inp->inp_socket;
	switch (so->so_type) {
	case SOCK_DGRAM: /* UDP or DCCP */
	case SOCK_CONN_DGRAM:
		portalgo_proto = PORTALGO_UDP;
		break;
	case SOCK_STREAM: /* TCP or SCTP */
		portalgo_proto = PORTALGO_TCP;
		break;
	default:
		return EPFNOSUPPORT;
	}

	switch (inp->inp_af) {
#ifdef INET
	case AF_INET: {
		portalgo_af = PORTALGO_IPV4;
		if (inp->inp_flags & INP_LOWPORT) {
			*mymin = lowportmin;
			*mymax = lowportmax;
			*lastport = table->inpt_lastlow;
			portalgo_range = PORTALGO_LOWPORT;
		} else {
			*mymin = anonportmin;
			*mymax = anonportmax;
			*lastport = table->inpt_lastport;
			portalgo_range = PORTALGO_HIGHPORT;
		}
		break;
	}
#endif
#ifdef INET6
	case AF_INET6: {
		portalgo_af = PORTALGO_IPV6;
		if (inp->inp_flags & IN6P_LOWPORT) {
			*mymin = ip6_lowportmin;
			*mymax = ip6_lowportmax;
			*lastport = table->inpt_lastlow;
			portalgo_range = PORTALGO_LOWPORT;
		} else {
			*mymin = ip6_anonportmin;
			*mymax = ip6_anonportmax;
			*lastport = table->inpt_lastport;
			portalgo_range = PORTALGO_HIGHPORT;
		}
		break;
	}
#endif
	default:
		return EAFNOSUPPORT;
	}

	if (*mymin > *mymax) {	/* sanity check */
		u_int16_t swp;

		swp = *mymin;
		*mymin = *mymax;
		*mymax = swp;
	}

	DPRINTF("%s mymin:%d mymax:%d lastport:%d\n", __func__,
	    *mymin, *mymax, *lastport);

	*pnext_ephemeral = &portalgo_next_ephemeral[portalgo_proto]
	    [portalgo_af][portalgo_range][algo];

	DPRINTF("%s portalgo_proto:%d portalgo_af:%d portalgo_range:%d\n",
	    __func__, portalgo_proto, portalgo_af, portalgo_range);
	return 0;
}

/*
 * Check whether the port picked by the port randomizer is available
 * and whether KAUTH approves of our choice. This part of the code
 * shamelessly copied from in_pcb.c.
 */
static bool
check_suitable_port(uint16_t port, struct inpcb *inp, kauth_cred_t cred)
{
	struct inpcbtable * const table = inp->inp_table;
#ifdef INET
	vestigial_inpcb_t vestigial;
#endif
	int error;
#ifdef INET6
	struct socket *so;
	int wild = 0;
#endif

	DPRINTF("%s called for argument %d\n", __func__, port);

	switch (inp->inp_af) {
#ifdef INET
	case AF_INET: { /* IPv4 */
		struct inpcb *pcb;
		struct sockaddr_in sin;

		if (__BITMAP_ISSET(port, &inet4_reserve))
			return false;

		sin.sin_addr = in4p_laddr(inp);
		pcb = inpcb_lookup_local(table, sin.sin_addr, htons(port), 1,
		    &vestigial);

		DPRINTF("%s inpcb_lookup_local returned %p and "
		    "vestigial.valid %d\n",
		    __func__, pcb, vestigial.valid);

		if ((!pcb) && (!vestigial.valid)) {
			enum kauth_network_req req;

			/* We have a free port. Check with the secmodel. */
			if (inp->inp_flags & INP_LOWPORT) {
#ifndef IPNOPRIVPORTS
				req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
#else
				req = KAUTH_REQ_NETWORK_BIND_PORT;
#endif
			} else
				req = KAUTH_REQ_NETWORK_BIND_PORT;

			sin.sin_port = port;
			error = kauth_authorize_network(cred,
			    KAUTH_NETWORK_BIND,
			    req, inp->inp_socket, &sin, NULL);
			DPRINTF("%s kauth_authorize_network returned %d\n",
			    __func__, error);

			if (error == 0) {
				DPRINTF("%s port approved\n", __func__);
				return true;	/* KAUTH agrees */
			}
		}
		break;
	}
#endif
#ifdef INET6
	case AF_INET6: { /* IPv6 */
		struct sockaddr_in6 sin6;
		void *t;

		if (__BITMAP_ISSET(port, &inet6_reserve))
			return false;

		sin6.sin6_addr = in6p_laddr(inp);
		so = inp->inp_socket;

		/* XXX: this is redundant when called from in6pcb_bind */
		if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0 &&
		    ((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0 ||
			(so->so_options & SO_ACCEPTCONN) == 0))
			wild = 1;

#ifdef INET
		if (IN6_IS_ADDR_V4MAPPED(&sin6.sin6_addr)) {
			t = inpcb_lookup_local(table,
			    *(struct in_addr *)&sin6.sin6_addr.s6_addr32[3],
			    htons(port), wild, &vestigial);
			if (!t && vestigial.valid) {
				DPRINTF("%s inpcb_lookup_local returned "
				    "a result\n", __func__);
				return false;
			}
		} else
#endif
		{
			t = in6pcb_lookup_local(table, &sin6.sin6_addr,
			    htons(port), wild, &vestigial);
			if (!t && vestigial.valid) {
				DPRINTF("%s in6pcb_lookup_local returned "
				    "a result\n", __func__);
				return false;
			}
		}
		if (t == NULL) {
			enum kauth_network_req req;

			/* We have a free port. Check with the secmodel. */
			if (inp->inp_flags & IN6P_LOWPORT) {
#ifndef IPNOPRIVPORTS
				req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
#else
				req = KAUTH_REQ_NETWORK_BIND_PORT;
#endif
			} else {
				req = KAUTH_REQ_NETWORK_BIND_PORT;
			}

			sin6.sin6_port = port;
			error = kauth_authorize_network(cred,
			    KAUTH_NETWORK_BIND, req, so, &sin6, NULL);
			if (error) {
				/* Secmodel says no. Keep looking. */
				DPRINTF("%s secmodel says no\n", __func__);
				return false;
			}
			DPRINTF("%s port approved\n", __func__);
			return true;
		}
		break;
	}
#endif
	default:
		DPRINTF("%s unknown address family\n", __func__);
		return false;
	}
	return false;
}

/* This is the default BSD algorithm, as described in RFC 6056 */
static int
algo_bsd(int algo, uint16_t *port, struct inpcb *inp, kauth_cred_t cred)
{
	uint16_t count;
	uint16_t mymin, mymax, lastport;
	uint16_t *next_ephemeral;
	int error;

	DPRINTF("%s called\n", __func__);
	error = pcb_getports(inp, &lastport, &mymin, &mymax,
	    &next_ephemeral, algo);
	if (error)
		return error;
	count = mymax - mymin + 1;
	do {
		uint16_t myport = *next_ephemeral;

		if (myport < mymin || mymax < myport)
			myport = mymax;
		*next_ephemeral = myport - 1;
		if (check_suitable_port(myport, inp, cred)) {
			*port = myport;
			DPRINTF("%s returning port %d\n", __func__, *port);
			return 0;
		}
		count--;
	} while (count > 0);

	DPRINTF("%s returning EAGAIN\n", __func__);
	return EAGAIN;
}

/*
 * The straightforward algorithm that increments the port number
 * by a random amount.
 */
static int
algo_random_start(int algo, uint16_t *port, struct inpcb *inp,
    kauth_cred_t cred)
{
	uint16_t count, num_ephemeral;
	uint16_t mymin, mymax, lastport;
	uint16_t *next_ephemeral;
	int error;

	DPRINTF("%s called\n", __func__);

	error = pcb_getports(inp, &lastport, &mymin, &mymax,
	    &next_ephemeral, algo);
	if (error)
		return error;

	num_ephemeral = mymax - mymin + 1;

	DPRINTF("num_ephemeral: %u\n", num_ephemeral);

	*next_ephemeral = mymin + (cprng_fast32() % num_ephemeral);

	DPRINTF("next_ephemeral initially: %u\n", *next_ephemeral);

	count = num_ephemeral;

	do {
		if (check_suitable_port(*next_ephemeral, inp, cred)) {
			*port = *next_ephemeral;
			DPRINTF("%s returning port %d\n", __func__, *port);
			return 0;
		}
		if (*next_ephemeral == mymax) {
			*next_ephemeral = mymin;
		} else
			(*next_ephemeral)++;

		count--;


		DPRINTF("next_ephemeral: %u count: %u\n", *next_ephemeral,
		    count);

	} while (count > 0);

	DPRINTF("%s returning EINVAL\n", __func__);

	return EINVAL;
}

/*
 * Since there is no state kept on the ports tried, we might actually
 * give up before exhausting the free ports.
 */
static int
algo_random_pick(int algo, uint16_t *port, struct inpcb *inp,
    kauth_cred_t cred)
{
	uint16_t count, num_ephemeral;
	uint16_t mymin, mymax, lastport;
	uint16_t *next_ephemeral;
	int error;

	DPRINTF("%s called\n", __func__);

	error = pcb_getports(inp, &lastport, &mymin, &mymax,
	    &next_ephemeral, algo);
	if (error)
		return error;

	num_ephemeral = mymax - mymin + 1;

	DPRINTF("num_ephemeral: %u\n", num_ephemeral);
	*next_ephemeral = mymin + (cprng_fast32() % num_ephemeral);

	DPRINTF("next_ephemeral initially: %u\n", *next_ephemeral);

	count = num_ephemeral;

	do {
		if (check_suitable_port(*next_ephemeral, inp, cred)) {
			*port = *next_ephemeral;
			DPRINTF("%s returning port %d\n", __func__, *port);
			return 0;
		}
		*next_ephemeral = mymin +
		    (cprng_fast32() % num_ephemeral);

		count--;

		DPRINTF("next_ephemeral: %u count: %u\n",
		    *next_ephemeral, count);
	} while (count > 0);

	DPRINTF("%s returning EINVAL\n", __func__);

	return EINVAL;
}

/* This is the implementation from FreeBSD, with tweaks */
static uint16_t
Fhash(const struct inpcb *inp)
{
	MD5_CTX f_ctx;
	uint32_t Ff[4];
	uint32_t secret_f[4];
	uint32_t offset;
	uint16_t soffset[2];

	cprng_fast(secret_f, sizeof(secret_f));

	MD5Init(&f_ctx);
	switch (inp->inp_af) {
#ifdef INET
	case AF_INET: {
		MD5Update(&f_ctx, (const u_char *)&const_in4p_laddr(inp),
		    sizeof(const_in4p_laddr(inp)));
		MD5Update(&f_ctx, (const u_char *)&const_in4p_faddr(inp),
		    sizeof(const_in4p_faddr(inp)));
		MD5Update(&f_ctx, (const u_char *)&inp->inp_fport,
		    sizeof(inp->inp_fport));
		break;
	}
#endif
#ifdef INET6
	case AF_INET6: {
		MD5Update(&f_ctx, (const u_char *)&const_in6p_laddr(inp),
		    sizeof(const_in6p_laddr(inp)));
		MD5Update(&f_ctx, (const u_char *)&const_in6p_faddr(inp),
		    sizeof(const_in6p_faddr(inp)));
		MD5Update(&f_ctx, (const u_char *)&inp->inp_fport,
		    sizeof(inp->inp_fport));
		break;
	}
#endif
	default:
		break;
	}
	MD5Update(&f_ctx, (const u_char *)secret_f, sizeof(secret_f));
	MD5Final((u_char *)&Ff, &f_ctx);

	offset = (Ff[0] ^ Ff[1]) ^ (Ff[2] ^ Ff[3]);

	memcpy(&soffset, &offset, sizeof(soffset));

	return soffset[0] ^ soffset[1];
}

/*
 * Checks whether the tuple is complete. If not, marks the pcb for
 * late binding.
 */
static bool
iscompletetuple(struct inpcb *inp)
{

	switch (inp->inp_af) {
#ifdef INET
	case AF_INET: {
		if (inp->inp_fport == 0 || in_nullhost(in4p_faddr(inp))) {
			DPRINTF("%s fport or faddr missing, delaying port "
			    "to connect/send\n", __func__);
			inp->inp_bindportonsend = true;
			return false;
		} else {
			inp->inp_bindportonsend = false;
		}
		break;
	}
#endif
#ifdef INET6
	case AF_INET6: {
		if (inp->inp_fport == 0 || memcmp(&in6p_faddr(inp),
		    &in6addr_any, sizeof(in6p_faddr(inp))) == 0) {
			DPRINTF("%s fport or faddr missing, delaying port "
			    "to connect/send\n", __func__);
			inp->inp_bindportonsend = true;
			return false;
		} else {
			inp->inp_bindportonsend = false;
		}
		break;
	}
#endif
	default:
		DPRINTF("%s incorrect address family\n", __func__);
		return false;
	}

	return true;
}

static int
algo_hash(int algo, uint16_t *port, struct inpcb *inp,
    kauth_cred_t cred)
{
	uint16_t count, num_ephemeral;
	uint16_t mymin, mymax, lastport;
	uint16_t *next_ephemeral;
	uint16_t offset, myport;
	int error;

	DPRINTF("%s called\n", __func__);

	error = pcb_getports(inp, &lastport, &mymin, &mymax,
	    &next_ephemeral, algo);
	if (error)
		return error;

	if (!iscompletetuple(inp)) {
		*port = 0;
		return 0;
	}

	/* Ephemeral port selection function */
	num_ephemeral = mymax - mymin + 1;

	DPRINTF("num_ephemeral: %d\n", num_ephemeral);

	offset = Fhash(inp);

	count = num_ephemeral;
	do {
		myport = mymin + (*next_ephemeral + offset)
		    % num_ephemeral;

		(*next_ephemeral)++;

		if (check_suitable_port(myport, inp, cred)) {
			*port = myport;
			DPRINTF("%s returning port %d\n", __func__, *port);
			return 0;
		}
		count--;
	} while (count > 0);

	DPRINTF("%s returning EINVAL\n", __func__);

	return EINVAL;
}

static int
algo_doublehash(int algo, uint16_t *port, struct inpcb *inp,
    kauth_cred_t cred)
{
	uint16_t count, num_ephemeral;
	uint16_t mymin, mymax, lastport;
	uint16_t *next_ephemeral;
	uint16_t offset, myport;
	static uint16_t dhtable[8];
	size_t idx;
	int error;

	DPRINTF("%s called\n", __func__);

	error = pcb_getports(inp, &lastport, &mymin, &mymax,
	    &next_ephemeral, algo);
	if (error)
		return error;

	if (!iscompletetuple(inp)) {
		*port = 0;
		return 0;
	}
	/* first time initialization */
	if (dhtable[0] == 0)
		for (size_t i = 0; i < __arraycount(dhtable); i++)
			dhtable[i] = cprng_fast32() & 0xffff;

	/* Ephemeral port selection function */
	num_ephemeral = mymax - mymin + 1;
	offset = Fhash(inp);
	idx = Fhash(inp) % __arraycount(dhtable);	/* G */
	count = num_ephemeral;

	do {
		myport = mymin + (offset + dhtable[idx])
		    % num_ephemeral;
		dhtable[idx]++;

		if (check_suitable_port(myport, inp, cred)) {
			*port = myport;
			DPRINTF("%s returning port %d\n", __func__, *port);
			return 0;
		}
		count--;

	} while (count > 0);

	DPRINTF("%s returning EINVAL\n", __func__);

	return EINVAL;
}

static int
algo_randinc(int algo, uint16_t *port, struct inpcb *inp,
    kauth_cred_t cred)
{
	static const uint16_t N = 500;	/* Determines the trade-off */
	uint16_t count, num_ephemeral;
	uint16_t mymin, mymax, lastport;
	uint16_t *next_ephemeral;
	uint16_t myport;
	int error;

	DPRINTF("%s called\n", __func__);

	error = pcb_getports(inp, &lastport, &mymin, &mymax,
	    &next_ephemeral, algo);
	if (error)
		return error;

	if (*next_ephemeral == 0)
		*next_ephemeral = cprng_fast32() & 0xffff;

	/* Ephemeral port selection function */
	num_ephemeral = mymax - mymin + 1;

	count = num_ephemeral;
	do {
		*next_ephemeral = *next_ephemeral +
		    (cprng_fast32() % N) + 1;
		myport = mymin +
		    (*next_ephemeral % num_ephemeral);

		if (check_suitable_port(myport, inp, cred)) {
			*port = myport;
			DPRINTF("%s returning port %d\n", __func__, *port);
			return 0;
		}
		count--;
	} while (count > 0);

	return EINVAL;
}

/* The generic function called in order to pick a port. */
int
portalgo_randport(uint16_t *port, struct inpcb *inp, kauth_cred_t cred)
{
	int algo, error;
	uint16_t lport;
	int default_algo;

	DPRINTF("%s called\n", __func__);

	if (inp->inp_portalgo == PORTALGO_DEFAULT) {
		switch (inp->inp_af) {
#ifdef INET
		case AF_INET:
			default_algo = inet4_portalgo;
			break;
#endif
#ifdef INET6
		case AF_INET6:
			default_algo = inet6_portalgo;
			break;
#endif
		default:
			return EINVAL;
		}

		if (default_algo == PORTALGO_DEFAULT)
			algo = PORTALGO_BSD;
		else
			algo = default_algo;
	}
	else /* socket specifies the algorithm */
		algo = inp->inp_portalgo;

	KASSERT(algo >= 0);
	KASSERT(algo < NALGOS);

	switch (inp->inp_af) {
#ifdef INET
	case AF_INET: {
		char buf[INET_ADDRSTRLEN];
		DPRINTF("local addr: %s\n", IN_PRINT(buf, &in4p_laddr(inp)));
		DPRINTF("local port: %d\n", inp->inp_lport);
		DPRINTF("foreign addr: %s\n", IN_PRINT(buf, &in4p_faddr(inp)));
		DPRINTF("foreign port: %d\n", inp->inp_fport);
		break;
	}
#endif
#ifdef INET6
	case AF_INET6: {
		char buf[INET6_ADDRSTRLEN];
		DPRINTF("local addr: %s\n", IN6_PRINT(buf, &in6p_laddr(inp)));
		DPRINTF("local port: %d\n", inp->inp_lport);
		DPRINTF("foreign addr: %s\n", IN6_PRINT(buf,
		    &in6p_laddr(inp)));
		DPRINTF("foreign port: %d\n", inp->inp_fport);
		break;
	}
#endif
	default:
		break;
	}

	DPRINTF("%s portalgo = %d\n", __func__, algo);

	error = (*algos[algo].func)(algo, &lport, inp, cred);
	if (error == 0) {
		*port = lport;
	} else if (error != EAGAIN) {
		uint16_t lastport, mymin, mymax, *pnext_ephemeral;

		error = pcb_getports(inp, &lastport, &mymin,
		    &mymax, &pnext_ephemeral, algo);
		if (error)
			return error;
		*port = lastport - 1;
	}
	return error;
}

/* Sets the algorithm to be used globally */
static int
portalgo_algo_name_select(const char *name, int *algo)
{
	size_t ai;

	DPRINTF("%s called\n", __func__);

	for (ai = 0; ai < NALGOS; ai++)
		if (strcmp(algos[ai].name, name) == 0) {
			DPRINTF("%s: found idx %zu\n", __func__, ai);
			*algo = ai;
			return 0;
		}
	return EINVAL;
}

/* Sets the algorithm to be used by the pcb inp. */
int
portalgo_algo_index_select(struct inpcb *inp, int algo)
{

	DPRINTF("%s called with algo %d for pcb %p\n", __func__, algo, inp );

	if ((algo < 0 || algo >= NALGOS) &&
	    (algo != PORTALGO_DEFAULT))
		return EINVAL;

	inp->inp_portalgo = algo;
	return 0;
}

/*
 * The sysctl hook that is supposed to check that we are picking one
 * of the valid algorithms.
 */
static int
sysctl_portalgo_selected(SYSCTLFN_ARGS, int *algo)
{
	struct sysctlnode node;
	int error;
	char newalgo[PORTALGO_MAXLEN];

	DPRINTF("%s called\n", __func__);

	strlcpy(newalgo, algos[*algo].name, sizeof(newalgo));

	node = *rnode;
	node.sysctl_data = newalgo;
	node.sysctl_size = sizeof(newalgo);

	error = sysctl_lookup(SYSCTLFN_CALL(&node));

	DPRINTF("newalgo: %s\n", newalgo);

	if (error || newp == NULL ||
	    strncmp(newalgo, algos[*algo].name, sizeof(newalgo)) == 0)
		return error;

#ifdef KAUTH_NETWORK_SOCKET_PORT_RANDOMIZE
	if (l != NULL && (error = kauth_authorize_system(l->l_cred,
	    KAUTH_NETWORK_SOCKET, KAUTH_NETWORK_SOCKET_PORT_RANDOMIZE, newname,
	    NULL, NULL)) != 0)
		return error;
#endif

	mutex_enter(softnet_lock);
	error = portalgo_algo_name_select(newalgo, algo);
	mutex_exit(softnet_lock);
	return error;
}

static int
sysctl_portalgo_reserve(SYSCTLFN_ARGS, bitmap *bt)
{
	struct sysctlnode node;
	int error;

	DPRINTF("%s called\n", __func__);

	node = *rnode;
	node.sysctl_data = bt;
	node.sysctl_size = sizeof(*bt);

	error = sysctl_lookup(SYSCTLFN_CALL(&node));

	if (error || newp == NULL)
		return error;

#ifdef KAUTH_NETWORK_SOCKET_PORT_RESERVE
	if (l != NULL && (error = kauth_authorize_system(l->l_cred,
	    KAUTH_NETWORK_SOCKET, KAUTH_NETWORK_SOCKET_PORT_RESERVE, bt,
	    NULL, NULL)) != 0)
		return error;
#endif
	return error;
}

#ifdef INET
/*
 * The sysctl hook that is supposed to check that we are picking one
 * of the valid algorithms.
 */
int
sysctl_portalgo_selected4(SYSCTLFN_ARGS)
{

	return sysctl_portalgo_selected(SYSCTLFN_CALL(rnode), &inet4_portalgo);
}

int
sysctl_portalgo_reserve4(SYSCTLFN_ARGS)
{

	return sysctl_portalgo_reserve(SYSCTLFN_CALL(rnode), &inet4_reserve);
}
#endif

#ifdef INET6
int
sysctl_portalgo_selected6(SYSCTLFN_ARGS)
{

	return sysctl_portalgo_selected(SYSCTLFN_CALL(rnode), &inet6_portalgo);
}

int
sysctl_portalgo_reserve6(SYSCTLFN_ARGS)
{
	return sysctl_portalgo_reserve(SYSCTLFN_CALL(rnode), &inet6_reserve);
}
#endif

/*
 * The sysctl hook that returns the available
 * algorithms.
 */
int
sysctl_portalgo_available(SYSCTLFN_ARGS)
{
	size_t ai, len = 0;
	struct sysctlnode node;
	char availalgo[NALGOS * PORTALGO_MAXLEN];

	DPRINTF("%s called\n", __func__);

	availalgo[0] = '\0';

	for (ai = 0; ai < NALGOS; ai++) {
		len = strlcat(availalgo, algos[ai].name, sizeof(availalgo));
		if (ai < NALGOS - 1)
			strlcat(availalgo, " ", sizeof(availalgo));
	}

	DPRINTF("available algos: %s\n", availalgo);

	node = *rnode;
	node.sysctl_data = availalgo;
	node.sysctl_size = len;

	return sysctl_lookup(SYSCTLFN_CALL(&node));
}