summaryrefslogtreecommitdiff
path: root/src/core/gnunet-service-core_kx.c
blob: d226b65e2cf6307075ee71e2496d3e94a8f12cb1 (plain)
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
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
/*
     This file is part of GNUnet.
     Copyright (C) 2009-2013, 2016 GNUnet e.V.

     GNUnet is free software: you can redistribute it and/or modify it
     under the terms of the GNU Affero General Public License as published
     by the Free Software Foundation, either version 3 of the License,
     or (at your option) any later version.

     GNUnet 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
     Affero General Public License for more details.

     You should have received a copy of the GNU Affero General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.

     SPDX-License-Identifier: AGPL3.0-or-later
*/

/**
 * @file core/gnunet-service-core_kx.c
 * @brief code for managing the key exchange (SET_KEY, PING, PONG) with other
 * peers
 * @author Christian Grothoff
 */
#include "platform.h"
#include "gnunet-service-core_kx.h"
#include "gnunet-service-core.h"
#include "gnunet-service-core_sessions.h"
#include "gnunet_statistics_service.h"
#include "gnunet_transport_service.h"
#include "gnunet_constants.h"
#include "gnunet_signatures.h"
#include "gnunet_protocols.h"
#include "core.h"

/**
 * Enable expensive (and possibly problematic for privacy!) logging of KX.
 */
#define DEBUG_KX 0

/**
 * How long do we wait for SET_KEY confirmation initially?
 */
#define INITIAL_SET_KEY_RETRY_FREQUENCY \
  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)

/**
 * What is the minimum frequency for a PING message?
 */
#define MIN_PING_FREQUENCY \
  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)

/**
 * How often do we rekey?
 */
#define REKEY_FREQUENCY \
  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)

/**
 * What time difference do we tolerate?
 */
#define REKEY_TOLERANCE \
  GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)

/**
 * What is the maximum age of a message for us to consider processing
 * it?  Note that this looks at the timestamp used by the other peer,
 * so clock skew between machines does come into play here.  So this
 * should be picked high enough so that a little bit of clock skew
 * does not prevent peers from connecting to us.
 */
#define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS


GNUNET_NETWORK_STRUCT_BEGIN

/**
 * Message transmitted with the signed ephemeral key of a peer.  The
 * session key is then derived from the two ephemeral keys (ECDHE).
 */
struct EphemeralKeyMessage
{

  /**
   * Message type is #GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY.
   */
  struct GNUNET_MessageHeader header;

  /**
   * Status of the sender (should be in `enum PeerStateMachine`), nbo.
   */
  int32_t sender_status GNUNET_PACKED;

  /**
   * An ECC signature of the @e origin_identity asserting the validity
   * of the given ephemeral key.
   */
  struct GNUNET_CRYPTO_EddsaSignature signature;

  /**
   * Information about what is being signed.
   */
  struct GNUNET_CRYPTO_EccSignaturePurpose purpose;

  /**
   * At what time was this key created (beginning of validity).
   */
  struct GNUNET_TIME_AbsoluteNBO creation_time;

  /**
   * When does the given ephemeral key expire (end of validity).
   */
  struct GNUNET_TIME_AbsoluteNBO expiration_time;

  /**
   * Ephemeral public ECC key.
   */
  struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key;

  /**
   * Public key of the signing peer (persistent version, not the
   * ephemeral public key).
   */
  struct GNUNET_PeerIdentity origin_identity;
};


/**
 * We're sending an (encrypted) PING to the other peer to check if it
 * can decrypt.  The other peer should respond with a PONG with the
 * same content, except this time encrypted with the receiver's key.
 */
struct PingMessage
{
  /**
   * Message type is #GNUNET_MESSAGE_TYPE_CORE_PING.
   */
  struct GNUNET_MessageHeader header;

  /**
   * Seed for the IV
   */
  uint32_t iv_seed GNUNET_PACKED;

  /**
   * Intended target of the PING, used primarily to check
   * that decryption actually worked.
   */
  struct GNUNET_PeerIdentity target;

  /**
   * Random number chosen to make replay harder.
   */
  uint32_t challenge GNUNET_PACKED;
};


/**
 * Response to a PING.  Includes data from the original PING.
 */
struct PongMessage
{
  /**
   * Message type is #GNUNET_MESSAGE_TYPE_CORE_PONG.
   */
  struct GNUNET_MessageHeader header;

  /**
   * Seed for the IV
   */
  uint32_t iv_seed GNUNET_PACKED;

  /**
   * Random number to make replay attacks harder.
   */
  uint32_t challenge GNUNET_PACKED;

  /**
   * Reserved, always zero.
   */
  uint32_t reserved;

  /**
   * Intended target of the PING, used primarily to check
   * that decryption actually worked.
   */
  struct GNUNET_PeerIdentity target;
};


/**
 * Encapsulation for encrypted messages exchanged between
 * peers.  Followed by the actual encrypted data.
 */
struct EncryptedMessage
{
  /**
   * Message type is #GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE.
   */
  struct GNUNET_MessageHeader header;

  /**
   * Random value used for IV generation.
   */
  uint32_t iv_seed GNUNET_PACKED;

  /**
   * MAC of the encrypted message (starting at @e sequence_number),
   * used to verify message integrity. Everything after this value
   * (excluding this value itself) will be encrypted and
   * authenticated.  #ENCRYPTED_HEADER_SIZE must be set to the offset
   * of the *next* field.
   */
  struct GNUNET_HashCode hmac;

  /**
   * Sequence number, in network byte order.  This field
   * must be the first encrypted/decrypted field
   */
  uint32_t sequence_number GNUNET_PACKED;

  /**
   * Reserved, always zero.
   */
  uint32_t reserved GNUNET_PACKED;

  /**
   * Timestamp.  Used to prevent replay of ancient messages
   * (recent messages are caught with the sequence number).
   */
  struct GNUNET_TIME_AbsoluteNBO timestamp;
};
GNUNET_NETWORK_STRUCT_END


/**
 * Number of bytes (at the beginning) of `struct EncryptedMessage`
 * that are NOT encrypted.
 */
#define ENCRYPTED_HEADER_SIZE \
  (offsetof (struct EncryptedMessage, sequence_number))


/**
 * Information about the status of a key exchange with another peer.
 */
struct GSC_KeyExchangeInfo
{

  /**
   * DLL.
   */
  struct GSC_KeyExchangeInfo *next;

  /**
   * DLL.
   */
  struct GSC_KeyExchangeInfo *prev;

  /**
   * Identity of the peer.
   */
  const struct GNUNET_PeerIdentity *peer;

  /**
   * Message queue for sending messages to @a peer.
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * Our message stream tokenizer (for encrypted payload).
   */
  struct GNUNET_MessageStreamTokenizer *mst;

  /**
   * PING message we transmit to the other peer.
   */
  struct PingMessage ping;

  /**
   * Ephemeral public ECC key of the other peer.
   */
  struct GNUNET_CRYPTO_EcdhePublicKey other_ephemeral_key;

  /**
   * Key we use to encrypt our messages for the other peer
   * (initialized by us when we do the handshake).
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey encrypt_key;

  /**
   * Key we use to decrypt messages from the other peer
   * (given to us by the other peer during the handshake).
   */
  struct GNUNET_CRYPTO_SymmetricSessionKey decrypt_key;

