File: ikev2_message.c

package info (click to toggle)
libreswan 5.2-2.3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 81,644 kB
  • sloc: ansic: 129,988; sh: 32,018; xml: 20,646; python: 10,303; makefile: 3,022; javascript: 1,506; sed: 574; yacc: 511; perl: 264; awk: 52
file content (1506 lines) | stat: -rw-r--r-- 48,160 bytes parent folder | download | duplicates (2)
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
/* IKEv2 message routines, for Libreswan
 *
 * Copyright (C) 2007-2008 Michael Richardson <mcr@xelerance.com>
 * Copyright (C) 2008-2011 Paul Wouters <paul@xelerance.com>
 * Copyright (C) 2008 Antony Antony <antony@xelerance.com>
 * Copyright (C) 2008-2009 David McCullough <david_mccullough@securecomputing.com>
 * Copyright (C) 2010,2012 Avesh Agarwal <avagarwa@redhat.com>
 * Copyright (C) 2010 Tuomo Soini <tis@foobar.fi
 * Copyright (C) 2012-2019 Paul Wouters <pwouters@redhat.com>
 * Copyright (C) 2012-2017 Antony Antony <antony@phenome.org>
 * Copyright (C) 2013-2019 D. Hugh Redelmeier <hugh@mimosa.com>
 * Copyright (C) 2013 David McCullough <ucdevel@gmail.com>
 * Copyright (C) 2013 Matt Rogers <mrogers@redhat.com>
 * Copyright (C) 2015-2019 Andrew Cagney <cagney@gnu.org>
 * Copyright (C) 2017 Sahana Prasad <sahana.prasad07@gmail.com>
 * Copyright (C) 2017 Vukasin Karadzic <vukasin.karadzic@gmail.com>
 * Copyright (C) 2017 Mayank Totale <mtotale@gmail.com>
 * Copyright (C) 2020 Yulia Kuzovkova <ukuzovkova@gmail.com>
 * Copyright (C) 2020 Nupur Agrawal <nupur202000@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.  See <https://www.gnu.org/licenses/gpl2.txt>.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 */


#include "defs.h"

#include "log.h"
#include "ikev2_message.h"
#include "server.h"
#include "state.h"
#include "connections.h"
#include "ike_alg.h"
#include "crypt_cipher.h"
#include "pluto_stats.h"
#include "demux.h"	/* for struct msg_digest */
#include "rnd.h"
#include "crypt_prf.h"
#include "send.h"	/* record_outbound_ike_message() */
#include "ip_info.h"
#include "iface.h"
#include "ip_protocol.h"
#include "ikev2_send.h"
#include "ikev2_notification.h"

/*
 * Determine the IKE version we will use for the IKE packet
 * Normally, this is "2.0", but in the future we might need to
 * change that. Version used is the minimum 2.x version both
 * sides support. So if we support 2.1, and they support 2.0,
 * we should sent 2.0 (not implemented until we hit 2.1 ourselves)
 * We also have some impair functions that modify the major/minor
 * version on purpose - for testing
 *
 * rcv_version: the received IKE version, 0 if we don't know
 *
 * top 4 bits are major version, lower 4 bits are minor version
 */
static uint8_t build_ikev2_version(void)
{
	/* TODO: if bumping, we should also set the Version flag in the ISAKMP header */
	return ((IKEv2_MAJOR_VERSION + (impair.major_version_bump ? 1 : 0))
			<< ISA_MAJ_SHIFT) |
	       (IKEv2_MINOR_VERSION + (impair.minor_version_bump ? 1 : 0));
}

uint8_t build_ikev2_critical(bool impaired, struct logger *logger)
{
	uint8_t octet = 0;
	if (impaired) {
		/* flip the expected bit */
		llog(RC_LOG, logger, "IMPAIR: setting (should be off) critical payload bit");
		octet = ISAKMP_PAYLOAD_CRITICAL;
	} else {
		octet = ISAKMP_PAYLOAD_NONCRITICAL;
	}
	if (impair.send_bogus_payload_flag) {
		llog(RC_LOG, logger, "IMPAIR: adding bogus bit to critical octet");
		octet |= ISAKMP_PAYLOAD_FLAG_LIBRESWAN_BOGUS;
	}
	return octet;
}

/*
 * Open an IKEv2 message, return the message body.
 *
 * Request: IKE, which must be non-NULL, is used to determine the IKE
 * SA Initiator / Responder role; MD must be NULL (after all a request
 * has no response).
 *
 * Response: If IKE is non-NULL then it is used to determine the IKE
 * SA Initiator / Responder role (NULL implies IKE SA Initiator); MD
 * must be non-NULL (the message being responded to).
 */

static bool open_v2_message_body(struct pbs_out *message,
				 const struct ike_sa *ike,
				 const struct msg_digest *md,
				 enum ikev2_exchange exchange_type,
				 struct pbs_out *body)
{
	*body = (struct pbs_out) {0};

	/* at least one, possibly both */
	passert(ike != NULL || md != NULL);

	struct isakmp_hdr hdr = {
		.isa_flags = impair.send_bogus_isakmp_flag ? ISAKMP_FLAGS_RESERVED_BIT6 : LEMPTY,
		.isa_version = build_ikev2_version(),
		.isa_xchg = exchange_type,
		.isa_length = 0, /* filled in when PBS is closed */
	};

	/*
	 * I (Initiator) flag
	 *
	 * If there is an IKE SA, the sa_role can be used.
	 *
	 * If there is no IKE SA, then, presumably, this is a response
	 * to an initial exchange and the flag should be clear.
	 *
	 * The other possibility is that this is a response to an
	 * IKEv++ message, just assume this is the initial exchange
	 * and the I flag should be clear (see 1.5.  Informational
	 * Messages outside of an IKE SA).  The other option would be
	 * to flip MD's I bit, but since this is IKEv++, there may not
	 * even be an I bit.
	 */
	enum sa_role sa_role = (ike != NULL ? ike->sa.st_sa_role : SA_RESPONDER);
	if (sa_role == SA_INITIATOR) {
		hdr.isa_flags |= ISAKMP_FLAGS_v2_IKE_I;
	}

	/*
	 * R (Response) flag
	 *
	 * If there's no MD, then this must be a new exchange request
	 * - R(Responder) flag clear.
	 *
	 * If there is an MD, then this must be a response -
	 * R(Responder) flag set.
	 *
	 * Note that when MD!= NULL, v2_msg_role() can't be called (as
	 * a cross check) as this code used to force a response to a
	 * message that is close to bogus requests (1.5.
	 * Informational Messages outside of an IKE SA - where the
	 * response is forced.
	 */
	enum message_role message_role = (md != NULL ? MESSAGE_RESPONSE : MESSAGE_REQUEST);
	if (message_role == MESSAGE_RESPONSE) {
		hdr.isa_flags |= ISAKMP_FLAGS_v2_MSG_R;
	}