  /**
   * At what time did the other peer generate the decryption key?
   */
  struct GNUNET_TIME_Absolute foreign_key_expires;

  /**
   * When should the session time out (if there are no PONGs)?
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * What was the last timeout we informed our monitors about?
   */
  struct GNUNET_TIME_Absolute last_notify_timeout;

  /**
   * At what frequency are we currently re-trying SET_KEY messages?
   */
  struct GNUNET_TIME_Relative set_key_retry_frequency;

  /**
   * ID of task used for re-trying SET_KEY and PING message.
   */
  struct GNUNET_SCHEDULER_Task *retry_set_key_task;

  /**
   * ID of task used for sending keep-alive pings.
   */
  struct GNUNET_SCHEDULER_Task *keep_alive_task;

  /**
   * Bit map indicating which of the 32 sequence numbers before the
   * last were received (good for accepting out-of-order packets and
   * estimating reliability of the connection)
   */
  uint32_t last_packets_bitmap;

  /**
   * last sequence number received on this connection (highest)
   */
  uint32_t last_sequence_number_received;

  /**
   * last sequence number transmitted
   */
  uint32_t last_sequence_number_sent;

  /**
   * What was our PING challenge number (for this peer)?
   */
  uint32_t ping_challenge;

  /**
   * #GNUNET_YES if this peer currently has excess bandwidth.
   */
  int has_excess_bandwidth;

  /**
   * What is our connection status?
   */
  enum GNUNET_CORE_KxState status;
};


/**
 * Transport service.
 */
static struct GNUNET_TRANSPORT_CoreHandle *transport;

/**
 * Our private key.
 */
static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;

/**
 * Our ephemeral private key.
 */
static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;

/**
 * Current message we send for a key exchange.
 */
static struct EphemeralKeyMessage current_ekm;

/**
 * DLL head.
 */
static struct GSC_KeyExchangeInfo *kx_head;

/**
 * DLL tail.
 */
static struct GSC_KeyExchangeInfo *kx_tail;

/**
 * Task scheduled for periodic re-generation (and thus rekeying) of our
 * ephemeral key.
 */
static struct GNUNET_SCHEDULER_Task *rekey_task;

/**
 * Notification context for broadcasting to monitors.
 */
static struct GNUNET_NotificationContext *nc;


/**
 * Calculate seed value we should use for a message.
 *
 * @param kx key exchange context
 */
static uint32_t
calculate_seed (struct GSC_KeyExchangeInfo *kx)
{
  /* Note: may want to make this non-random and instead
     derive from key material to avoid having an undetectable
     side-channel */
  return htonl (
    GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
}


/**
 * Inform all monitors about the KX state of the given peer.
 *
 * @param kx key exchange state to inform about
 */
static void
monitor_notify_all (struct GSC_KeyExchangeInfo *kx)
{
  struct MonitorNotifyMessage msg;

  msg.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
  msg.header.size = htons (sizeof (msg));
  msg.state = htonl ((uint32_t) kx->status);
  msg.peer = *kx->peer;
  msg.timeout = GNUNET_TIME_absolute_hton (kx->timeout);
  GNUNET_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
  kx->last_notify_timeout = kx->timeout;
}


/**
 * Derive an authentication key from "set key" information
 *
 * @param akey authentication key to derive
 * @param skey session key to use
 * @param seed seed to use
 */
static void
derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
                 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
                 uint32_t seed)
{
  static const char ctx[] = "authentication key";
#if DEBUG_KX
  struct GNUNET_HashCode sh;

  GNUNET_CRYPTO_hash (skey, sizeof (*skey), &sh);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Deriving Auth key from SKEY %s and seed %u\n",
              GNUNET_h2s (&sh),
              (unsigned int) seed);
#endif
  GNUNET_CRYPTO_hmac_derive_key (akey,
                                 skey,
                                 &seed,
                                 sizeof (seed),
                                 skey,
                                 sizeof (
                                   struct GNUNET_CRYPTO_SymmetricSessionKey),
                                 ctx,
                                 sizeof (ctx),
                                 NULL);
}


/**
 * Derive an IV from packet information
 *
 * @param iv initialization vector to initialize
 * @param skey session key to use
 * @param seed seed to use
 * @param identity identity of the other peer to use
 */
static void
derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
           const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
           uint32_t seed,
           const struct GNUNET_PeerIdentity *identity)
{
  static const char ctx[] = "initialization vector";
#if DEBUG_KX
  struct GNUNET_HashCode sh;

  GNUNET_CRYPTO_hash (skey, sizeof (*skey), &sh);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Deriving IV from SKEY %s and seed %u for peer %s\n",
              GNUNET_h2s (&sh),
              (unsigned int) seed,
              GNUNET_i2s (identity));
#endif
  GNUNET_CRYPTO_symmetric_derive_iv (iv,
                                     skey,
                                     &seed,
                                     sizeof (seed),
                                     identity,
                                     sizeof (struct GNUNET_PeerIdentity),
                                     ctx,
                                     sizeof (ctx),
                                     NULL);
}


/**
 * Derive an IV from pong packet information
 *
 * @param iv initialization vector to initialize
 * @param skey session key to use
 * @param seed seed to use
 * @param challenge nonce to use
 * @param identity identity of the other peer to use
 */
static void
derive_pong_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
                const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
                uint32_t seed,
                uint32_t challenge,
                const struct GNUNET_PeerIdentity *identity)
{
  static const char ctx[] = "pong initialization vector";
#if DEBUG_KX
  struct GNUNET_HashCode sh;

  GNUNET_CRYPTO_hash (skey, sizeof (*skey), &sh);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Deriving PONG IV from SKEY %s and seed %u/%u for %s\n",
              GNUNET_h2s (&sh),
              (unsigned int) seed,
              (unsigned int) challenge,
              GNUNET_i2s (identity));
#endif
  GNUNET_CRYPTO_symmetric_derive_iv (iv,
                                     skey,
                                     &seed,
                                     sizeof (seed),
                                     identity,
                                     sizeof (struct GNUNET_PeerIdentity),
                                     &challenge,
                                     sizeof (challenge),
                                     ctx,
                                     sizeof (ctx),
                                     NULL);
}


/**
 * Derive an AES key from key material
 *
 * @param sender peer identity of the sender
 * @param receiver peer identity of the sender
 * @param key_material high entropy key material to use
 * @param skey set to derived session key
 */
static void
derive_aes_key (const struct GNUNET_PeerIdentity *sender,
                const struct GNUNET_PeerIdentity *receiver,
                const struct GNUNET_HashCode *key_material,
                struct GNUNET_CRYPTO_SymmetricSessionKey *skey)
{
  static const char ctx[] = "aes key generation vector";
#if DEBUG_KX
  struct GNUNET_HashCode sh;

  GNUNET_CRYPTO_hash (skey, sizeof (*skey), &sh);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Deriving AES Keys for %s to %s from %s\n",
              GNUNET_i2s (sender),
              GNUNET_i2s2 (receiver),
              GNUNET_h2s (key_material));
#endif
  GNUNET_CRYPTO_kdf (skey,
                     sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
                     ctx,
                     sizeof (ctx),
                     key_material,
                     sizeof (struct GNUNET_HashCode),
                     sender,
                     sizeof (struct GNUNET_PeerIdentity),
                     receiver,
                     sizeof (struct GNUNET_PeerIdentity),
                     NULL);
}


/**
 * Encrypt size bytes from @a in and write the result to @a out.  Use the
 * @a kx key for outbound traffic of the given neighbour.
 *
 * @param kx key information context
 * @param iv initialization vector to use
 * @param in ciphertext
 * @param out plaintext
 * @param size size of @a in/@a out
 * @return #GNUNET_OK on success
 */
static int
do_encrypt (struct GSC_KeyExchangeInfo *kx,
            const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
            const void *in,
            void *out,
            size_t size)
{
  if (size != (uint16_t) size)
  {
    GNUNET_break (0);
    return GNUNET_NO;
  }
  GNUNET_assert (size == GNUNET_CRYPTO_symmetric_encrypt (in,
                                                          (uint16_t) size,
                                                          &kx->encrypt_key,
                                                          iv,
                                                          out));
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# bytes encrypted"),
                            size,
                            GNUNET_NO);
  /* the following is too sensitive to write to log files by accident,
     so we require manual intervention to get this one... */
#if DEBUG_KX
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Encrypted %u bytes for `%s' using key %u, IV %u\n",
              (unsigned int) size,
              GNUNET_i2s (kx->peer),
              (unsigned int) kx->encrypt_key.crc32,
              GNUNET_CRYPTO_crc32_n (iv, sizeof (iv)));
#endif
  return GNUNET_OK;
}


/**
 * Decrypt size bytes from @a in and write the result to @a out.  Use
 * the @a kx key for inbound traffic of the given neighbour.  This
 * function does NOT do any integrity-checks on the result.
 *
 * @param kx key information context
 * @param iv initialization vector to use
 * @param in ciphertext
 * @param out plaintext
 * @param size size of @a in / @a out
 * @return #GNUNET_OK on success
 */
static int
do_decrypt (struct GSC_KeyExchangeInfo *kx,
            const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
            const void *in,
            void *out,
            size_t size)
{
  if (size != (uint16_t) size)
  {
    GNUNET_break (0);
    return GNUNET_NO;
  }
  if ((kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) &&
      (kx->status != GNUNET_CORE_KX_STATE_UP) &&
      (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (size != GNUNET_CRYPTO_symmetric_decrypt (in,
                                               (uint16_t) size,
                                               &kx->decrypt_key,
                                               iv,
                                               out))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# bytes decrypted"),
                            size,
                            GNUNET_NO);
  /* the following is too sensitive to write to log files by accident,
     so we require manual intervention to get this one... */
#if DEBUG_KX
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Decrypted %u bytes from `%s' using key %u, IV %u\n",
              (unsigned int) size,
              GNUNET_i2s (kx->peer),
              (unsigned int) kx->decrypt_key.crc32,
              GNUNET_CRYPTO_crc32_n (iv, sizeof (*iv)));
#endif
  return GNUNET_OK;
}


/**
 * Send our key (and encrypted PING) to the other peer.
 *
 * @param kx key exchange context
 */
static void
send_key (struct GSC_KeyExchangeInfo *kx);


/**
 * Task that will retry #send_key() if our previous attempt failed.
 *
 * @param cls our `struct GSC_KeyExchangeInfo`
 */
static void
set_key_retry_task (void *cls)
{
  struct GSC_KeyExchangeInfo *kx = cls;

  kx->retry_set_key_task = NULL;
  kx->set_key_retry_frequency =
    GNUNET_TIME_STD_BACKOFF (kx->set_key_retry_frequency);
  GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status);
  send_key (kx);
}


/**
 * Create a fresh PING message for transmission to the other peer.
 *
 * @param kx key exchange context to create PING for
 */
static void
setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
{
  struct PingMessage pp;
  struct PingMessage *pm;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;

  pm = &kx->ping;
  kx->ping_challenge =
    GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
  pm->header.size = htons (sizeof (struct PingMessage));
  pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
  pm->iv_seed = calculate_seed (kx);
  derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, kx->peer);
  pp.challenge = kx->ping_challenge;
  pp.target = *kx->peer;
  do_encrypt (kx,
              &iv,
              &pp.target,
              &pm->target,
              sizeof (struct PingMessage) -
                ((void *) &pm->target - (void *) pm));
}


/**
 * Deliver P2P message to interested clients.  Invokes send twice,
 * once for clients that want the full message, and once for clients
 * that only want the header
 *
 * @param cls the `struct GSC_KeyExchangeInfo`
 * @param m the message
 * @return #GNUNET_OK on success,
 *    #GNUNET_NO to stop further processing (no error)
 *    #GNUNET_SYSERR to stop further processing with error
 */
static int
deliver_message (void *cls, const struct GNUNET_MessageHeader *m)
{
  struct GSC_KeyExchangeInfo *kx = cls;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Decrypted message of type %d from %s\n",
              ntohs (m->type),
              GNUNET_i2s (kx->peer));
  if (GNUNET_CORE_KX_STATE_UP != kx->status)
  {
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop ("# PAYLOAD dropped (out of order)"),
                              1,
                              GNUNET_NO);
    return GNUNET_OK;
  }
  switch (ntohs (m->type))
  {
  case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
  case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
    GSC_SESSIONS_set_typemap (kx->peer, m);
    return GNUNET_OK;
  case GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP:
    GSC_SESSIONS_confirm_typemap (kx->peer, m);
    return GNUNET_OK;
  default:
    GSC_CLIENTS_deliver_message (kx->peer,
                                 m,
                                 ntohs (m->size),
                                 GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
    GSC_CLIENTS_deliver_message (kx->peer,
                                 m,
                                 sizeof (struct GNUNET_MessageHeader),
                                 GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
  }
  return GNUNET_OK;
}


/**
 * Function called by transport to notify us that
 * a peer connected to us (on the network level).
 * Starts the key exchange with the given peer.
 *
 * @param cls closure (NULL)
 * @param pid identity of the peer to do a key exchange with
 * @return key exchange information context
 */
static void *
handle_transport_notify_connect (void *cls,
                                 const struct GNUNET_PeerIdentity *pid,
                                 struct GNUNET_MQ_Handle *mq)
{
  struct GSC_KeyExchangeInfo *kx;
  struct GNUNET_HashCode h1;
  struct GNUNET_HashCode h2;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Initiating key exchange with `%s'\n",
              GNUNET_i2s (pid));
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# key exchanges initiated"),
                            1,
                            GNUNET_NO);
  kx = GNUNET_new (struct GSC_KeyExchangeInfo);
  kx->mst = GNUNET_MST_create (&deliver_message, kx);
  kx->mq = mq;
  kx->peer = pid;
  kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
  GNUNET_CONTAINER_DLL_insert (kx_head, kx_tail, kx);
  kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
  monitor_notify_all (kx);
  GNUNET_CRYPTO_hash (pid, sizeof (struct GNUNET_PeerIdentity), &h1);
  GNUNET_CRYPTO_hash (&GSC_my_identity,
                      sizeof (struct GNUNET_PeerIdentity),
                      &h2);
  if (0 < GNUNET_CRYPTO_hash_cmp (&h1, &h2))
  {
    /* peer with "lower" identity starts KX, otherwise we typically end up
       with both peers starting the exchange and transmit the 'set key'
       message twice */
    send_key (kx);
  }
  else
  {
    /* peer with "higher" identity starts a delayed KX, if the "lower" peer
     * does not start a KX since it sees no reasons to do so  */
    kx->retry_set_key_task =
      GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
                                    &set_key_retry_task,
                                    kx);
  }
  return kx;
}


/**
 * Function called by transport telling us that a peer
 * disconnected.
 * Stop key exchange with the given peer.  Clean up key material.
 *
 * @param cls closure
 * @param peer the peer that disconnected
 * @param handler_cls the `struct GSC_KeyExchangeInfo` of the peer
 */
static void
handle_transport_notify_disconnect (void *cls,
                                    const struct GNUNET_PeerIdentity *peer,
                                    void *handler_cls)
{
  struct GSC_KeyExchangeInfo *kx = handler_cls;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Peer `%s' disconnected from us.\n",
              GNUNET_i2s (peer));
  GSC_SESSIONS_end (kx->peer);
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# key exchanges stopped"),
                            1,
                            GNUNET_NO);
  if (NULL != kx->retry_set_key_task)
  {
    GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
    kx->retry_set_key_task = NULL;
  }
  if (NULL != kx->keep_alive_task)
  {
    GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
    kx->keep_alive_task = NULL;
  }
  kx->status = GNUNET_CORE_KX_PEER_DISCONNECT;
  monitor_notify_all (kx);
  GNUNET_CONTAINER_DLL_remove (kx_head, kx_tail, kx);
  GNUNET_MST_destroy (kx->mst);
  GNUNET_free (kx);
}