	/*
	 * SPI (aka cookies).
	 */
	if (ike != NULL) {
		/*
		 * Note that when the original initiator sends the
		 * IKE_SA_INIT request, the still zero SPIr will be
		 * copied.
		 */
		hdr.isa_ike_initiator_spi = ike->sa.st_ike_spis.initiator;
		hdr.isa_ike_responder_spi = ike->sa.st_ike_spis.responder;
	} else {
		/*
		 * Either error response notification to IKE_SA_INIT
		 * or "Informational Messages outside of an IKE SA".
		 * Use the IKE SPIs from the request.
		 */
		passert(md != NULL);
		hdr.isa_ike_initiator_spi = md->hdr.isa_ike_initiator_spi;
		hdr.isa_ike_responder_spi = md->hdr.isa_ike_responder_spi;
	}

	/*
	 * Message ID
	 */
	if (md != NULL) {
		/*
		 * Since there is a message digest (MD) it is assumed
		 * to contain a message request.  Presumably this open
		 * is for the message response - use the Message ID
		 * from the request.  A better choice would be
		 * .st_v2_msgid_windows.responder.recv+1, but it isn't
		 * clear if/when that value is updated and the IKE SA
		 * isn't always available.
		 */
		hdr.isa_msgid = md->hdr.isa_msgid;
	} else {
		/*
		 * If it isn't a response then use the IKE SA's
		 * .st_v2_msgid_windows.initiator.sent+1.  The field
		 * will be updated as part of finishing the state
		 * transition and sending the message.
		 */
		passert(ike != NULL);
		hdr.isa_msgid = ike->sa.st_v2_msgid_windows.initiator.sent + 1;
	}

	if (impair.bad_ike_auth_xchg) {
		llog_sa(RC_LOG, ike, "IMPAIR: Instead of replying with IKE_AUTH, forging an INFORMATIONAL reply");
		if ((hdr.isa_flags & ISAKMP_FLAGS_v2_MSG_R) && exchange_type == ISAKMP_v2_IKE_AUTH) {
			hdr.isa_xchg = ISAKMP_v2_INFORMATIONAL;
		}
	}

	if (!pbs_out_struct(message, &isakmp_hdr_desc, &hdr, sizeof(hdr), body)) {
		/* already logged */
		return false;
	}

	if (!emit_v2UNKNOWN("unencrypted", exchange_type,
			    &impair.add_unknown_v2_payload_to,
			    body)) {
		return false;
	}

	return true;
}

/*
 * This code assumes that the encrypted part of an IKE message starts
 * with an Initialization Vector (IV) of enc_blocksize of random
 * octets.  The IV will subsequently be discarded after decryption.
 * This is true of Cipher Block Chaining mode (CBC).
 */
static bool emit_v2SK_iv(struct v2SK_payload *sk)
{
	/* compute location/size */
	sk->wire_iv = chunk2(sk->pbs.cur, sk->ike->sa.st_oakley.ta_encrypt->wire_iv_size);
	/* make space */
	if (!pbs_out_zero(&sk->pbs, sk->wire_iv.len, "IV")) {
		/* already logged */
		return false; /*fatal*/
	}
	return true;
}

static bool open_body_v2SK_payload(struct pbs_out *container,
				   struct ike_sa *ike,
				   struct logger *logger,
				   struct v2SK_payload *sk)
{
	*sk = (struct v2SK_payload) {
		.logger = logger,
		.ike = ike,
		.payload = {
		    .ptr = container->cur,
		    .len = 0,	/* computed at end; set here to silence GCC 6.10 */
		}
	};

	/* emit Encryption Payload header */

	struct ikev2_generic e = {
		.isag_length = 0, /* filled in later */
		.isag_critical = build_ikev2_critical(false, ike->sa.logger),
	};
	if (!pbs_out_struct(container, &ikev2_sk_desc, &e, sizeof(e), &sk->pbs)) {
		llog(RC_LOG, logger,
		     "error initializing SK header for encrypted %s message",
		     container->name);
		return false;
	}

	/*
	 * Additional Authenticated Data - AAD - is everything so far:
	 * i.e., the IKE header and payload headers.
	 *
	 * RFC5282 says: The Initialization Vector and Ciphertext
	 * fields [...] MUST NOT be included in the associated data.
	 */

	sk->aad = chunk2(sk->pbs.container->start, sk->pbs.cur - sk->pbs.container->start);

	/* emit IV and save location */

	if (!emit_v2SK_iv(sk)) {
		llog(RC_LOG, logger,
		     "error initializing IV for encrypted %s message",
		     container->name);
		return false;
	}

	/* save cleartext start */

	sk->cleartext.ptr = sk->pbs.cur;
	sk->cleartext.len = 0; /* to be determined */

	passert(sk->wire_iv.ptr <= sk->cleartext.ptr);

	/* XXX: coverity thinks .container (set to E by out_struct()
	 * above) can be NULL. */
	passert(sk->pbs.container != NULL && sk->pbs.container->name == container->name);

	ldbg(sk->logger, "%s() %s=[%zu,%zu) %s=[%zu,%zu)",
	     __func__,
#define R(N) #N, sk->N.ptr - sk->payload.ptr, sk->N.len
	     R(aad),
	     R(wire_iv));
#undef R

	return true;
}

static bool close_v2SK_payload(struct v2SK_payload *sk)
{
	/*
	 * Save cleartext end, excluding any padding.
	 *
	 * When chopping .cleartext into fragments, the last fragment
	 * will get its own padding.
	 */

	sk->cleartext.len = sk->pbs.cur - sk->cleartext.ptr;

	/* emit padding + pad-length */

	size_t padding;
	if (sk->ike->sa.st_oakley.ta_encrypt->pad_to_blocksize) {
		const size_t blocksize = sk->ike->sa.st_oakley.ta_encrypt->enc_blocksize;
		padding = pad_up(sk->pbs.cur - sk->cleartext.ptr, blocksize);
		if (padding == 0) {
			padding = blocksize;
		}
	} else {
		padding = 1;
	}
	sk->padding = chunk2(sk->pbs.cur, padding);
	ldbg(sk->logger, "adding %zd bytes of padding (including 1 byte padding-length)", padding);
	for (unsigned i = 0; i < padding; i++) {
		if (!pbs_out_repeated_byte(&sk->pbs, i, 1, "padding and length")) {
			/* already logged */
			return false; /*fatal*/
		}
	}
	PASSERT(sk->logger, sk->padding.ptr + sk->padding.len == sk->pbs.cur);

	/* emit space for integrity checksum data; save location */

	size_t integ_size = (encrypt_desc_is_aead(sk->ike->sa.st_oakley.ta_encrypt)
			     ? sk->ike->sa.st_oakley.ta_encrypt->aead_tag_size
			     : sk->ike->sa.st_oakley.ta_integ->integ_output_size);
	if (integ_size == 0) {
		llog_pexpect(sk->logger, HERE,
			     "error initializing integrity checksum for encrypted %s payload",
			     sk->pbs.container->name);
		return false;
	}
	sk->integrity = chunk2(sk->pbs.cur, integ_size);
	if (!pbs_out_zero(&sk->pbs, integ_size, "length of truncated HMAC/KEY")) {
		/* already logged */
		return false; /*fatal*/
	}

	/* close the SK payload */

	sk->payload.len = sk->pbs.cur - sk->payload.ptr;
	close_output_pbs(&sk->pbs);

	ldbg(sk->logger, "%s() payload=%zu bytes %s=[%zu,%zu) %s=[%zu,%zu) %s=[%zu,%zu) %s=[%zu,%zu) %s=[%zu,%zu)",
	     __func__, sk->padding.len,
#define R(N) #N, sk->N.ptr - sk->payload.ptr, sk->N.len
	     R(aad),
	     R(cleartext),
	     R(wire_iv),
	     R(padding),
	     R(integrity));
#undef R
	return true;
}

bool encrypt_v2SK_payload(struct v2SK_payload *sk)
{
	struct ike_sa *ike = sk->ike;

	/*
	 * Will encrypt .cleartext + .padding (they are assumed to be
	 * contigious).
	 *
	 * Just note that .cleartext doesn't include the padding.
	 * This is because when .cleartext gets chopped up into
	 * fragments the last fragment does its own padding.
	 */
	ldbg(sk->logger, "%p %zu %p", sk->aad.ptr, sk->aad.len, sk->wire_iv.ptr);
	PASSERT(sk->logger, sk->aad.ptr + sk->aad.len == sk->wire_iv.ptr);
	PASSERT(sk->logger, sk->wire_iv.ptr + sk->wire_iv.len == sk->cleartext.ptr);
	PASSERT(sk->logger, sk->cleartext.ptr + sk->cleartext.len == sk->padding.ptr);
	PASSERT(sk->logger, sk->padding.ptr + sk->padding.len == sk->integrity.ptr);
	chunk_t enc = chunk2(sk->cleartext.ptr, sk->cleartext.len + sk->padding.len);

	chunk_t salt;
	PK11SymKey *authkey;
	/* encrypt with our end's key */
	switch (ike->sa.st_sa_role) {
	case SA_INITIATOR:
		authkey = ike->sa.st_skey_ai_nss;
		salt = ike->sa.st_skey_initiator_salt;
		break;
	case SA_RESPONDER:
		authkey = ike->sa.st_skey_ar_nss;
		salt = ike->sa.st_skey_responder_salt;
		break;
	default:
		bad_case(ike->sa.st_sa_role);
	}

	/* now, encrypt */
	if (DBGP(DBG_CRYPT)) {
		LDBG_log(sk->logger, "data before [authenticated] encryption:");
		LDBG_hunk(sk->logger, enc);
		LDBG_log(sk->logger, "integ before [authenticated] encryption:");
		LDBG_hunk(sk->logger, sk->integrity);
	}

	/* encrypt and authenticate the block */
	if (encrypt_desc_is_aead(ike->sa.st_oakley.ta_encrypt)) {
		pexpect(sk->integrity.len == ike->sa.st_oakley.ta_encrypt->aead_tag_size);
		chunk_t text_and_tag = chunk2(enc.ptr, enc.len + sk->integrity.len);

		/* now, encrypt */
		if (DBGP(DBG_CRYPT)) {
		    DBG_dump_hunk("Salt before authenticated encryption:", salt);
		    LDBG_log(sk->logger, "IV before authenticated encryption:");
		    LDBG_hunk(sk->logger, sk->wire_iv);
		    LDBG_log(sk->logger, "AAD before authenticated encryption:");
		    LDBG_hunk(sk->logger, sk->aad);
		}

		if (!cipher_context_op_aead(ike->sa.st_ike_encrypt_cipher_context,
					    sk->wire_iv, HUNK_AS_SHUNK(sk->aad),
					    text_and_tag, enc.len, sk->integrity.len,
					    sk->logger)) {
			return false;
		}

	} else {
		/* note: no iv is longer than MAX_CBC_BLOCK_SIZE */
		cipher_context_op_normal(ike->sa.st_ike_encrypt_cipher_context,
					 sk->wire_iv, enc, /*ikev1_iv*/NULL,
					 sk->logger);

		/* note: saved_iv's updated value is discarded */

		/* okay, authenticate from beginning of IV */
		struct crypt_prf *ctx = crypt_prf_init_symkey("integ", ike->sa.st_oakley.ta_integ->prf,
							      "authkey", authkey, sk->logger);
		chunk_t message = chunk2(sk->aad.ptr, sk->integrity.ptr - sk->aad.ptr);
		crypt_prf_update_bytes(ctx, "message", message.ptr, message.len);
		passert(sk->integrity.len == ike->sa.st_oakley.ta_integ->integ_output_size);
		struct crypt_mac mac = crypt_prf_final_mac(&ctx, ike->sa.st_oakley.ta_integ);
		memcpy_hunk(sk->integrity.ptr, mac, sk->integrity.len);

		if (DBGP(DBG_CRYPT)) {
			LDBG_log(sk->logger, "data being hmac:");
			LDBG_hunk(sk->logger, message);
			LDBG_log(sk->logger, "out calculated auth:");
			LDBG_hunk(sk->logger, sk->integrity);
		}
	}

	if (DBGP(DBG_CRYPT)) {
		LDBG_log(sk->logger, "data after [authenticated] encryption:");
		LDBG_hunk(sk->logger,  enc);
		LDBG_log(sk->logger, "integ after [authenticated] encryption:");
		LDBG_hunk(sk->logger, sk->integrity);
	}

	return true;
}

/*
 * ikev2_decrypt_msg: decode the payload.
 * The result is stored in-place.
 * Calls ikev2_process_payloads to decode the payloads within.
 *
 * This code assumes that the encrypted part of an IKE message starts
 * with an Initialization Vector (IV) of WIRE_IV_SIZE random octets.
 * We will discard the IV after decryption.
 *
 * The (optional) salt, wire-iv, and (optional) 1 are combined to form
 * the actual starting-variable (a.k.a. IV).
 */