/**
 * Send our PING to the other peer.
 *
 * @param kx key exchange context
 */
static void
send_ping (struct GSC_KeyExchangeInfo *kx)
{
  struct GNUNET_MQ_Envelope *env;

  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# PING messages transmitted"),
                            1,
                            GNUNET_NO);
  env = GNUNET_MQ_msg_copy (&kx->ping.header);
  GNUNET_MQ_send (kx->mq, env);
}


/**
 * Derive fresh session keys from the current ephemeral keys.
 *
 * @param kx session to derive keys for
 */
static void
derive_session_keys (struct GSC_KeyExchangeInfo *kx)
{
  struct GNUNET_HashCode key_material;

  if (GNUNET_OK != GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
                                           &kx->other_ephemeral_key,
                                           &key_material))
  {
    GNUNET_break (0);
    return;
  }
  derive_aes_key (&GSC_my_identity, kx->peer, &key_material, &kx->encrypt_key);
  derive_aes_key (kx->peer, &GSC_my_identity, &key_material, &kx->decrypt_key);
  memset (&key_material, 0, sizeof (key_material));
  /* fresh key, reset sequence numbers */
  kx->last_sequence_number_received = 0;
  kx->last_packets_bitmap = 0;
  setup_fresh_ping (kx);
}


/**
 * We received a #GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY message.
 * Validate and update our key material and status.
 *
 * @param cls key exchange status for the corresponding peer
 * @param m the set key message we received
 */
static void
handle_ephemeral_key (void *cls, const struct EphemeralKeyMessage *m)
{
  struct GSC_KeyExchangeInfo *kx = cls;
  struct GNUNET_TIME_Absolute start_t;
  struct GNUNET_TIME_Absolute end_t;
  struct GNUNET_TIME_Absolute now;
  enum GNUNET_CORE_KxState sender_status;

  end_t = GNUNET_TIME_absolute_ntoh (m->expiration_time);
  if (((GNUNET_CORE_KX_STATE_KEY_RECEIVED == kx->status) ||
       (GNUNET_CORE_KX_STATE_UP == kx->status) ||
       (GNUNET_CORE_KX_STATE_REKEY_SENT == kx->status)) &&
      (end_t.abs_value_us < kx->foreign_key_expires.abs_value_us))
  {
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop ("# old ephemeral keys ignored"),
                              1,
                              GNUNET_NO);
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Received expired EPHEMERAL_KEY from %s\n",
                GNUNET_i2s (&m->origin_identity));
    return;
  }
  if (0 == memcmp (&m->ephemeral_key,
                   &kx->other_ephemeral_key,
                   sizeof (m->ephemeral_key)))
  {
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# duplicate ephemeral keys ignored"),
                              1,
                              GNUNET_NO);
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Ignoring duplicate EPHEMERAL_KEY from %s\n",
                GNUNET_i2s (&m->origin_identity));
    return;
  }
  if (0 != memcmp (&m->origin_identity,
                   kx->peer,
                   sizeof (struct GNUNET_PeerIdentity)))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Received EPHEMERAL_KEY from %s, but expected %s\n",
                GNUNET_i2s (&m->origin_identity),
                GNUNET_i2s_full (kx->peer));
    GNUNET_break_op (0);
    return;
  }
  if ((ntohl (m->purpose.size) !=
       sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
         sizeof (struct GNUNET_TIME_AbsoluteNBO) +
         sizeof (struct GNUNET_TIME_AbsoluteNBO) +
         sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
         sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) ||
      (GNUNET_OK !=
       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY,
                                   &m->purpose,
                                   &m->signature,
                                   &m->origin_identity.public_key)))
  {
    /* invalid signature */
    GNUNET_break_op (0);
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# EPHEMERAL_KEYs rejected (bad signature)"),
                              1,
                              GNUNET_NO);
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Received EPHEMERAL_KEY from %s with bad signature\n",
                GNUNET_i2s (&m->origin_identity));
    return;
  }
  now = GNUNET_TIME_absolute_get ();
  start_t = GNUNET_TIME_absolute_ntoh (m->creation_time);
  if ((end_t.abs_value_us <
       GNUNET_TIME_absolute_subtract (now, REKEY_TOLERANCE).abs_value_us) ||
      (start_t.abs_value_us >
       GNUNET_TIME_absolute_add (now, REKEY_TOLERANCE).abs_value_us))
  {
    GNUNET_log (
      GNUNET_ERROR_TYPE_WARNING,
      _ (
        "EPHEMERAL_KEY from peer `%s' rejected as its validity range does not match our system time (%llu not in [%llu,%llu]).\n"),
      GNUNET_i2s (kx->peer),
      (unsigned long long) now.abs_value_us,
      (unsigned long long) start_t.abs_value_us,
      (unsigned long long) end_t.abs_value_us);
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# EPHEMERAL_KEY messages rejected due to time"),
                              1,
                              GNUNET_NO);
    return;
  }
#if DEBUG_KX
  {
    struct GNUNET_HashCode eh;

    GNUNET_CRYPTO_hash (&m->ephemeral_key, sizeof (m->ephemeral_key), &eh);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Received valid EPHEMERAL_KEY `%s' from `%s' in state %d.\n",
                GNUNET_h2s (&eh),
                GNUNET_i2s (kx->peer),
                kx->status);
  }
#endif
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# valid ephemeral keys received"),
                            1,
                            GNUNET_NO);
  kx->other_ephemeral_key = m->ephemeral_key;
  kx->foreign_key_expires = end_t;
  derive_session_keys (kx);

  /* check if we still need to send the sender our key */
  sender_status = (enum GNUNET_CORE_KxState) ntohl (m->sender_status);
  switch (sender_status)
  {
  case GNUNET_CORE_KX_STATE_DOWN:
    GNUNET_break_op (0);
    break;
  case GNUNET_CORE_KX_STATE_KEY_SENT:
    /* fine, need to send our key after updating our status, see below */
    GSC_SESSIONS_reinit (kx->peer);
    break;
  case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
    /* other peer already got our key, but typemap did go down */
    GSC_SESSIONS_reinit (kx->peer);
    break;
  case GNUNET_CORE_KX_STATE_UP:
    /* other peer already got our key, typemap NOT down */
    break;
  case GNUNET_CORE_KX_STATE_REKEY_SENT:
    /* other peer already got our key, typemap NOT down */
    break;
  default:
    GNUNET_break (0);
    break;
  }
  /* check if we need to confirm everything is fine via PING + PONG */
  switch (kx->status)
  {
  case GNUNET_CORE_KX_STATE_DOWN:
    GNUNET_assert (NULL == kx->keep_alive_task);
    kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED;
    monitor_notify_all (kx);
    if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
      send_key (kx);
    else
      send_ping (kx);
    break;
  case GNUNET_CORE_KX_STATE_KEY_SENT:
    GNUNET_assert (NULL == kx->keep_alive_task);
    kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED;
    monitor_notify_all (kx);
    if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
      send_key (kx);
    else
      send_ping (kx);
    break;
  case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
    GNUNET_assert (NULL == kx->keep_alive_task);
    if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
      send_key (kx);
    else
      send_ping (kx);
    break;
  case GNUNET_CORE_KX_STATE_UP:
    kx->status = GNUNET_CORE_KX_STATE_REKEY_SENT;
    monitor_notify_all (kx);
    if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
      send_key (kx);
    else
      send_ping (kx);
    break;
  case GNUNET_CORE_KX_STATE_REKEY_SENT:
    if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status)
      send_key (kx);
    else
      send_ping (kx);
    break;
  default:
    GNUNET_break (0);
    break;
  }
}


/**
 * We received a PING message.  Validate and transmit
 * a PONG message.
 *
 * @param cls key exchange status for the corresponding peer
 * @param m the encrypted PING message itself
 */
static void
handle_ping (void *cls, const struct PingMessage *m)
{
  struct GSC_KeyExchangeInfo *kx = cls;
  struct PingMessage t;
  struct PongMessage tx;
  struct PongMessage *tp;
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;

  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# PING messages received"),
                            1,
                            GNUNET_NO);
  if ((kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) &&
      (kx->status != GNUNET_CORE_KX_STATE_UP) &&
      (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT))
  {
    /* ignore */
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# PING messages dropped (out of order)"),
                              1,
                              GNUNET_NO);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Core service receives PING request from `%s'.\n",
              GNUNET_i2s (kx->peer));
  derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
  if (GNUNET_OK != do_decrypt (kx,
                               &iv,
                               &m->target,
                               &t.target,
                               sizeof (struct PingMessage) -
                                 ((void *) &m->target - (void *) m)))
  {
    GNUNET_break_op (0);
    return;
  }
  if (0 !=
      memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
  {
    if (GNUNET_CORE_KX_STATE_REKEY_SENT != kx->status)
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Decryption of PING from peer `%s' failed, PING for `%s'?\n",
                  GNUNET_i2s (kx->peer),
                  GNUNET_i2s2 (&t.target));
    else
      GNUNET_log (
        GNUNET_ERROR_TYPE_DEBUG,
        "Decryption of PING from peer `%s' failed after rekey (harmless)\n",
        GNUNET_i2s (kx->peer));
    GNUNET_break_op (0);
    return;
  }
  /* construct PONG */
  tx.reserved = 0;
  tx.challenge = t.challenge;
  tx.target = t.target;
  env = GNUNET_MQ_msg (tp, GNUNET_MESSAGE_TYPE_CORE_PONG);
  tp->iv_seed = calculate_seed (kx);
  derive_pong_iv (&iv, &kx->encrypt_key, tp->iv_seed, t.challenge, kx->peer);
  do_encrypt (kx,
              &iv,
              &tx.challenge,
              &tp->challenge,
              sizeof (struct PongMessage) -
                ((void *) &tp->challenge - (void *) tp));
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# PONG messages created"),
                            1,
                            GNUNET_NO);
  GNUNET_MQ_send (kx->mq, env);
}


/**
 * Task triggered when a neighbour entry is about to time out
 * (and we should prevent this by sending a PING).
 *
 * @param cls the `struct GSC_KeyExchangeInfo`
 */