static bool verify_and_decrypt_v2_message(struct ike_sa *ike,
					  chunk_t text,
					  shunk_t *plain,
					  size_t iv_offset)
{
	if (!ike->sa.hidden_variables.st_skeyid_calculated) {
		endpoint_buf b;
		llog_pexpect(ike->sa.logger, HERE,
			     "received encrypted packet from %s but no exponents for state #%lu to decrypt it",
			     str_endpoint_sensitive(&ike->sa.st_remote_endpoint, &b),
			     ike->sa.st_serialno);
		return false;
	}

	chunk_t wire_iv = chunk2(text.ptr + iv_offset, ike->sa.st_oakley.ta_encrypt->wire_iv_size);
	size_t integ_size = (encrypt_desc_is_aead(ike->sa.st_oakley.ta_encrypt)
			     ? ike->sa.st_oakley.ta_encrypt->aead_tag_size
			     : ike->sa.st_oakley.ta_integ->integ_output_size);

	/*
	 * check to see if length is plausible:
	 * - wire-IV
	 * - encoded data (possibly empty)
	 * - at least one padding-length byte
	 * - truncated integrity digest / tag
	 */
	uint8_t *payload_end = text.ptr + text.len;
	if (payload_end < (wire_iv.ptr + wire_iv.len + 1 + integ_size)) {
		llog_sa(RC_LOG, ike,
			  "encrypted payload impossibly short (%tu)",
			  payload_end - wire_iv.ptr);
		return false;
	}

	uint8_t *auth_start = text.ptr;
	chunk_t integ = chunk2(payload_end - integ_size, integ_size);
	chunk_t enc = chunk2(wire_iv.ptr + wire_iv.len,
			     integ.ptr - wire_iv.ptr - wire_iv.len);

	/*
	 * Check that the payload is block-size aligned.
	 *
	 * Per rfc7296 "the recipient MUST accept any length that
	 * results in proper alignment".
	 *
	 * Do this before the payload's integrity has been verified as
	 * block-alignment requirements aren't exactly secret
	 * (originally this was being done between integrity and
	 * decrypt).
	 */
	size_t enc_blocksize = ike->sa.st_oakley.ta_encrypt->enc_blocksize;
	bool pad_to_blocksize = ike->sa.st_oakley.ta_encrypt->pad_to_blocksize;
	if (pad_to_blocksize) {
		if (enc.len % enc_blocksize != 0) {
			llog_sa(RC_LOG, ike,
				  "discarding invalid packet: %zu octet payload length is not a multiple of encryption block-size (%zu)",
				  enc.len, enc_blocksize);
			return false;
		}
	}

	chunk_t salt;
	PK11SymKey *authkey;
	switch (ike->sa.st_sa_role) {
	case SA_INITIATOR:
		/* need responders key */
		authkey = ike->sa.st_skey_ar_nss;
		salt = ike->sa.st_skey_responder_salt;
		break;
	case SA_RESPONDER:
		/* need initiators key */
		authkey = ike->sa.st_skey_ai_nss;
		salt = ike->sa.st_skey_initiator_salt;
		break;
	default:
		bad_case(ike->sa.st_sa_role);
	}

	/* authenticate and decrypt the block. */

	if (encrypt_desc_is_aead(ike->sa.st_oakley.ta_encrypt)) {
		/*
		 * Additional Authenticated Data - AAD - size.
		 * RFC5282 says: The Initialization Vector and Ciphertext
		 * fields [...] MUST NOT be included in the associated
		 * data.
		 */
		shunk_t aad = shunk2(auth_start, enc.ptr - auth_start - wire_iv.len);
		chunk_t text_and_tag = chunk2(enc.ptr, enc.len + integ.len);

		/* decrypt */
		if (DBGP(DBG_CRYPT)) {
			DBG_dump_hunk("Salt before authenticated decryption:", salt);
			LDBG_log(ike->sa.logger, "IV before authenticated decryption:");
			LDBG_hunk(ike->sa.logger, wire_iv);
			LDBG_log(ike->sa.logger, "AAD before authenticated decryption:");
			LDBG_hunk(ike->sa.logger, aad);
			LDBG_log(ike->sa.logger, "integ before authenticated decryption:");
			LDBG_hunk(ike->sa.logger, integ);
			LDBG_log(ike->sa.logger, "payload before decryption:");
			LDBG_hunk(ike->sa.logger, enc);
		}

		if (!cipher_context_op_aead(ike->sa.st_ike_decrypt_cipher_context,
					    wire_iv, aad,
					    text_and_tag, enc.len, integ.len,
					    ike->sa.logger)) {
			return false;
		}

		if (DBGP(DBG_CRYPT)) {
			LDBG_log(ike->sa.logger, "data after authenticated decryption:");
			LDBG_hunk(ike->sa.logger, enc);
			LDBG_hunk(ike->sa.logger, integ);
		}

	} else {
		/*
		 * check authenticator.  The last INTEG_SIZE bytes are
		 * the truncated digest.
		 */
		struct crypt_prf *ctx = crypt_prf_init_symkey("auth", ike->sa.st_oakley.ta_integ->prf,
							      "authkey", authkey, ike->sa.logger);
		crypt_prf_update_bytes(ctx, "message", auth_start, integ.ptr - auth_start);
		struct crypt_mac td = crypt_prf_final_mac(&ctx, ike->sa.st_oakley.ta_integ);

		if (!hunk_memeq(td, integ.ptr, integ.len)) {
			llog_sa(RC_LOG, ike, "failed to match authenticator");
			return false;
		}

		dbg("authenticator matched");

		if (DBGP(DBG_CRYPT)) {
			LDBG_log(ike->sa.logger, "payload before decryption:");
			LDBG_hunk(ike->sa.logger, enc);
		}

		/* note: no iv is longer than MAX_CBC_BLOCK_SIZE */
		cipher_context_op_normal(ike->sa.st_ike_decrypt_cipher_context,
					 wire_iv, enc, /*ikev1_iv*/NULL,
					 ike->sa.logger);

		if (DBGP(DBG_CRYPT)) {
			LDBG_log(ike->sa.logger, "payload after decryption:");
			LDBG_hunk(ike->sa.logger, enc);
		}

	}

	/*
	 * Check the padding.
	 *
	 * Per rfc7296 "The sender SHOULD set the Pad Length to the
	 * minimum value that makes the combination of the payloads,
	 * the Padding, and the Pad Length a multiple of the block
	 * size, but the recipient MUST accept any length that results
	 * in proper alignment."
	 *
	 * Notice the "should".  RACOON, for instance, sends extra
	 * blocks of padding that contain random bytes.
	 */
	uint8_t padlen = enc.ptr[enc.len - 1] + 1;
	if (padlen > enc.len) {
		llog_sa(RC_LOG, ike,
			  "discarding invalid packet: padding-length %u (octet 0x%02x) is larger than %zu octet payload length",
			  padlen, padlen - 1, enc.len);
		return false;
	}
	if (pad_to_blocksize) {
		if (padlen > enc_blocksize) {
			/* probably racoon */
			dbg("payload contains %zu blocks of extra padding (padding-length: %d (octet 0x%2x), encryption block-size: %zu)",
			    (padlen - 1) / enc_blocksize,
			    padlen, padlen - 1, enc_blocksize);
		}
	} else {
		if (padlen > 1) {
			dbg("payload contains %u octets of extra padding (padding-length: %u (octet 0x%2x))",
			    padlen - 1, padlen, padlen - 1);
		}
	}

	/*
	 * Don't check the contents of the pad octets; racoon, for
	 * instance, sets them to random values.
	 */
	dbg("stripping %u octets as pad", padlen);
	*plain = shunk2(enc.ptr, enc.len - padlen);

	return true;
}

/*
 * Incoming IKEv2 fragments.
 */

static const char *ignore_v2_incoming_fragment(struct v2_incoming_fragments *frags,
					       struct msg_digest *md,
					       struct ikev2_skf *skf_hdr)
{
	/* Sanity check header */

	if (skf_hdr->isaskf_number == 0) {
		return "fragment number must be 1 or greater (not 0)";
	}

	if (skf_hdr->isaskf_number > skf_hdr->isaskf_total) {
		return "fragment number must be no greater than the total number of fragments";
	}

	if (skf_hdr->isaskf_total > MAX_IKE_FRAGMENTS) {
		return "total number of fragments must be no more than MAX_IKE_FRAGMENTS";
	}

	if (skf_hdr->isaskf_number == 1 && skf_hdr->isaskf_np == ISAKMP_NEXT_v2NONE) {
		return "first fragment's next payload must not be ISAKMP_NEXT_v2NONE";
	}

	if (skf_hdr->isaskf_number > 1 && skf_hdr->isaskf_np != ISAKMP_NEXT_v2NONE) {
		return "later fragment's next payload must be ISAKMP_NEXT_v2NONE";
	}

	/* header's ok; if it's the first it is always good */

	if (frags == NULL) {
		return NULL;
	}

	/* is it consistent with previous fragments */

	if (md->hdr.isa_xchg != frags->xchg) {
		return "message exchange does not match";
	}

	if (frags->total == 0) {
		return "message is not fragmented";
	}

	if (skf_hdr->isaskf_total != frags->total) {
		return "fragment total changed";
	}

	if (frags->frags[skf_hdr->isaskf_number].text.ptr != NULL) {
		/* retain earlier fragment with same index */
		return "repeat";
	}

	return NULL;
}

/*
 * IKEv2 message fragment:
 *
 *                       1                   2                   3
 *     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 * message_pbs.start (AAD):
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |                       IKE SA Initiator's SPI                  |
 *   |                                                               |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |                       IKE SA Responder's SPI                  |
 *   |                                                               |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |  Next Payload | MjVer | MnVer | Exchange Type |     Flags     |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |                          Message ID                           |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |                            Length                             |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 * skf_pbs.start:
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   | Next Payload  |C|  RESERVED   |         Payload Length        |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |        Fragment Number        |        Total Fragments        |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 * skf_pbs.cur:
 * pointed to by iv_offset; IV length determined by crypto suite
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |                     Initialization Vector                     |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 * cipher text (plain text after trimming):
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   ~                      Encrypted content                        ~
 *   +               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |               |             Padding (0-255 octets)            |
 *   +-+-+-+-+-+-+-+-+                               +-+-+-+-+-+-+-+-+
 *   |                                               |  Pad Length   |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   ~                    Integrity Checksum Data                    ~
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 * skf_pbs.roof:
 * message_pbs.roof:
 */

enum collected_fragment collect_v2_incoming_fragment(struct ike_sa *ike,
						     struct msg_digest *md,
						     struct v2_incoming_fragments **frags)
{
	if (!ike->sa.st_v2_ike_fragmentation_enabled) {
		llog_sa(RC_LOG, ike, "ignoring fragment as peer never proposed fragmentation");
		return FRAGMENT_IGNORED;
	}

	struct ikev2_skf *skf_hdr = &md->chain[ISAKMP_NEXT_v2SKF]->payload.v2skf;

	dbg("received IKE encrypted fragment number '%u', total number '%u', next payload '%u'",
	    skf_hdr->isaskf_number, skf_hdr->isaskf_total, skf_hdr->isaskf_np);

	const char *why = ignore_v2_incoming_fragment((*frags), md, skf_hdr);
	if (why != NULL) {
		llog_sa(RC_LOG, ike, "dropping fragment %u of %u as %s",
			skf_hdr->isaskf_number, skf_hdr->isaskf_total, why);
		return FRAGMENT_IGNORED;
	}

	/* locate what is interesting */

	/* entire SKF pbs; cur points past SKF header */
	const struct pbs_in *skf_pbs = &md->chain[ISAKMP_NEXT_v2SKF]->pbs;
	/* entire payload: AAD+SKF-header+IV+cipher-text) */
	chunk_t text = chunk2(md->packet_pbs.start, skf_pbs->roof - md->packet_pbs.start);
	/* first thing after SKF header is Initialization Vector */
	unsigned iv_offset = skf_pbs->cur - md->packet_pbs.start;

	/* if possible, decrypt (in place) */

	shunk_t plain = null_shunk;
	if (ike->sa.hidden_variables.st_skeyid_calculated) {
		/*
		 * Try to decrypt in-place.
		 *
		 * If this fails, don't even bother saving the
		 * packet.
		 *
		 * After the call, PLAIN is pointing at the
		 * decrypted plain-text within TEXT.
		 */
		if (!verify_and_decrypt_v2_message(ike, text, &plain,
						   iv_offset)) {
			llog_sa(RC_LOG, ike,
				"fragment %u of %u invalid",
				skf_hdr->isaskf_number,
				skf_hdr->isaskf_total);
			return FRAGMENT_IGNORED;
		}
		dbg("fragment %u of %u decrypted",
		    skf_hdr->isaskf_number,
		    skf_hdr->isaskf_total);
	}

	/* make space for the fragment (it's worth saving) */

	if ((*frags) == NULL) {
		*frags = alloc_thing(struct v2_incoming_fragments, "incoming v2_ike_rfrags");
		(*frags)->total = skf_hdr->isaskf_total;
		(*frags)->xchg = md->hdr.isa_xchg;
		/* may not be fragment 1; will replace when it arrives */
		(*frags)->md = md_addref(md);
	}

	/* save the fragment */

	passert((*frags)->count < (*frags)->total);
	(*frags)->count++;
	struct v2_incoming_fragment *frag = &(*frags)->frags[skf_hdr->isaskf_number];
	passert(skf_hdr->isaskf_number < elemsof((*frags)->frags));
	passert(frag->text.ptr == NULL);
	passert(frag->plain.ptr == NULL);
	passert(frag->text.len == 0);
	passert(frag->plain.len == 0);
	frag->text = clone_hunk(text, "incoming IKEv2 encrypted fragment");
	frag->iv_offset = iv_offset;
	if (ike->sa.hidden_variables.st_skeyid_calculated) {
		/*
		 * Since TEXT has been decrypted (PLAIN points into
		 * TEXT at the unencrypted blob), update frag's .plain
		 * so it points in frag's .text.
		 */
		ptrdiff_t plain_offset = (const uint8*)plain.ptr - (const uint8_t*)text.ptr;
		frag->plain = shunk2(frag->text.ptr + plain_offset, plain.len);
	}

	/*
	 * Additionally, save fragment 1.  The first fragment's
	 * message is needed for two reasons:
	 *
	 * - the next-payload field in the first fragment's SKF header
	 * is used as the next-payload field of the reconstituted SK
	 * payload header
	 *
	 * - any unencrypted payloads from the first message are
	 * included in the reconstituted message
	 *
	 * RFC 7383:
	 *  2.5.3.  Fragmenting Messages Containing Unprotected Payloads
	 *
	 *  Currently, there are no IKEv2 exchanges that define
	 *  messages, containing both unprotected payloads and
	 *  payloads, that are protected by the Encrypted payload.
	 *  However, IKEv2 does not prohibit such construction.  If
	 *  some future IKEv2 extension defines such a message and it
	 *  needs to be fragmented, all unprotected payloads MUST be
	 *  placed in the first fragment (with the Fragment Number
	 *  field equal to 1), along with the Encrypted Fragment
	 *  payload, which MUST be present in every IKE Fragment
	 *  message and be the last payload in it.
	 *
	 * XXX: to be honest, the use of "protected" here seems
	 * confused.  The entire message is protected, it is just that
	 * the SKF payload is encrypted.
	 *
	 * If .md contains some other fragment saved earlier by the
	 * above, replace it now.
	 */
	if (skf_hdr->isaskf_number == 1) {
		(*frags)->first_np = skf_hdr->isaskf_np;
		md_delref(&(*frags)->md);
		(*frags)->md = md_addref(md);
	}