static void
send_keep_alive (void *cls)
{
  struct GSC_KeyExchangeInfo *kx = cls;
  struct GNUNET_TIME_Relative retry;
  struct GNUNET_TIME_Relative left;

  kx->keep_alive_task = NULL;
  left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
  if (0 == left.rel_value_us)
  {
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop ("# sessions terminated by timeout"),
                              1,
                              GNUNET_NO);
    GSC_SESSIONS_end (kx->peer);
    kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
    monitor_notify_all (kx);
    send_key (kx);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Sending KEEPALIVE to `%s'\n",
              GNUNET_i2s (kx->peer));
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# keepalive messages sent"),
                            1,
                            GNUNET_NO);
  setup_fresh_ping (kx);
  send_ping (kx);
  retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
                                    MIN_PING_FREQUENCY);
  kx->keep_alive_task =
    GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
}


/**
 * We've seen a valid message from the other peer.
 * Update the time when the session would time out
 * and delay sending our keep alive message further.
 *
 * @param kx key exchange where we saw activity
 */
static void
update_timeout (struct GSC_KeyExchangeInfo *kx)
{
  struct GNUNET_TIME_Relative delta;

  kx->timeout =
    GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  delta =
    GNUNET_TIME_absolute_get_difference (kx->last_notify_timeout, kx->timeout);
  if (delta.rel_value_us > 5LL * 1000LL * 1000LL)
  {
    /* we only notify monitors about timeout changes if those
       are bigger than the threshold (5s) */
    monitor_notify_all (kx);
  }
  if (NULL != kx->keep_alive_task)
    GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
  kx->keep_alive_task = GNUNET_SCHEDULER_add_delayed (
    GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2),
    &send_keep_alive,
    kx);
}


/**
 * We received a PONG message.  Validate and update our status.
 *
 * @param kx key exchange context for the the PONG
 * @param m the encrypted PONG message itself
 */
static void
handle_pong (void *cls, const struct PongMessage *m)
{
  struct GSC_KeyExchangeInfo *kx = cls;
  struct PongMessage t;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;

  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# PONG messages received"),
                            1,
                            GNUNET_NO);
  switch (kx->status)
  {
  case GNUNET_CORE_KX_STATE_DOWN:
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# PONG messages dropped (connection down)"),
                              1,
                              GNUNET_NO);
    return;
  case GNUNET_CORE_KX_STATE_KEY_SENT:
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# PONG messages dropped (out of order)"),
                              1,
                              GNUNET_NO);
    return;
  case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
    break;
  case GNUNET_CORE_KX_STATE_UP:
    break;
  case GNUNET_CORE_KX_STATE_REKEY_SENT:
    break;
  default:
    GNUNET_break (0);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Core service receives PONG response from `%s'.\n",
              GNUNET_i2s (kx->peer));
  /* mark as garbage, just to be sure */
  memset (&t, 255, sizeof (t));
  derive_pong_iv (&iv,
                  &kx->decrypt_key,
                  m->iv_seed,
                  kx->ping_challenge,
                  &GSC_my_identity);
  if (GNUNET_OK != do_decrypt (kx,
                               &iv,
                               &m->challenge,
                               &t.challenge,
                               sizeof (struct PongMessage) -
                                 ((void *) &m->challenge - (void *) m)))
  {
    GNUNET_break_op (0);
    return;
  }
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# PONG messages decrypted"),
                            1,
                            GNUNET_NO);
  if ((0 !=
       memcmp (&t.target, kx->peer, sizeof (struct GNUNET_PeerIdentity))) ||
      (kx->ping_challenge != t.challenge))
  {
    /* PONG malformed */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Received malformed PONG wanted sender `%s' with challenge %u\n",
                GNUNET_i2s (kx->peer),
                (unsigned int) kx->ping_challenge);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Received malformed PONG received from `%s' with challenge %u\n",
                GNUNET_i2s (&t.target),
                (unsigned int) t.challenge);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received valid PONG from `%s'\n",
              GNUNET_i2s (kx->peer));
  /* no need to resend key any longer */
  if (NULL != kx->retry_set_key_task)
  {
    GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
    kx->retry_set_key_task = NULL;
  }
  switch (kx->status)
  {
  case GNUNET_CORE_KX_STATE_DOWN:
    GNUNET_assert (0); /* should be impossible */
    return;
  case GNUNET_CORE_KX_STATE_KEY_SENT:
    GNUNET_assert (0); /* should be impossible */
    return;
  case GNUNET_CORE_KX_STATE_KEY_RECEIVED:
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# session keys confirmed via PONG"),
                              1,
                              GNUNET_NO);
    kx->status = GNUNET_CORE_KX_STATE_UP;
    monitor_notify_all (kx);
    GSC_SESSIONS_create (kx->peer, kx);
    GNUNET_assert (NULL == kx->keep_alive_task);
    update_timeout (kx);
    break;
  case GNUNET_CORE_KX_STATE_UP:
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop ("# timeouts prevented via PONG"),
                              1,
                              GNUNET_NO);
    update_timeout (kx);
    break;
  case GNUNET_CORE_KX_STATE_REKEY_SENT:
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# rekey operations confirmed via PONG"),
                              1,
                              GNUNET_NO);
    kx->status = GNUNET_CORE_KX_STATE_UP;
    monitor_notify_all (kx);
    update_timeout (kx);
    break;
  default:
    GNUNET_break (0);
    break;
  }
}


/**
 * Send our key to the other peer.
 *
 * @param kx key exchange context
 */
static void
send_key (struct GSC_KeyExchangeInfo *kx)
{
  struct GNUNET_MQ_Envelope *env;

  GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status);
  if (NULL != kx->retry_set_key_task)
  {
    GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
    kx->retry_set_key_task = NULL;
  }
  /* always update sender status in SET KEY message */
#if DEBUG_KX
  {
    struct GNUNET_HashCode hc;

    GNUNET_CRYPTO_hash (&current_ekm.ephemeral_key,
                        sizeof (current_ekm.ephemeral_key),
                        &hc);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Sending EPHEMERAL_KEY %s to `%s' (my status: %d)\n",
                GNUNET_h2s (&hc),
                GNUNET_i2s (kx->peer),
                kx->status);
  }
#endif
  current_ekm.sender_status = htonl ((int32_t) (kx->status));
  env = GNUNET_MQ_msg_copy (&current_ekm.header);
  GNUNET_MQ_send (kx->mq, env);
  if (GNUNET_CORE_KX_STATE_KEY_SENT != kx->status)
    send_ping (kx);
  kx->retry_set_key_task =
    GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
                                  &set_key_retry_task,
                                  kx);
}


/**
 * Encrypt and transmit a message with the given payload.
 *
 * @param kx key exchange context
 * @param payload payload of the message
 * @param payload_size number of bytes in @a payload
 */
void
GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
                             const void *payload,
                             size_t payload_size)
{
  size_t used = payload_size + sizeof (struct EncryptedMessage);
  char pbuf[used]; /* plaintext */
  struct EncryptedMessage *em; /* encrypted message */
  struct EncryptedMessage *ph; /* plaintext header */
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  struct GNUNET_CRYPTO_AuthKey auth_key;

  ph = (struct EncryptedMessage *) pbuf;
  ph->sequence_number = htonl (++kx->last_sequence_number_sent);
  ph->iv_seed = calculate_seed (kx);
  ph->reserved = 0;
  ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
  GNUNET_memcpy (&ph[1], payload, payload_size);
  env = GNUNET_MQ_msg_extra (em,
                             payload_size,
                             GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE);
  em->iv_seed = ph->iv_seed;
  derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, kx->peer);
  GNUNET_assert (GNUNET_OK == do_encrypt (kx,
                                          &iv,
                                          &ph->sequence_number,
                                          &em->sequence_number,
                                          used - ENCRYPTED_HEADER_SIZE));