	return (*frags)->count == (*frags)->total ? FRAGMENTS_COMPLETE : FRAGMENTS_MISSING;
}

bool decrypt_v2_incoming_fragments(struct ike_sa *ike,
				   struct v2_incoming_fragments **frags)
{
	for (unsigned i = 1; i <= (*frags)->total; i++) {
		struct v2_incoming_fragment *frag = &(*frags)->frags[i];
		if (frag->text.ptr != NULL) {
			/*
			 * Point PLAIN at the encrypted fragment and
			 * then decrypt in-place.  After the
			 * decryption, PLAIN will have been adjusted
			 * to just point at the data.
			 *
			 * For moment log the individual fragments
			 * that are invalid (too verbose VS helping
			 * responder figure out where things go
			 * wrong).
			 */
			if (!verify_and_decrypt_v2_message(ike, frag->text,
							   &frag->plain,
							   frag->iv_offset)) {
				llog_sa(RC_LOG, ike,
					"saved fragment %u of %u invalid; dropped",
					i, (*frags)->total);
				/* release the frag */
				(*frags)->count--;
				free_chunk_content(&frag->text);
				frag->text = empty_chunk;
				frag->plain = null_shunk;
				frag->iv_offset = 0;
			}
			dbg("saved fragment %u of %u decrypted",
			    i, (*frags)->total);
		}
	}

	/* see what, if anything, is left */

	if ((*frags)->count == 0) {
		/*
		 * Without a valid fragment there's no way to trust
		 * .md and .total, start again from scratch.
		 */
		dbg("all fragments were invalid, .total can NOT be trusted");
		free_v2_incoming_fragments(frags);
		return false;
	}

	if ((*frags)->count < (*frags)->total) {
		/* more to do */
		dbg("some, but not all fragments were invalid, .total can be trusted");
		return false;
	}

	return true;
}

struct msg_digest *reassemble_v2_incoming_fragments(struct v2_incoming_fragments **frags)
{
	dbg("reassembling incoming fragments");
	struct msg_digest *md = md_addref((*frags)->md);
	passert(md->chain[ISAKMP_NEXT_v2SK] == NULL);
	passert(md->chain[ISAKMP_NEXT_v2SKF] != NULL);
	pexpect(md->chain[ISAKMP_NEXT_v2SKF]->payload.v2skf.isaskf_number == 1);
	passert(md->digest_roof < elemsof(md->digest));

	/*
	 * Pass 1: Compute the total payload size.
	 */
	unsigned size = 0;
	for (unsigned i = 1; i <= (*frags)->total; i++) {
		struct v2_incoming_fragment *frag = &(*frags)->frags[i];
		pexpect(frag->plain.ptr != NULL);
		size += frag->plain.len;
	}

	/*
	 * Pass 2: Re-assemble the fragments into the .raw_packet
	 * buffer.
	 */
	pexpect(md->raw_packet.ptr == NULL); /* empty */
	md->raw_packet = alloc_chunk(size, "IKEv2 fragments buffer");
	unsigned int offset = 0;
	for (unsigned i = 1; i <= (*frags)->total; i++) {
		struct v2_incoming_fragment *frag = &(*frags)->frags[i];
		passert(offset + frag->plain.len <= size);
		memcpy(md->raw_packet.ptr + offset,
		       frag->plain.ptr, frag->plain.len);
		offset += frag->plain.len;
	}

	/*
	 * Fake up enough of an SK payload_digest to fool the caller
	 * and then scribble that all over the SKF (updating the SK
	 * and SKF .chain[] pointers).
	 */
	struct payload_digest sk = {
		.pbs = pbs_in_from_shunk(HUNK_AS_SHUNK(md->raw_packet), "decrypted SFK payloads"),
		.payload_type = ISAKMP_NEXT_v2SK,
		.payload.generic.isag_np = (*frags)->first_np,
	};
	struct payload_digest *skf = md->chain[ISAKMP_NEXT_v2SKF];
	md->chain[ISAKMP_NEXT_v2SKF] = NULL;
	md->chain[ISAKMP_NEXT_v2SK] = skf;
	*skf = sk; /* scribble */

	/* save the fragment total; used later by duplicate code */
	md->v2_frags_total = (*frags)->total;

	/* clean up */
	free_v2_incoming_fragments(frags);
	return md;
}

/*
 * Decrypt the, possibly fragmented message intended for ST.
 *
 * Since the message fragments are stored in the recipient's ST
 * (either IKE or CHILD SA), it, and not the IKE SA is needed.
 *
 * The bytes to be decryted are roughly .cursor + sizeof(IV) - .roof.
 */
bool ikev2_decrypt_msg(struct ike_sa *ike, struct msg_digest *md)
{
	struct pbs_in *sk_pbs = &md->chain[ISAKMP_NEXT_v2SK]->pbs;
	/*
	 * If so impaired, clone the encrypted message before it gets
	 * decrypted in-place (but only once).
	 */
	if (impair.replay_encrypted && !md->fake_clone) {
		llog_sa(RC_LOG, ike,
			  "IMPAIR: cloning incoming encrypted message and scheduling its replay");
		schedule_md_event("replay encrypted message",
				  clone_raw_md(md, HERE));
	}

	/*
	 * Having read the SK header, the .cursor is pointing at the
	 * IV.  Lets corrupt it!
	 */
	size_t iv_offset = sk_pbs->cur - md->packet_pbs.start;
	if (impair.corrupt_encrypted && !md->fake_clone) {
		llog_sa(RC_LOG, ike,
			  "IMPAIR: corrupting incoming encrypted message's SK payload's first byte");
		md->packet_pbs.start[iv_offset] = ~(md->packet_pbs.start[iv_offset]);
	}

	chunk_t message = chunk2(md->packet_pbs.start, sk_pbs->roof - md->packet_pbs.start);
	shunk_t plain = null_shunk; /*to be sure*/
	bool ok = verify_and_decrypt_v2_message(ike, message, &plain, iv_offset);
	md->chain[ISAKMP_NEXT_v2SK]->pbs = pbs_in_from_shunk(plain, "decrypted SK payload");

	enum_buf xb;
	ldbg(ike->sa.logger, PRI_SO" ikev2 %s decrypt %s",
	     pri_so(ike->sa.st_serialno),
	     str_enum(&ikev2_exchange_names, md->hdr.isa_xchg, &xb),
	     ok ? "success" : "failed");

	return ok;
}

/*
 * IKEv2 fragments:
 *
 *                        1                   2                   3
 *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   | Next Payload  |C|  RESERVED   |         Payload Length        |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |        Fragment Number        |        Total Fragments        |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |                     Initialization Vector                     |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   ~                      Encrypted content                        ~
 *   +               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   |               |             Padding (0-255 octets)            |
 *   +-+-+-+-+-+-+-+-+                               +-+-+-+-+-+-+-+-+
 *   |                                               |  Pad Length   |
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *   ~                    Integrity Checksum Data                    ~
 *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *

 *
 */