#if DEBUG_KX
  {
    struct GNUNET_HashCode hc;

    GNUNET_CRYPTO_hash (&ph->sequence_number,
                        used - ENCRYPTED_HEADER_SIZE,
                        &hc);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Encrypted payload `%s' of %u bytes for %s\n",
                GNUNET_h2s (&hc),
                (unsigned int) (used - ENCRYPTED_HEADER_SIZE),
                GNUNET_i2s (kx->peer));
  }
#endif
  derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed);
  GNUNET_CRYPTO_hmac (&auth_key,
                      &em->sequence_number,
                      used - ENCRYPTED_HEADER_SIZE,
                      &em->hmac);
#if DEBUG_KX
  {
    struct GNUNET_HashCode hc;

    GNUNET_CRYPTO_hash (&auth_key, sizeof (auth_key), &hc);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "For peer %s, used AC %s to create hmac %s\n",
                GNUNET_i2s (kx->peer),
                GNUNET_h2s (&hc),
                GNUNET_h2s2 (&em->hmac));
  }
#endif
  kx->has_excess_bandwidth = GNUNET_NO;
  GNUNET_MQ_send (kx->mq, env);
}


/**
 * We received an encrypted message.  Check that it is
 * well-formed (size-wise).
 *
 * @param cls key exchange context for encrypting the message
 * @param m encrypted message
 * @return #GNUNET_OK if @a msg is well-formed (size-wise)
 */
static int
check_encrypted (void *cls, const struct EncryptedMessage *m)
{
  uint16_t size = ntohs (m->header.size) - sizeof (*m);

  if (size < sizeof (struct GNUNET_MessageHeader))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * We received an encrypted message.  Decrypt, validate and
 * pass on to the appropriate clients.
 *
 * @param cls key exchange context for encrypting the message
 * @param m encrypted message
 */
static void
handle_encrypted (void *cls, const struct EncryptedMessage *m)
{
  struct GSC_KeyExchangeInfo *kx = cls;
  struct EncryptedMessage *pt; /* plaintext */
  struct GNUNET_HashCode ph;
  uint32_t snum;
  struct GNUNET_TIME_Absolute t;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  struct GNUNET_CRYPTO_AuthKey auth_key;
  uint16_t size = ntohs (m->header.size);
  char buf[size] GNUNET_ALIGN;

  if (GNUNET_CORE_KX_STATE_UP != kx->status)
  {
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# DATA message dropped (out of order)"),
                              1,
                              GNUNET_NO);
    return;
  }
  if (0 ==
      GNUNET_TIME_absolute_get_remaining (kx->foreign_key_expires).rel_value_us)
  {
    GNUNET_log (
      GNUNET_ERROR_TYPE_WARNING,
      _ (
        "Session to peer `%s' went down due to key expiration (should not happen)\n"),
      GNUNET_i2s (kx->peer));
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# sessions terminated by key expiration"),
                              1,
                              GNUNET_NO);
    GSC_SESSIONS_end (kx->peer);
    if (NULL != kx->keep_alive_task)
    {
      GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
      kx->keep_alive_task = NULL;
    }
    kx->status = GNUNET_CORE_KX_STATE_KEY_SENT;
    monitor_notify_all (kx);
    send_key (kx);
    return;
  }

  /* validate hash */
#if DEBUG_KX
  {
    struct GNUNET_HashCode hc;

    GNUNET_CRYPTO_hash (&m->sequence_number, size - ENCRYPTED_HEADER_SIZE, &hc);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Received encrypted payload `%s' of %u bytes from %s\n",
                GNUNET_h2s (&hc),
                (unsigned int) (size - ENCRYPTED_HEADER_SIZE),
                GNUNET_i2s (kx->peer));
  }
#endif
  derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed);
  GNUNET_CRYPTO_hmac (&auth_key,
                      &m->sequence_number,
                      size - ENCRYPTED_HEADER_SIZE,
                      &ph);
#if DEBUG_KX
  {
    struct GNUNET_HashCode hc;

    GNUNET_CRYPTO_hash (&auth_key, sizeof (auth_key), &hc);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "For peer %s, used AC %s to verify hmac %s\n",
                GNUNET_i2s (kx->peer),
                GNUNET_h2s (&hc),
                GNUNET_h2s2 (&m->hmac));
  }
#endif
  if (0 != memcmp (&ph, &m->hmac, sizeof (struct GNUNET_HashCode)))
  {
    /* checksum failed */
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Failed checksum validation for a message from `%s'\n",
                GNUNET_i2s (kx->peer));
    return;
  }
  derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
  /* decrypt */
  if (GNUNET_OK != do_decrypt (kx,
                               &iv,
                               &m->sequence_number,
                               &buf[ENCRYPTED_HEADER_SIZE],
                               size - ENCRYPTED_HEADER_SIZE))
  {
    GNUNET_break_op (0);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Decrypted %u bytes from %s\n",
              (unsigned int) (size - ENCRYPTED_HEADER_SIZE),
              GNUNET_i2s (kx->peer));
  pt = (struct EncryptedMessage *) buf;

  /* validate sequence number */
  snum = ntohl (pt->sequence_number);
  if (kx->last_sequence_number_received == snum)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Received duplicate message, ignoring.\n");
    /* duplicate, ignore */
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop ("# bytes dropped (duplicates)"),
                              size,
                              GNUNET_NO);
    return;
  }
  if ((kx->last_sequence_number_received > snum) &&
      (kx->last_sequence_number_received - snum > 32))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Received ancient out of sequence message, ignoring.\n");
    /* ancient out of sequence, ignore */
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# bytes dropped (out of sequence)"),
                              size,
                              GNUNET_NO);
    return;
  }
  if (kx->last_sequence_number_received > snum)
  {
    uint32_t rotbit = 1U << (kx->last_sequence_number_received - snum - 1);

    if ((kx->last_packets_bitmap & rotbit) != 0)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Received duplicate message, ignoring.\n");
      GNUNET_STATISTICS_update (GSC_stats,
                                gettext_noop ("# bytes dropped (duplicates)"),
                                size,
                                GNUNET_NO);
      /* duplicate, ignore */
      return;
    }
    kx->last_packets_bitmap |= rotbit;
  }
  if (kx->last_sequence_number_received < snum)
  {
    unsigned int shift = (snum - kx->last_sequence_number_received);

    if (shift >= 8 * sizeof (kx->last_packets_bitmap))
      kx->last_packets_bitmap = 0;
    else
      kx->last_packets_bitmap <<= shift;
    kx->last_sequence_number_received = snum;
  }

  /* check timestamp */
  t = GNUNET_TIME_absolute_ntoh (pt->timestamp);
  if (GNUNET_TIME_absolute_get_duration (t).rel_value_us >
      MAX_MESSAGE_AGE.rel_value_us)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Message received far too old (%s). Content ignored.\n",
                GNUNET_STRINGS_relative_time_to_string (
                  GNUNET_TIME_absolute_get_duration (t),
                  GNUNET_YES));
    GNUNET_STATISTICS_update (GSC_stats,
                              gettext_noop (
                                "# bytes dropped (ancient message)"),
                              size,
                              GNUNET_NO);
    return;
  }

  /* process decrypted message(s) */
  update_timeout (kx);
  GNUNET_STATISTICS_update (GSC_stats,
                            gettext_noop ("# bytes of payload decrypted"),
                            size - sizeof (struct EncryptedMessage),
                            GNUNET_NO);
  if (GNUNET_OK !=
      GNUNET_MST_from_buffer (kx->mst,
                              &buf[sizeof (struct EncryptedMessage)],
                              size - sizeof (struct EncryptedMessage),
                              GNUNET_YES,
                              GNUNET_NO))
    GNUNET_break_op (0);
}


/**
 * One of our neighbours has excess bandwidth, remember this.
 *
 * @param cls NULL
 * @param pid identity of the peer with excess bandwidth
 * @param connect_cls the `struct Neighbour`
 */
static void
handle_transport_notify_excess_bw (void *cls,
                                   const struct GNUNET_PeerIdentity *pid,
                                   void *connect_cls)
{
  struct GSC_KeyExchangeInfo *kx = connect_cls;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Peer %s has excess bandwidth available\n",
              GNUNET_i2s (pid));
  kx->has_excess_bandwidth = GNUNET_YES;
  GSC_SESSIONS_solicit (pid);
}


/**
 * Setup the message that links the ephemeral key to our persistent
 * public key and generate the appropriate signature.
 */
static void
sign_ephemeral_key ()
{
  current_ekm.header.size = htons (sizeof (struct EphemeralKeyMessage));
  current_ekm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY);
  current_ekm.sender_status = 0; /* to be set later */
  current_ekm.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY);
  current_ekm.purpose.size =
    htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
           sizeof (struct GNUNET_TIME_AbsoluteNBO) +
           sizeof (struct GNUNET_TIME_AbsoluteNBO) +
           sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
           sizeof (struct GNUNET_PeerIdentity));
  current_ekm.creation_time =
    GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
  if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (GSC_cfg,
                                                          "core",
                                                          "USE_EPHEMERAL_KEYS"))
  {
    current_ekm.expiration_time =
      GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (
        GNUNET_TIME_relative_add (REKEY_FREQUENCY, REKEY_TOLERANCE)));
  }
  else
  {
    current_ekm.expiration_time =
      GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
  }
  GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key,
                                      &current_ekm.ephemeral_key);
  current_ekm.origin_identity = GSC_my_identity;
  GNUNET_assert (GNUNET_OK ==
                 GNUNET_CRYPTO_eddsa_sign (my_private_key,
                                           &current_ekm.purpose,
                                           &current_ekm.signature));
}


/**
 * Task run to trigger rekeying.
 *
 * @param cls closure, NULL
 */
static void
do_rekey (void *cls)
{
  struct GSC_KeyExchangeInfo *pos;

  rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY, &do_rekey, NULL);
  if (NULL != my_ephemeral_key)
    GNUNET_free (my_ephemeral_key);
  my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
  GNUNET_assert (NULL != my_ephemeral_key);
  sign_ephemeral_key ();
  {
    struct GNUNET_HashCode eh;

    GNUNET_CRYPTO_hash (&current_ekm.ephemeral_key,
                        sizeof (current_ekm.ephemeral_key),
                        &eh);
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Rekeying to %s\n", GNUNET_h2s (&eh));
  }
  for (pos = kx_head; NULL != pos; pos = pos->next)
  {
    if (GNUNET_CORE_KX_STATE_UP == pos->status)
    {
      pos->status = GNUNET_CORE_KX_STATE_REKEY_SENT;
      monitor_notify_all (pos);
      derive_session_keys (pos);
    }
    if (GNUNET_CORE_KX_STATE_DOWN == pos->status)
    {
      pos->status = GNUNET_CORE_KX_STATE_KEY_SENT;
      monitor_notify_all (pos);
    }
    monitor_notify_all (pos);
    send_key (pos);
  }
}


/**
 * Initialize KX subsystem.
 *
 * @param pk private key to use for the peer
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
int
GSC_KX_init (struct GNUNET_CRYPTO_EddsaPrivateKey *pk)
{
  struct GNUNET_MQ_MessageHandler handlers[] =
    {GNUNET_MQ_hd_fixed_size (ephemeral_key,
                              GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY,
                              struct EphemeralKeyMessage,
                              NULL),
     GNUNET_MQ_hd_fixed_size (ping,
                              GNUNET_MESSAGE_TYPE_CORE_PING,
                              struct PingMessage,
                              NULL),
     GNUNET_MQ_hd_fixed_size (pong,
                              GNUNET_MESSAGE_TYPE_CORE_PONG,
                              struct PongMessage,
                              NULL),
     GNUNET_MQ_hd_var_size (encrypted,
                            GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE,
                            struct EncryptedMessage,
                            NULL),
     GNUNET_MQ_handler_end ()};

  my_private_key = pk;
  GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
                                      &GSC_my_identity.public_key);
  my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
  if (NULL == my_ephemeral_key)
  {
    GNUNET_break (0);
    GNUNET_free (my_private_key);
    my_private_key = NULL;
    return GNUNET_SYSERR;
  }
  sign_ephemeral_key ();
  {
    struct GNUNET_HashCode eh;

    GNUNET_CRYPTO_hash (&current_ekm.ephemeral_key,
                        sizeof (current_ekm.ephemeral_key),
                        &eh);
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Starting with ephemeral key %s\n",
                GNUNET_h2s (&eh));
  }

  nc = GNUNET_notification_context_create (1);
  rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY, &do_rekey, NULL);
  transport =
    GNUNET_TRANSPORT_core_connect (GSC_cfg,
                                   &GSC_my_identity,
                                   handlers,
                                   NULL,
                                   &handle_transport_notify_connect,
                                   &handle_transport_notify_disconnect,
                                   &handle_transport_notify_excess_bw);
  if (NULL == transport)
  {
    GSC_KX_done ();
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Shutdown KX subsystem.
 */
void
GSC_KX_done ()
{
  if (NULL != transport)
  {
    GNUNET_TRANSPORT_core_disconnect (transport);
    transport = NULL;
  }
  if (NULL != rekey_task)
  {
    GNUNET_SCHEDULER_cancel (rekey_task);
    rekey_task = NULL;
  }
  if (NULL != my_ephemeral_key)
  {
    GNUNET_free (my_ephemeral_key);
    my_ephemeral_key = NULL;
  }
  if (NULL != my_private_key)
  {
    GNUNET_free (my_private_key);
    my_private_key = NULL;
  }
  if (NULL != nc)
  {
    GNUNET_notification_context_destroy (nc);
    nc = NULL;
  }
}


/**
 * Check how many messages are queued for the given neighbour.
 *
 * @param kxinfo data about neighbour to check
 * @return number of items in the message queue
 */
unsigned int
GSC_NEIGHBOURS_get_queue_length (const struct GSC_KeyExchangeInfo *kxinfo)
{
  return GNUNET_MQ_get_length (kxinfo->mq);
}


/**
 * Check if the given neighbour has excess bandwidth available.
 *
 * @param target neighbour to check
 * @return #GNUNET_YES if excess bandwidth is available, #GNUNET_NO if not
 */
int
GSC_NEIGHBOURS_check_excess_bandwidth (const struct GSC_KeyExchangeInfo *kxinfo)
{
  return kxinfo->has_excess_bandwidth;
}


/**
 * Handle #GNUNET_MESSAGE_TYPE_CORE_MONITOR_PEERS request.  For this
 * request type, the client does not have to have transmitted an INIT
 * request.  All current peers are returned, regardless of which
 * message types they accept.
 *
 * @param mq message queue to add for monitoring
 */
void
GSC_KX_handle_client_monitor_peers (struct GNUNET_MQ_Handle *mq)
{
  struct GNUNET_MQ_Envelope *env;
  struct MonitorNotifyMessage *done_msg;
  struct GSC_KeyExchangeInfo *kx;

  GNUNET_notification_context_add (nc, mq);
  for (kx = kx_head; NULL != kx; kx = kx->next)
  {
    struct GNUNET_MQ_Envelope *env;
    struct MonitorNotifyMessage *msg;

    env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
    msg->state = htonl ((uint32_t) kx->status);
    msg->peer = *kx->peer;
    msg->timeout = GNUNET_TIME_absolute_hton (kx->timeout);
    GNUNET_MQ_send (mq, env);
  }
  env = GNUNET_MQ_msg (done_msg, GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY);
  done_msg->state = htonl ((uint32_t) GNUNET_CORE_KX_ITERATION_FINISHED);
  done_msg->timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS);
  GNUNET_MQ_send (mq, env);
}


/* end of gnunet-service-core_kx.c */