static bool record_outbound_fragment(struct logger *logger,
				     struct ike_sa *ike,
				     const struct isakmp_hdr *hdr,
				     enum next_payload_types_ikev2 skf_np,
				     struct v2_outgoing_fragment **fragp,
				     chunk_t *fragment,	/* read-only */
				     unsigned int number, unsigned int total,
				     const char *desc)
{
	struct fragment_pbs_out message_fragment;
	if (!open_fragment_pbs_out("fragment", &message_fragment, logger)) {
		return false;
	}

	/* HDR out */

	struct pbs_out body;
	if (!pbs_out_struct(&message_fragment.pbs, &isakmp_hdr_desc, hdr, sizeof(*hdr), &body))
		return false;

	/*
	 * Fake up an SK payload description sufficient to fool the
	 * encryption code.
	 *
	 * While things are close, they are not identical - an SKF
	 * payload header has extra fields and, for the first
	 * fragment, forces the Next Payload.
	 */

	struct v2SK_payload skf = {
		.ike = ike,
		.logger = logger,
		.payload = {
		    .ptr = body.cur,
		    .len = 0 /* computed at end; set here to silence GCC 4.8.5 */
		}
	};

	/*
	 * emit SKF header, save location.
	 *
	 * In the first fragment, .NP is set to the SK payload's next
	 * payload type.
	 */

	const struct ikev2_skf e = {
		.isaskf_np = skf_np, /* needed */
		.isaskf_critical = build_ikev2_critical(false, ike->sa.logger),
		.isaskf_number = number,
		.isaskf_total = total,
	};
	if (!pbs_out_struct(&body, &ikev2_skf_desc, &e, sizeof(e), &skf.pbs))
		return false;

	/*
	 * Additional Authenticated Data - AAD - is everything so far:
	 * i.e., the IKE header and payload headers.
	 *
	 * RFC5282 says: The Initialization Vector and Ciphertext
	 * fields [...] MUST NOT be included in the associated data.
	 */

	skf.aad = chunk2(skf.pbs.container->start, skf.pbs.cur - skf.pbs.container->start);

	/* emit IV and save location */

	if (!emit_v2SK_iv(&skf)) {
		llog(RC_LOG, logger,
		     "error initializing IV for encrypted %s message",
		     desc);
		return false;
	}

	/* save cleartext start */

	skf.cleartext.ptr = skf.pbs.cur;

	/* output the fragment */

	if (!out_hunk(*fragment, &skf.pbs, "cleartext fragment"))
		return false;

	if (!close_v2SK_payload(&skf)) {
		return false;
	}

	close_output_pbs(&body);
	close_output_pbs(&message_fragment.pbs);

	if (!encrypt_v2SK_payload(&skf)) {
		llog(RC_LOG, logger, "error encrypting fragment %u", number);
		return false;
	}

	dbg("recording fragment %u", number);
	record_v2_outgoing_fragment(&message_fragment.pbs, desc, fragp);
	return true;
}

static bool record_outbound_fragments(const struct pbs_out *body,
				      struct v2SK_payload *sk,
				      const char *desc,
				      struct v2_outgoing_fragment **frags)
{
	free_v2_outgoing_fragments(frags);

	/*
	 * fragment contents:
	 * - sometimes:	NON_ESP_MARKER (RFC3948) (NON_ESP_MARKER_SIZE) (4)
	 * - always:	isakmp header (NSIZEOF_isakmp_hdr) (28)
	 * - always:	ikev2_skf header (NSIZEOF_ikev2_skf) (8)
	 * - variable:	IV (no IV is longer than SHA2_512_DIGEST_SIZE) (64 or less)
	 * - variable:	fragment's data
	 * - variable:	padding (no padding is longer than MAX_CBC_BLOCK_SIZE) (16 or less)
	 */

	/*
	 * XXX: this math seems very contrived, can the fragment()
	 * function above be left to do the computation on-the-fly?
	 */

	unsigned int len = endpoint_info(sk->ike->sa.st_remote_endpoint)->ikev2_max_fragment_size;

	/*
	 * If we are doing NAT, so that the other end doesn't mistake
	 * this message for ESP, each message needs a non-ESP_Marker
	 * prefix.
	 */
	if (sk->ike->sa.st_iface_endpoint != NULL && sk->ike->sa.st_iface_endpoint->esp_encapsulation_enabled)
		len -= NON_ESP_MARKER_SIZE;

	len -= NSIZEOF_isakmp_hdr + NSIZEOF_ikev2_skf;

	len -= (encrypt_desc_is_aead(sk->ike->sa.st_oakley.ta_encrypt)
		? sk->ike->sa.st_oakley.ta_encrypt->aead_tag_size
		: sk->ike->sa.st_oakley.ta_integ->integ_output_size);

	if (sk->ike->sa.st_oakley.ta_encrypt->pad_to_blocksize)
		len &= ~(sk->ike->sa.st_oakley.ta_encrypt->enc_blocksize - 1);

	len -= 2;	/* ??? what's this? */

	passert(sk->cleartext.len != 0);

	unsigned int nfrags = (sk->cleartext.len + len - 1) / len;

	if (nfrags > MAX_IKE_FRAGMENTS) {
		llog(RC_LOG, sk->logger,
			    "fragmenting this %zu byte message into %u byte chunks leads to too many frags",
			    sk->cleartext.len, len);
		return false;
	}

	/*
	 * Extract the hdr from the original unfragmented message.
	 * Set it up for auto-update of its next payload field chain.
	 */
	struct isakmp_hdr hdr;
	{
		shunk_t message = pbs_out_all(body);
		struct pbs_in pbs = pbs_in_from_shunk(message, "sk hdr");
		struct pbs_in ignored;
		diag_t d = pbs_in_struct(&pbs, &isakmp_hdr_desc, &hdr, sizeof(hdr), &ignored);
		if (d != NULL) {
			llog(RC_LOG, sk->logger, "%s", str_diag(d));
			pfree_diag(&d);
			return false;
		}
	}
	hdr.isa_np = ISAKMP_NEXT_v2NONE; /* clear NP */

	/*
	 * Extract the SK's next payload field from the original
	 * unfragmented message.  This is used as the first SKF's NP
	 * field, the rest have NP=NONE(0).
	 */
	enum next_payload_types_ikev2 skf_np;
	{
		struct pbs_in pbs = pbs_in_from_shunk(HUNK_AS_SHUNK(sk->payload), "sk");
		struct ikev2_generic e;
		struct pbs_in ignored;
		diag_t d = pbs_in_struct(&pbs, &ikev2_sk_desc, &e, sizeof(e), &ignored);
		if (d != NULL) {
			llog(RC_LOG, sk->logger, "%s", str_diag(d));
			pfree_diag(&d);
			return false;
		}
		skf_np = e.isag_np;
	}

	unsigned int number = 1;
	unsigned int offset = 0;

	struct v2_outgoing_fragment **frag = frags;
	while (true) {
		passert(*frag == NULL);
		chunk_t fragment = chunk2(sk->cleartext.ptr + offset,
					  PMIN(sk->cleartext.len - offset, len));
		if (!record_outbound_fragment(sk->logger, sk->ike, &hdr, skf_np, frag,
					      &fragment, number, nfrags, desc)) {
			return false;
		}
		frag = &(*frag)->next;

		offset += fragment.len;
		number++;
		skf_np = ISAKMP_NEXT_v2NONE;

		if (offset >= sk->cleartext.len) {
			break;
		}
	}

	return true;
}

/*
 * Record the message ready for sending.  If needed, first fragment
 * it.
 */

static stf_status record_v2SK_message(struct pbs_out *msg,
				      struct v2SK_payload *sk,
				      const char *what,
				      struct v2_outgoing_fragment **outgoing_fragments)
{
	size_t len = pbs_out_all(msg).len;

	/*
	 * If we are doing NAT, so that the other end doesn't mistake
	 * this message for ESP, each message needs a non-ESP_Marker
	 * prefix.
	 */
	if (!pexpect(sk->ike->sa.st_iface_endpoint != NULL) &&
	    sk->ike->sa.st_iface_endpoint->esp_encapsulation_enabled)
		len += NON_ESP_MARKER_SIZE;

	/* IPv4 and IPv6 have different fragment sizes */
	if (sk->ike->sa.st_iface_endpoint->io->protocol == &ip_protocol_udp &&
	    sk->ike->sa.st_v2_ike_fragmentation_enabled &&
	    len >= endpoint_info(sk->ike->sa.st_remote_endpoint)->ikev2_max_fragment_size) {
		if (!record_outbound_fragments(msg, sk, what, outgoing_fragments)) {
			dbg("record outbound fragments failed");
			return STF_INTERNAL_ERROR;
		}
	} else {
		if (!encrypt_v2SK_payload(sk)) {
			llog(RC_LOG, sk->logger,
				    "error encrypting %s message", what);
			return STF_INTERNAL_ERROR;
		}
		dbg("recording outgoing fragment failed");
		record_v2_message(msg, what, outgoing_fragments);
	}
	return STF_OK;
}

struct ikev2_id build_v2_id_payload(const struct host_end *end, shunk_t *body,
				    const char *what, struct logger *logger)
{
	struct ikev2_id id_header = {
		.isai_type = id_to_payload(&end->id, &end->addr, body),
		.isai_critical = build_ikev2_critical(false, logger),
	};
	if (impair.send_nonzero_reserved_id) {
		llog(RC_LOG, logger, "IMPAIR: setting reserved byte 3 of %s to 0x%02x",
		     what, ISAKMP_PAYLOAD_FLAG_LIBRESWAN_BOGUS);
		id_header.isai_res3 = ISAKMP_PAYLOAD_FLAG_LIBRESWAN_BOGUS;
	}
	return id_header;
}

bool open_v2_message(const char *story,
		     struct ike_sa *ike, struct logger *logger,
		     struct msg_digest *request_md,
		     enum ikev2_exchange exchange_type,
		     uint8_t *buf, size_t sizeof_buf,
		     struct v2_message *message,
		     enum payload_security security)
{
	*message = (struct v2_message) {
		.story = story,
		.logger = logger,
		.security = security,
		.outgoing_fragments = (request_md == NULL ? &ike->sa.st_v2_msgid_windows.initiator.outgoing_fragments :
				       &ike->sa.st_v2_msgid_windows.responder.outgoing_fragments),
	};

	message->message = open_pbs_out(story, buf, sizeof_buf, logger);

	if (!open_v2_message_body(&message->message, ike, request_md,
				  exchange_type, &message->body)) {
		llog(RC_LOG, message->logger,
		     "error initializing hdr for encrypted notification");
		return false;
	}

	switch (security) {
	case ENCRYPTED_PAYLOAD:
		/*
		 * Never encrypt the initial exchange (peer requires
		 * Nr in response before it can compute keys and
		 * decrypt it).
		 */
		if (exchange_type == ISAKMP_v2_IKE_SA_INIT ||
		    exchange_type == ISAKMP_v2_IKE_SESSION_RESUME) {
			name_buf nb;
			llog_pexpect(message->logger, HERE,
				     "exchange type %s is invalid for encrypted notification",
				     str_enum_short(&ikev2_exchange_names, exchange_type, &nb));
			return false;
		}
		/*
		 * Encrypting requires an IKE SA for the keys.
		 */
		if (PBAD(message->logger, ike == NULL)) {
			return false;
		}
		/*
		 * Encryption requires the IKE SA to have keys.
		 */
		if (!PEXPECT(message->logger, ike->sa.hidden_variables.st_skeyid_calculated)) {
			return false;
		}
		if (!open_body_v2SK_payload(&message->body, ike, logger, &message->sk)) {
			return false;
		}
		message->pbs = &message->sk.pbs;
		if (!emit_v2UNKNOWN("encrypted", exchange_type,
				    &impair.add_unknown_v2_payload_to_sk,
				    message->pbs)) {
			return false;
		}
		break;
	case UNENCRYPTED_PAYLOAD:
		/*
		 * Only send the initial exchange unencrypted (peer
		 * needs unencrypted response containing Nr before it
		 * can generate keys; all following exchanges should
		 * be encrypted).
		 *
		 * Note that .ST_SKEYID_CALCULATED may be set. With
		 * IKE_SESSION_RESUME, it is computed before building
		 * the response (for IKE_SA_INIT it is only computed
		 * upon the arrival of the IKE_AUTH message).
		 */
		if (exchange_type != ISAKMP_v2_IKE_SA_INIT &&
		    exchange_type != ISAKMP_v2_IKE_SESSION_RESUME) {
			name_buf nb;
			llog_pexpect(message->logger, HERE,
				     "exchange type %s is invalid for encrypted notification",
				     str_enum_short(&ikev2_exchange_names, exchange_type, &nb));
			return false;
		}
		message->pbs = &message->body;
		break;
	}

	return true;
}

bool close_v2_message(struct v2_message *message)
{
	if (impair.add_v2_notification.enabled) {
		if (!emit_v2N(impair.add_v2_notification.value, message->pbs)) {
			return false;
		}
	}

	switch (message->security) {
	case ENCRYPTED_PAYLOAD:
		if (!close_v2SK_payload(&message->sk)) {
			return false;
		}
		break;
	case UNENCRYPTED_PAYLOAD:
		break;
	}
	close_output_pbs(&message->body);
	close_output_pbs(&message->message);
	return true;
}

bool close_and_record_v2_message(struct v2_message *message)
{
	if (!close_v2_message(message)) {
		return false;
	}

	switch (message->security) {
	case ENCRYPTED_PAYLOAD:
		if (record_v2SK_message(&message->message,
					&message->sk,
					message->story,
					message->outgoing_fragments) != STF_OK) {
			return false;
		}
		return true;
	case UNENCRYPTED_PAYLOAD:
		record_v2_message(&message->message, message->story,
				  message->outgoing_fragments);
		return true;
	}
	bad_case(message->security);
}