summaryrefslogtreecommitdiffstats
path: root/doc/gnutls.info-1
blob: 199798f66bf77cdb91dc4adef0c6c6687d1878bb (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
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
This is gnutls.info, produced by makeinfo version 6.8 from gnutls.texi.

This manual is last updated 9 February 2023 for version 3.7.9 of GnuTLS.

Copyright (C) 2001-2023 Free Software Foundation, Inc.\\ Copyright (C)
2001-2023 Nikos Mavrogiannopoulos

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.3 or any later version published by the Free Software
     Foundation; with no Invariant Sections, no Front-Cover Texts, and
     no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License".
INFO-DIR-SECTION Software libraries
START-INFO-DIR-ENTRY
* GnuTLS: (gnutls).		GNU Transport Layer Security Library.
END-INFO-DIR-ENTRY

INFO-DIR-SECTION System Administration
START-INFO-DIR-ENTRY
* certtool: (gnutls)certtool Invocation.	Manipulate certificates and keys.
* gnutls-serv: (gnutls)gnutls-serv Invocation.	GnuTLS test server.
* gnutls-cli: (gnutls)gnutls-cli Invocation.	GnuTLS test client.
* gnutls-cli-debug: (gnutls)gnutls-cli-debug Invocation.	GnuTLS debug client.
* psktool: (gnutls)psktool Invocation.	Simple TLS-Pre-Shared-Keys manager.
* srptool: (gnutls)srptool Invocation.	Simple SRP password tool.
END-INFO-DIR-ENTRY


File: gnutls.info,  Node: Top,  Next: Preface,  Up: (dir)

GnuTLS
******

This manual is last updated 9 February 2023 for version 3.7.9 of GnuTLS.

Copyright (C) 2001-2023 Free Software Foundation, Inc.\\ Copyright (C)
2001-2023 Nikos Mavrogiannopoulos

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.3 or any later version published by the Free Software
     Foundation; with no Invariant Sections, no Front-Cover Texts, and
     no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License".

* Menu:

* Preface::
* Introduction to GnuTLS::
* Introduction to TLS::
* Authentication methods::
* Hardware security modules and abstract key types::
* How to use GnuTLS in applications::
* GnuTLS application examples::
* System-wide configuration of the library::
* Using GnuTLS as a cryptographic library::
* Other included programs::
* Internal architecture of GnuTLS::
* Upgrading from previous versions::
* Support::
* Error codes::
* Supported ciphersuites::
* API reference::
* Copying Information::
* Bibliography::
* Function and Data Index::
* Concept Index::


File: gnutls.info,  Node: Preface,  Next: Introduction to GnuTLS,  Prev: Top,  Up: Top

1 Preface
*********

This document demonstrates and explains the GnuTLS library API. A brief
introduction to the protocols and the technology involved is also
included so that an application programmer can better understand the
GnuTLS purpose and actual offerings.  Even if GnuTLS is a typical
library software, it operates over several security and cryptographic
protocols which require the programmer to make careful and correct usage
of them.  Otherwise it is likely to only obtain a false sense of
security.  The term of security is very broad even if restricted to
computer software, and cannot be confined to a single cryptographic
library.  For that reason, do not consider any program secure just
because it uses GnuTLS; there are several ways to compromise a program
or a communication line and GnuTLS only helps with some of them.

Although this document tries to be self contained, basic network
programming and public key infrastructure (PKI) knowledge is assumed in
most of it.  A good introduction to networking can be found in [*note
STEVENS::], to public key infrastructure in [*note GUTPKI::] and to
security engineering in [*note ANDERSON::].

Updated versions of the GnuTLS software and this document will be
available from <https://www.gnutls.org/>.


File: gnutls.info,  Node: Introduction to GnuTLS,  Next: Introduction to TLS,  Prev: Preface,  Up: Top

2 Introduction to GnuTLS
************************

In brief GnuTLS can be described as a library which offers an API to
access secure communication protocols.  These protocols provide privacy
over insecure lines, and were designed to prevent eavesdropping,
tampering, or message forgery.

Technically GnuTLS is a portable ANSI C based library which implements
the protocols ranging from SSL 3.0 to TLS 1.3 (see *note Introduction to
TLS::, for a detailed description of the protocols), accompanied with
the required framework for authentication and public key infrastructure.
Important features of the GnuTLS library include:

   * Support for TLS 1.3, TLS 1.2, TLS 1.1, TLS 1.0 and optionally SSL
     3.0 protocols.

   * Support for Datagram TLS 1.0 and 1.2.

   * Support for handling and verification of X.509 certificates.

   * Support for password authentication using TLS-SRP.

   * Support for keyed authentication using TLS-PSK.

   * Support for TPM, PKCS #11 tokens and smart-cards.

The GnuTLS library consists of three independent parts, namely the "TLS
protocol part", the "Certificate part", and the "Cryptographic back-end"
part.  The "TLS protocol part" is the actual protocol implementation,
and is entirely implemented within the GnuTLS library.  The "Certificate
part" consists of the certificate parsing, and verification functions
and it uses functionality from the libtasn1 library.  The "Cryptographic
back-end" is provided by the nettle and gmplib libraries.

* Menu:

* Downloading and installing::
* Installing for a software distribution::
* Document overview::


File: gnutls.info,  Node: Downloading and installing,  Next: Installing for a software distribution,  Up: Introduction to GnuTLS

2.1 Downloading and installing
==============================

GnuTLS is available for download at:
<https://www.gnutls.org/download.html>

GnuTLS uses a development cycle where even minor version numbers
indicate a stable release and a odd minor version number indicate a
development release.  For example, GnuTLS 1.6.3 denote a stable release
since 6 is even, and GnuTLS 1.7.11 denote a development release since 7
is odd.

GnuTLS depends on 'nettle' and 'gmplib', and you will need to install it
before installing GnuTLS. The 'nettle' library is available from
<https://www.lysator.liu.se/~nisse/nettle/>, while 'gmplib' is available
from <https://www.gmplib.org/>.  Don't forget to verify the
cryptographic signature after downloading source code packages.

The package is then extracted, configured and built like many other
packages that use Autoconf.  For detailed information on configuring and
building it, refer to the 'INSTALL' file that is part of the
distribution archive.  Typically you invoke './configure' and then 'make
check install'.  There are a number of compile-time parameters, as
discussed below.

Several parts of GnuTLS require ASN.1 functionality, which is provided
by a library called libtasn1.  A copy of libtasn1 is included in GnuTLS.
If you want to install it separately (e.g., to make it possibly to use
libtasn1 in other programs), you can get it from
<https://www.gnu.org/software/libtasn1/>.

The compression library, 'libz', the PKCS #11 helper library 'p11-kit',
the TPM library 'trousers', as well as the IDN library 'libidn'(1) are
optional dependencies.  Check the README file in the distribution on how
to obtain these libraries.

A few 'configure' options may be relevant, summarized below.  They
disable or enable particular features, to create a smaller library with
only the required features.  Note however, that although a smaller
library is generated, the included programs are not guaranteed to
compile if some of these options are given.

--disable-srp-authentication
--disable-psk-authentication
--disable-anon-authentication
--disable-dhe
--disable-ecdhe
--disable-openssl-compatibility
--disable-dtls-srtp-support
--disable-alpn-support
--disable-heartbeat-support
--disable-libdane
--without-p11-kit
--without-tpm
--without-zlib


For the complete list, refer to the output from 'configure --help'.

   ---------- Footnotes ----------

   (1) Needed to use RFC6125 name comparison in internationalized
domains.


File: gnutls.info,  Node: Installing for a software distribution,  Next: Document overview,  Prev: Downloading and installing,  Up: Introduction to GnuTLS

2.2 Installing for a software distribution
==========================================

When installing for a software distribution, it is often desirable to
preconfigure GnuTLS with the system-wide paths and files.  There two
important configuration options, one sets the trust store in system,
which are the CA certificates to be used by programs by default (if they
don't override it), and the other sets to DNSSEC root key file used by
unbound for DNSSEC verification.

For the latter the following configuration option is available, and if
not specified GnuTLS will try to auto-detect the location of that file.
--with-unbound-root-key-file


To set the trust store the following options are available.
--with-default-trust-store-file
--with-default-trust-store-dir
--with-default-trust-store-pkcs11

The first option is used to set a PEM file which contains a list of
trusted certificates, while the second will read all certificates in the
given path.  The recommended option is the last, which allows to use a
PKCS #11 trust policy module.  That module not only provides the trusted
certificates, but allows the categorization of them using purpose, e.g.,
CAs can be restricted for e-mail usage only, or administrative
restrictions of CAs, for examples by restricting a CA to only issue
certificates for a given DNS domain using NameConstraints.  A publicly
available PKCS #11 trust module is p11-kit's trust module(1).

   ---------- Footnotes ----------

   (1) <https://p11-glue.github.io/p11-glue/trust-module.html>


File: gnutls.info,  Node: Document overview,  Prev: Installing for a software distribution,  Up: Introduction to GnuTLS

2.3 Overview
============

In this document we present an overview of the supported security
protocols in *note Introduction to TLS::, and continue by providing more
information on the certificate authentication in *note Certificate
authentication::, and shared-key as well anonymous authentication in
*note Shared-key and anonymous authentication::.  We elaborate on
certificate authentication by demonstrating advanced usage of the API in
*note More on certificate authentication::.  The core of the TLS library
is presented in *note How to use GnuTLS in applications:: and example
applications are listed in *note GnuTLS application examples::.  In
*note Other included programs:: the usage of few included programs that
may assist debugging is presented.  The last chapter is *note Internal
architecture of GnuTLS:: that provides a short introduction to GnuTLS'
internal architecture.


File: gnutls.info,  Node: Introduction to TLS,  Next: Authentication methods,  Prev: Introduction to GnuTLS,  Up: Top

3 Introduction to TLS and DTLS
******************************

TLS stands for "Transport Layer Security" and is the successor of SSL,
the Secure Sockets Layer protocol [*note SSL3::] designed by Netscape.
TLS is an Internet protocol, defined by IETF(1), described in [*note
RFC5246::].  The protocol provides confidentiality, and authentication
layers over any reliable transport layer.  The description, above,
refers to TLS 1.0 but applies to all other TLS versions as the
differences between the protocols are not major.

The DTLS protocol, or "Datagram TLS" [*note RFC4347::] is a protocol
with identical goals as TLS, but can operate under unreliable transport
layers such as UDP.  The discussions below apply to this protocol as
well, except when noted otherwise.

* Menu:

* TLS layers::
* The transport layer::
* The TLS record protocol::
* The TLS Alert Protocol::
* The TLS Handshake Protocol::
* TLS Extensions::
* How to use TLS in application protocols::
* On SSL 2 and older protocols::

   ---------- Footnotes ----------

   (1) IETF, or Internet Engineering Task Force, is a large open
international community of network designers, operators, vendors, and
researchers concerned with the evolution of the Internet architecture
and the smooth operation of the Internet.  It is open to any interested
individual.


File: gnutls.info,  Node: TLS layers,  Next: The transport layer,  Up: Introduction to TLS

3.1 TLS Layers
==============

TLS is a layered protocol, and consists of the record protocol, the
handshake protocol and the alert protocol.  The record protocol is to
serve all other protocols and is above the transport layer.  The record
protocol offers symmetric encryption, and data authenticity(1).  The
alert protocol offers some signaling to the other protocols.  It can
help informing the peer for the cause of failures and other error
conditions.  *Note The Alert Protocol::, for more information.  The
alert protocol is above the record protocol.

The handshake protocol is responsible for the security parameters'
negotiation, the initial key exchange and authentication.  *Note The
Handshake Protocol::, for more information about the handshake protocol.
The protocol layering in TLS is shown in *note Figure 3.1:
fig-tls-layers.

[image src="gnutls-layers.png"]



Figure 3.1: The TLS protocol layers.

   ---------- Footnotes ----------

   (1) In early versions of TLS compression was optionally available as
well.  This is no longer the case in recent versions of the protocol.


File: gnutls.info,  Node: The transport layer,  Next: The TLS record protocol,  Prev: TLS layers,  Up: Introduction to TLS

3.2 The Transport Layer
=======================

TLS is not limited to any transport layer and can be used above any
transport layer, as long as it is a reliable one.  DTLS can be used over
reliable and unreliable transport layers.  GnuTLS supports TCP and UDP
layers transparently using the Berkeley sockets API. However, any
transport layer can be used by providing callbacks for GnuTLS to access
the transport layer (for details see *note Setting up the transport
layer::).


File: gnutls.info,  Node: The TLS record protocol,  Next: The TLS Alert Protocol,  Prev: The transport layer,  Up: Introduction to TLS

3.3 The TLS record protocol
===========================

The record protocol is the secure communications provider.  Its purpose
is to encrypt, and authenticate packets.  The record layer functions can
be called at any time after the handshake process is finished, when
there is need to receive or send data.  In DTLS however, due to
re-transmission timers used in the handshake out-of-order handshake data
might be received for some time (maximum 60 seconds) after the handshake
process is finished.

The functions to access the record protocol are limited to send and
receive functions, which might, given the importance of this protocol in
TLS, seem awkward.  This is because the record protocol's parameters are
all set by the handshake protocol.  The record protocol initially starts
with NULL parameters, which means no encryption, and no MAC is used.
Encryption and authentication begin just after the handshake protocol
has finished.

* Menu:

* Encryption algorithms used in the record layer::
* Compression algorithms and the record layer::
* On Record Padding::


File: gnutls.info,  Node: Encryption algorithms used in the record layer,  Next: Compression algorithms and the record layer,  Up: The TLS record protocol

3.3.1 Encryption algorithms used in the record layer
----------------------------------------------------

Confidentiality in the record layer is achieved by using symmetric
ciphers like 'AES' or 'CHACHA20'.  Ciphers are encryption algorithms
that use a single, secret, key to encrypt and decrypt data.  Early
versions of TLS separated between block and stream ciphers and had
message authentication plugged in to them by the protocol, though later
versions switched to using authenticated-encryption (AEAD) ciphers.  The
AEAD ciphers are defined to combine encryption and authentication, and
as such they are not only more efficient, as the primitives used are
designed to interoperate nicely, but they are also known to interoperate
in a secure way.

The supported in GnuTLS ciphers and MAC algorithms are shown in *note
Table 3.1: tab:ciphers. and *note Table 3.2: tab:macs.

Algorithm      Type    Applicable  Description
                       Protocols
----------------------------------------------------------------------------
AES-128-GCM,   AEAD    TLS 1.2,    This is the AES algorithm in the
AES-256-GCM            TLS 1.3     authenticated encryption GCM mode.
                                   This mode combines message
                                   authentication and encryption and can
                                   be extremely fast on CPUs that support
                                   hardware acceleration.
                                   
AES-128-CCM,   AEAD    TLS 1.2,    This is the AES algorithm in the
AES-256-CCM            TLS 1.3     authenticated encryption CCM mode.
                                   This mode combines message
                                   authentication and encryption and is
                                   often used by systems without AES or
                                   GCM acceleration support.
                                   
CHACHA20-POLY1305AEAD  TLS 1.2,    CHACHA20-POLY1305 is an authenticated
                       TLS 1.3     encryption algorithm based on CHACHA20
                                   cipher and POLY1305 MAC. CHACHA20 is a
                                   refinement of SALSA20 algorithm, an
                                   approved cipher by the European
                                   ESTREAM project.  POLY1305 is
                                   Wegman-Carter, one-time authenticator.
                                   The combination provides a fast stream
                                   cipher suitable for systems where a
                                   hardware AES accelerator is not
                                   available.
                                   
AES-128-CCM-8, AEAD    TLS 1.2,    This is the AES algorithm in the
AES-256-CCM-8          TLS 1.3     authenticated encryption CCM mode with
                                   a truncated to 64-bit authentication
                                   tag.  This mode is for communication
                                   with restricted systems.
                                   
CAMELLIA-128-GCM,AEAD  TLS 1.2     This is the CAMELLIA algorithm in the
CAMELLIA-256-GCM                   authenticated encryption GCM mode.
                                   
AES-128-CBC,   Legacy  TLS 1.0,    AES or RIJNDAEL is the block cipher
AES-256-CBC    (block) TLS 1.1,    algorithm that replaces the old DES
                       TLS 1.2     algorithm.  It has 128 bits block size
                                   and is used in CBC mode.
                                   
CAMELLIA-128-CBC,LegacyTLS 1.0,    This is an 128-bit block cipher
CAMELLIA-256-CBC(block)TLS 1.1,    developed by Mitsubishi and NTT. It is
                       TLS 1.2     one of the approved ciphers of the
                                   European NESSIE and Japanese CRYPTREC
                                   projects.
                                   
3DES-CBC       Legacy  TLS 1.0,    This is the DES block cipher algorithm
               (block) TLS 1.1,    used with triple encryption (EDE). Has
                       TLS 1.2     64 bits block size and is used in CBC
                                   mode.
                                   
ARCFOUR-128    Legacy  TLS 1.0,    ARCFOUR-128 is a compatible algorithm
               (stream)TLS 1.1,    with RSA's RC4 algorithm, which is
                       TLS 1.2     considered to be a trade secret.  It
                                   is a considered to be broken, and is
                                   only used for compatibility purposed.
                                   For this reason it is not enabled by
                                   default.
                                   
GOST28147-TC26Z-CNTLegacyTLS 1.2   This is a 64-bit block cipher GOST
               (stream)            28147-89 with TC26Z S-Box working in
                                   CNT mode.  It is one of the approved
                                   ciphers in Russia.  It is not enabled
                                   by default.
                                   
NULL           Legacy  TLS 1.0,    NULL is the empty/identity cipher
               (stream)TLS 1.1,    which doesn't encrypt any data.  It
                       TLS 1.2     can be combined with data
                                   authentication under TLS 1.2 or
                                   earlier, but is only used transiently
                                   under TLS 1.3 until encryption starts.
                                   This cipher cannot be negotiated by
                                   default (need to be explicitly
                                   enabled) under TLS 1.2, and cannot be
                                   negotiated at all under TLS 1.3.  When
                                   enabled, TLS 1.3 (or later) support
                                   will be implicitly disabled.
                                   


Table 3.1: Supported ciphers in TLS.

Algorithm      Description
------------------------------------------------------------------
MAC-MD5        This is an HMAC based on MD5 a cryptographic
               hash algorithm designed by Ron Rivest.  Outputs
               128 bits of data.
               
MAC-SHA1       An HMAC based on the SHA1 cryptographic hash
               algorithm designed by NSA. Outputs 160 bits of
               data.
               
MAC-SHA256     An HMAC based on SHA2-256.  Outputs 256 bits of
               data.
               
MAC-SHA384     An HMAC based on SHA2-384.  Outputs 384 bits of
               data.
               
GOST28147-TC26Z-IMITThis is a 64-bit block cipher GOST 28147-89 with
               TC26Z S-Box working in special MAC mode called
               Imitovstavks.  It is one of the approved MAC
               algorithms in Russia.  Outputs 32 bits of data.
               It is not enabled by default.
               
MAC-AEAD       This indicates that an authenticated encryption
               algorithm, such as GCM, is in use.
               


Table 3.2: Supported MAC algorithms in TLS.


File: gnutls.info,  Node: Compression algorithms and the record layer,  Next: On Record Padding,  Prev: Encryption algorithms used in the record layer,  Up: The TLS record protocol

3.3.2 Compression algorithms and the record layer
-------------------------------------------------

In early versions of TLS the record layer supported compression.
However, that proved to be problematic in many ways, and enabled several
attacks based on traffic analysis on the transported data.  For that
newer versions of the protocol no longer offer compression, and GnuTLS
since 3.6.0 no longer implements any support for compression.


File: gnutls.info,  Node: On Record Padding,  Prev: Compression algorithms and the record layer,  Up: The TLS record protocol

3.3.3 On record padding
-----------------------

The TLS 1.3 protocol allows for extra padding of records to prevent
statistical analysis based on the length of exchanged messages.  GnuTLS
takes advantage of this feature, by allowing the user to specify the
amount of padding for a particular message.  The simplest interface is
provided by *note gnutls_record_send2::, and is made available when
under TLS1.3; alternatively *note gnutls_record_can_use_length_hiding::
can be queried.

Note that this interface is not sufficient to completely hide the length
of the data.  The application code may reveal the data transferred by
leaking its data processing time, or by leaking the TLS1.3 record
processing time by GnuTLS. That is because under TLS1.3 the padding
removal time depends on the padding data for an efficient
implementation.  To make that processing constant time the *note
gnutls_init:: function must be called with the flag
'GNUTLS_SAFE_PADDING_CHECK'.

 -- Function: ssize_t gnutls_record_send2 (gnutls_session_t SESSION,
          const void * DATA, size_t DATA_SIZE, size_t PAD, unsigned
          FLAGS)
     SESSION: is a 'gnutls_session_t' type.

     DATA: contains the data to send

     DATA_SIZE: is the length of the data

     PAD: padding to be added to the record

     FLAGS: must be zero

     This function is identical to 'gnutls_record_send()' except that it
     takes an extra argument to specify padding to be added the record.
     To determine the maximum size of padding, use
     'gnutls_record_get_max_size()' and 'gnutls_record_overhead_size()'
     .

     Note that in order for GnuTLS to provide constant time processing
     of padding and data in TLS1.3, the flag 'GNUTLS_SAFE_PADDING_CHECK'
     must be used in 'gnutls_init()' .

     *Returns:* The number of bytes sent, or a negative error code.  The
     number of bytes sent might be less than 'data_size' .  The maximum
     number of bytes this function can send in a single call depends on
     the negotiated maximum record size.

     *Since:* 3.6.3

Older GnuTLS versions provided an API suitable for cases where the
sender sends data that are always within a given range.  That API is
still available, and consists of the following functions.

'UNSIGNED *note gnutls_record_can_use_length_hiding:: (gnutls_session_t SESSION)'
'SSIZE_T *note gnutls_record_send_range:: (gnutls_session_t SESSION, const void * DATA, size_t DATA_SIZE, const gnutls_range_st * RANGE)'


File: gnutls.info,  Node: The TLS Alert Protocol,  Next: The TLS Handshake Protocol,  Prev: The TLS record protocol,  Up: Introduction to TLS

3.4 The TLS alert protocol
==========================

The alert protocol is there to allow signals to be sent between peers.
These signals are mostly used to inform the peer about the cause of a
protocol failure.  Some of these signals are used internally by the
protocol and the application protocol does not have to cope with them
(e.g.  'GNUTLS_A_CLOSE_NOTIFY'), and others refer to the application
protocol solely (e.g.  'GNUTLS_A_USER_CANCELLED').  An alert signal
includes a level indication which may be either fatal or warning (under
TLS1.3 all alerts are fatal).  Fatal alerts always terminate the current
connection, and prevent future re-negotiations using the current session
ID. All supported alert messages are summarized in the table below.

The alert messages are protected by the record protocol, thus the
information that is included does not leak.  You must take extreme care
for the alert information not to leak to a possible attacker, via public
log files etc.

Alert                                    ID      Description
------------------------------------------------------------------------
GNUTLS_A_CLOSE_NOTIFY                    0       Close notify
GNUTLS_A_UNEXPECTED_MESSAGE              10      Unexpected message
GNUTLS_A_BAD_RECORD_MAC                  20      Bad record MAC
GNUTLS_A_DECRYPTION_FAILED               21      Decryption failed
GNUTLS_A_RECORD_OVERFLOW                 22      Record overflow
GNUTLS_A_DECOMPRESSION_FAILURE           30      Decompression failed
GNUTLS_A_HANDSHAKE_FAILURE               40      Handshake failed
GNUTLS_A_SSL3_NO_CERTIFICATE             41      No certificate (SSL
                                                 3.0)
GNUTLS_A_BAD_CERTIFICATE                 42      Certificate is bad
GNUTLS_A_UNSUPPORTED_CERTIFICATE         43      Certificate is not
                                                 supported
GNUTLS_A_CERTIFICATE_REVOKED             44      Certificate was
                                                 revoked
GNUTLS_A_CERTIFICATE_EXPIRED             45      Certificate is
                                                 expired
GNUTLS_A_CERTIFICATE_UNKNOWN             46      Unknown certificate
GNUTLS_A_ILLEGAL_PARAMETER               47      Illegal parameter
GNUTLS_A_UNKNOWN_CA                      48      CA is unknown
GNUTLS_A_ACCESS_DENIED                   49      Access was denied
GNUTLS_A_DECODE_ERROR                    50      Decode error
GNUTLS_A_DECRYPT_ERROR                   51      Decrypt error
GNUTLS_A_EXPORT_RESTRICTION              60      Export restriction
GNUTLS_A_PROTOCOL_VERSION                70      Error in protocol
                                                 version
GNUTLS_A_INSUFFICIENT_SECURITY           71      Insufficient
                                                 security
GNUTLS_A_INTERNAL_ERROR                  80      Internal error
GNUTLS_A_INAPPROPRIATE_FALLBACK          86      Inappropriate
                                                 fallback
GNUTLS_A_USER_CANCELED                   90      User canceled
GNUTLS_A_NO_RENEGOTIATION                100     No renegotiation is
                                                 allowed
GNUTLS_A_MISSING_EXTENSION               109     An extension was
                                                 expected but was not
                                                 seen
GNUTLS_A_UNSUPPORTED_EXTENSION           110     An unsupported
                                                 extension was sent
GNUTLS_A_CERTIFICATE_UNOBTAINABLE        111     Could not retrieve
                                                 the specified
                                                 certificate
GNUTLS_A_UNRECOGNIZED_NAME               112     The server name sent
                                                 was not recognized
GNUTLS_A_UNKNOWN_PSK_IDENTITY            115     The SRP/PSK username
                                                 is missing or not
                                                 known
GNUTLS_A_CERTIFICATE_REQUIRED            116     Certificate is
                                                 required
GNUTLS_A_NO_APPLICATION_PROTOCOL         120     No supported
                                                 application protocol
                                                 could be negotiated


File: gnutls.info,  Node: The TLS Handshake Protocol,  Next: TLS Extensions,  Prev: The TLS Alert Protocol,  Up: Introduction to TLS

3.5 The TLS handshake protocol
==============================

The handshake protocol is responsible for the ciphersuite negotiation,
the initial key exchange, and the authentication of the two peers.  This
is fully controlled by the application layer, thus your program has to
set up the required parameters.  The main handshake function is *note
gnutls_handshake::.  In the next paragraphs we elaborate on the
handshake protocol, i.e., the ciphersuite negotiation.

* Menu:

* TLS Cipher Suites::           TLS session parameters.
* Authentication::              TLS authentication.
* Client Authentication::       Requesting a certificate from the client.
* Resuming Sessions::           Reusing previously established keys.


File: gnutls.info,  Node: TLS Cipher Suites,  Next: Authentication,  Up: The TLS Handshake Protocol

3.5.1 TLS ciphersuites
----------------------

The TLS cipher suites have slightly different meaning under different
protocols.  Under TLS 1.3, a cipher suite indicates the symmetric
encryption algorithm in use, as well as the pseudo-random function (PRF)
used in the TLS session.

Under TLS 1.2 or early the handshake protocol negotiates cipher suites
of a special form illustrated by the 'TLS_DHE_RSA_WITH_3DES_CBC_SHA'
cipher suite name.  A typical cipher suite contains these parameters:

   * The key exchange algorithm.  'DHE_RSA' in the example.

   * The Symmetric encryption algorithm and mode '3DES_CBC' in this
     example.

   * The MAC(1) algorithm used for authentication.  'MAC_SHA' is used in
     the above example.

The cipher suite negotiated in the handshake protocol will affect the
record protocol, by enabling encryption and data authentication.  Note
that you should not over rely on TLS to negotiate the strongest
available cipher suite.  Do not enable ciphers and algorithms that you
consider weak.

All the supported ciphersuites are listed in *note ciphersuites::.

   ---------- Footnotes ----------

   (1) MAC stands for Message Authentication Code.  It can be described
as a keyed hash algorithm.  See RFC2104.


File: gnutls.info,  Node: Authentication,  Next: Client Authentication,  Prev: TLS Cipher Suites,  Up: The TLS Handshake Protocol

3.5.2 Authentication
--------------------

The key exchange algorithms of the TLS protocol offer authentication,
which is a prerequisite for a secure connection.  The available
authentication methods in GnuTLS, under TLS 1.3 or earlier versions,
follow.

   * Certificate authentication: Authenticated key exchange using public
     key infrastructure and X.509 certificates.
   * PSK authentication: Authenticated key exchange using a pre-shared
     key.

Under TLS 1.2 or earlier versions, the following authentication methods
are also available.

   * SRP authentication: Authenticated key exchange using a password.
   * Anonymous authentication: Key exchange without peer authentication.


File: gnutls.info,  Node: Client Authentication,  Next: Resuming Sessions,  Prev: Authentication,  Up: The TLS Handshake Protocol

3.5.3 Client authentication
---------------------------

In the case of ciphersuites that use certificate authentication, the
authentication of the client is optional in TLS.  A server may request a
certificate from the client using the *note
gnutls_certificate_server_set_request:: function.  We elaborate in *note
Certificate credentials::.


File: gnutls.info,  Node: Resuming Sessions,  Prev: Client Authentication,  Up: The TLS Handshake Protocol

3.5.4 Resuming sessions
-----------------------

The TLS handshake process performs expensive calculations and a busy
server might easily be put under load.  To reduce the load, session
resumption may be used.  This is a feature of the TLS protocol which
allows a client to connect to a server after a successful handshake,
without the expensive calculations.  This is achieved by re-using the
previously established keys, meaning the server needs to store the state
of established connections (unless session tickets are used - *note
Session tickets::).

Session resumption is an integral part of GnuTLS, and *note Session
resumption::, *note ex-resume-client:: illustrate typical uses of it.


File: gnutls.info,  Node: TLS Extensions,  Next: How to use TLS in application protocols,  Prev: The TLS Handshake Protocol,  Up: Introduction to TLS

3.6 TLS extensions
==================

A number of extensions to the TLS protocol have been proposed mainly in
[*note TLSEXT::].  The extensions supported in GnuTLS are discussed in
the subsections that follow.

* Menu:

* Maximum fragment length negotiation::
* Server name indication::
* Session tickets::
* HeartBeat::
* Safe renegotiation::
* OCSP status request::
* SRTP::
* False Start::
* Application Layer Protocol Negotiation (ALPN)::
* Extensions and Supplemental Data::


File: gnutls.info,  Node: Maximum fragment length negotiation,  Next: Server name indication,  Up: TLS Extensions

3.6.1 Maximum fragment length negotiation
-----------------------------------------

This extension allows a TLS implementation to negotiate a smaller value
for record packet maximum length.  This extension may be useful to
clients with constrained capabilities.  The functions shown below can be
used to control this extension.

'SIZE_T *note gnutls_record_get_max_size:: (gnutls_session_t SESSION)'
'SSIZE_T *note gnutls_record_set_max_size:: (gnutls_session_t SESSION, size_t SIZE)'


File: gnutls.info,  Node: Server name indication,  Next: Session tickets,  Prev: Maximum fragment length negotiation,  Up: TLS Extensions

3.6.2 Server name indication
----------------------------

A common problem in HTTPS servers is the fact that the TLS protocol is
not aware of the hostname that a client connects to, when the handshake
procedure begins.  For that reason the TLS server has no way to know
which certificate to send.

This extension solves that problem within the TLS protocol, and allows a
client to send the HTTP hostname before the handshake begins within the
first handshake packet.  The functions *note gnutls_server_name_set::
and *note gnutls_server_name_get:: can be used to enable this extension,
or to retrieve the name sent by a client.

'INT *note gnutls_server_name_set:: (gnutls_session_t SESSION, gnutls_server_name_type_t TYPE, const void * NAME, size_t NAME_LENGTH)'
'INT *note gnutls_server_name_get:: (gnutls_session_t SESSION, void * DATA, size_t * DATA_LENGTH, unsigned int * TYPE, unsigned int INDX)'


File: gnutls.info,  Node: Session tickets,  Next: HeartBeat,  Prev: Server name indication,  Up: TLS Extensions

3.6.3 Session tickets
---------------------

To resume a TLS session, the server normally stores session parameters.
This complicates deployment, and can be avoided by delegating the
storage to the client.  Because session parameters are sensitive they
are encrypted and authenticated with a key only known to the server and
then sent to the client.  The Session Tickets extension is described in
RFC 5077 [*note TLSTKT::].

A disadvantage of session tickets is that they eliminate the effects of
forward secrecy when a server uses the same key for long time.  That is,
the secrecy of all sessions on a server using tickets depends on the
ticket key being kept secret.  For that reason server keys should be
rotated and discarded regularly.

Since version 3.1.3 GnuTLS clients transparently support session
tickets, unless forward secrecy is explicitly requested (with the PFS
priority string).

Under TLS 1.3 session tickets are mandatory for session resumption, and
they do not share the forward secrecy concerns as with TLS 1.2 or
earlier.


File: gnutls.info,  Node: HeartBeat,  Next: Safe renegotiation,  Prev: Session tickets,  Up: TLS Extensions

3.6.4 HeartBeat
---------------

This is a TLS extension that allows to ping and receive confirmation
from the peer, and is described in [*note RFC6520::].  The extension is
disabled by default and *note gnutls_heartbeat_enable:: can be used to
enable it.  A policy may be negotiated to only allow sending heartbeat
messages or sending and receiving.  The current session policy can be
checked with *note gnutls_heartbeat_allowed::.  The requests coming from
the peer result to 'GNUTLS_E_HEARTBEAT_PING_RECEIVED' being returned
from the receive function.  Ping requests to peer can be send via *note
gnutls_heartbeat_ping::.

'UNSIGNED *note gnutls_heartbeat_allowed:: (gnutls_session_t SESSION, unsigned int TYPE)'
'VOID *note gnutls_heartbeat_enable:: (gnutls_session_t SESSION, unsigned int TYPE)'

'INT *note gnutls_heartbeat_ping:: (gnutls_session_t SESSION, size_t DATA_SIZE, unsigned int MAX_TRIES, unsigned int FLAGS)'
'INT *note gnutls_heartbeat_pong:: (gnutls_session_t SESSION, unsigned int FLAGS)'
'VOID *note gnutls_heartbeat_set_timeouts:: (gnutls_session_t SESSION, unsigned int RETRANS_TIMEOUT, unsigned int TOTAL_TIMEOUT)'
'UNSIGNED INT *note gnutls_heartbeat_get_timeout:: (gnutls_session_t SESSION)'


File: gnutls.info,  Node: Safe renegotiation,  Next: OCSP status request,  Prev: HeartBeat,  Up: TLS Extensions

3.6.5 Safe renegotiation
------------------------

TLS gives the option to two communicating parties to renegotiate and
update their security parameters.  One useful example of this feature
was for a client to initially connect using anonymous negotiation to a
server, and the renegotiate using some authenticated ciphersuite.  This
occurred to avoid having the client sending its credentials in the
clear.

However this renegotiation, as initially designed would not ensure that
the party one is renegotiating is the same as the one in the initial
negotiation.  For example one server could forward all renegotiation
traffic to an other server who will see this traffic as an initial
negotiation attempt.

This might be seen as a valid design decision, but it seems it was not
widely known or understood, thus today some application protocols use
the TLS renegotiation feature in a manner that enables a malicious
server to insert content of his choice in the beginning of a TLS
session.

The most prominent vulnerability was with HTTPS. There servers request a
renegotiation to enforce an anonymous user to use a certificate in order
to access certain parts of a web site.  The attack works by having the
attacker simulate a client and connect to a server, with server-only
authentication, and send some data intended to cause harm.  The server
will then require renegotiation from him in order to perform the
request.  When the proper client attempts to contact the server, the
attacker hijacks that connection and forwards traffic to the initial
server that requested renegotiation.  The attacker will not be able to
read the data exchanged between the client and the server.  However, the
server will (incorrectly) assume that the initial request sent by the
attacker was sent by the now authenticated client.  The result is a
prefix plain-text injection attack.

The above is just one example.  Other vulnerabilities exists that do not
rely on the TLS renegotiation to change the client's authenticated
status (either TLS or application layer).

While fixing these application protocols and implementations would be
one natural reaction, an extension to TLS has been designed that
cryptographically binds together any renegotiated handshakes with the
initial negotiation.  When the extension is used, the attack is detected
and the session can be terminated.  The extension is specified in [*note
RFC5746::].

GnuTLS supports the safe renegotiation extension.  The default behavior
is as follows.  Clients will attempt to negotiate the safe renegotiation
extension when talking to servers.  Servers will accept the extension
when presented by clients.  Clients and servers will permit an initial
handshake to complete even when the other side does not support the safe
renegotiation extension.  Clients and servers will refuse renegotiation
attempts when the extension has not been negotiated.

Note that permitting clients to connect to servers when the safe
renegotiation extension is not enabled, is open up for attacks.
Changing this default behavior would prevent interoperability against
the majority of deployed servers out there.  We will reconsider this
default behavior in the future when more servers have been upgraded.
Note that it is easy to configure clients to always require the safe
renegotiation extension from servers.

To modify the default behavior, we have introduced some new priority
strings (see *note Priority Strings::).  The '%UNSAFE_RENEGOTIATION'
priority string permits (re-)handshakes even when the safe renegotiation
extension was not negotiated.  The default behavior is
'%PARTIAL_RENEGOTIATION' that will prevent renegotiation with clients
and servers not supporting the extension.  This is secure for servers
but leaves clients vulnerable to some attacks, but this is a trade-off
between security and compatibility with old servers.  The
'%SAFE_RENEGOTIATION' priority string makes clients and servers require
the extension for every handshake.  The latter is the most secure option
for clients, at the cost of not being able to connect to legacy servers.
Servers will also deny clients that do not support the extension from
connecting.

It is possible to disable use of the extension completely, in both
clients and servers, by using the '%DISABLE_SAFE_RENEGOTIATION' priority
string however we strongly recommend you to only do this for debugging
and test purposes.

The default values if the flags above are not specified are:

'Server:'
     %PARTIAL_RENEGOTIATION

'Client:'
     %PARTIAL_RENEGOTIATION

For applications we have introduced a new API related to safe
renegotiation.  The *note gnutls_safe_renegotiation_status:: function is
used to check if the extension has been negotiated on a session, and can
be used both by clients and servers.


File: gnutls.info,  Node: OCSP status request,  Next: SRTP,  Prev: Safe renegotiation,  Up: TLS Extensions

3.6.6 OCSP status request
-------------------------

The Online Certificate Status Protocol (OCSP) is a protocol that allows
the client to verify the server certificate for revocation without
messing with certificate revocation lists.  Its drawback is that it
requires the client to connect to the server's CA OCSP server and
request the status of the certificate.  This extension however, enables
a TLS server to include its CA OCSP server response in the handshake.
That is an HTTPS server may periodically run 'ocsptool' (see *note
ocsptool Invocation::) to obtain its certificate revocation status and
serve it to the clients.  That way a client avoids an additional
connection to the OCSP server.

See *note OCSP stapling:: for further information.

Since version 3.1.3 GnuTLS clients transparently support the certificate
status request.


File: gnutls.info,  Node: SRTP,  Next: False Start,  Prev: OCSP status request,  Up: TLS Extensions

3.6.7 SRTP
----------

The TLS protocol was extended in [*note RFC5764::] to provide keying
material to the Secure RTP (SRTP) protocol.  The SRTP protocol provides
an encapsulation of encrypted data that is optimized for voice data.
With the SRTP TLS extension two peers can negotiate keys using TLS or
DTLS and obtain keying material for use with SRTP. The available SRTP
profiles are listed below.

'GNUTLS_SRTP_AES128_CM_HMAC_SHA1_80'
     128 bit AES with a 80 bit HMAC-SHA1
'GNUTLS_SRTP_AES128_CM_HMAC_SHA1_32'
     128 bit AES with a 32 bit HMAC-SHA1
'GNUTLS_SRTP_NULL_HMAC_SHA1_80'
     NULL cipher with a 80 bit HMAC-SHA1
'GNUTLS_SRTP_NULL_HMAC_SHA1_32'
     NULL cipher with a 32 bit HMAC-SHA1


Figure 3.2: Supported SRTP profiles

To enable use the following functions.

'INT *note gnutls_srtp_set_profile:: (gnutls_session_t SESSION, gnutls_srtp_profile_t PROFILE)'
'INT *note gnutls_srtp_set_profile_direct:: (gnutls_session_t SESSION, const char * PROFILES, const char ** ERR_POS)'

To obtain the negotiated keys use the function below.

 -- Function: int gnutls_srtp_get_keys (gnutls_session_t SESSION, void *
          KEY_MATERIAL, unsigned int KEY_MATERIAL_SIZE, gnutls_datum_t *
          CLIENT_KEY, gnutls_datum_t * CLIENT_SALT, gnutls_datum_t *
          SERVER_KEY, gnutls_datum_t * SERVER_SALT)
     SESSION: is a 'gnutls_session_t' type.

     KEY_MATERIAL: Space to hold the generated key material

     KEY_MATERIAL_SIZE: The maximum size of the key material

     CLIENT_KEY: The master client write key, pointing inside the key
     material

     CLIENT_SALT: The master client write salt, pointing inside the key
     material

     SERVER_KEY: The master server write key, pointing inside the key
     material

     SERVER_SALT: The master server write salt, pointing inside the key
     material

     This is a helper function to generate the keying material for SRTP.
     It requires the space of the key material to be pre-allocated
     (should be at least 2x the maximum key size and salt size).  The
     'client_key' , 'client_salt' , 'server_key' and 'server_salt' are
     convenience datums that point inside the key material.  They may be
     'NULL' .

     *Returns:* On success the size of the key material is returned,
     otherwise, 'GNUTLS_E_SHORT_MEMORY_BUFFER' if the buffer given is
     not sufficient, or a negative error code.

     Since 3.1.4

Other helper functions are listed below.

'INT *note gnutls_srtp_get_selected_profile:: (gnutls_session_t SESSION, gnutls_srtp_profile_t * PROFILE)'
'CONST CHAR * *note gnutls_srtp_get_profile_name:: (gnutls_srtp_profile_t PROFILE)'
'INT *note gnutls_srtp_get_profile_id:: (const char * NAME, gnutls_srtp_profile_t * PROFILE)'


File: gnutls.info,  Node: False Start,  Next: Application Layer Protocol Negotiation (ALPN),  Prev: SRTP,  Up: TLS Extensions

3.6.8 False Start
-----------------

The TLS protocol was extended in [*note RFC7918::] to allow the client
to send data to server in a single round trip.  This change however
operates on the borderline of the TLS protocol security guarantees and
should be used for the cases where the reduced latency outperforms the
risk of an adversary intercepting the transferred data.  In GnuTLS
applications can use the GNUTLS_ENABLE_FALSE_START as option to *note
gnutls_init:: to request an early return of the *note gnutls_handshake::
function.  After that early return the application is expected to
transfer any data to be piggybacked on the last handshake message.

After handshake's early termination, the application is expected to
transmit data using *note gnutls_record_send::, and call *note
gnutls_record_recv:: on any received data as soon, to ensure that
handshake completes timely.  That is, especially relevant for
applications which set an explicit time limit for the handshake process
via *note gnutls_handshake_set_timeout::.

Note however, that the API ensures that the early return will not happen
if the false start requirements are not satisfied.  That is, on
ciphersuites which are not whitelisted for false start or on
insufficient key sizes, the handshake process will complete properly
(i.e., no early return).  To verify that false start was used you may
use *note gnutls_session_get_flags:: and check for the
GNUTLS_SFLAGS_FALSE_START flag.  For GnuTLS the false start is
whitelisted for the following key exchange methods (see [*note
RFC7918::] for rationale)
   * DHE
   * ECDHE
but only when the negotiated parameters exceed 'GNUTLS_SEC_PARAM_HIGH'
-see *note Table 6.7: tab:key-sizes, and when under (D)TLS 1.2 or later.


File: gnutls.info,  Node: Application Layer Protocol Negotiation (ALPN),  Next: Extensions and Supplemental Data,  Prev: False Start,  Up: TLS Extensions

3.6.9 Application Layer Protocol Negotiation (ALPN)
---------------------------------------------------

The TLS protocol was extended in 'RFC7301' to provide the application
layer a method of negotiating the application protocol version.  This
allows for negotiation of the application protocol during the TLS
handshake, thus reducing round-trips.  The application protocol is
described by an opaque string.  To enable, use the following functions.

'INT *note gnutls_alpn_set_protocols:: (gnutls_session_t SESSION, const gnutls_datum_t * PROTOCOLS, unsigned PROTOCOLS_SIZE, unsigned int FLAGS)'
'INT *note gnutls_alpn_get_selected_protocol:: (gnutls_session_t SESSION, gnutls_datum_t * PROTOCOL)'

Note that these functions are intended to be used with protocols that
are registered in the Application Layer Protocol Negotiation IANA
registry.  While you can use them for other protocols (at the risk of
collisions), it is preferable to register them.


File: gnutls.info,  Node: Extensions and Supplemental Data,  Prev: Application Layer Protocol Negotiation (ALPN),  Up: TLS Extensions

3.6.10 Extensions and Supplemental Data
---------------------------------------

It is possible to transfer supplemental data during the TLS handshake,
following [*note RFC4680::].  This is for "custom" protocol
modifications for applications which may want to transfer additional
data (e.g.  additional authentication messages).  Such an exchange
requires a custom extension to be registered.  The provided API for this
functionality is low-level and described in *note TLS Hello Extension
Handling::.


File: gnutls.info,  Node: How to use TLS in application protocols,  Next: On SSL 2 and older protocols,  Prev: TLS Extensions,  Up: Introduction to TLS

3.7 How to use TLS in application protocols
===========================================

This chapter is intended to provide some hints on how to use TLS over
simple custom made application protocols.  The discussion below mainly
refers to the TCP/IP transport layer but may be extended to other ones
too.

* Menu:

* Separate ports::
* Upward negotiation::


File: gnutls.info,  Node: Separate ports,  Next: Upward negotiation,  Up: How to use TLS in application protocols

3.7.1 Separate ports
--------------------

Traditionally SSL was used in application protocols by assigning a new
port number for the secure services.  By doing this two separate ports
were assigned, one for the non-secure sessions, and one for the secure
sessions.  This method ensures that if a user requests a secure session
then the client will attempt to connect to the secure port and fail
otherwise.  The only possible attack with this method is to perform a
denial of service attack.  The most famous example of this method is
"HTTP over TLS" or HTTPS protocol [*note RFC2818::].

Despite its wide use, this method has several issues.  This approach
starts the TLS Handshake procedure just after the client connects on the
--so called-- secure port.  That way the TLS protocol does not know
anything about the client, and popular methods like the host advertising
in HTTP do not work(1).  There is no way for the client to say "I
connected to YYY server" before the Handshake starts, so the server
cannot possibly know which certificate to use.

Other than that it requires two separate ports to run a single service,
which is unnecessary complication.  Due to the fact that there is a
limitation on the available privileged ports, this approach was soon
deprecated in favor of upward negotiation.

   ---------- Footnotes ----------

   (1) See also the Server Name Indication extension on *note
serverind::.


File: gnutls.info,  Node: Upward negotiation,  Prev: Separate ports,  Up: How to use TLS in application protocols

3.7.2 Upward negotiation
------------------------

Other application protocols(1) use a different approach to enable the
secure layer.  They use something often called as the "TLS upgrade"
method.  This method is quite tricky but it is more flexible.  The idea
is to extend the application protocol to have a "STARTTLS" request,
whose purpose it to start the TLS protocols just after the client
requests it.  This approach does not require any extra port to be
reserved.  There is even an extension to HTTP protocol to support this
method [*note RFC2817::].

The tricky part, in this method, is that the "STARTTLS" request is sent
in the clear, thus is vulnerable to modifications.  A typical attack is
to modify the messages in a way that the client is fooled and thinks
that the server does not have the "STARTTLS" capability.  See a typical
conversation of a hypothetical protocol:

     (client connects to the server)

     CLIENT: HELLO I'M MR. XXX

     SERVER: NICE TO MEET YOU XXX

     CLIENT: PLEASE START TLS

     SERVER: OK

     *** TLS STARTS

     CLIENT: HERE ARE SOME CONFIDENTIAL DATA

And an example of a conversation where someone is acting in between:

     (client connects to the server)

     CLIENT: HELLO I'M MR. XXX

     SERVER: NICE TO MEET YOU XXX

     CLIENT: PLEASE START TLS

     (here someone inserts this message)

     SERVER: SORRY I DON'T HAVE THIS CAPABILITY

     CLIENT: HERE ARE SOME CONFIDENTIAL DATA

As you can see above the client was fooled, and was naïve enough to send
the confidential data in the clear, despite the server telling the
client that it does not support "STARTTLS".

How do we avoid the above attack?  As you may have already noticed this
situation is easy to avoid.  The client has to ask the user before it
connects whether the user requests TLS or not.  If the user answered
that he certainly wants the secure layer the last conversation should
be:

     (client connects to the server)

     CLIENT: HELLO I'M MR. XXX

     SERVER: NICE TO MEET YOU XXX

     CLIENT: PLEASE START TLS

     (here someone inserts this message)

     SERVER: SORRY I DON'T HAVE THIS CAPABILITY

     CLIENT: BYE

     (the client notifies the user that the secure connection was not
     possible)

This method, if implemented properly, is far better than the traditional
method, and the security properties remain the same, since only denial
of service is possible.  The benefit is that the server may request
additional data before the TLS Handshake protocol starts, in order to
send the correct certificate, use the correct password file, or anything
else!

   ---------- Footnotes ----------

   (1) See LDAP, IMAP etc.


File: gnutls.info,  Node: On SSL 2 and older protocols,  Prev: How to use TLS in application protocols,  Up: Introduction to TLS

3.8 On SSL 2 and older protocols
================================

One of the initial decisions in the GnuTLS development was to implement
the known security protocols for the transport layer.  Initially TLS 1.0
was implemented since it was the latest at that time, and was considered
to be the most advanced in security properties.  Later the SSL 3.0
protocol was implemented since it is still the only protocol supported
by several servers and there are no serious security vulnerabilities
known.

One question that may arise is why we didn't implement SSL 2.0 in the
library.  There are several reasons, most important being that it has
serious security flaws, unacceptable for a modern security library.
Other than that, this protocol is barely used by anyone these days since
it has been deprecated since 1996.  The security problems in SSL 2.0
include:

   * Message integrity compromised.  The SSLv2 message authentication
     uses the MD5 function, and is insecure.

   * Man-in-the-middle attack.  There is no protection of the handshake
     in SSLv2, which permits a man-in-the-middle attack.

   * Truncation attack.  SSLv2 relies on TCP FIN to close the session,
     so the attacker can forge a TCP FIN, and the peer cannot tell if it
     was a legitimate end of data or not.

   * Weak message integrity for export ciphers.  The cryptographic keys
     in SSLv2 are used for both message authentication and encryption,
     so if weak encryption schemes are negotiated (say 40-bit keys) the
     message authentication code uses the same weak key, which isn't
     necessary.

Other protocols such as Microsoft's PCT 1 and PCT 2 were not implemented
because they were also abandoned and deprecated by SSL 3.0 and later TLS
1.0.


File: gnutls.info,  Node: Authentication methods,  Next: Hardware security modules and abstract key types,  Prev: Introduction to TLS,  Up: Top

4 Authentication methods
************************

The initial key exchange of the TLS protocol performs authentication of
the peers.  In typical scenarios the server is authenticated to the
client, and optionally the client to the server.

While many associate TLS with X.509 certificates and public key
authentication, the protocol supports various authentication methods,
including pre-shared keys, and passwords.  In this chapter a description
of the existing authentication methods is provided, as well as some
guidance on which use-cases each method can be used at.

* Menu:

* Certificate authentication::
* More on certificate authentication::
* Shared-key and anonymous authentication::
* Selecting an appropriate authentication method::


File: gnutls.info,  Node: Certificate authentication,  Next: More on certificate authentication,  Up: Authentication methods

4.1 Certificate authentication
==============================

The most known authentication method of TLS are certificates.  The PKIX
[*note PKIX::] public key infrastructure is daily used by anyone using a
browser today.  GnuTLS provides a simple API to verify the X.509
certificates as in [*note PKIX::].

The key exchange algorithms supported by certificate authentication are
shown in *note Table 4.1: tab:key-exchange.

Key exchange   Description
               
------------------------------------------------------------------
RSA            The RSA algorithm is used to encrypt a key and
               send it to the peer.  The certificate must allow
               the key to be used for encryption.
               
DHE_RSA        The RSA algorithm is used to sign ephemeral
               Diffie-Hellman parameters which are sent to the
               peer.  The key in the certificate must allow the
               key to be used for signing.  Note that key
               exchange algorithms which use ephemeral
               Diffie-Hellman parameters, offer perfect forward
               secrecy.  That means that even if the private
               key used for signing is compromised, it cannot
               be used to reveal past session data.
               
ECDHE_RSA      The RSA algorithm is used to sign ephemeral
               elliptic curve Diffie-Hellman parameters which
               are sent to the peer.  The key in the
               certificate must allow the key to be used for
               signing.  It also offers perfect forward
               secrecy.  That means that even if the private
               key used for signing is compromised, it cannot
               be used to reveal past session data.
               
DHE_DSS        The DSA algorithm is used to sign ephemeral
               Diffie-Hellman parameters which are sent to the
               peer.  The certificate must contain DSA
               parameters to use this key exchange algorithm.
               DSA is the algorithm of the Digital Signature
               Standard (DSS).
               
ECDHE_ECDSA    The Elliptic curve DSA algorithm is used to sign
               ephemeral elliptic curve Diffie-Hellman
               parameters which are sent to the peer.  The
               certificate must contain ECDSA parameters (i.e.,
               EC and marked for signing) to use this key
               exchange algorithm.
               


Table 4.1: Supported key exchange algorithms.

* Menu:

* X.509 certificates::
* OpenPGP certificates::
* Raw public-keys::
* Advanced certificate verification::
* Digital signatures::


File: gnutls.info,  Node: X.509 certificates,  Next: OpenPGP certificates,  Up: Certificate authentication

4.1.1 X.509 certificates
------------------------

The X.509 protocols rely on a hierarchical trust model.  In this trust
model Certification Authorities (CAs) are used to certify entities.
Usually more than one certification authorities exist, and certification
authorities may certify other authorities to issue certificates as well,
following a hierarchical model.

[image src="gnutls-x509.png"]



Figure 4.1: An example of the X.509 hierarchical trust model.

One needs to trust one or more CAs for his secure communications.  In
that case only the certificates issued by the trusted authorities are
acceptable.  The framework is illustrated on *note Figure 4.1: fig-x509.

* Menu:

* X.509 certificate structure::
* Importing an X.509 certificate::
* X.509 certificate names::
* X.509 distinguished names::
* X.509 extensions::
* X.509 public and private keys::
* Verifying X.509 certificate paths::
* Verifying a certificate in the context of TLS session::
* Verification using PKCS11::


File: gnutls.info,  Node: X.509 certificate structure,  Next: Importing an X.509 certificate,  Up: X.509 certificates

4.1.1.1 X.509 certificate structure
...................................

An X.509 certificate usually contains information about the certificate
holder, the signer, a unique serial number, expiration dates and some
other fields [*note PKIX::] as shown in *note Table 4.2: tab:x509.

Field          Description
               
------------------------------------------------------------------
version        The field that indicates the version of the
               certificate.
               
serialNumber   This field holds a unique serial number per
               certificate.
               
signature      The issuing authority's signature.
               
issuer         Holds the issuer's distinguished name.
               
validity       The activation and expiration dates.
               
subject        The subject's distinguished name of the
               certificate.
               
extensions     The extensions are fields only present in
               version 3 certificates.
               


Table 4.2: X.509 certificate fields.

The certificate's _subject or issuer name_ is not just a single string.
It is a Distinguished name and in the ASN.1 notation is a sequence of
several object identifiers with their corresponding values.  Some of
available OIDs to be used in an X.509 distinguished name are defined in
'gnutls/x509.h'.

The _Version_ field in a certificate has values either 1 or 3 for
version 3 certificates.  Version 1 certificates do not support the
extensions field so it is not possible to distinguish a CA from a
person, thus their usage should be avoided.

The _validity_ dates are there to indicate the date that the specific
certificate was activated and the date the certificate's key would be
considered invalid.

In GnuTLS the X.509 certificate structures are handled using the
'gnutls_x509_crt_t' type and the corresponding private keys with the
'gnutls_x509_privkey_t' type.  All the available functions for X.509
certificate handling have their prototypes in 'gnutls/x509.h'.  An
example program to demonstrate the X.509 parsing capabilities can be
found in *note ex-x509-info::.


File: gnutls.info,  Node: Importing an X.509 certificate,  Next: X.509 certificate names,  Prev: X.509 certificate structure,  Up: X.509 certificates

4.1.1.2 Importing an X.509 certificate
......................................

The certificate structure should be initialized using *note
gnutls_x509_crt_init::, and a certificate structure can be imported
using *note gnutls_x509_crt_import::.

'INT *note gnutls_x509_crt_init:: (gnutls_x509_crt_t * CERT)'
'INT *note gnutls_x509_crt_import:: (gnutls_x509_crt_t CERT, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
'VOID *note gnutls_x509_crt_deinit:: (gnutls_x509_crt_t CERT)'

In several functions an array of certificates is required.  To assist in
initialization and import the following two functions are provided.

'INT *note gnutls_x509_crt_list_import:: (gnutls_x509_crt_t * CERTS, unsigned int * CERT_MAX, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, unsigned int FLAGS)'
'INT *note gnutls_x509_crt_list_import2:: (gnutls_x509_crt_t ** CERTS, unsigned int * SIZE, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, unsigned int FLAGS)'

In all cases after use a certificate must be deinitialized using *note
gnutls_x509_crt_deinit::.  Note that although the functions above apply
to 'gnutls_x509_crt_t' structure, similar functions exist for the CRL
structure 'gnutls_x509_crl_t'.


File: gnutls.info,  Node: X.509 certificate names,  Next: X.509 distinguished names,  Prev: Importing an X.509 certificate,  Up: X.509 certificates

4.1.1.3 X.509 certificate names
...............................

X.509 certificates allow for multiple names and types of names to be
specified.  CA certificates often rely on X.509 distinguished names (see
*note X.509 distinguished names::) for unique identification, while
end-user and server certificates rely on the 'subject alternative
names'.  The subject alternative names provide a typed name, e.g., a DNS
name, or an email address, which identifies the owner of the
certificate.  The following functions provide access to that names.

'INT *note gnutls_x509_crt_get_subject_alt_name2:: (gnutls_x509_crt_t CERT, unsigned int SEQ, void * SAN, size_t * SAN_SIZE, unsigned int * SAN_TYPE, unsigned int * CRITICAL)'
'INT *note gnutls_x509_crt_set_subject_alt_name:: (gnutls_x509_crt_t CRT, gnutls_x509_subject_alt_name_t TYPE, const void * DATA, unsigned int DATA_SIZE, unsigned int FLAGS)'
'INT *note gnutls_subject_alt_names_init:: (gnutls_subject_alt_names_t * SANS)'
'INT *note gnutls_subject_alt_names_get:: (gnutls_subject_alt_names_t SANS, unsigned int SEQ, unsigned int * SAN_TYPE, gnutls_datum_t * SAN, gnutls_datum_t * OTHERNAME_OID)'
'INT *note gnutls_subject_alt_names_set:: (gnutls_subject_alt_names_t SANS, unsigned int SAN_TYPE, const gnutls_datum_t * SAN, const char * OTHERNAME_OID)'

Note however, that server certificates often used the Common Name (CN),
part of the certificate DistinguishedName to place a single DNS address.
That practice is discouraged (see [*note RFC6125::]), because only a
single address can be specified, and the CN field is free-form making
matching ambiguous.


File: gnutls.info,  Node: X.509 distinguished names,  Next: X.509 extensions,  Prev: X.509 certificate names,  Up: X.509 certificates

4.1.1.4 X.509 distinguished names
.................................

The "subject" of an X.509 certificate is not described by a single name,
but rather with a distinguished name.  This in X.509 terminology is a
list of strings each associated an object identifier.  To make things
simple GnuTLS provides *note gnutls_x509_crt_get_dn2:: which follows the
rules in [*note RFC4514::] and returns a single string.  Access to each
string by individual object identifiers can be accessed using *note
gnutls_x509_crt_get_dn_by_oid::.

 -- Function: int gnutls_x509_crt_get_dn2 (gnutls_x509_crt_t CERT,
          gnutls_datum_t * DN)
     CERT: should contain a 'gnutls_x509_crt_t' type

     DN: a pointer to a structure to hold the name; must be freed using
     'gnutls_free()'

     This function will allocate buffer and copy the name of the
     Certificate.  The name will be in the form "C=xxxx,O=yyyy,CN=zzzz"
     as described in RFC4514.  The output string will be ASCII or UTF-8
     encoded, depending on the certificate data.

     This function does not output a fully RFC4514 compliant string, if
     that is required see 'gnutls_x509_crt_get_dn3()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.1.10
'INT *note gnutls_x509_crt_get_dn:: (gnutls_x509_crt_t CERT, char * BUF, size_t * BUF_SIZE)'
'INT *note gnutls_x509_crt_get_dn_by_oid:: (gnutls_x509_crt_t CERT, const char * OID, unsigned INDX, unsigned int RAW_FLAG, void * BUF, size_t * BUF_SIZE)'
'INT *note gnutls_x509_crt_get_dn_oid:: (gnutls_x509_crt_t CERT, unsigned INDX, void * OID, size_t * OID_SIZE)'

Similar functions exist to access the distinguished name of the issuer
of the certificate.

'INT *note gnutls_x509_crt_get_issuer_dn:: (gnutls_x509_crt_t CERT, char * BUF, size_t * BUF_SIZE)'
'INT *note gnutls_x509_crt_get_issuer_dn2:: (gnutls_x509_crt_t CERT, gnutls_datum_t * DN)'
'INT *note gnutls_x509_crt_get_issuer_dn_by_oid:: (gnutls_x509_crt_t CERT, const char * OID, unsigned INDX, unsigned int RAW_FLAG, void * BUF, size_t * BUF_SIZE)'
'INT *note gnutls_x509_crt_get_issuer_dn_oid:: (gnutls_x509_crt_t CERT, unsigned INDX, void * OID, size_t * OID_SIZE)'
'INT *note gnutls_x509_crt_get_issuer:: (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'

The more powerful *note gnutls_x509_crt_get_subject:: and *note
gnutls_x509_dn_get_rdn_ava:: provide efficient but low-level access to
the contents of the distinguished name structure.

'INT *note gnutls_x509_crt_get_subject:: (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'
'INT *note gnutls_x509_crt_get_issuer:: (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'

 -- Function: int gnutls_x509_dn_get_rdn_ava (gnutls_x509_dn_t DN, int
          IRDN, int IAVA, gnutls_x509_ava_st * AVA)
     DN: a pointer to DN

     IRDN: index of RDN

     IAVA: index of AVA.

     AVA: Pointer to structure which will hold output information.

     Get pointers to data within the DN. The format of the 'ava'
     structure is shown below.

     struct gnutls_x509_ava_st { gnutls_datum_t oid; gnutls_datum_t
     value; unsigned long value_tag; };

     The X.509 distinguished name is a sequence of sequences of strings
     and this is what the 'irdn' and 'iava' indexes model.

     Note that 'ava' will contain pointers into the 'dn' structure which
     in turns points to the original certificate.  Thus you should not
     modify any data or deallocate any of those.

     This is a low-level function that requires the caller to do the
     value conversions when necessary (e.g.  from UCS-2).

     *Returns:* Returns 0 on success, or an error code.


File: gnutls.info,  Node: X.509 extensions,  Next: X.509 public and private keys,  Prev: X.509 distinguished names,  Up: X.509 certificates

4.1.1.5 X.509 extensions
........................

X.509 version 3 certificates include a list of extensions that can be
used to obtain additional information on the subject or the issuer of
the certificate.  Those may be e-mail addresses, flags that indicate
whether the belongs to a CA etc.  All the supported X.509 version 3
extensions are shown in *note Table 4.3: tab:x509-ext.

The certificate extensions access is split into two parts.  The first
requires to retrieve the extension, and the second is the parsing part.

To enumerate and retrieve the DER-encoded extension data available in a
certificate the following two functions are available.
'INT *note gnutls_x509_crt_get_extension_info:: (gnutls_x509_crt_t CERT, unsigned INDX, void * OID, size_t * OID_SIZE, unsigned int * CRITICAL)'
'INT *note gnutls_x509_crt_get_extension_data2:: (gnutls_x509_crt_t CERT, unsigned INDX, gnutls_datum_t * DATA)'
'INT *note gnutls_x509_crt_get_extension_by_oid2:: (gnutls_x509_crt_t CERT, const char * OID, unsigned INDX, gnutls_datum_t * OUTPUT, unsigned int * CRITICAL)'

After a supported DER-encoded extension is retrieved it can be parsed
using the APIs in 'x509-ext.h'.  Complex extensions may require
initializing an intermediate structure that holds the parsed extension
data.  Examples of simple parsing functions are shown below.
'INT *note gnutls_x509_ext_import_basic_constraints:: (const gnutls_datum_t * EXT, unsigned int * CA, int * PATHLEN)'
'INT *note gnutls_x509_ext_export_basic_constraints:: (unsigned int CA, int PATHLEN, gnutls_datum_t * EXT)'
'INT *note gnutls_x509_ext_import_key_usage:: (const gnutls_datum_t * EXT, unsigned int * KEY_USAGE)'
'INT *note gnutls_x509_ext_export_key_usage:: (unsigned int USAGE, gnutls_datum_t * EXT)'

More complex extensions, such as Name Constraints, require an
intermediate structure, in that case 'gnutls_x509_name_constraints_t' to
be initialized in order to store the parsed extension data.
'INT *note gnutls_x509_ext_import_name_constraints:: (const gnutls_datum_t * EXT, gnutls_x509_name_constraints_t NC, unsigned int FLAGS)'
'INT *note gnutls_x509_ext_export_name_constraints:: (gnutls_x509_name_constraints_t NC, gnutls_datum_t * EXT)'

After the name constraints are extracted in the structure, the following
functions can be used to access them.

'INT *note gnutls_x509_name_constraints_get_permitted:: (gnutls_x509_name_constraints_t NC, unsigned IDX, unsigned * TYPE, gnutls_datum_t * NAME)'
'INT *note gnutls_x509_name_constraints_get_excluded:: (gnutls_x509_name_constraints_t NC, unsigned IDX, unsigned * TYPE, gnutls_datum_t * NAME)'
'INT *note gnutls_x509_name_constraints_add_permitted:: (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
'INT *note gnutls_x509_name_constraints_add_excluded:: (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
'UNSIGNED *note gnutls_x509_name_constraints_check:: (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
'UNSIGNED *note gnutls_x509_name_constraints_check_crt:: (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, gnutls_x509_crt_t CERT)'

Other utility functions are listed below.
'INT *note gnutls_x509_name_constraints_init:: (gnutls_x509_name_constraints_t * NC)'
'VOID *note gnutls_x509_name_constraints_deinit:: (gnutls_x509_name_constraints_t NC)'

Similar functions exist for all of the other supported extensions,
listed in *note Table 4.3: tab:x509-ext.

Extension              OID            Description
                                      
--------------------------------------------------------------------
Subject key id         2.5.29.14      An identifier of the key of
                                      the subject.
                                      
Key usage              2.5.29.15      Constraints the key's usage
                                      of the certificate.
                                      
Private key usage      2.5.29.16      Constraints the validity
period                                time of the private key.
                                      
Subject alternative    2.5.29.17      Alternative names to
name                                  subject's distinguished
                                      name.
                                      
Issuer alternative     2.5.29.18      Alternative names to the
name                                  issuer's distinguished
                                      name.
                                      
Basic constraints      2.5.29.19      Indicates whether this is a
                                      CA certificate or not, and
                                      specify the maximum path
                                      lengths of certificate
                                      chains.
                                      
Name constraints       2.5.29.30      A field in CA certificates
                                      that restricts the scope of
                                      the name of issued
                                      certificates.
                                      
CRL distribution       2.5.29.31      This extension is set by
points                                the CA, in order to inform
                                      about the location of
                                      issued Certificate
                                      Revocation Lists.
                                      
Certificate policy     2.5.29.32      This extension is set to
                                      indicate the certificate
                                      policy as object identifier
                                      and may contain a
                                      descriptive string or URL.
                                      
Extended key usage     2.5.29.54      Inhibit any policy
                                      extension.  Constraints the
                                      any policy OID
                                      ('GNUTLS_X509_OID_POLICY_ANY')
                                      use in the policy
                                      extension.
                                      
Authority key          2.5.29.35      An identifier of the key of
identifier                            the issuer of the
                                      certificate.  That is used
                                      to distinguish between
                                      different keys of the same
                                      issuer.
                                      
Extended key usage     2.5.29.37      Constraints the purpose of
                                      the certificate.
                                      
Authority              1.3.6.1.5.5.7.1.1Information on services by
information access                    the issuer of the
                                      certificate.
                                      
Proxy Certification    1.3.6.1.5.5.7.1.14Proxy Certificates includes
Information                           this extension that
                                      contains the OID of the
                                      proxy policy language used,
                                      and can specify limits on
                                      the maximum lengths of
                                      proxy chains.  Proxy
                                      Certificates are specified
                                      in [*note RFC3820::].
                                      


Table 4.3: Supported X.509 certificate extensions.

Note, that there are also direct APIs to access extensions that may be
simpler to use for non-complex extensions.  They are available in
'x509.h' and some examples are listed below.
'INT *note gnutls_x509_crt_get_basic_constraints:: (gnutls_x509_crt_t CERT, unsigned int * CRITICAL, unsigned int * CA, int * PATHLEN)'
'INT *note gnutls_x509_crt_set_basic_constraints:: (gnutls_x509_crt_t CRT, unsigned int CA, int PATHLENCONSTRAINT)'
'INT *note gnutls_x509_crt_get_key_usage:: (gnutls_x509_crt_t CERT, unsigned int * KEY_USAGE, unsigned int * CRITICAL)'
'INT *note gnutls_x509_crt_set_key_usage:: (gnutls_x509_crt_t CRT, unsigned int USAGE)'


File: gnutls.info,  Node: X.509 public and private keys,  Next: Verifying X.509 certificate paths,  Prev: X.509 extensions,  Up: X.509 certificates

4.1.1.6 Accessing public and private keys
.........................................

Each X.509 certificate contains a public key that corresponds to a
private key.  To get a unique identifier of the public key the *note
gnutls_x509_crt_get_key_id:: function is provided.  To export the public
key or its parameters you may need to convert the X.509 structure to a
'gnutls_pubkey_t'.  See *note Abstract public keys:: for more
information.

 -- Function: int gnutls_x509_crt_get_key_id (gnutls_x509_crt_t CRT,
          unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t *
          OUTPUT_DATA_SIZE)
     CRT: Holds the certificate

     FLAGS: should be one of the flags from 'gnutls_keyid_flags_t'

     OUTPUT_DATA: will contain the key ID

     OUTPUT_DATA_SIZE: holds the size of output_data (and will be
     replaced by the actual size of parameters)

     This function will return a unique ID that depends on the public
     key parameters.  This ID can be used in checking whether a
     certificate corresponds to the given private key.

     If the buffer provided is not long enough to hold the output, then
     *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will
     be returned.  The output will normally be a SHA-1 hash output,
     which is 20 bytes.

     *Returns:* In case of failure a negative error code will be
     returned, and 0 on success.

The private key parameters may be directly accessed by using one of the
following functions.

'INT *note gnutls_x509_privkey_get_pk_algorithm2:: (gnutls_x509_privkey_t KEY, unsigned int * BITS)'
'INT *note gnutls_x509_privkey_export_rsa_raw2:: (gnutls_x509_privkey_t KEY, gnutls_datum_t * M, gnutls_datum_t * E, gnutls_datum_t * D, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * U, gnutls_datum_t * E1, gnutls_datum_t * E2)'
'INT *note gnutls_x509_privkey_export_ecc_raw:: (gnutls_x509_privkey_t KEY, gnutls_ecc_curve_t * CURVE, gnutls_datum_t * X, gnutls_datum_t * Y, gnutls_datum_t * K)'
'INT *note gnutls_x509_privkey_export_dsa_raw:: (gnutls_x509_privkey_t KEY, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G, gnutls_datum_t * Y, gnutls_datum_t * X)'
'INT *note gnutls_x509_privkey_get_key_id:: (gnutls_x509_privkey_t KEY, unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'


File: gnutls.info,  Node: Verifying X.509 certificate paths,  Next: Verifying a certificate in the context of TLS session,  Prev: X.509 public and private keys,  Up: X.509 certificates

4.1.1.7 Verifying X.509 certificate paths
.........................................

Verifying certificate paths is important in X.509 authentication.  For
this purpose the following functions are provided.

 -- Function: int gnutls_x509_trust_list_add_cas
          (gnutls_x509_trust_list_t LIST, const gnutls_x509_crt_t *
          CLIST, unsigned CLIST_SIZE, unsigned int FLAGS)
     LIST: The list

     CLIST: A list of CAs

     CLIST_SIZE: The length of the CA list

     FLAGS: flags from 'gnutls_trust_list_flags_t'

     This function will add the given certificate authorities to the
     trusted list.  The CAs in 'clist' must not be deinitialized during
     the lifetime of 'list' .

     If the flag 'GNUTLS_TL_NO_DUPLICATES' is specified, then this
     function will ensure that no duplicates will be present in the
     final trust list.

     If the flag 'GNUTLS_TL_NO_DUPLICATE_KEY' is specified, then this
     function will ensure that no certificates with the same key are
     present in the final trust list.

     If either 'GNUTLS_TL_NO_DUPLICATE_KEY' or 'GNUTLS_TL_NO_DUPLICATES'
     are given, 'gnutls_x509_trust_list_deinit()' must be called with
     parameter 'all' being 1.

     *Returns:* The number of added elements is returned; that includes
     duplicate entries.

     *Since:* 3.0.0

 -- Function: int gnutls_x509_trust_list_add_named_crt
          (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t CERT, const
          void * NAME, size_t NAME_SIZE, unsigned int FLAGS)
     LIST: The list

     CERT: A certificate

     NAME: An identifier for the certificate

     NAME_SIZE: The size of the identifier

     FLAGS: should be 0.

     This function will add the given certificate to the trusted list
     and associate it with a name.  The certificate will not be be used
     for verification with 'gnutls_x509_trust_list_verify_crt()' but
     with 'gnutls_x509_trust_list_verify_named_crt()' or
     'gnutls_x509_trust_list_verify_crt2()' - the latter only since
     GnuTLS 3.4.0 and if a hostname is provided.

     In principle this function can be used to set individual "server"
     certificates that are trusted by the user for that specific server
     but for no other purposes.

     The certificate 'cert' must not be deinitialized during the
     lifetime of the 'list' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0.0

 -- Function: int gnutls_x509_trust_list_add_crls
          (gnutls_x509_trust_list_t LIST, const gnutls_x509_crl_t *
          CRL_LIST, unsigned CRL_SIZE, unsigned int FLAGS, unsigned int
          VERIFICATION_FLAGS)
     LIST: The list

     CRL_LIST: A list of CRLs

     CRL_SIZE: The length of the CRL list

     FLAGS: flags from 'gnutls_trust_list_flags_t'

     VERIFICATION_FLAGS: gnutls_certificate_verify_flags if flags
     specifies GNUTLS_TL_VERIFY_CRL

     This function will add the given certificate revocation lists to
     the trusted list.  The CRLs in 'crl_list' must not be deinitialized
     during the lifetime of 'list' .

     This function must be called after
     'gnutls_x509_trust_list_add_cas()' to allow verifying the CRLs for
     validity.  If the flag 'GNUTLS_TL_NO_DUPLICATES' is given, then the
     final CRL list will not contain duplicate entries.

     If the flag 'GNUTLS_TL_NO_DUPLICATES' is given,
     'gnutls_x509_trust_list_deinit()' must be called with parameter
     'all' being 1.

     If flag 'GNUTLS_TL_VERIFY_CRL' is given the CRLs will be verified
     before being added, and if verification fails, they will be
     skipped.

     *Returns:* The number of added elements is returned; that includes
     duplicate entries.

     *Since:* 3.0

 -- Function: int gnutls_x509_trust_list_verify_crt
          (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t * CERT_LIST,
          unsigned int CERT_LIST_SIZE, unsigned int FLAGS, unsigned int
          * VOUTPUT, gnutls_verify_output_function FUNC)
     LIST: The list

     CERT_LIST: is the certificate list to be verified

     CERT_LIST_SIZE: is the certificate list size

     FLAGS: Flags that may be used to change the verification algorithm.
     Use OR of the gnutls_certificate_verify_flags enumerations.

     VOUTPUT: will hold the certificate verification output.

     FUNC: If non-null will be called on each chain element verification
     with the output.

     This function will try to verify the given certificate and return
     its status.  The 'voutput' parameter will hold an OR'ed sequence of
     'gnutls_certificate_status_t' flags.

     The details of the verification are the same as in
     'gnutls_x509_trust_list_verify_crt2()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0

 -- Function: int gnutls_x509_trust_list_verify_crt2
          (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t * CERT_LIST,
          unsigned int CERT_LIST_SIZE, gnutls_typed_vdata_st * DATA,
          unsigned int ELEMENTS, unsigned int FLAGS, unsigned int *
          VOUTPUT, gnutls_verify_output_function FUNC)
     LIST: The list

     CERT_LIST: is the certificate list to be verified

     CERT_LIST_SIZE: is the certificate list size

     DATA: an array of typed data

     ELEMENTS: the number of data elements

     FLAGS: Flags that may be used to change the verification algorithm.
     Use OR of the gnutls_certificate_verify_flags enumerations.

     VOUTPUT: will hold the certificate verification output.

     FUNC: If non-null will be called on each chain element verification
     with the output.

     This function will attempt to verify the given certificate chain
     and return its status.  The 'voutput' parameter will hold an OR'ed
     sequence of 'gnutls_certificate_status_t' flags.

     When a certificate chain of 'cert_list_size' with more than one
     certificates is provided, the verification status will apply to the
     first certificate in the chain that failed verification.  The
     verification process starts from the end of the chain (from CA to
     end certificate).  The first certificate in the chain must be the
     end-certificate while the rest of the members may be sorted or not.

     Additionally a certificate verification profile can be specified
     from the ones in 'gnutls_certificate_verification_profiles_t' by
     ORing the result of 'GNUTLS_PROFILE_TO_VFLAGS()' to the
     verification flags.

     Additional verification parameters are possible via the 'data'
     types; the acceptable types are 'GNUTLS_DT_DNS_HOSTNAME' ,
     'GNUTLS_DT_IP_ADDRESS' and 'GNUTLS_DT_KEY_PURPOSE_OID' .  The
     former accepts as data a null-terminated hostname, and the latter a
     null-terminated object identifier (e.g., 'GNUTLS_KP_TLS_WWW_SERVER'
     ).  If a DNS hostname is provided then this function will compare
     the hostname in the end certificate against the given.  If names do
     not match the 'GNUTLS_CERT_UNEXPECTED_OWNER' status flag will be
     set.  In addition it will consider certificates provided with
     'gnutls_x509_trust_list_add_named_crt()' .

     If a key purpose OID is provided and the end-certificate contains
     the extended key usage PKIX extension, it will be required to match
     the provided OID or be marked for any purpose, otherwise
     verification will fail with 'GNUTLS_CERT_PURPOSE_MISMATCH' status.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.  Note that verification failure
     will not result to an error code, only 'voutput' will be updated.

     *Since:* 3.3.8

 -- Function: int gnutls_x509_trust_list_verify_named_crt
          (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t CERT, const
          void * NAME, size_t NAME_SIZE, unsigned int FLAGS, unsigned
          int * VOUTPUT, gnutls_verify_output_function FUNC)
     LIST: The list

     CERT: is the certificate to be verified

     NAME: is the certificate's name

     NAME_SIZE: is the certificate's name size

     FLAGS: Flags that may be used to change the verification algorithm.
     Use OR of the gnutls_certificate_verify_flags enumerations.

     VOUTPUT: will hold the certificate verification output.

     FUNC: If non-null will be called on each chain element verification
     with the output.

     This function will try to find a certificate that is associated
     with the provided name -see
     'gnutls_x509_trust_list_add_named_crt()' .  If a match is found the
     certificate is considered valid.  In addition to that this function
     will also check CRLs.  The 'voutput' parameter will hold an OR'ed
     sequence of 'gnutls_certificate_status_t' flags.

     Additionally a certificate verification profile can be specified
     from the ones in 'gnutls_certificate_verification_profiles_t' by
     ORing the result of 'GNUTLS_PROFILE_TO_VFLAGS()' to the
     verification flags.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0.0

 -- Function: int gnutls_x509_trust_list_add_trust_file
          (gnutls_x509_trust_list_t LIST, const char * CA_FILE, const
          char * CRL_FILE, gnutls_x509_crt_fmt_t TYPE, unsigned int
          TL_FLAGS, unsigned int TL_VFLAGS)
     LIST: The list

     CA_FILE: A file containing a list of CAs (optional)

     CRL_FILE: A file containing a list of CRLs (optional)

     TYPE: The format of the certificates

     TL_FLAGS: flags from 'gnutls_trust_list_flags_t'

     TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
     GNUTLS_TL_VERIFY_CRL

     This function will add the given certificate authorities to the
     trusted list.  PKCS '11' URLs are also accepted, instead of files,
     by this function.  A PKCS '11' URL implies a trust database (a
     specially marked module in p11-kit); the URL "pkcs11:" implies all
     trust databases in the system.  Only a single URL specifying trust
     databases can be set; they cannot be stacked with multiple calls.

     *Returns:* The number of added elements is returned.

     *Since:* 3.1

 -- Function: int gnutls_x509_trust_list_add_trust_mem
          (gnutls_x509_trust_list_t LIST, const gnutls_datum_t * CAS,
          const gnutls_datum_t * CRLS, gnutls_x509_crt_fmt_t TYPE,
          unsigned int TL_FLAGS, unsigned int TL_VFLAGS)
     LIST: The list

     CAS: A buffer containing a list of CAs (optional)

     CRLS: A buffer containing a list of CRLs (optional)

     TYPE: The format of the certificates

     TL_FLAGS: flags from 'gnutls_trust_list_flags_t'

     TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
     GNUTLS_TL_VERIFY_CRL

     This function will add the given certificate authorities to the
     trusted list.

     If this function is used 'gnutls_x509_trust_list_deinit()' must be
     called with parameter 'all' being 1.

     *Returns:* The number of added elements is returned.

     *Since:* 3.1

 -- Function: int gnutls_x509_trust_list_add_system_trust
          (gnutls_x509_trust_list_t LIST, unsigned int TL_FLAGS,
          unsigned int TL_VFLAGS)
     LIST: The structure of the list

     TL_FLAGS: GNUTLS_TL_*

     TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
     GNUTLS_TL_VERIFY_CRL

     This function adds the system's default trusted certificate
     authorities to the trusted list.  Note that on unsupported systems
     this function returns 'GNUTLS_E_UNIMPLEMENTED_FEATURE' .

     This function implies the flag 'GNUTLS_TL_NO_DUPLICATES' .

     *Returns:* The number of added elements or a negative error code on
     error.

     *Since:* 3.1

The verification function will verify a given certificate chain against
a list of certificate authorities and certificate revocation lists, and
output a bit-wise OR of elements of the 'gnutls_certificate_status_t'
enumeration shown in *note Figure 4.2: gnutls_certificate_status_t.  The
'GNUTLS_CERT_INVALID' flag is always set on a verification error and
more detailed flags will also be set when appropriate.

'GNUTLS_CERT_INVALID'
     The certificate is not signed by one of the known authorities or
     the signature is invalid (deprecated by the flags
     'GNUTLS_CERT_SIGNATURE_FAILURE' and 'GNUTLS_CERT_SIGNER_NOT_FOUND'
     ).
'GNUTLS_CERT_REVOKED'
     Certificate is revoked by its authority.  In X.509 this will be set
     only if CRLs are checked.
'GNUTLS_CERT_SIGNER_NOT_FOUND'
     The certificate's issuer is not known.  This is the case if the
     issuer is not included in the trusted certificate list.
'GNUTLS_CERT_SIGNER_NOT_CA'
     The certificate's signer was not a CA. This may happen if this was
     a version 1 certificate, which is common with some CAs, or a
     version 3 certificate without the basic constrains extension.
'GNUTLS_CERT_INSECURE_ALGORITHM'
     The certificate was signed using an insecure algorithm such as MD2
     or MD5.  These algorithms have been broken and should not be
     trusted.
'GNUTLS_CERT_NOT_ACTIVATED'
     The certificate is not yet activated.
'GNUTLS_CERT_EXPIRED'
     The certificate has expired.
'GNUTLS_CERT_SIGNATURE_FAILURE'
     The signature verification failed.
'GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED'
     The revocation data are old and have been superseded.
'GNUTLS_CERT_UNEXPECTED_OWNER'
     The owner is not the expected one.
'GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE'
     The revocation data have a future issue date.
'GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE'
     The certificate's signer constraints were violated.
'GNUTLS_CERT_MISMATCH'
     The certificate presented isn't the expected one (TOFU)
'GNUTLS_CERT_PURPOSE_MISMATCH'
     The certificate or an intermediate does not match the intended
     purpose (extended key usage).
'GNUTLS_CERT_MISSING_OCSP_STATUS'
     The certificate requires the server to send the certificate status,
     but no status was received.
'GNUTLS_CERT_INVALID_OCSP_STATUS'
     The received OCSP status response is invalid.
'GNUTLS_CERT_UNKNOWN_CRIT_EXTENSIONS'
     The certificate has extensions marked as critical which are not
     supported.


Figure 4.2: The 'gnutls_certificate_status_t' enumeration.

An example of certificate verification is shown in *note ex-verify2::.
It is also possible to have a set of certificates that are trusted for a
particular server but not to authorize other certificates.  This purpose
is served by the functions *note gnutls_x509_trust_list_add_named_crt::
and *note gnutls_x509_trust_list_verify_named_crt::.


File: gnutls.info,  Node: Verifying a certificate in the context of TLS session,  Next: Verification using PKCS11,  Prev: Verifying X.509 certificate paths,  Up: X.509 certificates

4.1.1.8 Verifying a certificate in the context of TLS session
.............................................................

When operating in the context of a TLS session, the trusted certificate
authority list may also be set using:
'INT *note gnutls_certificate_set_x509_trust_file:: (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)'
'INT *note gnutls_certificate_set_x509_trust_dir:: (gnutls_certificate_credentials_t CRED, const char * CA_DIR, gnutls_x509_crt_fmt_t TYPE)'
'INT *note gnutls_certificate_set_x509_crl_file:: (gnutls_certificate_credentials_t RES, const char * CRLFILE, gnutls_x509_crt_fmt_t TYPE)'
'INT *note gnutls_certificate_set_x509_system_trust:: (gnutls_certificate_credentials_t CRED)'

These functions allow the specification of the trusted certificate
authorities, either via a file, a directory or use the system-specified
certificate authorities.  Unless the authorities are application
specific, it is generally recommended to use the system trust storage
(see *note gnutls_certificate_set_x509_system_trust::).

Unlike the previous section it is not required to setup a trusted list,
and there are two approaches to verify the peer's certificate and
identity.  The recommended in GnuTLS 3.5.0 and later is via the *note
gnutls_session_set_verify_cert::, but for older GnuTLS versions you may
use an explicit callback set via *note
gnutls_certificate_set_verify_function:: and then utilize *note
gnutls_certificate_verify_peers3:: for verification.  The reported
verification status is identical to the verification functions described
in the previous section.

Note that in certain cases it is required to check the marked purpose of
the end certificate (e.g.  'GNUTLS_KP_TLS_WWW_SERVER'); in these cases
the more advanced *note gnutls_session_set_verify_cert2:: and *note
gnutls_certificate_verify_peers:: should be used instead.

There is also the possibility to pass some input to the verification
functions in the form of flags.  For *note
gnutls_x509_trust_list_verify_crt2:: the flags are passed directly, but
for *note gnutls_certificate_verify_peers3::, the flags are set using
*note gnutls_certificate_set_verify_flags::.  All the available flags
are part of the enumeration 'gnutls_certificate_verify_flags' shown in
*note Figure 4.3: gnutls_certificate_verify_flags.

'GNUTLS_VERIFY_DISABLE_CA_SIGN'
     If set a signer does not have to be a certificate authority.  This
     flag should normally be disabled, unless you know what this means.
'GNUTLS_VERIFY_DO_NOT_ALLOW_IP_MATCHES'
     When verifying a hostname prevent textual IP addresses from
     matching IP addresses in the certificate.  Treat the input only as
     a DNS name.
'GNUTLS_VERIFY_DO_NOT_ALLOW_SAME'
     If a certificate is not signed by anyone trusted but exists in the
     trusted CA list do not treat it as trusted.
'GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT'
     Allow CA certificates that have version 1 (both root and
     intermediate).  This might be dangerous since those haven't the
     basicConstraints extension.
'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2'
     Allow certificates to be signed using the broken MD2 algorithm.
'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5'
     Allow certificates to be signed using the broken MD5 algorithm.
'GNUTLS_VERIFY_DISABLE_TIME_CHECKS'
     Disable checking of activation and expiration validity periods of
     certificate chains.  Don't set this unless you understand the
     security implications.
'GNUTLS_VERIFY_DISABLE_TRUSTED_TIME_CHECKS'
     If set a signer in the trusted list is never checked for expiration
     or activation.
'GNUTLS_VERIFY_DO_NOT_ALLOW_X509_V1_CA_CRT'
     Do not allow trusted CA certificates that have version 1.  This
     option is to be used to deprecate all certificates of version 1.
'GNUTLS_VERIFY_DISABLE_CRL_CHECKS'
     Disable checking for validity using certificate revocation lists or
     the available OCSP data.
'GNUTLS_VERIFY_ALLOW_UNSORTED_CHAIN'
     A certificate chain is tolerated if unsorted (the case with many
     TLS servers out there).  This is the default since GnuTLS 3.1.4.
'GNUTLS_VERIFY_DO_NOT_ALLOW_UNSORTED_CHAIN'
     Do not tolerate an unsorted certificate chain.
'GNUTLS_VERIFY_DO_NOT_ALLOW_WILDCARDS'
     When including a hostname check in the verification, do not
     consider any wildcards.
'GNUTLS_VERIFY_USE_TLS1_RSA'
     This indicates that a (raw) RSA signature is provided as in the TLS
     1.0 protocol.  Not all functions accept this flag.
'GNUTLS_VERIFY_IGNORE_UNKNOWN_CRIT_EXTENSIONS'
     This signals the verification process, not to fail on unknown
     critical extensions.
'GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1'
     Allow certificates to be signed using the broken SHA1 hash
     algorithm.
'GNUTLS_VERIFY_RSA_PSS_FIXED_SALT_LENGTH'
     Disallow RSA-PSS signatures made with mismatching salt length with
     digest length, as mandated in RFC 8446 4.2.3.


Figure 4.3: The 'gnutls_certificate_verify_flags' enumeration.


File: gnutls.info,  Node: Verification using PKCS11,  Prev: Verifying a certificate in the context of TLS session,  Up: X.509 certificates

4.1.1.9 Verifying a certificate using PKCS #11
..............................................

Some systems provide a system wide trusted certificate storage
accessible using the PKCS #11 API. That is, the trusted certificates are
queried and accessed using the PKCS #11 API, and trusted certificate
properties, such as purpose, are marked using attached extensions.  One
example is the p11-kit trust module(1).

These special PKCS #11 modules can be used for GnuTLS certificate
verification if marked as trust policy modules, i.e., with
'trust-policy: yes' in the p11-kit module file.  The way to use them is
by specifying to the file verification function (e.g., *note
gnutls_certificate_set_x509_trust_file::), a pkcs11 URL, or simply
'pkcs11:' to use all the marked with trust policy modules.

The trust modules of p11-kit assign a purpose to trusted authorities
using the extended key usage object identifiers.  The common purposes
are shown in *note Table 4.4: tab:purposes.  Note that typically
according to [*note RFC5280::] the extended key usage object identifiers
apply to end certificates.  Their application to CA certificates is an
extension used by the trust modules.

Purpose        OID            Description
                              
--------------------------------------------------------------------------
GNUTLS_KP_TLS_WWW_SERVER1.3.6.1.5.5.7.3.1The certificate is to be used for TLS WWW
                              authentication.  When in a CA
                              certificate, it indicates that the CA is
                              allowed to sign certificates for TLS WWW
                              authentication.
                              
GNUTLS_KP_TLS_WWW_CLIENT1.3.6.1.5.5.7.3.2The certificate is to be used for TLS WWW
                              client authentication.  When in a CA
                              certificate, it indicates that the CA is
                              allowed to sign certificates for TLS WWW
                              client authentication.
                              
GNUTLS_KP_CODE_SIGNING1.3.6.1.5.5.7.3.3The certificate is to be used for code
                              signing.  When in a CA certificate, it
                              indicates that the CA is allowed to sign
                              certificates for code signing.
                              
GNUTLS_KP_EMAIL_PROTECTION1.3.6.1.5.5.7.3.4The certificate is to be used for email
                              protection.  When in a CA certificate, it
                              indicates that the CA is allowed to sign
                              certificates for email users.
                              
GNUTLS_KP_OCSP_SIGNING1.3.6.1.5.5.7.3.9The certificate is to be used for signing
                              OCSP responses.  When in a CA
                              certificate, it indicates that the CA is
                              allowed to sign certificates which sign
                              OCSP responses.
                              
GNUTLS_KP_ANY  2.5.29.37.0    The certificate is to be used for any
                              purpose.  When in a CA certificate, it
                              indicates that the CA is allowed to sign
                              any kind of certificates.
                              


Table 4.4: Key purpose object identifiers.

With such modules, it is recommended to use the verification functions
*note gnutls_x509_trust_list_verify_crt2::, or *note
gnutls_certificate_verify_peers::, which allow to explicitly specify the
key purpose.  The other verification functions which do not allow
setting a purpose, would operate as if 'GNUTLS_KP_TLS_WWW_SERVER' was
requested from the trusted authorities.

   ---------- Footnotes ----------

   (1) see <https://p11-glue.github.io/p11-glue/trust-module.html>.


File: gnutls.info,  Node: OpenPGP certificates,  Next: Raw public-keys,  Prev: X.509 certificates,  Up: Certificate authentication

4.1.2 OpenPGP certificates
--------------------------

Previous versions of GnuTLS supported limited OpenPGP key
authentication.  That functionality has been deprecated and is no longer
made available.  The reason is that, supporting alternative
authentication methods, when X.509 and PKIX were new on the Internet and
not well established, seemed like a good idea, in today's Internet X.509
is unquestionably the main container for certificates.  As such
supporting more options with no clear use-cases, is a distraction that
consumes considerable resources for improving and testing the library.
For that we have decided to drop this functionality completely in 3.6.0.


File: gnutls.info,  Node: Raw public-keys,  Next: Advanced certificate verification,  Prev: OpenPGP certificates,  Up: Certificate authentication

4.1.3 Raw public-keys
---------------------

There are situations in which a rather large certificate / certificate
chain is undesirable or impractical.  An example could be a resource
constrained sensor network in which you do want to use authentication of
and encryption between your devices but where your devices lack loads of
memory or processing power.  Furthermore, there are situations in which
you don't want to or can't rely on a PKIX. TLS is, next to a PKIX
environment, also commonly used with self-signed certificates in smaller
deployments where the self-signed certificates are distributed to all
involved protocol endpoints out-of-band.  This practice does, however,
still require the overhead of the certificate generation even though
none of the information found in the certificate is actually used.

With raw public-keys, only a subset of the information found in typical
certificates is utilized: namely, the SubjectPublicKeyInfo structure (in
ASN.1 format) of a PKIX certificate that carries the parameters
necessary to describe the public-key.  Other parameters found in PKIX
certificates are omitted.  By omitting various certificate-related
structures, the resulting raw public-key is kept fairly small in
comparison to the original certificate, and the code to process the keys
can be simpler.

It should be noted however, that the authenticity of these raw keys must
be verified by an out-of-band mechanism or something like TOFU.

* Menu:

* Importing raw public-keys::


File: gnutls.info,  Node: Importing raw public-keys,  Up: Raw public-keys

4.1.3.1 Importing raw public-keys
.................................

Raw public-keys and their private counterparts can best be handled by
using the abstract types 'gnutls_pubkey_t' and 'gnutls_privkey_t'
respectively.  To learn how to use these see *note Abstract key types::.


File: gnutls.info,  Node: Advanced certificate verification,  Next: Digital signatures,  Prev: Raw public-keys,  Up: Certificate authentication

4.1.4 Advanced certificate verification
---------------------------------------

The verification of X.509 certificates in the HTTPS and other Internet
protocols is typically done by loading a trusted list of commercial
Certificate Authorities (see *note
gnutls_certificate_set_x509_system_trust::), and using them as trusted
anchors.  However, there are several examples (eg.  the Diginotar
incident) where one of these authorities was compromised.  This risk can
be mitigated by using in addition to CA certificate verification, other
verification methods.  In this section we list the available in GnuTLS
methods.

* Menu:

* Verifying a certificate using trust on first use authentication::
* Verifying a certificate using DANE::


File: gnutls.info,  Node: Verifying a certificate using trust on first use authentication,  Next: Verifying a certificate using DANE,  Up: Advanced certificate verification

4.1.4.1 Verifying a certificate using trust on first use authentication
.......................................................................

It is possible to use a trust on first use (TOFU) authentication method
in GnuTLS. That is the concept used by the SSH programs, where the
public key of the peer is not verified, or verified in an out-of-bound
way, but subsequent connections to the same peer require the public key
to remain the same.  Such a system in combination with the typical CA
verification of a certificate, and OCSP revocation checks, can help to
provide multiple factor verification, where a single point of failure is
not enough to compromise the system.  For example a server compromise
may be detected using OCSP, and a CA compromise can be detected using
the trust on first use method.  Such a hybrid system with X.509 and
trust on first use authentication is shown in *note Client example with
SSH-style certificate verification::.

See *note Certificate verification:: on how to use the available
functionality.


File: gnutls.info,  Node: Verifying a certificate using DANE,  Prev: Verifying a certificate using trust on first use authentication,  Up: Advanced certificate verification

4.1.4.2 Verifying a certificate using DANE (DNSSEC)
...................................................

The DANE protocol is a protocol that can be used to verify TLS
certificates using the DNS (or better DNSSEC) protocols.  The DNS
security extensions (DNSSEC) provide an alternative public key
infrastructure to the commercial CAs that are typically used to sign TLS
certificates.  The DANE protocol takes advantage of the DNSSEC
infrastructure to verify TLS certificates.  This can be in addition to
the verification by CA infrastructure or may even replace it where
DNSSEC is fully deployed.  Note however, that DNSSEC deployment is
fairly new and it would be better to use it as an additional
verification method rather than the only one.

The DANE functionality is provided by the 'libgnutls-dane' library that
is shipped with GnuTLS and the function prototypes are in
'gnutls/dane.h'.  See *note Certificate verification:: for information
on how to use the library.

Note however, that the DANE RFC mandates the verification methods one
should use in addition to the validation via DNSSEC TLSA entries.
GnuTLS doesn't follow that RFC requirement, and the term DANE
verification in this manual refers to the TLSA entry verification.  In
GnuTLS any other verification methods can be used (e.g., PKIX or TOFU)
on top of DANE.


File: gnutls.info,  Node: Digital signatures,  Prev: Advanced certificate verification,  Up: Certificate authentication

4.1.5 Digital signatures
------------------------

In this section we will provide some information about digital
signatures, how they work, and give the rationale for disabling some of
the algorithms used.

Digital signatures work by using somebody's secret key to sign some
arbitrary data.  Then anybody else could use the public key of that
person to verify the signature.  Since the data may be arbitrary it is
not suitable input to a cryptographic digital signature algorithm.  For
this reason and also for performance cryptographic hash algorithms are
used to preprocess the input to the signature algorithm.  This works as
long as it is difficult enough to generate two different messages with
the same hash algorithm output.  In that case the same signature could
be used as a proof for both messages.  Nobody wants to sign an innocent
message of donating 1 euro to Greenpeace and find out that they donated
1.000.000 euros to Bad Inc.

For a hash algorithm to be called cryptographic the following three
requirements must hold:

  1. Preimage resistance.  That means the algorithm must be one way and
     given the output of the hash function H(x), it is impossible to
     calculate x.

  2. 2nd preimage resistance.  That means that given a pair x,y with
     y=H(x) it is impossible to calculate an x' such that y=H(x').

  3. Collision resistance.  That means that it is impossible to
     calculate random x and x' such H(x')=H(x).

The last two requirements in the list are the most important in digital
signatures.  These protect against somebody who would like to generate
two messages with the same hash output.  When an algorithm is considered
broken usually it means that the Collision resistance of the algorithm
is less than brute force.  Using the birthday paradox the brute force
attack takes 2^{((hash size) / 2)} operations.  Today colliding
certificates using the MD5 hash algorithm have been generated as shown
in [*note WEGER::].

There has been cryptographic results for the SHA-1 hash algorithms as
well, although they are not yet critical.  Before 2004, MD5 had a
presumed collision strength of 2^{64}, but it has been showed to have a
collision strength well under 2^{50}.  As of November 2005, it is
believed that SHA-1's collision strength is around 2^{63}.  We consider
this sufficiently hard so that we still support SHA-1.  We anticipate
that SHA-256/386/512 will be used in publicly-distributed certificates
in the future.  When 2^{63} can be considered too weak compared to the
computer power available sometime in the future, SHA-1 will be disabled
as well.  The collision attacks on SHA-1 may also get better, given the
new interest in tools for creating them.

4.1.5.1 Trading security for interoperability
.............................................

If you connect to a server and use GnuTLS' functions to verify the
certificate chain, and get a 'GNUTLS_CERT_INSECURE_ALGORITHM' validation
error (see *note Verifying X.509 certificate paths::), it means that
somewhere in the certificate chain there is a certificate signed using
'RSA-MD2' or 'RSA-MD5'.  These two digital signature algorithms are
considered broken, so GnuTLS fails verifying the certificate.  In some
situations, it may be useful to be able to verify the certificate chain
anyway, assuming an attacker did not utilize the fact that these
signatures algorithms are broken.  This section will give help on how to
achieve that.

It is important to know that you do not have to enable any of the flags
discussed here to be able to use trusted root CA certificates
self-signed using 'RSA-MD2' or 'RSA-MD5'.  The certificates in the
trusted list are considered trusted irrespective of the signature.

If you are using *note gnutls_certificate_verify_peers3:: to verify the
certificate chain, you can call *note
gnutls_certificate_set_verify_flags:: with the flags:
   * 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2'
   * 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5'
   * 'GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1'
   * 'GNUTLS_VERIFY_ALLOW_BROKEN'
as in the following example:

       gnutls_certificate_set_verify_flags (x509cred,
                                            GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5);

This will signal the verifier algorithm to enable 'RSA-MD5' when
verifying the certificates.

If you are using *note gnutls_x509_crt_verify:: or *note
gnutls_x509_crt_list_verify::, you can pass the
'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5' parameter directly in the 'flags'
parameter.

If you are using these flags, it may also be a good idea to warn the
user when verification failure occur for this reason.  The simplest is
to not use the flags by default, and only fall back to using them after
warning the user.  If you wish to inspect the certificate chain
yourself, you can use *note gnutls_certificate_get_peers:: to extract
the raw server's certificate chain, *note gnutls_x509_crt_list_import::
to parse each of the certificates, and then *note
gnutls_x509_crt_get_signature_algorithm:: to find out the signing
algorithm used for each certificate.  If any of the intermediary
certificates are using 'GNUTLS_SIGN_RSA_MD2' or 'GNUTLS_SIGN_RSA_MD5',
you could present a warning.


File: gnutls.info,  Node: More on certificate authentication,  Next: Shared-key and anonymous authentication,  Prev: Certificate authentication,  Up: Authentication methods

4.2 More on certificate authentication
======================================

Certificates are not the only structures involved in a public key
infrastructure.  Several other structures that are used for certificate
requests, encrypted private keys, revocation lists, GnuTLS abstract key
structures, etc., are discussed in this chapter.

* Menu:

* PKCS 10 certificate requests::
* PKIX certificate revocation lists::
* OCSP certificate status checking::
* OCSP stapling::
* Managing encrypted keys::
* certtool Invocation::            Invoking certtool
* ocsptool Invocation::            Invoking ocsptool
* danetool Invocation::            Invoking danetool


File: gnutls.info,  Node: PKCS 10 certificate requests,  Next: PKIX certificate revocation lists,  Up: More on certificate authentication

4.2.1 PKCS #10 certificate requests
-----------------------------------

A certificate request is a structure, which contain information about an
applicant of a certificate service.  It typically contains a public key,
a distinguished name and secondary data such as a challenge password.
GnuTLS supports the requests defined in PKCS #10 [*note RFC2986::].
Other formats of certificate requests are not currently supported by
GnuTLS.

A certificate request can be generated by associating it with a private
key, setting the subject's information and finally self signing it.  The
last step ensures that the requester is in possession of the private
key.

'INT *note gnutls_x509_crq_set_version:: (gnutls_x509_crq_t CRQ, unsigned int VERSION)'
'INT *note gnutls_x509_crq_set_dn:: (gnutls_x509_crq_t CRQ, const char * DN, const char ** ERR)'
'INT *note gnutls_x509_crq_set_dn_by_oid:: (gnutls_x509_crq_t CRQ, const char * OID, unsigned int RAW_FLAG, const void * DATA, unsigned int SIZEOF_DATA)'
'INT *note gnutls_x509_crq_set_key_usage:: (gnutls_x509_crq_t CRQ, unsigned int USAGE)'
'INT *note gnutls_x509_crq_set_key_purpose_oid:: (gnutls_x509_crq_t CRQ, const void * OID, unsigned int CRITICAL)'
'INT *note gnutls_x509_crq_set_basic_constraints:: (gnutls_x509_crq_t CRQ, unsigned int CA, int PATHLENCONSTRAINT)'

The *note gnutls_x509_crq_set_key:: and *note gnutls_x509_crq_sign2::
functions associate the request with a private key and sign it.  If a
request is to be signed with a key residing in a PKCS #11 token it is
recommended to use the signing functions shown in *note Abstract key
types::.

 -- Function: int gnutls_x509_crq_set_key (gnutls_x509_crq_t CRQ,
          gnutls_x509_privkey_t KEY)
     CRQ: should contain a 'gnutls_x509_crq_t' type

     KEY: holds a private key

     This function will set the public parameters from the given private
     key to the request.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

 -- Function: int gnutls_x509_crq_sign2 (gnutls_x509_crq_t CRQ,
          gnutls_x509_privkey_t KEY, gnutls_digest_algorithm_t DIG,
          unsigned int FLAGS)
     CRQ: should contain a 'gnutls_x509_crq_t' type

     KEY: holds a private key

     DIG: The message digest to use, i.e., 'GNUTLS_DIG_SHA256'

     FLAGS: must be 0

     This function will sign the certificate request with a private key.
     This must be the same key as the one used in
     'gnutls_x509_crt_set_key()' since a certificate request is self
     signed.

     This must be the last step in a certificate request generation
     since all the previously set parameters are now signed.

     A known limitation of this function is, that a newly-signed request
     will not be fully functional (e.g., for signature verification),
     until it is exported an re-imported.

     After GnuTLS 3.6.1 the value of 'dig' may be 'GNUTLS_DIG_UNKNOWN' ,
     and in that case, a suitable but reasonable for the key algorithm
     will be selected.

     *Returns:* 'GNUTLS_E_SUCCESS' on success, otherwise a negative
     error code.  'GNUTLS_E_ASN1_VALUE_NOT_FOUND' is returned if you
     didn't set all information in the certificate request (e.g., the
     version using 'gnutls_x509_crq_set_version()' ).

The following example is about generating a certificate request, and a
private key.  A certificate request can be later be processed by a CA
which should return a signed certificate.

/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/abstract.h>
#include <time.h>

/* This example will generate a private key and a certificate
 * request.
 */

int main(void)
{
        gnutls_x509_crq_t crq;
        gnutls_x509_privkey_t key;
        unsigned char buffer[10 * 1024];
        size_t buffer_size = sizeof(buffer);
        unsigned int bits;

        gnutls_global_init();

        /* Initialize an empty certificate request, and
         * an empty private key.
         */
        gnutls_x509_crq_init(&crq);

        gnutls_x509_privkey_init(&key);

        /* Generate an RSA key of moderate security.
         */
        bits =
            gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA,
                                        GNUTLS_SEC_PARAM_MEDIUM);
        gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, bits, 0);

        /* Add stuff to the distinguished name
         */
        gnutls_x509_crq_set_dn_by_oid(crq, GNUTLS_OID_X520_COUNTRY_NAME,
                                      0, "GR", 2);

        gnutls_x509_crq_set_dn_by_oid(crq, GNUTLS_OID_X520_COMMON_NAME,
                                      0, "Nikos", strlen("Nikos"));

        /* Set the request version.
         */
        gnutls_x509_crq_set_version(crq, 1);

        /* Set a challenge password.
         */
        gnutls_x509_crq_set_challenge_password(crq,
                                               "something to remember here");

        /* Associate the request with the private key
         */
        gnutls_x509_crq_set_key(crq, key);

        /* Self sign the certificate request.
         */
        gnutls_x509_crq_sign2(crq, key, GNUTLS_DIG_SHA1, 0);

        /* Export the PEM encoded certificate request, and
         * display it.
         */
        gnutls_x509_crq_export(crq, GNUTLS_X509_FMT_PEM, buffer,
                               &buffer_size);

        printf("Certificate Request: \n%s", buffer);


        /* Export the PEM encoded private key, and
         * display it.
         */
        buffer_size = sizeof(buffer);
        gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, buffer,
                                   &buffer_size);

        printf("\n\nPrivate key: \n%s", buffer);

        gnutls_x509_crq_deinit(crq);
        gnutls_x509_privkey_deinit(key);

        return 0;

}


File: gnutls.info,  Node: PKIX certificate revocation lists,  Next: OCSP certificate status checking,  Prev: PKCS 10 certificate requests,  Up: More on certificate authentication

4.2.2 PKIX certificate revocation lists
---------------------------------------

A certificate revocation list (CRL) is a structure issued by an
authority periodically containing a list of revoked certificates serial
numbers.  The CRL structure is signed with the issuing authorities'
keys.  A typical CRL contains the fields as shown in *note Table 4.5:
tab:crl.  Certificate revocation lists are used to complement the
expiration date of a certificate, in order to account for other reasons
of revocation, such as compromised keys, etc.

Each CRL is valid for limited amount of time and is required to provide,
except for the current issuing time, also the issuing time of the next
update.

Field          Description
               
------------------------------------------------------------------
version        The field that indicates the version of the CRL
               structure.
               
signature      A signature by the issuing authority.
               
issuer         Holds the issuer's distinguished name.
               
thisUpdate     The issuing time of the revocation list.
               
nextUpdate     The issuing time of the revocation list that
               will update that one.
               
revokedCertificatesList of revoked certificates serial numbers.
               
extensions     Optional CRL structure extensions.
               


Table 4.5: Certificate revocation list fields.

The basic CRL structure functions follow.

'INT *note gnutls_x509_crl_init:: (gnutls_x509_crl_t * CRL)'
'INT *note gnutls_x509_crl_import:: (gnutls_x509_crl_t CRL, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
'INT *note gnutls_x509_crl_export:: (gnutls_x509_crl_t CRL, gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'
'INT *note gnutls_x509_crl_export:: (gnutls_x509_crl_t CRL, gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'

Reading a CRL
.............

The most important function that extracts the certificate revocation
information from a CRL is *note gnutls_x509_crl_get_crt_serial::.  Other
functions that return other fields of the CRL structure are also
provided.

 -- Function: int gnutls_x509_crl_get_crt_serial (gnutls_x509_crl_t CRL,
          unsigned INDX, unsigned char * SERIAL, size_t * SERIAL_SIZE,
          time_t * T)
     CRL: should contain a 'gnutls_x509_crl_t' type

     INDX: the index of the certificate to extract (starting from 0)

     SERIAL: where the serial number will be copied

     SERIAL_SIZE: initially holds the size of serial

     T: if non null, will hold the time this certificate was revoked

     This function will retrieve the serial number of the specified, by
     the index, revoked certificate.

     Note that this function will have performance issues in large
     sequences of revoked certificates.  In that case use
     'gnutls_x509_crl_iter_crt_serial()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

'INT *note gnutls_x509_crl_get_version:: (gnutls_x509_crl_t CRL)'
'INT *note gnutls_x509_crl_get_issuer_dn:: (gnutls_x509_crl_t CRL, char * BUF, size_t * SIZEOF_BUF)'
'INT *note gnutls_x509_crl_get_issuer_dn2:: (gnutls_x509_crl_t CRL, gnutls_datum_t * DN)'
'TIME_T *note gnutls_x509_crl_get_this_update:: (gnutls_x509_crl_t CRL)'
'TIME_T *note gnutls_x509_crl_get_next_update:: (gnutls_x509_crl_t CRL)'
'INT *note gnutls_x509_crl_get_crt_count:: (gnutls_x509_crl_t CRL)'

Generation of a CRL
...................

The following functions can be used to generate a CRL.

'INT *note gnutls_x509_crl_set_version:: (gnutls_x509_crl_t CRL, unsigned int VERSION)'
'INT *note gnutls_x509_crl_set_crt_serial:: (gnutls_x509_crl_t CRL, const void * SERIAL, size_t SERIAL_SIZE, time_t REVOCATION_TIME)'
'INT *note gnutls_x509_crl_set_crt:: (gnutls_x509_crl_t CRL, gnutls_x509_crt_t CRT, time_t REVOCATION_TIME)'
'INT *note gnutls_x509_crl_set_next_update:: (gnutls_x509_crl_t CRL, time_t EXP_TIME)'
'INT *note gnutls_x509_crl_set_this_update:: (gnutls_x509_crl_t CRL, time_t ACT_TIME)'

The *note gnutls_x509_crl_sign2:: and *note
gnutls_x509_crl_privkey_sign:: functions sign the revocation list with a
private key.  The latter function can be used to sign with a key
residing in a PKCS #11 token.

 -- Function: int gnutls_x509_crl_sign2 (gnutls_x509_crl_t CRL,
          gnutls_x509_crt_t ISSUER, gnutls_x509_privkey_t ISSUER_KEY,
          gnutls_digest_algorithm_t DIG, unsigned int FLAGS)
     CRL: should contain a gnutls_x509_crl_t type

     ISSUER: is the certificate of the certificate issuer

     ISSUER_KEY: holds the issuer's private key

     DIG: The message digest to use.  GNUTLS_DIG_SHA256 is the safe
     choice unless you know what you're doing.

     FLAGS: must be 0

     This function will sign the CRL with the issuer's private key, and
     will copy the issuer's information into the CRL.

     This must be the last step in a certificate CRL since all the
     previously set parameters are now signed.

     A known limitation of this function is, that a newly-signed CRL
     will not be fully functional (e.g., for signature verification),
     until it is exported an re-imported.

     After GnuTLS 3.6.1 the value of 'dig' may be 'GNUTLS_DIG_UNKNOWN' ,
     and in that case, a suitable but reasonable for the key algorithm
     will be selected.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

 -- Function: int gnutls_x509_crl_privkey_sign (gnutls_x509_crl_t CRL,
          gnutls_x509_crt_t ISSUER, gnutls_privkey_t ISSUER_KEY,
          gnutls_digest_algorithm_t DIG, unsigned int FLAGS)
     CRL: should contain a gnutls_x509_crl_t type

     ISSUER: is the certificate of the certificate issuer

     ISSUER_KEY: holds the issuer's private key

     DIG: The message digest to use.  GNUTLS_DIG_SHA256 is the safe
     choice unless you know what you're doing.

     FLAGS: must be 0

     This function will sign the CRL with the issuer's private key, and
     will copy the issuer's information into the CRL.

     This must be the last step in a certificate CRL since all the
     previously set parameters are now signed.

     A known limitation of this function is, that a newly-signed CRL
     will not be fully functional (e.g., for signature verification),
     until it is exported an re-imported.

     After GnuTLS 3.6.1 the value of 'dig' may be 'GNUTLS_DIG_UNKNOWN' ,
     and in that case, a suitable but reasonable for the key algorithm
     will be selected.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     Since 2.12.0

Few extensions on the CRL structure are supported, including the CRL
number extension and the authority key identifier.

'INT *note gnutls_x509_crl_set_number:: (gnutls_x509_crl_t CRL, const void * NR, size_t NR_SIZE)'
'INT *note gnutls_x509_crl_set_authority_key_id:: (gnutls_x509_crl_t CRL, const void * ID, size_t ID_SIZE)'


File: gnutls.info,  Node: OCSP certificate status checking,  Next: OCSP stapling,  Prev: PKIX certificate revocation lists,  Up: More on certificate authentication

4.2.3 OCSP certificate status checking
--------------------------------------

Certificates may be revoked before their expiration time has been
reached.  There are several reasons for revoking certificates, but a
typical situation is when the private key associated with a certificate
has been compromised.  Traditionally, Certificate Revocation Lists
(CRLs) have been used by application to implement revocation checking,
however, several problems with CRLs have been identified [*note
RIVESTCRL::].

The Online Certificate Status Protocol, or OCSP [*note RFC2560::], is a
widely implemented protocol which performs certificate revocation status
checking.  An application that wish to verify the identity of a peer
will verify the certificate against a set of trusted certificates and
then check whether the certificate is listed in a CRL and/or perform an
OCSP check for the certificate.

Applications are typically expected to contact the OCSP server in order
to request the certificate validity status.  The OCSP server replies
with an OCSP response.  This section describes this online communication
(which can be avoided when using OCSP stapled responses, for that, see
*note OCSP stapling::).

Before performing the OCSP query, the application will need to figure
out the address of the OCSP server.  The OCSP server address can be
provided by the local user in manual configuration or may be stored in
the certificate that is being checked.  When stored in a certificate the
OCSP server is in the extension field called the Authority Information
Access (AIA). The following function extracts this information from a
certificate.

'INT *note gnutls_x509_crt_get_authority_info_access:: (gnutls_x509_crt_t CRT, unsigned int SEQ, int WHAT, gnutls_datum_t * DATA, unsigned int * CRITICAL)'

There are several functions in GnuTLS for creating and manipulating OCSP
requests and responses.  The general idea is that a client application
creates an OCSP request object, stores some information about the
certificate to check in the request, and then exports the request in DER
format.  The request will then need to be sent to the OCSP responder,
which needs to be done by the application (GnuTLS does not send and
receive OCSP packets).  Normally an OCSP response is received that the
application will need to import into an OCSP response object.  The
digital signature in the OCSP response needs to be verified against a
set of trust anchors before the information in the response can be
trusted.

The ASN.1 structure of OCSP requests are briefly as follows.  It is
useful to review the structures to get an understanding of which fields
are modified by GnuTLS functions.

     OCSPRequest     ::=     SEQUENCE {
         tbsRequest                  TBSRequest,
         optionalSignature   [0]     EXPLICIT Signature OPTIONAL }

     TBSRequest      ::=     SEQUENCE {
         version             [0]     EXPLICIT Version DEFAULT v1,
         requestorName       [1]     EXPLICIT GeneralName OPTIONAL,
         requestList                 SEQUENCE OF Request,
         requestExtensions   [2]     EXPLICIT Extensions OPTIONAL }

     Request         ::=     SEQUENCE {
         reqCert                     CertID,
         singleRequestExtensions     [0] EXPLICIT Extensions OPTIONAL }

     CertID          ::=     SEQUENCE {
         hashAlgorithm       AlgorithmIdentifier,
         issuerNameHash      OCTET STRING, -- Hash of Issuer's DN
         issuerKeyHash       OCTET STRING, -- Hash of Issuers public key
         serialNumber        CertificateSerialNumber }

The basic functions to initialize, import, export and deallocate OCSP
requests are the following.

'INT *note gnutls_ocsp_req_init:: (gnutls_ocsp_req_t * REQ)'
'VOID *note gnutls_ocsp_req_deinit:: (gnutls_ocsp_req_t REQ)'
'INT *note gnutls_ocsp_req_import:: (gnutls_ocsp_req_t REQ, const gnutls_datum_t * DATA)'
'INT *note gnutls_ocsp_req_export:: (gnutls_ocsp_req_const_t REQ, gnutls_datum_t * DATA)'
'INT *note gnutls_ocsp_req_print:: (gnutls_ocsp_req_const_t REQ, gnutls_ocsp_print_formats_t FORMAT, gnutls_datum_t * OUT)'

To generate an OCSP request the issuer name hash, issuer key hash, and
the checked certificate's serial number are required.  There are two
interfaces available for setting those in an OCSP request.  The is a
low-level function when you have the issuer name hash, issuer key hash,
and certificate serial number in binary form.  The second is more useful
if you have the certificate (and its issuer) in a 'gnutls_x509_crt_t'
type.  There is also a function to extract this information from
existing an OCSP request.

'INT *note gnutls_ocsp_req_add_cert_id:: (gnutls_ocsp_req_t REQ, gnutls_digest_algorithm_t DIGEST, const gnutls_datum_t * ISSUER_NAME_HASH, const gnutls_datum_t * ISSUER_KEY_HASH, const gnutls_datum_t * SERIAL_NUMBER)'
'INT *note gnutls_ocsp_req_add_cert:: (gnutls_ocsp_req_t REQ, gnutls_digest_algorithm_t DIGEST, gnutls_x509_crt_t ISSUER, gnutls_x509_crt_t CERT)'
'INT *note gnutls_ocsp_req_get_cert_id:: (gnutls_ocsp_req_const_t REQ, unsigned INDX, gnutls_digest_algorithm_t * DIGEST, gnutls_datum_t * ISSUER_NAME_HASH, gnutls_datum_t * ISSUER_KEY_HASH, gnutls_datum_t * SERIAL_NUMBER)'

Each OCSP request may contain a number of extensions.  Extensions are
identified by an Object Identifier (OID) and an opaque data buffer whose
syntax and semantics is implied by the OID. You can extract or set those
extensions using the following functions.

'INT *note gnutls_ocsp_req_get_extension:: (gnutls_ocsp_req_const_t REQ, unsigned INDX, gnutls_datum_t * OID, unsigned int * CRITICAL, gnutls_datum_t * DATA)'
'INT *note gnutls_ocsp_req_set_extension:: (gnutls_ocsp_req_t REQ, const char * OID, unsigned int CRITICAL, const gnutls_datum_t * DATA)'

A common OCSP Request extension is the nonce extension (OID
1.3.6.1.5.5.7.48.1.2), which is used to avoid replay attacks of earlier
recorded OCSP responses.  The nonce extension carries a value that is
intended to be sufficiently random and unique so that an attacker will
not be able to give a stale response for the same nonce.

'INT *note gnutls_ocsp_req_get_nonce:: (gnutls_ocsp_req_const_t REQ, unsigned int * CRITICAL, gnutls_datum_t * NONCE)'
'INT *note gnutls_ocsp_req_set_nonce:: (gnutls_ocsp_req_t REQ, unsigned int CRITICAL, const gnutls_datum_t * NONCE)'
'INT *note gnutls_ocsp_req_randomize_nonce:: (gnutls_ocsp_req_t REQ)'

The OCSP response structures is a complex structure.  A simplified
overview of it is in *note Table 4.6: tab:ocsp-response.  Note that a
response may contain information on multiple certificates.

Field          Description
               
------------------------------------------------------------------
version        The OCSP response version number (typically 1).
               
responder ID   An identifier of the responder (DN name or a
               hash of its key).
               
issue time     The time the response was generated.
               
thisUpdate     The issuing time of the revocation information.
               
nextUpdate     The issuing time of the revocation information
               that will update that one.
               
               Revoked certificates
               
certificate    The status of the certificate.
status         
certificate    The certificate's serial number.
serial         
revocationTime The time the certificate was revoked.
               
revocationReasonThe reason the certificate was revoked.
               


Table 4.6: The most important OCSP response fields.

We provide basic functions for initialization, importing, exporting and
deallocating OCSP responses.

'INT *note gnutls_ocsp_resp_init:: (gnutls_ocsp_resp_t * RESP)'
'VOID *note gnutls_ocsp_resp_deinit:: (gnutls_ocsp_resp_t RESP)'
'INT *note gnutls_ocsp_resp_import:: (gnutls_ocsp_resp_t RESP, const gnutls_datum_t * DATA)'
'INT *note gnutls_ocsp_resp_export:: (gnutls_ocsp_resp_const_t RESP, gnutls_datum_t * DATA)'
'INT *note gnutls_ocsp_resp_print:: (gnutls_ocsp_resp_const_t RESP, gnutls_ocsp_print_formats_t FORMAT, gnutls_datum_t * OUT)'

The utility function that extracts the revocation as well as other
information from a response is shown below.

 -- Function: int gnutls_ocsp_resp_get_single (gnutls_ocsp_resp_const_t
          RESP, unsigned INDX, gnutls_digest_algorithm_t * DIGEST,
          gnutls_datum_t * ISSUER_NAME_HASH, gnutls_datum_t *
          ISSUER_KEY_HASH, gnutls_datum_t * SERIAL_NUMBER, unsigned int
          * CERT_STATUS, time_t * THIS_UPDATE, time_t * NEXT_UPDATE,
          time_t * REVOCATION_TIME, unsigned int * REVOCATION_REASON)
     RESP: should contain a 'gnutls_ocsp_resp_t' type

     INDX: Specifies response number to get.  Use (0) to get the first
     one.

     DIGEST: output variable with 'gnutls_digest_algorithm_t' hash
     algorithm

     ISSUER_NAME_HASH: output buffer with hash of issuer's DN

     ISSUER_KEY_HASH: output buffer with hash of issuer's public key

     SERIAL_NUMBER: output buffer with serial number of certificate to
     check

     CERT_STATUS: a certificate status, a 'gnutls_ocsp_cert_status_t'
     enum.

     THIS_UPDATE: time at which the status is known to be correct.

     NEXT_UPDATE: when newer information will be available, or
     (time_t)-1 if unspecified

     REVOCATION_TIME: when 'cert_status' is 'GNUTLS_OCSP_CERT_REVOKED' ,
     holds time of revocation.

     REVOCATION_REASON: revocation reason, a 'gnutls_x509_crl_reason_t'
     enum.

     This function will return the certificate information of the 'indx'
     'ed response in the Basic OCSP Response 'resp' .  The information
     returned corresponds to the OCSP SingleResponse structure except
     the final singleExtensions.

     Each of the pointers to output variables may be NULL to indicate
     that the caller is not interested in that value.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error code is returned.  If you have reached
     the last CertID available 'GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE'
     will be returned.

The possible revocation reasons available in an OCSP response are shown
below.

'GNUTLS_X509_CRLREASON_UNSPECIFIED'
     Unspecified reason.
'GNUTLS_X509_CRLREASON_KEYCOMPROMISE'
     Private key compromised.
'GNUTLS_X509_CRLREASON_CACOMPROMISE'
     CA compromised.
'GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED'
     Affiliation has changed.
'GNUTLS_X509_CRLREASON_SUPERSEDED'
     Certificate superseded.
'GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION'
     Operation has ceased.
'GNUTLS_X509_CRLREASON_CERTIFICATEHOLD'
     Certificate is on hold.
'GNUTLS_X509_CRLREASON_REMOVEFROMCRL'
     Will be removed from delta CRL.
'GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN'
     Privilege withdrawn.
'GNUTLS_X509_CRLREASON_AACOMPROMISE'
     AA compromised.


Figure 4.4: The revocation reasons

Note, that the OCSP response needs to be verified against some set of
trust anchors before it can be relied upon.  It is also important to
check whether the received OCSP response corresponds to the certificate
being checked.

'INT *note gnutls_ocsp_resp_verify:: (gnutls_ocsp_resp_const_t RESP, gnutls_x509_trust_list_t TRUSTLIST, unsigned int * VERIFY, unsigned int FLAGS)'
'INT *note gnutls_ocsp_resp_verify_direct:: (gnutls_ocsp_resp_const_t RESP, gnutls_x509_crt_t ISSUER, unsigned int * VERIFY, unsigned int FLAGS)'
'INT *note gnutls_ocsp_resp_check_crt:: (gnutls_ocsp_resp_const_t RESP, unsigned int INDX, gnutls_x509_crt_t CRT)'


File: gnutls.info,  Node: OCSP stapling,  Next: Managing encrypted keys,  Prev: OCSP certificate status checking,  Up: More on certificate authentication

4.2.4 OCSP stapling
-------------------

To avoid applications contacting the OCSP server directly, TLS servers
can provide a "stapled" OCSP response in the TLS handshake.  That way
the client application needs to do nothing more.  GnuTLS will
automatically consider the stapled OCSP response during the TLS
certificate verification (see *note gnutls_certificate_verify_peers2::).
To disable the automatic OCSP verification the flag
'GNUTLS_VERIFY_DISABLE_CRL_CHECKS' should be specified to *note
gnutls_certificate_set_verify_flags::.

Since GnuTLS 3.5.1 the client certificate verification will consider the
[*note RFC7633::] OCSP-Must-staple certificate extension, and will
consider it while checking for stapled OCSP responses.  If the extension
is present and no OCSP staple is found, the certificate verification
will fail and the status code 'GNUTLS_CERT_MISSING_OCSP_STATUS' will
returned from the verification function.

Under TLS 1.2 only one stapled response can be sent by a server, the
OCSP response associated with the end-certificate.  Under TLS 1.3 a
server can send multiple OCSP responses, typically one for each
certificate in the certificate chain.  The following functions can be
used by a client application to retrieve the OCSP responses as sent by
the server.

'INT *note gnutls_ocsp_status_request_get:: (gnutls_session_t SESSION, gnutls_datum_t * RESPONSE)'
'INT *note gnutls_ocsp_status_request_get2:: (gnutls_session_t SESSION, unsigned IDX, gnutls_datum_t * RESPONSE)'

GnuTLS servers can provide OCSP responses to their clients using the
following functions.

'VOID *note gnutls_certificate_set_retrieve_function3:: (gnutls_certificate_credentials_t CRED, gnutls_certificate_retrieve_function3 * FUNC)'
'INT *note gnutls_certificate_set_ocsp_status_request_file2:: (gnutls_certificate_credentials_t SC, const char * RESPONSE_FILE, unsigned IDX, gnutls_x509_crt_fmt_t FMT)'
'UNSIGNED *note gnutls_ocsp_status_request_is_checked:: (gnutls_session_t SESSION, unsigned int FLAGS)'

A server is expected to provide the relevant certificate's OCSP
responses using *note
gnutls_certificate_set_ocsp_status_request_file2::, and ensure a
periodic reload/renew of the credentials.  An estimation of the OCSP
responses expiration can be obtained using the *note
gnutls_certificate_get_ocsp_expiration:: function.

 -- Function: time_t gnutls_certificate_get_ocsp_expiration
          (gnutls_certificate_credentials_t SC, unsigned IDX, int OIDX,
          unsigned FLAGS)
     SC: is a credentials structure.

     IDX: is a certificate chain index as returned by
     'gnutls_certificate_set_key()' and friends

     OIDX: is an OCSP response index

     FLAGS: should be zero

     This function returns the validity of the loaded OCSP responses, to
     provide information on when to reload/refresh them.

     Note that the credentials structure should be read-only when in
     use, thus when reloading, either the credentials structure must not
     be in use by any sessions, or a new credentials structure should be
     allocated for new sessions.

     When 'oidx' is (-1) then the minimum refresh time for all responses
     is returned.  Otherwise the index specifies the response
     corresponding to the 'odix' certificate in the certificate chain.

     *Returns:* On success, the expiration time of the OCSP response.
     Otherwise (time_t)(-1) on error, or (time_t)-2 on out of bounds.

     *Since:* 3.6.3

Prior to GnuTLS 3.6.4, the functions *note
gnutls_certificate_set_ocsp_status_request_function2:: *note
gnutls_certificate_set_ocsp_status_request_file:: were provided to set
OCSP responses.  These functions are still functional, but cannot be
used to set multiple OCSP responses as allowed by TLS1.3.

The responses can be updated periodically using the 'ocsptool' command
(see also *note ocsptool Invocation::).

     ocsptool --ask --load-cert server_cert.pem --load-issuer the_issuer.pem
              --load-signer the_issuer.pem --outfile ocsp.resp

In order to allow multiple OCSP responses to be concatenated, GnuTLS
supports PEM-encoded OCSP responses.  These can be generated using
'ocsptool' with the '-no-outder' parameter.


File: gnutls.info,  Node: Managing encrypted keys,  Next: certtool Invocation,  Prev: OCSP stapling,  Up: More on certificate authentication

4.2.5 Managing encrypted keys
-----------------------------

Transferring or storing private keys in plain may not be a good idea,
since any compromise is irreparable.  Storing the keys in hardware
security modules (see *note Smart cards and HSMs::) could solve the
storage problem but it is not always practical or efficient enough.
This section describes ways to store and transfer encrypted private
keys.

There are methods for key encryption, namely the PKCS #8, PKCS #12 and
OpenSSL's custom encrypted private key formats.  The PKCS #8 and the
OpenSSL's method allow encryption of the private key, while the PKCS #12
method allows, in addition, the bundling of accompanying data into the
structure.  That is typically the corresponding certificate, as well as
a trusted CA certificate.

High level functionality
........................

Generic and higher level private key import functions are available,
that import plain or encrypted keys and will auto-detect the encrypted
key format.

 -- Function: int gnutls_privkey_import_x509_raw (gnutls_privkey_t PKEY,
          const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT,
          const char * PASSWORD, unsigned int FLAGS)
     PKEY: The private key

     DATA: The private key data to be imported

     FORMAT: The format of the private key

     PASSWORD: A password (optional)

     FLAGS: an ORed sequence of gnutls_pkcs_encrypt_flags_t

     This function will import the given private key to the abstract
     'gnutls_privkey_t' type.

     The supported formats are basic unencrypted key, PKCS8, PKCS12,
     TSS2, and the openssl format.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.1.0

 -- Function: int gnutls_x509_privkey_import2 (gnutls_x509_privkey_t
          KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t
          FORMAT, const char * PASSWORD, unsigned int FLAGS)
     KEY: The data to store the parsed key

     DATA: The DER or PEM encoded key.

     FORMAT: One of DER or PEM

     PASSWORD: A password (optional)

     FLAGS: an ORed sequence of gnutls_pkcs_encrypt_flags_t

     This function will import the given DER or PEM encoded key, to the
     native 'gnutls_x509_privkey_t' format, irrespective of the input
     format.  The input format is auto-detected.

     The supported formats are basic unencrypted key, PKCS8, PKCS12, and
     the openssl format.

     If the provided key is encrypted but no password was given, then
     'GNUTLS_E_DECRYPTION_FAILED' is returned.  Since GnuTLS 3.4.0 this
     function will utilize the PIN callbacks if any.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

Any keys imported using those functions can be imported to a certificate
credentials structure using *note gnutls_certificate_set_key::, or
alternatively they can be directly imported using *note
gnutls_certificate_set_x509_key_file2::.

PKCS #8 structures
..................

PKCS #8 keys can be imported and exported as normal private keys using
the functions below.  An addition to the normal import functions, are a
password and a flags argument.  The flags can be any element of the
'gnutls_pkcs_encrypt_flags_t' enumeration.  Note however, that GnuTLS
only supports the PKCS #5 PBES2 encryption scheme.  Keys encrypted with
the obsolete PBES1 scheme cannot be decrypted.

'INT *note gnutls_x509_privkey_import_pkcs8:: (gnutls_x509_privkey_t KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, const char * PASSWORD, unsigned int FLAGS)'
'INT *note gnutls_x509_privkey_export_pkcs8:: (gnutls_x509_privkey_t KEY, gnutls_x509_crt_fmt_t FORMAT, const char * PASSWORD, unsigned int FLAGS, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'
'INT *note gnutls_x509_privkey_export2_pkcs8:: (gnutls_x509_privkey_t KEY, gnutls_x509_crt_fmt_t FORMAT, const char * PASSWORD, unsigned int FLAGS, gnutls_datum_t * OUT)'

'GNUTLS_PKCS_PLAIN'
     Unencrypted private key.
'GNUTLS_PKCS_PKCS12_3DES'
     PKCS-12 3DES.
'GNUTLS_PKCS_PKCS12_ARCFOUR'
     PKCS-12 ARCFOUR.
'GNUTLS_PKCS_PKCS12_RC2_40'
     PKCS-12 RC2-40.
'GNUTLS_PKCS_PBES2_3DES'
     PBES2 3DES.
'GNUTLS_PKCS_PBES2_AES_128'
     PBES2 AES-128.
'GNUTLS_PKCS_PBES2_AES_192'
     PBES2 AES-192.
'GNUTLS_PKCS_PBES2_AES_256'
     PBES2 AES-256.
'GNUTLS_PKCS_NULL_PASSWORD'
     Some schemas distinguish between an empty and a NULL password.
'GNUTLS_PKCS_PBES2_DES'
     PBES2 single DES.
'GNUTLS_PKCS_PBES1_DES_MD5'
     PBES1 with single DES; for compatibility with openssl only.
'GNUTLS_PKCS_PBES2_GOST_TC26Z'
     PBES2 GOST 28147-89 CFB with TC26-Z S-box.
'GNUTLS_PKCS_PBES2_GOST_CPA'
     PBES2 GOST 28147-89 CFB with CryptoPro-A S-box.
'GNUTLS_PKCS_PBES2_GOST_CPB'
     PBES2 GOST 28147-89 CFB with CryptoPro-B S-box.
'GNUTLS_PKCS_PBES2_GOST_CPC'
     PBES2 GOST 28147-89 CFB with CryptoPro-C S-box.
'GNUTLS_PKCS_PBES2_GOST_CPD'
     PBES2 GOST 28147-89 CFB with CryptoPro-D S-box.


Figure 4.5: Encryption flags

PKCS #12 structures
...................

A PKCS #12 structure [*note PKCS12::] usually contains a user's private
keys and certificates.  It is commonly used in browsers to export and
import the user's identities.  A file containing such a key can be
directly imported to a certificate credentials structure by using *note
gnutls_certificate_set_x509_simple_pkcs12_file::.

In GnuTLS the PKCS #12 structures are handled using the
'gnutls_pkcs12_t' type.  This is an abstract type that may hold several
'gnutls_pkcs12_bag_t' types.  The bag types are the holders of the
actual data, which may be certificates, private keys or encrypted data.
A bag of type encrypted should be decrypted in order for its data to be
accessed.

To reduce the complexity in parsing the structures the simple helper
function *note gnutls_pkcs12_simple_parse:: is provided.  For more
advanced uses, manual parsing of the structure is required using the
functions below.

'INT *note gnutls_pkcs12_get_bag:: (gnutls_pkcs12_t PKCS12, int INDX, gnutls_pkcs12_bag_t BAG)'
'INT *note gnutls_pkcs12_verify_mac:: (gnutls_pkcs12_t PKCS12, const char * PASS)'
'INT *note gnutls_pkcs12_bag_decrypt:: (gnutls_pkcs12_bag_t BAG, const char * PASS)'
'INT *note gnutls_pkcs12_bag_get_count:: (gnutls_pkcs12_bag_t BAG)'

 -- Function: int gnutls_pkcs12_simple_parse (gnutls_pkcs12_t P12, const
          char * PASSWORD, gnutls_x509_privkey_t * KEY,
          gnutls_x509_crt_t ** CHAIN, unsigned int * CHAIN_LEN,
          gnutls_x509_crt_t ** EXTRA_CERTS, unsigned int *
          EXTRA_CERTS_LEN, gnutls_x509_crl_t * CRL, unsigned int FLAGS)
     P12: A pkcs12 type

     PASSWORD: optional password used to decrypt the structure, bags and
     keys.

     KEY: a structure to store the parsed private key.

     CHAIN: the corresponding to key certificate chain (may be 'NULL' )

     CHAIN_LEN: will be updated with the number of additional (may be
     'NULL' )

     EXTRA_CERTS: optional pointer to receive an array of additional
     certificates found in the PKCS12 structure (may be 'NULL' ).

     EXTRA_CERTS_LEN: will be updated with the number of additional
     certs (may be 'NULL' ).

     CRL: an optional structure to store the parsed CRL (may be 'NULL'
     ).

     FLAGS: should be zero or one of GNUTLS_PKCS12_SP_*

     This function parses a PKCS12 structure in 'pkcs12' and extracts
     the private key, the corresponding certificate chain, any
     additional certificates and a CRL. The structures in 'key' ,
     'chain' 'crl' , and 'extra_certs' must not be initialized.

     The 'extra_certs' and 'extra_certs_len' parameters are optional and
     both may be set to 'NULL' .  If either is non-'NULL' , then both
     must be set.  The value for 'extra_certs' is allocated using
     'gnutls_malloc()' .

     Encrypted PKCS12 bags and PKCS8 private keys are supported, but
     only with password based security and the same password for all
     operations.

     Note that a PKCS12 structure may contain many keys and/or
     certificates, and there is no way to identify which key/certificate
     pair you want.  For this reason this function is useful for PKCS12
     files that contain only one key/certificate pair and/or one CRL.

     If the provided structure has encrypted fields but no password is
     provided then this function returns 'GNUTLS_E_DECRYPTION_FAILED' .

     Note that normally the chain constructed does not include self
     signed certificates, to comply with TLS' requirements.  If,
     however, the flag 'GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED' is
     specified then self signed certificates will be included in the
     chain.

     Prior to using this function the PKCS '12' structure integrity must
     be verified using 'gnutls_pkcs12_verify_mac()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.1.0
'INT *note gnutls_pkcs12_bag_get_data:: (gnutls_pkcs12_bag_t BAG, unsigned INDX, gnutls_datum_t * DATA)'
'INT *note gnutls_pkcs12_bag_get_key_id:: (gnutls_pkcs12_bag_t BAG, unsigned INDX, gnutls_datum_t * ID)'
'INT *note gnutls_pkcs12_bag_get_friendly_name:: (gnutls_pkcs12_bag_t BAG, unsigned INDX, char ** NAME)'

The functions below are used to generate a PKCS #12 structure.  An
example of their usage is shown at *note PKCS12 structure generation
example::.

'INT *note gnutls_pkcs12_set_bag:: (gnutls_pkcs12_t PKCS12, gnutls_pkcs12_bag_t BAG)'
'INT *note gnutls_pkcs12_bag_encrypt:: (gnutls_pkcs12_bag_t BAG, const char * PASS, unsigned int FLAGS)'
'INT *note gnutls_pkcs12_generate_mac:: (gnutls_pkcs12_t PKCS12, const char * PASS)'
'INT *note gnutls_pkcs12_bag_set_data:: (gnutls_pkcs12_bag_t BAG, gnutls_pkcs12_bag_type_t TYPE, const gnutls_datum_t * DATA)'
'INT *note gnutls_pkcs12_bag_set_crl:: (gnutls_pkcs12_bag_t BAG, gnutls_x509_crl_t CRL)'
'INT *note gnutls_pkcs12_bag_set_crt:: (gnutls_pkcs12_bag_t BAG, gnutls_x509_crt_t CRT)'
'INT *note gnutls_pkcs12_bag_set_key_id:: (gnutls_pkcs12_bag_t BAG, unsigned INDX, const gnutls_datum_t * ID)'
'INT *note gnutls_pkcs12_bag_set_friendly_name:: (gnutls_pkcs12_bag_t BAG, unsigned INDX, const char * NAME)'

OpenSSL encrypted keys
......................

Unfortunately the structures discussed in the previous sections are not
the only structures that may hold an encrypted private key.  For example
the OpenSSL library offers a custom key encryption method.  Those
structures are also supported in GnuTLS with *note
gnutls_x509_privkey_import_openssl::.

 -- Function: int gnutls_x509_privkey_import_openssl
          (gnutls_x509_privkey_t KEY, const gnutls_datum_t * DATA, const
          char * PASSWORD)
     KEY: The data to store the parsed key

     DATA: The DER or PEM encoded key.

     PASSWORD: the password to decrypt the key (if it is encrypted).

     This function will convert the given PEM encrypted to the native
     gnutls_x509_privkey_t format.  The output will be stored in 'key' .

     The 'password' should be in ASCII. If the password is not provided
     or wrong then 'GNUTLS_E_DECRYPTION_FAILED' will be returned.

     If the Certificate is PEM encoded it should have a header of
     "PRIVATE KEY" and the "DEK-Info" header.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.


File: gnutls.info,  Node: certtool Invocation,  Next: ocsptool Invocation,  Prev: Managing encrypted keys,  Up: More on certificate authentication

4.2.6 Invoking certtool
-----------------------

Tool to parse and generate X.509 certificates, requests and private
keys.  It can be used interactively or non interactively by specifying
the template command line option.

The tool accepts files or supported URIs via the -infile option.  In
case PIN is required for URI access you can provide it using the
environment variables GNUTLS_PIN and GNUTLS_SO_PIN.

certtool help/usage ('-?')
..........................

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     certtool - GnuTLS certificate tool
     Usage:  certtool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

     None:

        -d, --debug=num            Enable debugging
     				- it must be in the range:
     				  0 to 9999
        -V, --verbose              More verbose output
            --infile=file          Input file
     				- file must pre-exist
            --outfile=str          Output file

     Certificate related options:

        -i, --certificate-info     Print information on the given certificate
            --pubkey-info          Print information on a public key
        -s, --generate-self-signed Generate a self-signed certificate
        -c, --generate-certificate Generate a signed certificate
            --generate-proxy       Generates a proxy certificate
        -u, --update-certificate   Update a signed certificate
            --fingerprint          Print the fingerprint of the given certificate
            --key-id               Print the key ID of the given certificate
            --v1                   Generate an X.509 version 1 certificate (with no extensions)
            --sign-params=str      Sign a certificate with a specific signature algorithm

     Certificate request related options:

            --crq-info             Print information on the given certificate request
        -q, --generate-request     Generate a PKCS #10 certificate request
     				- prohibits the option 'infile'
            --no-crq-extensions    Do not use extensions in certificate requests

     PKCS#12 file related options:

            --p12-info             Print information on a PKCS #12 structure
            --p12-name=str         The PKCS #12 friendly name to use
            --to-p12               Generate a PKCS #12 structure

     Private key related options:

        -k, --key-info             Print information on a private key
            --p8-info              Print information on a PKCS #8 structure
            --to-rsa               Convert an RSA-PSS key to raw RSA format
        -p, --generate-privkey     Generate a private key
            --key-type=str         Specify the key type to use on key generation
            --bits=num             Specify the number of bits for key generation
            --curve=str            Specify the curve used for EC key generation
            --sec-param=str        Specify the security level [low, legacy, medium, high, ultra]
            --to-p8                Convert a given key to a PKCS #8 structure
        -8, --pkcs8                Use PKCS #8 format for private keys
            --provable             Generate a private key or parameters from a seed using a provable method
            --verify-provable-privkey  Verify a private key generated from a seed using a provable method
            --seed=str             When generating a private key use the given hex-encoded seed

     CRL related options:

        -l, --crl-info             Print information on the given CRL structure
            --generate-crl         Generate a CRL
            --verify-crl           Verify a Certificate Revocation List using a trusted list
     				- requires the option 'load-ca-certificate'

     Certificate verification related options:

        -e, --verify-chain         Verify a PEM encoded certificate chain
            --verify               Verify a PEM encoded certificate (chain) against a trusted set
            --verify-hostname=str  Specify a hostname to be used for certificate chain verification
            --verify-email=str     Specify a email to be used for certificate chain verification
     				- prohibits the option 'verify-hostname'
            --verify-purpose=str   Specify a purpose OID to be used for certificate chain verification
            --verify-allow-broken  Allow broken algorithms, such as MD5 for verification
            --verify-profile=str   Specify a security level profile to be used for verification

     PKCS#7 structure options:

            --p7-generate          Generate a PKCS #7 structure
            --p7-sign              Signs using a PKCS #7 structure
            --p7-detached-sign     Signs using a detached PKCS #7 structure
            --p7-include-cert      The signer's certificate will be included in the cert list
     				- enabled by default
     				- disabled as '--no-p7-include-cert'
            --p7-time              Will include a timestamp in the PKCS #7 structure
            --p7-show-data         Will show the embedded data in the PKCS #7 structure
            --p7-info              Print information on a PKCS #7 structure
            --p7-verify            Verify the provided PKCS #7 structure
            --smime-to-p7          Convert S/MIME to PKCS #7 structure

     Other options:

            --get-dh-params        List the included PKCS #3 encoded Diffie-Hellman parameters
            --dh-info              Print information PKCS #3 encoded Diffie-Hellman parameters
            --load-privkey=str     Loads a private key file
            --load-pubkey=str      Loads a public key file
            --load-request=str     Loads a certificate request file
            --load-certificate=str Loads a certificate file
            --load-ca-privkey=str  Loads the certificate authority's private key file
            --load-ca-certificate=str Loads the certificate authority's certificate file
            --load-crl=str         Loads the provided CRL
            --load-data=str        Loads auxiliary data
            --password=str         Password to use
            --null-password        Enforce a NULL password
            --empty-password       Enforce an empty password
            --hex-numbers          Print big number in an easier format to parse
            --cprint               In certain operations it prints the information in C-friendly format
            --hash=str             Hash algorithm to use for signing
            --salt-size=num        Specify the RSA-PSS key default salt size
            --inder                Use DER format for input certificates, private keys, and DH parameters
            --inraw                an alias for the 'inder' option
            --outder               Use DER format for output certificates, private keys, and DH parameters
            --outraw               an alias for the 'outder' option
            --template=str         Template file to use for non-interactive operation
            --stdout-info          Print information to stdout instead of stderr
            --ask-pass             Enable interaction for entering password when in batch mode
            --pkcs-cipher=str      Cipher to use for PKCS #8 and #12 operations
            --provider=str         Specify the PKCS #11 provider library
            --text                 Output textual information before PEM-encoded certificates, private keys, etc
     				- enabled by default
     				- disabled as '--no-text'

     Version, usage and configuration options:

        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     Tool to parse and generate X.509 certificates, requests and private keys.
     It can be used interactively or non interactively by
     specifying the template command line option.

     The tool accepts files or supported URIs via the --infile option. In case PIN
     is required for URI access you can provide it using the environment variables GNUTLS_PIN
     and GNUTLS_SO_PIN.


     Please send bug reports to:  <bugs@gnutls.org>


debug option (-d).
..................

This is the "enable debugging" option.  This option takes a
ArgumentType.NUMBER argument.  Specifies the debug level.

cert-options options
....................

Certificate related options.

pubkey-info option.
...................

This is the "print information on a public key" option.  The option
combined with -load-request, -load-pubkey, -load-privkey and
-load-certificate will extract the public key of the object in question.

fingerprint option.
...................

This is the "print the fingerprint of the given certificate" option.
This is a simple hash of the DER encoding of the certificate.  It can be
combined with the -hash parameter.  However, it is recommended for
identification to use the key-id which depends only on the certificate's
key.

key-id option.
..............

This is the "print the key id of the given certificate" option.  This is
a hash of the public key of the given certificate.  It identifies the
key uniquely, remains the same on a certificate renewal and depends only
on signed fields of the certificate.

certificate-pubkey option.
..........................

This is the "print certificate's public key" option.  This option is
deprecated as a duplicate of -pubkey-info

*NOTE**: THIS OPTION IS DEPRECATED*

sign-params option.
...................

This is the "sign a certificate with a specific signature algorithm"
option.  This option takes a ArgumentType.STRING argument.  This option
can be combined with -generate-certificate, to sign the certificate with
a specific signature algorithm variant.  The only option supported is
'RSA-PSS', and should be specified when the signer does not have a
certificate which is marked for RSA-PSS use only.

crq-options options
...................

Certificate request related options.

generate-request option (-q).
.............................

This is the "generate a pkcs #10 certificate request" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     infile.

Will generate a PKCS #10 certificate request.  To specify a private key
use -load-privkey.

pkcs12-options options
......................

PKCS#12 file related options.

p12-info option.
................

This is the "print information on a pkcs #12 structure" option.  This
option will dump the contents and print the metadata of the provided
PKCS #12 structure.

p12-name option.
................

This is the "the pkcs #12 friendly name to use" option.  This option
takes a ArgumentType.STRING argument.  The name to be used for the
primary certificate and private key in a PKCS #12 file.

to-p12 option.
..............

This is the "generate a pkcs #12 structure" option.  It requires a
certificate, a private key and possibly a CA certificate to be
specified.

key-options options
...................

Private key related options.

p8-info option.
...............

This is the "print information on a pkcs #8 structure" option.  This
option will print information about encrypted PKCS #8 structures.  That
option does not require the decryption of the structure.

to-rsa option.
..............

This is the "convert an rsa-pss key to raw rsa format" option.  It
requires an RSA-PSS key as input and will output a raw RSA key.  This
command is necessary for compatibility with applications that cannot
read RSA-PSS keys.

generate-privkey option (-p).
.............................

This is the "generate a private key" option.  When generating RSA-PSS
private keys, the -hash option will restrict the allowed hash for the
key; in the same keys the -salt-size option is also acceptable.

key-type option.
................

This is the "specify the key type to use on key generation" option.
This option takes a ArgumentType.STRING argument.  This option can be
combined with -generate-privkey, to specify the key type to be
generated.  Valid options are, 'rsa', 'rsa-pss', 'dsa', 'ecdsa',
'ed25519, 'ed448', 'x25519', and 'x448'.'.  When combined with
certificate generation it can be used to specify an RSA-PSS certificate
when an RSA key is given.

curve option.
.............

This is the "specify the curve used for ec key generation" option.  This
option takes a ArgumentType.STRING argument.  Supported values are
secp192r1, secp224r1, secp256r1, secp384r1 and secp521r1.

sec-param option.
.................

This is the "specify the security level [low, legacy, medium, high,
ultra]" option.  This option takes a ArgumentType.STRING argument
'Security parameter'.  This is alternative to the bits option.

to-p8 option.
.............

This is the "convert a given key to a pkcs #8 structure" option.  This
needs to be combined with -load-privkey.

provable option.
................

This is the "generate a private key or parameters from a seed using a
provable method" option.  This will use the FIPS PUB186-4 algorithms
(i.e., Shawe-Taylor) for provable key generation.  When specified the
private keys or parameters will be generated from a seed, and can be
later validated with -verify-provable-privkey to be correctly generated
from the seed.  You may specify -seed or allow GnuTLS to generate one
(recommended).  This option can be combined with -generate-privkey or
-generate-dh-params.

That option applies to RSA and DSA keys.  On the DSA keys the PQG
parameters are generated using the seed, and on RSA the two primes.

verify-provable-privkey option.
...............................

This is the "verify a private key generated from a seed using a provable
method" option.  This will use the FIPS-186-4 algorithms for provable
key generation.  You may specify -seed or use the seed stored in the
private key structure.

seed option.
............

This is the "when generating a private key use the given hex-encoded
seed" option.  This option takes a ArgumentType.STRING argument.  The
seed acts as a security parameter for the private key, and thus a seed
size which corresponds to the security level of the private key should
be provided (e.g., 256-bits seed).

crl-options options
...................

CRL related options.

generate-crl option.
....................

This is the "generate a crl" option.  This option generates a
Certificate Revocation List.  When combined with -load-crl it would use
the loaded CRL as base for the generated (i.e., all revoked certificates
in the base will be copied to the new CRL). To add new certificates to
the CRL use -load-certificate.

verify-crl option.
..................

This is the "verify a certificate revocation list using a trusted list"
option.

This option has some usage constraints.  It:
   * must appear in combination with the following options:
     load-ca-certificate.

The trusted certificate list must be loaded with -load-ca-certificate.

cert-verify-options options
...........................

Certificate verification related options.

verify-chain option (-e).
.........................

This is the "verify a pem encoded certificate chain" option.  Verifies
the validity of a certificate chain.  That is, an ordered set of
certificates where each one is the issuer of the previous, and the first
is the end-certificate to be validated.  In a proper chain the last
certificate is a self signed one.  It can be combined with
-verify-purpose or -verify-hostname.

verify option.
..............

This is the "verify a pem encoded certificate (chain) against a trusted
set" option.  The trusted certificate list can be loaded with
-load-ca-certificate.  If no certificate list is provided, then the
system's trusted certificate list is used.  Note that during
verification multiple paths may be explored.  On a successful
verification the successful path will be the last one.  It can be
combined with -verify-purpose or -verify-hostname.

verify-hostname option.
.......................

This is the "specify a hostname to be used for certificate chain
verification" option.  This option takes a ArgumentType.STRING argument.
This is to be combined with one of the verify certificate options.

verify-email option.
....................

This is the "specify a email to be used for certificate chain
verification" option.  This option takes a ArgumentType.STRING argument.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     verify-hostname.

This is to be combined with one of the verify certificate options.

verify-purpose option.
......................

This is the "specify a purpose oid to be used for certificate chain
verification" option.  This option takes a ArgumentType.STRING argument.
This object identifier restricts the purpose of the certificates to be
verified.  Example purposes are 1.3.6.1.5.5.7.3.1 (TLS WWW),
1.3.6.1.5.5.7.3.4 (EMAIL) etc.  Note that a CA certificate without a
purpose set (extended key usage) is valid for any purpose.

verify-allow-broken option.
...........................

This is the "allow broken algorithms, such as md5 for verification"
option.  This can be combined with -p7-verify, -verify or -verify-chain.

verify-profile option.
......................

This is the "specify a security level profile to be used for
verification" option.  This option takes a ArgumentType.STRING argument.
This option can be used to specify a certificate verification profile.
Certificate verification profiles correspond to the security level.
This should be one of 'none', 'very weak', 'low', 'legacy', 'medium',
'high', 'ultra', 'future'.  Note that by default no profile is applied,
unless one is set as minimum in the gnutls configuration file.

pkcs7-options options
.....................

PKCS#7 structure options.

p7-generate option.
...................

This is the "generate a pkcs #7 structure" option.  This option
generates a PKCS #7 certificate container structure.  To add
certificates in the structure use -load-certificate and -load-crl.

p7-sign option.
...............

This is the "signs using a pkcs #7 structure" option.  This option
generates a PKCS #7 structure containing a signature for the provided
data from infile.  The data are stored within the structure.  The signer
certificate has to be specified using -load-certificate and
-load-privkey.  The input to -load-certificate can be a list of
certificates.  In case of a list, the first certificate is used for
signing and the other certificates are included in the structure.

p7-detached-sign option.
........................

This is the "signs using a detached pkcs #7 structure" option.  This
option generates a PKCS #7 structure containing a signature for the
provided data from infile.  The signer certificate has to be specified
using -load-certificate and -load-privkey.  The input to
-load-certificate can be a list of certificates.  In case of a list, the
first certificate is used for signing and the other certificates are
included in the structure.

p7-include-cert option.
.......................

This is the "the signer's certificate will be included in the cert list"
option.

This option has some usage constraints.  It:
   * can be disabled with -no-p7-include-cert.
   * It is enabled by default.

This options works with -p7-sign or -p7-detached-sign and will include
or exclude the signer's certificate into the generated signature.

p7-time option.
...............

This is the "will include a timestamp in the pkcs #7 structure" option.
This option will include a timestamp in the generated signature

p7-show-data option.
....................

This is the "will show the embedded data in the pkcs #7 structure"
option.  This option can be combined with -p7-verify or -p7-info and
will display the embedded signed data in the PKCS #7 structure.

p7-verify option.
.................

This is the "verify the provided pkcs #7 structure" option.  This option
verifies the signed PKCS #7 structure.  The certificate list to use for
verification can be specified with -load-ca-certificate.  When no
certificate list is provided, then the system's certificate list is
used.  Alternatively a direct signer can be provided using
-load-certificate.  A key purpose can be enforced with the
-verify-purpose option, and the -load-data option will utilize detached
data.

other-options options
.....................

Other options.

generate-dh-params option.
..........................

This is the "generate pkcs #3 encoded diffie-hellman parameters" option.
The will generate random parameters to be used with Diffie-Hellman key
exchange.  The output parameters will be in PKCS #3 format.  Note that
it is recommended to use the -get-dh-params option instead.

*NOTE**: THIS OPTION IS DEPRECATED*

get-dh-params option.
.....................

This is the "list the included pkcs #3 encoded diffie-hellman
parameters" option.  Returns stored DH parameters in GnuTLS. Those
parameters returned are defined in RFC7919, and can be considered
standard parameters for a TLS key exchange.  This option is provided for
old applications which require DH parameters to be specified; modern
GnuTLS applications should not require them.

load-privkey option.
....................

This is the "loads a private key file" option.  This option takes a
ArgumentType.STRING argument.  This can be either a file or a PKCS #11
URL

load-pubkey option.
...................

This is the "loads a public key file" option.  This option takes a
ArgumentType.STRING argument.  This can be either a file or a PKCS #11
URL

load-request option.
....................

This is the "loads a certificate request file" option.  This option
takes a ArgumentType.STRING argument.  This option can be used with a
file

load-certificate option.
........................

This is the "loads a certificate file" option.  This option takes a
ArgumentType.STRING argument.  This option can be used with a file

load-ca-privkey option.
.......................

This is the "loads the certificate authority's private key file" option.
This option takes a ArgumentType.STRING argument.  This can be either a
file or a PKCS #11 URL

load-ca-certificate option.
...........................

This is the "loads the certificate authority's certificate file" option.
This option takes a ArgumentType.STRING argument.  This can be either a
file or a PKCS #11 URL

load-crl option.
................

This is the "loads the provided crl" option.  This option takes a
ArgumentType.STRING argument.  This option can be used with a file

load-data option.
.................

This is the "loads auxiliary data" option.  This option takes a
ArgumentType.STRING argument.  This option can be used with a file

password option.
................

This is the "password to use" option.  This option takes a
ArgumentType.STRING argument.  You can use this option to specify the
password in the command line instead of reading it from the tty.  Note,
that the command line arguments are available for view in others in the
system.  Specifying password as " is the same as specifying no password.

null-password option.
.....................

This is the "enforce a null password" option.  This option enforces a
NULL password.  This is different than the empty or no password in
schemas like PKCS #8.

empty-password option.
......................

This is the "enforce an empty password" option.  This option enforces an
empty password.  This is different than the NULL or no password in
schemas like PKCS #8.

cprint option.
..............

This is the "in certain operations it prints the information in
c-friendly format" option.  In certain operations it prints the
information in C-friendly format, suitable for including into C
programs.

rsa option.
...........

This is the "generate rsa key" option.  When combined with
-generate-privkey generates an RSA private key.

*NOTE**: THIS OPTION IS DEPRECATED*

dsa option.
...........

This is the "generate dsa key" option.  When combined with
-generate-privkey generates a DSA private key.

*NOTE**: THIS OPTION IS DEPRECATED*

ecc option.
...........

This is the "generate ecc (ecdsa) key" option.  When combined with
-generate-privkey generates an elliptic curve private key to be used
with ECDSA.

*NOTE**: THIS OPTION IS DEPRECATED*

ecdsa option.
.............

This is an alias for the 'ecc' option, *note the ecc option
documentation: certtool ecc.

hash option.
............

This is the "hash algorithm to use for signing" option.  This option
takes a ArgumentType.STRING argument.  Available hash functions are
SHA1, RMD160, SHA256, SHA384, SHA512, SHA3-224, SHA3-256, SHA3-384,
SHA3-512.

salt-size option.
.................

This is the "specify the rsa-pss key default salt size" option.  This
option takes a ArgumentType.NUMBER argument.  Typical keys shouldn't set
or restrict this option.

inder option.
.............

This is the "use der format for input certificates, private keys, and dh
parameters " option.  The input files will be assumed to be in DER or
RAW format.  Unlike options that in PEM input would allow multiple input
data (e.g.  multiple certificates), when reading in DER format a single
data structure is read.

inraw option.
.............

This is an alias for the 'inder' option, *note the inder option
documentation: certtool inder.

outder option.
..............

This is the "use der format for output certificates, private keys, and
dh parameters" option.  The output will be in DER or RAW format.

outraw option.
..............

This is an alias for the 'outder' option, *note the outder option
documentation: certtool outder.

ask-pass option.
................

This is the "enable interaction for entering password when in batch
mode" option.  This option will enable interaction to enter password
when in batch mode.  That is useful when the template option has been
specified.

pkcs-cipher option.
...................

This is the "cipher to use for pkcs #8 and #12 operations" option.  This
option takes a ArgumentType.STRING argument 'Cipher'.  Cipher may be one
of 3des, 3des-pkcs12, aes-128, aes-192, aes-256, rc2-40, arcfour.

provider option.
................

This is the "specify the pkcs #11 provider library" option.  This option
takes a ArgumentType.STRING argument.  This will override the default
options in /etc/gnutls/pkcs11.conf

text option.
............

This is the "output textual information before pem-encoded certificates,
private keys, etc" option.

This option has some usage constraints.  It:
   * can be disabled with -no-text.
   * It is enabled by default.

Output textual information before PEM-encoded data

version option (-v).
....................

This is the "output version information and exit" option.  This option
takes a ArgumentType.KEYWORD argument.  Output version of program and
exit.  The default mode is 'v', a simple version.  The 'c' mode will
print copyright information and 'n' will print the full copyright
notice.

help option (-h).
.................

This is the "display extended usage information and exit" option.
Display usage information and exit.

more-help option (-!).
......................

This is the "extended usage information passed thru pager" option.  Pass
the extended usage information through a pager.

certtool exit status
....................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

certtool See Also
.................

p11tool (1), psktool (1), srptool (1)

certtool Examples
.................

Generating private keys
.......................

To create an RSA private key, run:
     $ certtool --generate-privkey --outfile key.pem --rsa

To create a DSA or elliptic curves (ECDSA) private key use the above
command combined with 'dsa' or 'ecc' options.

Generating certificate requests
...............................

To create a certificate request (needed when the certificate is issued
by another party), run:
     certtool --generate-request --load-privkey key.pem \
        --outfile request.pem

If the private key is stored in a smart card you can generate a request
by specifying the private key object URL.
     $ ./certtool --generate-request --load-privkey "pkcs11:..." \
       --load-pubkey "pkcs11:..." --outfile request.pem

Generating a self-signed certificate
....................................

To create a self signed certificate, use the command:
     $ certtool --generate-privkey --outfile ca-key.pem
     $ certtool --generate-self-signed --load-privkey ca-key.pem \
        --outfile ca-cert.pem

Note that a self-signed certificate usually belongs to a certificate
authority, that signs other certificates.

Generating a certificate
........................

To generate a certificate using the previous request, use the command:
     $ certtool --generate-certificate --load-request request.pem \
        --outfile cert.pem --load-ca-certificate ca-cert.pem \
        --load-ca-privkey ca-key.pem

To generate a certificate using the private key only, use the command:
     $ certtool --generate-certificate --load-privkey key.pem \
        --outfile cert.pem --load-ca-certificate ca-cert.pem \
        --load-ca-privkey ca-key.pem

Certificate information
.......................

To view the certificate information, use:
     $ certtool --certificate-info --infile cert.pem

Changing the certificate format
...............................

To convert the certificate from PEM to DER format, use:
     $ certtool --certificate-info --infile cert.pem --outder --outfile cert.der

PKCS #12 structure generation
.............................

To generate a PKCS #12 structure using the previous key and certificate,
use the command:
     $ certtool --load-certificate cert.pem --load-privkey key.pem \
        --to-p12 --outder --outfile key.p12

Some tools (reportedly web browsers) have problems with that file
because it does not contain the CA certificate for the certificate.  To
work around that problem in the tool, you can use the
-load-ca-certificate parameter as follows:

     $ certtool --load-ca-certificate ca.pem \
       --load-certificate cert.pem --load-privkey key.pem \
       --to-p12 --outder --outfile key.p12

Obtaining Diffie-Hellman parameters
...................................

To obtain the RFC7919 parameters for Diffie-Hellman key exchange, use
the command:
     $ certtool --get-dh-params --outfile dh.pem --sec-param medium

Verifying a certificate
.......................

To verify a certificate in a file against the system's CA trust store
use the following command:
     $ certtool --verify --infile cert.pem

It is also possible to simulate hostname verification with the following
options:
     $ certtool --verify --verify-hostname www.example.com --infile cert.pem

Proxy certificate generation
............................

Proxy certificate can be used to delegate your credential to a
temporary, typically short-lived, certificate.  To create one from the
previously created certificate, first create a temporary key and then
generate a proxy certificate for it, using the commands:

     $ certtool --generate-privkey > proxy-key.pem
     $ certtool --generate-proxy --load-ca-privkey key.pem \
       --load-privkey proxy-key.pem --load-certificate cert.pem \
       --outfile proxy-cert.pem

Certificate revocation list generation
......................................

To create an empty Certificate Revocation List (CRL) do:

     $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem \
                --load-ca-certificate x509-ca.pem

To create a CRL that contains some revoked certificates, place the
certificates in a file and use '--load-certificate' as follows:

     $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem \
       --load-ca-certificate x509-ca.pem --load-certificate revoked-certs.pem

To verify a Certificate Revocation List (CRL) do:

     $ certtool --verify-crl --load-ca-certificate x509-ca.pem < crl.pem

certtool Files
..............

Certtool's template file format
...............................

A template file can be used to avoid the interactive questions of
certtool.  Initially create a file named 'cert.cfg' that contains the
information about the certificate.  The template can be used as below:

     $ certtool --generate-certificate --load-privkey key.pem  \
        --template cert.cfg --outfile cert.pem \
        --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem

An example certtool template file that can be used to generate a
certificate request or a self signed certificate follows.

     # X.509 Certificate options
     #
     # DN options

     # The organization of the subject.
     organization = "Koko inc."

     # The organizational unit of the subject.
     unit = "sleeping dept."

     # The locality of the subject.
     # locality =

     # The state of the certificate owner.
     state = "Attiki"

     # The country of the subject. Two letter code.
     country = GR

     # The common name of the certificate owner.
     cn = "Cindy Lauper"

     # A user id of the certificate owner.
     #uid = "clauper"

     # Set domain components
     #dc = "name"
     #dc = "domain"

     # If the supported DN OIDs are not adequate you can set
     # any OID here.
     # For example set the X.520 Title and the X.520 Pseudonym
     # by using OID and string pairs.
     #dn_oid = "2.5.4.12 Dr."
     #dn_oid = "2.5.4.65 jackal"

     # This is deprecated and should not be used in new
     # certificates.
     # pkcs9_email = "none@none.org"

     # An alternative way to set the certificate's distinguished name directly
     # is with the "dn" option. The attribute names allowed are:
     # C (country), street, O (organization), OU (unit), title, CN (common name),
     # L (locality), ST (state), placeOfBirth, gender, countryOfCitizenship,
     # countryOfResidence, serialNumber, telephoneNumber, surName, initials,
     # generationQualifier, givenName, pseudonym, dnQualifier, postalCode, name,
     # businessCategory, DC, UID, jurisdictionOfIncorporationLocalityName,
     # jurisdictionOfIncorporationStateOrProvinceName,
     # jurisdictionOfIncorporationCountryName, XmppAddr, and numeric OIDs.

     #dn = "cn = Nikos,st = New\, Something,C=GR,surName=Mavrogiannopoulos,2.5.4.9=Arkadias"

     # The serial number of the certificate
     # The value is in decimal (i.e. 1963) or hex (i.e. 0x07ab).
     # Comment the field for a random serial number.
     serial = 007

     # In how many days, counting from today, this certificate will expire.
     # Use -1 if there is no expiration date.
     expiration_days = 700

     # Alternatively you may set concrete dates and time. The GNU date string
     # formats are accepted. See:
     # https://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html

     #activation_date = "2004-02-29 16:21:42"
     #expiration_date = "2025-02-29 16:24:41"

     # X.509 v3 extensions

     # A dnsname in case of a WWW server.
     #dns_name = "www.none.org"
     #dns_name = "www.morethanone.org"

     # An othername defined by an OID and a hex encoded string
     #other_name = "1.3.6.1.5.2.2 302ca00d1b0b56414e5245494e2e4f5247a11b3019a006020400000002a10f300d1b047269636b1b0561646d696e"
     #other_name_utf8 = "1.2.4.5.6 A UTF8 string"
     #other_name_octet = "1.2.4.5.6 A string that will be encoded as ASN.1 octet string"

     # Allows writing an XmppAddr Identifier
     #xmpp_name = juliet@im.example.com

     # Names used in PKINIT
     #krb5_principal = user@REALM.COM
     #krb5_principal = HTTP/user@REALM.COM

     # A subject alternative name URI
     #uri = "https://www.example.com"

     # An IP address in case of a server.
     #ip_address = "192.168.1.1"

     # An email in case of a person
     email = "none@none.org"

     # TLS feature (rfc7633) extension. That can is used to indicate mandatory TLS
     # extension features to be provided by the server. In practice this is used
     # to require the Status Request (extid: 5) extension from the server. That is,
     # to require the server holding this certificate to provide a stapled OCSP response.
     # You can have multiple lines for multiple TLS features.

     # To ask for OCSP status request use:
     #tls_feature = 5

     # Challenge password used in certificate requests
     challenge_password = 123456

     # Password when encrypting a private key
     #password = secret

     # An URL that has CRLs (certificate revocation lists)
     # available. Needed in CA certificates.
     #crl_dist_points = "https://www.getcrl.crl/getcrl/"

     # Whether this is a CA certificate or not
     #ca

     # Subject Unique ID (in hex)
     #subject_unique_id = 00153224

     # Issuer Unique ID (in hex)
     #issuer_unique_id = 00153225

     #### Key usage

     # The following key usage flags are used by CAs and end certificates

     # Whether this certificate will be used to sign data (needed
     # in TLS DHE ciphersuites). This is the digitalSignature flag
     # in RFC5280 terminology.
     signing_key

     # Whether this certificate will be used to encrypt data (needed
     # in TLS RSA ciphersuites). Note that it is preferred to use different
     # keys for encryption and signing. This is the keyEncipherment flag
     # in RFC5280 terminology.
     encryption_key

     # Whether this key will be used to sign other certificates. The
     # keyCertSign flag in RFC5280 terminology.
     #cert_signing_key

     # Whether this key will be used to sign CRLs. The
     # cRLSign flag in RFC5280 terminology.
     #crl_signing_key

     # The keyAgreement flag of RFC5280. Its purpose is loosely
     # defined. Not use it unless required by a protocol.
     #key_agreement

     # The dataEncipherment flag of RFC5280. Its purpose is loosely
     # defined. Not use it unless required by a protocol.
     #data_encipherment

     # The nonRepudiation flag of RFC5280. Its purpose is loosely
     # defined. Not use it unless required by a protocol.
     #non_repudiation

     #### Extended key usage (key purposes)

     # The following extensions are used in an end certificate
     # to clarify its purpose. Some CAs also use it to indicate
     # the types of certificates they are purposed to sign.


     # Whether this certificate will be used for a TLS client;
     # this sets the id-kp-clientAuth (1.3.6.1.5.5.7.3.2) of
     # extended key usage.
     #tls_www_client

     # Whether this certificate will be used for a TLS server;
     # this sets the id-kp-serverAuth (1.3.6.1.5.5.7.3.1) of
     # extended key usage.
     #tls_www_server

     # Whether this key will be used to sign code. This sets the
     # id-kp-codeSigning (1.3.6.1.5.5.7.3.3) of extended key usage
     # extension.
     #code_signing_key

     # Whether this key will be used to sign OCSP data. This sets the
     # id-kp-OCSPSigning (1.3.6.1.5.5.7.3.9) of extended key usage extension.
     #ocsp_signing_key

     # Whether this key will be used for time stamping. This sets the
     # id-kp-timeStamping (1.3.6.1.5.5.7.3.8) of extended key usage extension.
     #time_stamping_key

     # Whether this key will be used for email protection. This sets the
     # id-kp-emailProtection (1.3.6.1.5.5.7.3.4) of extended key usage extension.
     #email_protection_key

     # Whether this key will be used for IPsec IKE operations (1.3.6.1.5.5.7.3.17).
     #ipsec_ike_key

     ## adding custom key purpose OIDs

     # for microsoft smart card logon
     # key_purpose_oid = 1.3.6.1.4.1.311.20.2.2

     # for email protection
     # key_purpose_oid = 1.3.6.1.5.5.7.3.4

     # for any purpose (must not be used in intermediate CA certificates)
     # key_purpose_oid = 2.5.29.37.0

     ### end of key purpose OIDs

     ### Adding arbitrary extensions
     # This requires to provide the extension OIDs, as well as the extension data in
     # hex format. The following two options are available since GnuTLS 3.5.3.
     #add_extension = "1.2.3.4 0x0AAB01ACFE"

     # As above but encode the data as an octet string
     #add_extension = "1.2.3.4 octet_string(0x0AAB01ACFE)"

     # For portability critical extensions shouldn't be set to certificates.
     #add_critical_extension = "5.6.7.8 0x1AAB01ACFE"

     # When generating a certificate from a certificate
     # request, then honor the extensions stored in the request
     # and store them in the real certificate.
     #honor_crq_extensions

     # Alternatively only specific extensions can be copied.
     #honor_crq_ext = 2.5.29.17
     #honor_crq_ext = 2.5.29.15

     # Path length constraint. Sets the maximum number of
     # certificates that can be used to certify this certificate.
     # (i.e. the certificate chain length)
     #path_len = -1
     #path_len = 2

     # OCSP URI
     # ocsp_uri = https://my.ocsp.server/ocsp

     # CA issuers URI
     # ca_issuers_uri = https://my.ca.issuer

     # Certificate policies
     #policy1 = 1.3.6.1.4.1.5484.1.10.99.1.0
     #policy1_txt = "This is a long policy to summarize"
     #policy1_url = https://www.example.com/a-policy-to-read

     #policy2 = 1.3.6.1.4.1.5484.1.10.99.1.1
     #policy2_txt = "This is a short policy"
     #policy2_url = https://www.example.com/another-policy-to-read

     # The number of additional certificates that may appear in a
     # path before the anyPolicy is no longer acceptable.
     #inhibit_anypolicy_skip_certs 1

     # Name constraints

     # DNS
     #nc_permit_dns = example.com
     #nc_exclude_dns = test.example.com

     # EMAIL
     #nc_permit_email = "nmav@ex.net"

     # Exclude subdomains of example.com
     #nc_exclude_email = .example.com

     # Exclude all e-mail addresses of example.com
     #nc_exclude_email = example.com

     # IP
     #nc_permit_ip = 192.168.0.0/16
     #nc_exclude_ip = 192.168.5.0/24
     #nc_permit_ip = fc0a:eef2:e7e7:a56e::/64


     # Options for proxy certificates
     #proxy_policy_language = 1.3.6.1.5.5.7.21.1


     # Options for generating a CRL

     # The number of days the next CRL update will be due.
     # next CRL update will be in 43 days
     #crl_next_update = 43

     # this is the 5th CRL by this CA
     # The value is in decimal (i.e. 1963) or hex (i.e. 0x07ab).
     # Comment the field for a time-based number.
     # Time-based CRL numbers generated in GnuTLS 3.6.3 and later
     # are significantly larger than those generated in previous
     # versions. Since CRL numbers need to be monotonic, you need
     # to specify the CRL number here manually if you intend to
     # downgrade to an earlier version than 3.6.3 after publishing
     # the CRL as it is not possible to specify CRL numbers greater
     # than 2**63-2 using hex notation in those versions.
     #crl_number = 5

     # Specify the update dates more precisely.
     #crl_this_update_date = "2004-02-29 16:21:42"
     #crl_next_update_date = "2025-02-29 16:24:41"

     # The date that the certificates will be made seen as
     # being revoked.
     #crl_revocation_date = "2025-02-29 16:24:41"



File: gnutls.info,  Node: ocsptool Invocation,  Next: danetool Invocation,  Prev: certtool Invocation,  Up: More on certificate authentication

4.2.7 Invoking ocsptool
-----------------------

On verification
---------------

Responses are typically signed/issued by designated certificates or
certificate authorities and thus this tool requires on verification the
certificate of the issuer or the full certificate chain in order to
determine the appropriate signing authority.  The specified certificate
of the issuer is assumed trusted.

ocsptool help/usage ('-?')
..........................

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     ocsptool - GnuTLS OCSP tool
     Usage:  ocsptool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

     None:

        -d, --debug=num            Enable debugging
     				- it must be in the range:
     				  0 to 9999
        -V, --verbose              More verbose output
            --infile=file          Input file
     				- file must pre-exist
            --outfile=str          Output file
            --ask[=str]            Ask an OCSP/HTTP server on a certificate validity
        -e, --verify-response      Verify response
        -i, --request-info         Print information on a OCSP request
        -j, --response-info        Print information on a OCSP response
        -q, --generate-request     Generates an OCSP request
            --nonce                Use (or not) a nonce to OCSP request
            --load-chain=file      Reads a set of certificates forming a chain from file
     				- file must pre-exist
            --load-issuer=file     Reads issuer's certificate from file
     				- file must pre-exist
            --load-cert=file       Reads the certificate to check from file
     				- file must pre-exist
            --load-trust=file      Read OCSP trust anchors from file
     				- prohibits the option 'load-signer'
     				- file must pre-exist
            --load-signer=file     Reads the OCSP response signer from file
     				- prohibits the option 'load-trust'
     				- file must pre-exist
            --inder                Use DER format for input certificates and private keys
            --outder               Use DER format for output of responses (this is the default)
            --outpem               Use PEM format for output of responses
        -Q, --load-request=file    Reads the DER encoded OCSP request from file
     				- file must pre-exist
        -S, --load-response=file   Reads the DER encoded OCSP response from file
     				- file must pre-exist
            --ignore-errors        Ignore any verification errors
            --verify-allow-broken  Allow broken algorithms, such as MD5 for verification

     Version, usage and configuration options:

        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     ocsptool is a program that can parse and print information about
     OCSP requests/responses, generate requests and verify responses. Unlike
     other GnuTLS applications it outputs DER encoded structures by default
     unless the '--outpem' option is specified.

     Please send bug reports to:  <bugs@gnutls.org>


debug option (-d).
..................

This is the "enable debugging" option.  This option takes a
ArgumentType.NUMBER argument.  Specifies the debug level.

ask option.
...........

This is the "ask an ocsp/http server on a certificate validity" option.
This option takes a ArgumentType.STRING argument 'server name|url'.
Connects to the specified HTTP OCSP server and queries on the validity
of the loaded certificate.  Its argument can be a URL or a plain server
name.  It can be combined with -load-chain, where it checks all
certificates in the provided chain, or with -load-cert and -load-issuer
options.  The latter checks the provided certificate against its
specified issuer certificate.

verify-response option (-e).
............................

This is the "verify response" option.  Verifies the provided OCSP
response against the system trust anchors (unless -load-trust is
provided).  It requires the -load-signer or -load-chain options to
obtain the signer of the OCSP response.

request-info option (-i).
.........................

This is the "print information on a ocsp request" option.  Display
detailed information on the provided OCSP request.

response-info option (-j).
..........................

This is the "print information on a ocsp response" option.  Display
detailed information on the provided OCSP response.

load-trust option.
..................

This is the "read ocsp trust anchors from file" option.  This option
takes a ArgumentType.FILE argument.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     load-signer.

When verifying an OCSP response read the trust anchors from the provided
file.  When this is not provided, the system's trust anchors will be
used.

outder option.
..............

This is the "use der format for output of responses (this is the
default)" option.  The output will be in DER encoded format.  Unlike
other GnuTLS tools, this is the default for this tool

outpem option.
..............

This is the "use pem format for output of responses" option.  The output
will be in PEM format.

verify-allow-broken option.
...........................

This is the "allow broken algorithms, such as md5 for verification"
option.  This can be combined with -verify-response.

version option (-v).
....................

This is the "output version information and exit" option.  This option
takes a ArgumentType.KEYWORD argument.  Output version of program and
exit.  The default mode is 'v', a simple version.  The 'c' mode will
print copyright information and 'n' will print the full copyright
notice.

help option (-h).
.................

This is the "display extended usage information and exit" option.
Display usage information and exit.

more-help option (-!).
......................

This is the "extended usage information passed thru pager" option.  Pass
the extended usage information through a pager.

ocsptool exit status
....................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

ocsptool See Also
.................

certtool (1)

ocsptool Examples
.................

Print information about an OCSP request
.......................................

To parse an OCSP request and print information about the content, the
'-i' or '--request-info' parameter may be used as follows.  The '-Q'
parameter specify the name of the file containing the OCSP request, and
it should contain the OCSP request in binary DER format.

     $ ocsptool -i -Q ocsp-request.der

The input file may also be sent to standard input like this:

     $ cat ocsp-request.der | ocsptool --request-info

Print information about an OCSP response
........................................

Similar to parsing OCSP requests, OCSP responses can be parsed using the
'-j' or '--response-info' as follows.

     $ ocsptool -j -Q ocsp-response.der
     $ cat ocsp-response.der | ocsptool --response-info

Generate an OCSP request
........................

The '-q' or '--generate-request' parameters are used to generate an OCSP
request.  By default the OCSP request is written to standard output in
binary DER format, but can be stored in a file using '--outfile'.  To
generate an OCSP request the issuer of the certificate to check needs to
be specified with '--load-issuer' and the certificate to check with
'--load-cert'.  By default PEM format is used for these files, although
'--inder' can be used to specify that the input files are in DER format.

     $ ocsptool -q --load-issuer issuer.pem --load-cert client.pem \
                --outfile ocsp-request.der

When generating OCSP requests, the tool will add an OCSP extension
containing a nonce.  This behaviour can be disabled by specifying
'--no-nonce'.

Verify signature in OCSP response
.................................

To verify the signature in an OCSP response the '-e' or
'--verify-response' parameter is used.  The tool will read an OCSP
response in DER format from standard input, or from the file specified
by '--load-response'.  The OCSP response is verified against a set of
trust anchors, which are specified using '--load-trust'.  The trust
anchors are concatenated certificates in PEM format.  The certificate
that signed the OCSP response needs to be in the set of trust anchors,
or the issuer of the signer certificate needs to be in the set of trust
anchors and the OCSP Extended Key Usage bit has to be asserted in the
signer certificate.

     $ ocsptool -e --load-trust issuer.pem \
                --load-response ocsp-response.der

The tool will print status of verification.

Verify signature in OCSP response against given certificate
...........................................................

It is possible to override the normal trust logic if you know that a
certain certificate is supposed to have signed the OCSP response, and
you want to use it to check the signature.  This is achieved using
'--load-signer' instead of '--load-trust'.  This will load one
certificate and it will be used to verify the signature in the OCSP
response.  It will not check the Extended Key Usage bit.

     $ ocsptool -e --load-signer ocsp-signer.pem \
                --load-response ocsp-response.der

This approach is normally only relevant in two situations.  The first is
when the OCSP response does not contain a copy of the signer
certificate, so the '--load-trust' code would fail.  The second is if
you want to avoid the indirect mode where the OCSP response signer
certificate is signed by a trust anchor.

Real-world example
..................

Here is an example of how to generate an OCSP request for a certificate
and to verify the response.  For illustration we'll use the
'blog.josefsson.org' host, which (as of writing) uses a certificate from
CACert.  First we'll use 'gnutls-cli' to get a copy of the server
certificate chain.  The server is not required to send this information,
but this particular one is configured to do so.

     $ echo | gnutls-cli -p 443 blog.josefsson.org --save-cert chain.pem

The saved certificates normally contain a pointer to where the OCSP
responder is located, in the Authority Information Access Information
extension.  For example, from 'certtool -i < chain.pem' there is this
information:

     		Authority Information Access Information (not critical):
     			Access Method: 1.3.6.1.5.5.7.48.1 (id-ad-ocsp)
     			Access Location URI: https://ocsp.CAcert.org/

This means that ocsptool can discover the servers to contact over HTTP.
We can now request information on the chain certificates.

     $ ocsptool --ask --load-chain chain.pem

The request is sent via HTTP to the OCSP server address found in the
certificates.  It is possible to override the address of the OCSP server
as well as ask information on a particular certificate using -load-cert
and -load-issuer.

     $ ocsptool --ask https://ocsp.CAcert.org/ --load-chain chain.pem


File: gnutls.info,  Node: danetool Invocation,  Prev: ocsptool Invocation,  Up: More on certificate authentication

4.2.8 Invoking danetool
-----------------------

Tool to generate and check DNS resource records for the DANE protocol.

danetool help/usage ('-?')
..........................

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     danetool - GnuTLS DANE tool
     Usage:  danetool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

     None:

        -d, --debug=num            Enable debugging
     				- it must be in the range:
     				  0 to 9999
        -V, --verbose              More verbose output
            --outfile=str          Output file
            --load-pubkey=str      Loads a public key file
            --load-certificate=str Loads a certificate file
            --dlv=str              Sets a DLV file
            --hash=str             Hash algorithm to use for signing
            --check=str            Check a host's DANE TLSA entry
            --check-ee             Check only the end-entity's certificate
            --check-ca             Check only the CA's certificate
            --tlsa-rr              Print the DANE RR data on a certificate or public key
     				- requires the option 'host'
            --host=str             Specify the hostname to be used in the DANE RR
            --proto=str            The protocol set for DANE data (tcp, udp etc.)
            --port=str             The port or service to connect to, for DANE data
            --app-proto            an alias for the 'starttls-proto' option
            --starttls-proto=str   The application protocol to be used to obtain the server's certificate (https, ftp, smtp, imap, ldap, xmpp, lmtp, pop3, nntp, sieve, postgres)
            --ca                   Whether the provided certificate or public key is a Certificate Authority
            --x509                 Use the hash of the X.509 certificate, rather than the public key
            --local                an alias for the 'domain' option
            --domain               The provided certificate or public key is issued by the local domain
     				- enabled by default
     				- disabled as '--no-domain'
            --local-dns            Use the local DNS server for DNSSEC resolving
            --insecure             Do not verify any DNSSEC signature
            --inder                Use DER format for input certificates and private keys
            --inraw                an alias for the 'inder' option
            --print-raw            Print the received DANE data in raw format
            --quiet                Suppress several informational messages

     Version, usage and configuration options:

        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     Tool to generate and check DNS resource records for the DANE protocol.

     Please send bug reports to:  <bugs@gnutls.org>


debug option (-d).
..................

This is the "enable debugging" option.  This option takes a
ArgumentType.NUMBER argument.  Specifies the debug level.

load-pubkey option.
...................

This is the "loads a public key file" option.  This option takes a
ArgumentType.STRING argument.  This can be either a file or a PKCS #11
URL

load-certificate option.
........................

This is the "loads a certificate file" option.  This option takes a
ArgumentType.STRING argument.  This can be either a file or a PKCS #11
URL

dlv option.
...........

This is the "sets a dlv file" option.  This option takes a
ArgumentType.STRING argument.  This sets a DLV file to be used for
DNSSEC verification.

hash option.
............

This is the "hash algorithm to use for signing" option.  This option
takes a ArgumentType.STRING argument.  Available hash functions are
SHA1, RMD160, SHA256, SHA384, SHA512.

check option.
.............

This is the "check a host's dane tlsa entry" option.  This option takes
a ArgumentType.STRING argument.  Obtains the DANE TLSA entry from the
given hostname and prints information.  Note that the actual certificate
of the host can be provided using -load-certificate, otherwise danetool
will connect to the server to obtain it.  The exit code on verification
success will be zero.

check-ee option.
................

This is the "check only the end-entity's certificate" option.  Checks
the end-entity's certificate only.  Trust anchors or CAs are not
considered.

check-ca option.
................

This is the "check only the ca's certificate" option.  Checks the trust
anchor's and CA's certificate only.  End-entities are not considered.

tlsa-rr option.
...............

This is the "print the dane rr data on a certificate or public key"
option.

This option has some usage constraints.  It:
   * must appear in combination with the following options: host.

This command prints the DANE RR data needed to enable DANE on a DNS
server.

host option.
............

This is the "specify the hostname to be used in the dane rr" option.
This option takes a ArgumentType.STRING argument 'Hostname'.  This
command sets the hostname for the DANE RR.

proto option.
.............

This is the "the protocol set for dane data (tcp, udp etc.)"  option.
This option takes a ArgumentType.STRING argument 'Protocol'.  This
command specifies the protocol for the service set in the DANE data.

app-proto option.
.................

This is an alias for the 'starttls-proto' option, *note the
starttls-proto option documentation: danetool starttls-proto.

starttls-proto option.
......................

This is the "the application protocol to be used to obtain the server's
certificate (https, ftp, smtp, imap, ldap, xmpp, lmtp, pop3, nntp,
sieve, postgres)" option.  This option takes a ArgumentType.STRING
argument.  When the server's certificate isn't provided danetool will
connect to the server to obtain the certificate.  In that case it is
required to know the protocol to talk with the server prior to
initiating the TLS handshake.

ca option.
..........

This is the "whether the provided certificate or public key is a
certificate authority" option.  Marks the DANE RR as a CA certificate if
specified.

x509 option.
............

This is the "use the hash of the x.509 certificate, rather than the
public key" option.  This option forces the generated record to contain
the hash of the full X.509 certificate.  By default only the hash of the
public key is used.

local option.
.............

This is an alias for the 'domain' option, *note the domain option
documentation: danetool domain.

domain option.
..............

This is the "the provided certificate or public key is issued by the
local domain" option.

This option has some usage constraints.  It:
   * can be disabled with -no-domain.
   * It is enabled by default.

DANE distinguishes certificates and public keys offered via the DNSSEC
to trusted and local entities.  This flag indicates that this is a
domain-issued certificate, meaning that there could be no CA involved.

local-dns option.
.................

This is the "use the local dns server for dnssec resolving" option.
This option will use the local DNS server for DNSSEC. This is disabled
by default due to many servers not allowing DNSSEC.

insecure option.
................

This is the "do not verify any dnssec signature" option.  Ignores any
DNSSEC signature verification results.

inder option.
.............

This is the "use der format for input certificates and private keys"
option.  The input files will be assumed to be in DER or RAW format.
Unlike options that in PEM input would allow multiple input data (e.g.
multiple certificates), when reading in DER format a single data
structure is read.

inraw option.
.............

This is an alias for the 'inder' option, *note the inder option
documentation: danetool inder.

print-raw option.
.................

This is the "print the received dane data in raw format" option.  This
option will print the received DANE data.

quiet option.
.............

This is the "suppress several informational messages" option.  In that
case on the exit code can be used as an indication of verification
success

version option (-v).
....................

This is the "output version information and exit" option.  This option
takes a ArgumentType.KEYWORD argument.  Output version of program and
exit.  The default mode is 'v', a simple version.  The 'c' mode will
print copyright information and 'n' will print the full copyright
notice.

help option (-h).
.................

This is the "display extended usage information and exit" option.
Display usage information and exit.

more-help option (-!).
......................

This is the "extended usage information passed thru pager" option.  Pass
the extended usage information through a pager.

danetool exit status
....................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

danetool See Also
.................

certtool (1)

danetool Examples
.................

DANE TLSA RR generation
.......................

To create a DANE TLSA resource record for a certificate (or public key)
that was issued localy and may or may not be signed by a CA use the
following command.
     $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem

To create a DANE TLSA resource record for a CA signed certificate, which
will be marked as such use the following command.
     $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem \
       --no-domain

The former is useful to add in your DNS entry even if your certificate
is signed by a CA. That way even users who do not trust your CA will be
able to verify your certificate using DANE.

In order to create a record for the CA signer of your certificate use
the following.
     $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem \
       --ca --no-domain

To read a server's DANE TLSA entry, use:
     $ danetool --check www.example.com --proto tcp --port 443

To verify an HTTPS server's DANE TLSA entry, use:
     $ danetool --check www.example.com --proto tcp --port 443 --load-certificate chain.pem

To verify an SMTP server's DANE TLSA entry, use:
     $ danetool --check www.example.com --proto tcp --starttls-proto=smtp --load-certificate chain.pem


File: gnutls.info,  Node: Shared-key and anonymous authentication,  Next: Selecting an appropriate authentication method,  Prev: More on certificate authentication,  Up: Authentication methods

4.3 Shared-key and anonymous authentication
===========================================

In addition to certificate authentication, the TLS protocol may be used
with password, shared-key and anonymous authentication methods.  The
rest of this chapter discusses details of these methods.

* Menu:

* PSK authentication::
* SRP authentication::
* Anonymous authentication::


File: gnutls.info,  Node: PSK authentication,  Next: SRP authentication,  Up: Shared-key and anonymous authentication

4.3.1 PSK authentication
------------------------

* Menu:

* Authentication using PSK::
* psktool Invocation::             Invoking psktool


File: gnutls.info,  Node: Authentication using PSK,  Next: psktool Invocation,  Up: PSK authentication

4.3.1.1 Authentication using PSK
................................

Authentication using Pre-shared keys is a method to authenticate using
usernames and binary keys.  This protocol avoids making use of public
key infrastructure and expensive calculations, thus it is suitable for
constraint clients.  It is available under all TLS protocol versions.

The implementation in GnuTLS is based on [*note TLSPSK::].  The
supported PSK key exchange methods are:

'PSK:'
     Authentication using the PSK protocol (no forward secrecy).

'DHE-PSK:'
     Authentication using the PSK protocol and Diffie-Hellman key
     exchange.  This method offers perfect forward secrecy.

'ECDHE-PSK:'
     Authentication using the PSK protocol and Elliptic curve
     Diffie-Hellman key exchange.  This method offers perfect forward
     secrecy.

'RSA-PSK:'
     Authentication using the PSK protocol for the client and an RSA
     certificate for the server.  This is not available under TLS 1.3.

Helper functions to generate and maintain PSK keys are also included in
GnuTLS.

'INT *note gnutls_key_generate:: (gnutls_datum_t * KEY, unsigned int KEY_SIZE)'
'INT *note gnutls_hex_encode:: (const gnutls_datum_t * DATA, char * RESULT, size_t * RESULT_SIZE)'
'INT *note gnutls_hex_decode:: (const gnutls_datum_t * HEX_DATA, void * RESULT, size_t * RESULT_SIZE)'


File: gnutls.info,  Node: psktool Invocation,  Prev: Authentication using PSK,  Up: PSK authentication

4.3.1.2 Invoking psktool
........................

Program that generates random keys for use with TLS-PSK. The keys are
stored in hexadecimal format in a key file.

psktool help/usage ('-?')
.........................

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     psktool - GnuTLS PSK tool
     Usage:  psktool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

     None:

        -d, --debug=num            Enable debugging
     				- it must be in the range:
     				  0 to 9999
        -s, --keysize=num          Specify the key size in bytes (default is 32-bytes or 256-bits)
     				- it must be in the range:
     				  0 to 512
        -u, --username=str         Specify the username to use
        -p, --pskfile=str          Specify a pre-shared key file

     Version, usage and configuration options:

        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     Program  that generates random keys for use with TLS-PSK. The
     keys are stored in hexadecimal format in a key file.

     Please send bug reports to:  <bugs@gnutls.org>


debug option (-d).
..................

This is the "enable debugging" option.  This option takes a
ArgumentType.NUMBER argument.  Specifies the debug level.

pskfile option (-p).
....................

This is the "specify a pre-shared key file" option.  This option takes a
ArgumentType.STRING argument.  This option will specify the pre-shared
key file to store the generated keys.

passwd option.
..............

This is an alias for the 'pskfile' option, *note the pskfile option
documentation: psktool pskfile.

version option (-v).
....................

This is the "output version information and exit" option.  This option
takes a ArgumentType.KEYWORD argument.  Output version of program and
exit.  The default mode is 'v', a simple version.  The 'c' mode will
print copyright information and 'n' will print the full copyright
notice.

help option (-h).
.................

This is the "display extended usage information and exit" option.
Display usage information and exit.

more-help option (-!).
......................

This is the "extended usage information passed thru pager" option.  Pass
the extended usage information through a pager.

psktool exit status
...................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

psktool See Also
................

gnutls-cli-debug (1), gnutls-serv (1), srptool (1), certtool (1)

psktool Examples
................

To add a user 'psk_identity' in 'keys.psk' for use with GnuTLS run:
     $ ./psktool -u psk_identity -p keys.psk
     Generating a random key for user 'psk_identity'
     Key stored to keys.psk
     $ cat keys.psk
     psk_identity:88f3824b3e5659f52d00e959bacab954b6540344
     $

This command will create 'keys.psk' if it does not exist and will add
user 'psk_identity'.


File: gnutls.info,  Node: SRP authentication,  Next: Anonymous authentication,  Prev: PSK authentication,  Up: Shared-key and anonymous authentication

4.3.2 SRP authentication
------------------------

* Menu:

* Authentication using SRP::
* srptool Invocation::             Invoking srptool


File: gnutls.info,  Node: Authentication using SRP,  Next: srptool Invocation,  Up: SRP authentication

4.3.2.1 Authentication using SRP
................................

GnuTLS supports authentication via the Secure Remote Password or SRP
protocol (see [*note TOMSRP: RFC2945.] for a description).  The SRP key
exchange is an extension to the TLS protocol, and it provides an
authenticated with a password key exchange.  The peers can be identified
using a single password, or there can be combinations where the client
is authenticated using SRP and the server using a certificate.  It is
only available under TLS 1.2 or earlier versions.

The advantage of SRP authentication, over other proposed secure password
authentication schemes, is that SRP is not susceptible to off-line
dictionary attacks.  Moreover, SRP does not require the server to hold
the user's password.  This kind of protection is similar to the one used
traditionally in the UNIX '/etc/passwd' file, where the contents of this
file did not cause harm to the system security if they were revealed.
The SRP needs instead of the plain password something called a verifier,
which is calculated using the user's password, and if stolen cannot be
used to impersonate the user.

Typical conventions in SRP are a password file, called 'tpasswd' that
holds the SRP verifiers (encoded passwords) and another file,
'tpasswd.conf', which holds the allowed SRP parameters.  The included in
GnuTLS helper follow those conventions.  The srptool program, discussed
in the next section is a tool to manipulate the SRP parameters.

The implementation in GnuTLS is based on [*note TLSSRP::].  The
supported key exchange methods are shown below.  Enabling any of these
key exchange methods in a session disables support for TLS1.3.

'SRP:'
     Authentication using the SRP protocol.

'SRP_DSS:'
     Client authentication using the SRP protocol.  Server is
     authenticated using a certificate with DSA parameters.

'SRP_RSA:'
     Client authentication using the SRP protocol.  Server is
     authenticated using a certificate with RSA parameters.

 -- Function: int gnutls_srp_verifier (const char * USERNAME, const char
          * PASSWORD, const gnutls_datum_t * SALT, const gnutls_datum_t
          * GENERATOR, const gnutls_datum_t * PRIME, gnutls_datum_t *
          RES)
     USERNAME: is the user's name

     PASSWORD: is the user's password

     SALT: should be some randomly generated bytes

     GENERATOR: is the generator of the group

     PRIME: is the group's prime

     RES: where the verifier will be stored.

     This function will create an SRP verifier, as specified in RFC2945.
     The 'prime' and 'generator' should be one of the static parameters
     defined in gnutls/gnutls.h or may be generated.

     The verifier will be allocated with 'gnutls_malloc' () and will be
     stored in 'res' using binary format.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, or an
     error code.

'INT *note gnutls_srp_base64_encode2:: (const gnutls_datum_t * DATA, gnutls_datum_t * RESULT)'
'INT *note gnutls_srp_base64_decode2:: (const gnutls_datum_t * B64_DATA, gnutls_datum_t * RESULT)'


File: gnutls.info,  Node: srptool Invocation,  Prev: Authentication using SRP,  Up: SRP authentication

4.3.2.2 Invoking srptool
........................

Simple program that emulates the programs in the Stanford SRP (Secure
Remote Password) libraries using GnuTLS. It is intended for use in
places where you don't expect SRP authentication to be the used for
system users.

In brief, to use SRP you need to create two files.  These are the
password file that holds the users and the verifiers associated with
them and the configuration file to hold the group parameters (called
tpasswd.conf).

srptool help/usage ('-?')
.........................

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     srptool - GnuTLS SRP tool
     Usage:  srptool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...

     None:

        -d, --debug=num            Enable debugging
     				- it must be in the range:
     				  0 to 9999
        -i, --index=num            specify the index of the group parameters in tpasswd.conf to use
        -u, --username=str         specify a username
        -p, --passwd=str           specify a password file
        -s, --salt=num             specify salt size
            --verify               just verify the password
        -v, --passwd-conf=str      specify a password conf file
            --create-conf=str      Generate a password configuration file

     Version, usage and configuration options:

        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.

     Simple program that emulates the programs in the Stanford SRP (Secure
     Remote Password) libraries using GnuTLS.  It is intended for use in  places
     where you don't expect SRP authentication to be the used for system users.

     In  brief,  to use SRP you need to create two files. These are the password
     file that holds the users and the verifiers associated with  them  and  the
     configuration file to hold the group parameters (called tpasswd.conf).

     Please send bug reports to:  <bugs@gnutls.org>


debug option (-d).
..................

This is the "enable debugging" option.  This option takes a
ArgumentType.NUMBER argument.  Specifies the debug level.

verify option.
..............

This is the "just verify the password" option.  Verifies the password
provided against the password file.

passwd-conf option (-v).
........................

This is the "specify a password conf file" option.  This option takes a
ArgumentType.STRING argument.  Specify a filename or a PKCS #11 URL to
read the CAs from.

create-conf option.
...................

This is the "generate a password configuration file" option.  This
option takes a ArgumentType.STRING argument.  This generates a password
configuration file (tpasswd.conf) containing the required for TLS
parameters.

version option (-v).
....................

This is the "output version information and exit" option.  This option
takes a ArgumentType.KEYWORD argument.  Output version of program and
exit.  The default mode is 'v', a simple version.  The 'c' mode will
print copyright information and 'n' will print the full copyright
notice.

help option (-h).
.................

This is the "display extended usage information and exit" option.
Display usage information and exit.

more-help option (-!).
......................

This is the "extended usage information passed thru pager" option.  Pass
the extended usage information through a pager.

srptool exit status
...................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

srptool See Also
................

gnutls-cli-debug (1), gnutls-serv (1), srptool (1), psktool (1),
certtool (1)

srptool Examples
................

To create 'tpasswd.conf' which holds the g and n values for SRP protocol
(generator and a large prime), run:
     $ srptool --create-conf /etc/tpasswd.conf

This command will create '/etc/tpasswd' and will add user 'test' (you
will also be prompted for a password).  Verifiers are stored by default
in the way libsrp expects.
     $ srptool --passwd /etc/tpasswd --passwd-conf /etc/tpasswd.conf -u test

This command will check against a password.  If the password matches the
one in '/etc/tpasswd' you will get an ok.
     $ srptool --passwd /etc/tpasswd --passwd\-conf /etc/tpasswd.conf --verify -u test


File: gnutls.info,  Node: Anonymous authentication,  Prev: SRP authentication,  Up: Shared-key and anonymous authentication

4.3.3 Anonymous authentication
------------------------------

The anonymous key exchange offers encryption without any indication of
the peer's identity.  This kind of authentication is vulnerable to a man
in the middle attack, but can be used even if there is no prior
communication or shared trusted parties with the peer.  It is useful to
establish a session over which certificate authentication will occur in
order to hide the indentities of the participants from passive
eavesdroppers.  It is only available under TLS 1.2 or earlier versions.

Unless in the above case, it is not recommended to use anonymous
authentication.  In the cases where there is no prior communication with
the peers, an alternative with better properties, such as key
continuity, is trust on first use (see *note Verifying a certificate
using trust on first use authentication::).

The available key exchange algorithms for anonymous authentication are
shown below, but note that few public servers support them, and they
have to be explicitly enabled.  These ciphersuites are negotiated only
under TLS 1.2.

'ANON_DH:'
     This algorithm exchanges Diffie-Hellman parameters.

'ANON_ECDH:'
     This algorithm exchanges elliptic curve Diffie-Hellman parameters.
     It is more efficient than ANON_DH on equivalent security levels.


File: gnutls.info,  Node: Selecting an appropriate authentication method,  Prev: Shared-key and anonymous authentication,  Up: Authentication methods

4.4 Selecting an appropriate authentication method
==================================================

This section provides some guidance on how to use the available
authentication methods in GnuTLS in various scenarios.

4.4.1 Two peers with an out-of-band channel
-------------------------------------------

Let's consider two peers who need to communicate over an untrusted
channel (the Internet), but have an out-of-band channel available.  The
latter channel is considered safe from eavesdropping and message
modification and thus can be used for an initial bootstrapping of the
protocol.  The options available are:
   * Pre-shared keys (see *note PSK authentication::).  The server and a
     client communicate a shared randomly generated key over the trusted
     channel and use it to negotiate further sessions over the untrusted
     channel.

   * Passwords (see *note SRP authentication::).  The client
     communicates to the server its username and password of choice and
     uses it to negotiate further sessions over the untrusted channel.

   * Public keys (see *note Certificate authentication::).  The client
     and the server exchange their public keys (or fingerprints of them)
     over the trusted channel.  On future sessions over the untrusted
     channel they verify the key being the same (similar to *note
     Verifying a certificate using trust on first use authentication::).

Provided that the out-of-band channel is trusted all of the above
provide a similar level of protection.  An out-of-band channel may be
the initial bootstrapping of a user's PC in a corporate environment,
in-person communication, communication over an alternative network (e.g.
the phone network), etc.

4.4.2 Two peers without an out-of-band channel
----------------------------------------------

When an out-of-band channel is not available a peer cannot be reliably
authenticated.  What can be done, however, is to allow some form of
registration of users connecting for the first time and ensure that
their keys remain the same after that initial connection.  This is
termed key continuity or trust on first use (TOFU).

The available option is to use public key authentication (see *note
Certificate authentication::).  The client and the server store each
other's public keys (or fingerprints of them) and associate them with
their identity.  On future sessions over the untrusted channel they
verify the keys being the same (see *note Verifying a certificate using
trust on first use authentication::).

To mitigate the uncertainty of the information exchanged in the first
connection other channels over the Internet may be used, e.g., DNSSEC
(see *note Verifying a certificate using DANE::).

4.4.3 Two peers and a trusted third party
-----------------------------------------

When a trusted third party is available (or a certificate authority) the
most suitable option is to use certificate authentication (see *note
Certificate authentication::).  The client and the server obtain
certificates that associate their identity and public keys using a
digital signature by the trusted party and use them to on the subsequent
communications with each other.  Each party verifies the peer's
certificate using the trusted third party's signature.  The parameters
of the third party's signature are present in its certificate which must
be available to all communicating parties.

While the above is the typical authentication method for servers in the
Internet by using the commercial CAs, the users that act as clients in
the protocol rarely possess such certificates.  In that case a hybrid
method can be used where the server is authenticated by the client using
the commercial CAs and the client is authenticated based on some
information the client provided over the initial server-authenticated
channel.  The available options are:
   * Passwords (see *note SRP authentication::).  The client
     communicates to the server its username and password of choice on
     the initial server-authenticated connection and uses it to
     negotiate further sessions.  This is possible because the SRP
     protocol allows for the server to be authenticated using a
     certificate and the client using the password.

   * Public keys (see *note Certificate authentication::).  The client
     sends its public key to the server (or a fingerprint of it) over
     the initial server-authenticated connection.  On future sessions
     the client verifies the server using the third party certificate
     and the server verifies that the client's public key remained the
     same (see *note Verifying a certificate using trust on first use
     authentication::).


File: gnutls.info,  Node: Hardware security modules and abstract key types,  Next: How to use GnuTLS in applications,  Prev: Authentication methods,  Up: Top

5 Abstract key types and Hardware security modules
**************************************************

In several cases storing the long term cryptographic keys in a hard disk
or even in memory poses a significant risk.  Once the system they are
stored is compromised the keys must be replaced as the secrecy of future
sessions is no longer guaranteed.  Moreover, past sessions that were not
protected by a perfect forward secrecy offering ciphersuite are also to
be assumed compromised.

If such threats need to be addressed, then it may be wise storing the
keys in a security module such as a smart card, an HSM or the TPM chip.
Those modules ensure the protection of the cryptographic keys by only
allowing operations on them and preventing their extraction.  The
purpose of the abstract key API is to provide an API that will allow the
handle of keys in memory and files, as well as keys stored in such
modules.

In GnuTLS the approach is to handle all keys transparently by the high
level API, e.g., the API that loads a key or certificate from a file.
The high-level API will accept URIs in addition to files that specify
keys on an HSM or in TPM, and a callback function will be used to obtain
any required keys.  The URI format is defined in [*note PKCS11URI::].

More information on the API is provided in the next sections.  Examples
of a URI of a certificate stored in an HSM, as well as a key stored in
the TPM chip are shown below.  To discover the URIs of the objects the
'p11tool' (see *note p11tool Invocation::).
     pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315; \
     manufacturer=EnterSafe;object=test1;type=cert


* Menu:

* Abstract key types::
* Application-specific keys::
* Smart cards and HSMs::
* Trusted Platform Module::


File: gnutls.info,  Node: Abstract key types,  Next: Application-specific keys,  Up: Hardware security modules and abstract key types

5.1 Abstract key types
======================

Since there are many forms of a public or private keys supported by
GnuTLS such as X.509, PKCS #11 or TPM it is desirable to allow common
operations on them.  For these reasons the abstract 'gnutls_privkey_t'
and 'gnutls_pubkey_t' were introduced in 'gnutls/abstract.h' header.
Those types are initialized using a specific type of key and then can be
used to perform operations in an abstract way.  For example in order to
sign an X.509 certificate with a key that resides in a token the
following steps can be used.

     #include <gnutls/abstract.h>

     void sign_cert( gnutls_x509_crt_t to_be_signed)
     {
     gnutls_x509_crt_t ca_cert;
     gnutls_privkey_t abs_key;

       /* initialize the abstract key */
       gnutls_privkey_init(&abs_key);

       /* keys stored in tokens are identified by URLs */
       gnutls_privkey_import_url(abs_key, key_url);

       gnutls_x509_crt_init(&ca_cert);
       gnutls_x509_crt_import_url(&ca_cert, cert_url);

       /* sign the certificate to be signed */
       gnutls_x509_crt_privkey_sign(to_be_signed, ca_cert, abs_key,
                                    GNUTLS_DIG_SHA256, 0);
     }

* Menu:

* Abstract public keys::
* Abstract private keys::
* Operations::


File: gnutls.info,  Node: Abstract public keys,  Next: Abstract private keys,  Up: Abstract key types

5.1.1 Public keys
-----------------

An abstract 'gnutls_pubkey_t' can be initialized and freed by using the
functions below.

'INT *note gnutls_pubkey_init:: (gnutls_pubkey_t * KEY)'
'VOID *note gnutls_pubkey_deinit:: (gnutls_pubkey_t KEY)'

After initialization its values can be imported from an existing
structure like 'gnutls_x509_crt_t', or through an ASN.1 encoding of the
X.509 'SubjectPublicKeyInfo' sequence.

'INT *note gnutls_pubkey_import_x509:: (gnutls_pubkey_t KEY, gnutls_x509_crt_t CRT, unsigned int FLAGS)'
'INT *note gnutls_pubkey_import_pkcs11:: (gnutls_pubkey_t KEY, gnutls_pkcs11_obj_t OBJ, unsigned int FLAGS)'

'INT *note gnutls_pubkey_import_url:: (gnutls_pubkey_t KEY, const char * URL, unsigned int FLAGS)'
'INT *note gnutls_pubkey_import_privkey:: (gnutls_pubkey_t KEY, gnutls_privkey_t PKEY, unsigned int USAGE, unsigned int FLAGS)'
'INT *note gnutls_pubkey_import:: (gnutls_pubkey_t KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
'INT *note gnutls_pubkey_export:: (gnutls_pubkey_t KEY, gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'

 -- Function: int gnutls_pubkey_export2 (gnutls_pubkey_t KEY,
          gnutls_x509_crt_fmt_t FORMAT, gnutls_datum_t * OUT)
     KEY: Holds the certificate

     FORMAT: the format of output params.  One of PEM or DER.

     OUT: will contain a certificate PEM or DER encoded

     This function will export the public key to DER or PEM format.  The
     contents of the exported data is the SubjectPublicKeyInfo X.509
     structure.

     The output buffer will be allocated using 'gnutls_malloc()' .

     If the structure is PEM encoded, it will have a header of "BEGIN
     CERTIFICATE".

     *Returns:* In case of failure a negative error code will be
     returned, and 0 on success.

     *Since:* 3.1.3

Other helper functions that allow directly importing from raw X.509
structures are shown below.

'INT *note gnutls_pubkey_import_x509_raw:: (gnutls_pubkey_t PKEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, unsigned int FLAGS)'

An important function is *note gnutls_pubkey_import_url:: which will
import public keys from URLs that identify objects stored in tokens (see
*note Smart cards and HSMs:: and *note Trusted Platform Module::).  A
function to check for a supported by GnuTLS URL is *note
gnutls_url_is_supported::.

 -- Function: unsigned gnutls_url_is_supported (const char * URL)
     URL: A URI to be tested

     Check whether the provided 'url' is supported.  Depending on the
     system libraries GnuTLS may support pkcs11, tpmkey or other URLs.

     *Returns:* return non-zero if the given URL is supported, and zero
     if it is not known.

     *Since:* 3.1.0

Additional functions are available that will return information over a
public key, such as a unique key ID, as well as a function that given a
public key fingerprint would provide a memorable sketch.

Note that *note gnutls_pubkey_get_key_id:: calculates a SHA1 digest of
the public key as a DER-formatted, subjectPublicKeyInfo object.  Other
implementations use different approaches, e.g., some use the "common
method" described in section 4.2.1.2 of [*note RFC5280::] which
calculates a digest on a part of the subjectPublicKeyInfo object.

'INT *note gnutls_pubkey_get_pk_algorithm:: (gnutls_pubkey_t KEY, unsigned int * BITS)'
'INT *note gnutls_pubkey_get_preferred_hash_algorithm:: (gnutls_pubkey_t KEY, gnutls_digest_algorithm_t * HASH, unsigned int * MAND)'
'INT *note gnutls_pubkey_get_key_id:: (gnutls_pubkey_t KEY, unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'
'INT *note gnutls_random_art:: (gnutls_random_art_t TYPE, const char * KEY_TYPE, unsigned int KEY_SIZE, void * FPR, size_t FPR_SIZE, gnutls_datum_t * ART)'

To export the key-specific parameters, or obtain a unique key ID the
following functions are provided.

'INT *note gnutls_pubkey_export_rsa_raw2:: (gnutls_pubkey_t KEY, gnutls_datum_t * M, gnutls_datum_t * E, unsigned FLAGS)'
'INT *note gnutls_pubkey_export_dsa_raw2:: (gnutls_pubkey_t KEY, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G, gnutls_datum_t * Y, unsigned FLAGS)'
'INT *note gnutls_pubkey_export_ecc_raw2:: (gnutls_pubkey_t KEY, gnutls_ecc_curve_t * CURVE, gnutls_datum_t * X, gnutls_datum_t * Y, unsigned int FLAGS)'
'INT *note gnutls_pubkey_export_ecc_x962:: (gnutls_pubkey_t KEY, gnutls_datum_t * PARAMETERS, gnutls_datum_t * ECPOINT)'


File: gnutls.info,  Node: Abstract private keys,  Next: Operations,  Prev: Abstract public keys,  Up: Abstract key types

5.1.2 Private keys
------------------

An abstract 'gnutls_privkey_t' can be initialized and freed by using the
functions below.

'INT *note gnutls_privkey_init:: (gnutls_privkey_t * KEY)'
'VOID *note gnutls_privkey_deinit:: (gnutls_privkey_t KEY)'

After initialization its values can be imported from an existing
structure like 'gnutls_x509_privkey_t', but unlike public keys it cannot
be exported.  That is to allow abstraction over keys stored in hardware
that makes available only operations.

'INT *note gnutls_privkey_import_x509:: (gnutls_privkey_t PKEY, gnutls_x509_privkey_t KEY, unsigned int FLAGS)'
'INT *note gnutls_privkey_import_pkcs11:: (gnutls_privkey_t PKEY, gnutls_pkcs11_privkey_t KEY, unsigned int FLAGS)'

Other helper functions that allow directly importing from raw X.509
structures are shown below.  Again, as with public keys, private keys
can be imported from a hardware module using URLs.

 -- Function: int gnutls_privkey_import_url (gnutls_privkey_t KEY, const
          char * URL, unsigned int FLAGS)
     KEY: A key of type 'gnutls_privkey_t'

     URL: A PKCS 11 url

     FLAGS: should be zero

     This function will import a PKCS11 or TPM URL as a private key.
     The supported URL types can be checked using
     'gnutls_url_is_supported()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.1.0

'INT *note gnutls_privkey_import_x509_raw:: (gnutls_privkey_t PKEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT, const char * PASSWORD, unsigned int FLAGS)'
'INT *note gnutls_privkey_get_pk_algorithm:: (gnutls_privkey_t KEY, unsigned int * BITS)'
'GNUTLS_PRIVKEY_TYPE_T *note gnutls_privkey_get_type:: (gnutls_privkey_t KEY)'
'INT *note gnutls_privkey_status:: (gnutls_privkey_t KEY)'

In order to support cryptographic operations using an external API, the
following function is provided.  This allows for a simple extensibility
API without resorting to PKCS #11.

 -- Function: int gnutls_privkey_import_ext4 (gnutls_privkey_t PKEY,
          void * USERDATA, gnutls_privkey_sign_data_func SIGN_DATA_FN,
          gnutls_privkey_sign_hash_func SIGN_HASH_FN,
          gnutls_privkey_decrypt_func DECRYPT_FN,
          gnutls_privkey_deinit_func DEINIT_FN, gnutls_privkey_info_func
          INFO_FN, unsigned int FLAGS)
     PKEY: The private key

     USERDATA: private data to be provided to the callbacks

     SIGN_DATA_FN: callback for signature operations (may be 'NULL' )

     SIGN_HASH_FN: callback for signature operations (may be 'NULL' )

     DECRYPT_FN: callback for decryption operations (may be 'NULL' )

     DEINIT_FN: a deinitialization function

     INFO_FN: returns info about the public key algorithm (should not be
     'NULL' )

     FLAGS: Flags for the import

     This function will associate the given callbacks with the
     'gnutls_privkey_t' type.  At least one of the callbacks must be
     non-null.  If a deinitialization function is provided then flags is
     assumed to contain 'GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE' .

     Note that in contrast with the signing function of
     'gnutls_privkey_import_ext3()' , the signing functions provided to
     this function take explicitly the signature algorithm as parameter
     and different functions are provided to sign the data and hashes.

     The 'sign_hash_fn' is to be called to sign pre-hashed data.  The
     input to the callback is the output of the hash (such as SHA256)
     corresponding to the signature algorithm.  For RSA PKCS'1'
     signatures, the signature algorithm can be set to
     'GNUTLS_SIGN_RSA_RAW' , and in that case the data should be handled
     as if they were an RSA PKCS'1' DigestInfo structure.

     The 'sign_data_fn' is to be called to sign data.  The input data
     will be he data to be signed (and hashed), with the provided
     signature algorithm.  This function is to be used for signature
     algorithms like Ed25519 which cannot take pre-hashed data as input.

     When both 'sign_data_fn' and 'sign_hash_fn' functions are provided
     they must be able to operate on all the supported signature
     algorithms, unless prohibited by the type of the algorithm (e.g.,
     as with Ed25519).

     The 'info_fn' must provide information on the signature algorithms
     supported by this private key, and should support the flags
     'GNUTLS_PRIVKEY_INFO_PK_ALGO' ,
     'GNUTLS_PRIVKEY_INFO_HAVE_SIGN_ALGO' and
     'GNUTLS_PRIVKEY_INFO_PK_ALGO_BITS' .  It must return -1 on unknown
     flags.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.6.0

On the private keys where exporting of parameters is possible (i.e.,
software keys), the following functions are also available.

'INT *note gnutls_privkey_export_rsa_raw2:: (gnutls_privkey_t KEY, gnutls_datum_t * M, gnutls_datum_t * E, gnutls_datum_t * D, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * U, gnutls_datum_t * E1, gnutls_datum_t * E2, unsigned int FLAGS)'
'INT *note gnutls_privkey_export_dsa_raw2:: (gnutls_privkey_t KEY, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G, gnutls_datum_t * Y, gnutls_datum_t * X, unsigned int FLAGS)'
'INT *note gnutls_privkey_export_ecc_raw2:: (gnutls_privkey_t KEY, gnutls_ecc_curve_t * CURVE, gnutls_datum_t * X, gnutls_datum_t * Y, gnutls_datum_t * K, unsigned int FLAGS)'


File: gnutls.info,  Node: Operations,  Prev: Abstract private keys,  Up: Abstract key types

5.1.3 Operations
----------------

The abstract key types can be used to access signing and signature
verification operations with the underlying keys.

 -- Function: int gnutls_pubkey_verify_data2 (gnutls_pubkey_t PUBKEY,
          gnutls_sign_algorithm_t ALGO, unsigned int FLAGS, const
          gnutls_datum_t * DATA, const gnutls_datum_t * SIGNATURE)
     PUBKEY: Holds the public key

     ALGO: The signature algorithm used

     FLAGS: Zero or an OR list of 'gnutls_certificate_verify_flags'

     DATA: holds the signed data

     SIGNATURE: contains the signature

     This function will verify the given signed data, using the
     parameters from the certificate.

     *Returns:* In case of a verification failure
     'GNUTLS_E_PK_SIG_VERIFY_FAILED' is returned, and zero or positive
     code on success.  For known to be insecure signatures this function
     will return 'GNUTLS_E_INSUFFICIENT_SECURITY' unless the flag
     'GNUTLS_VERIFY_ALLOW_BROKEN' is specified.

     *Since:* 3.0

 -- Function: int gnutls_pubkey_verify_hash2 (gnutls_pubkey_t KEY,
          gnutls_sign_algorithm_t ALGO, unsigned int FLAGS, const
          gnutls_datum_t * HASH, const gnutls_datum_t * SIGNATURE)
     KEY: Holds the public key

     ALGO: The signature algorithm used

     FLAGS: Zero or an OR list of 'gnutls_certificate_verify_flags'

     HASH: holds the hash digest to be verified

     SIGNATURE: contains the signature

     This function will verify the given signed digest, using the
     parameters from the public key.  Note that unlike
     'gnutls_privkey_sign_hash()' , this function accepts a signature
     algorithm instead of a digest algorithm.  You can use
     'gnutls_pk_to_sign()' to get the appropriate value.

     *Returns:* In case of a verification failure
     'GNUTLS_E_PK_SIG_VERIFY_FAILED' is returned, and zero or positive
     code on success.  For known to be insecure signatures this function
     will return 'GNUTLS_E_INSUFFICIENT_SECURITY' unless the flag
     'GNUTLS_VERIFY_ALLOW_BROKEN' is specified.

     *Since:* 3.0

 -- Function: int gnutls_pubkey_encrypt_data (gnutls_pubkey_t KEY,
          unsigned int FLAGS, const gnutls_datum_t * PLAINTEXT,
          gnutls_datum_t * CIPHERTEXT)
     KEY: Holds the public key

     FLAGS: should be 0 for now

     PLAINTEXT: The data to be encrypted

     CIPHERTEXT: contains the encrypted data

     This function will encrypt the given data, using the public key.
     On success the 'ciphertext' will be allocated using
     'gnutls_malloc()' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.0

 -- Function: int gnutls_privkey_sign_data (gnutls_privkey_t SIGNER,
          gnutls_digest_algorithm_t HASH, unsigned int FLAGS, const
          gnutls_datum_t * DATA, gnutls_datum_t * SIGNATURE)
     SIGNER: Holds the key

     HASH: should be a digest algorithm

     FLAGS: Zero or one of 'gnutls_privkey_flags_t'

     DATA: holds the data to be signed

     SIGNATURE: will contain the signature allocated with
     'gnutls_malloc()'

     This function will sign the given data using a signature algorithm
     supported by the private key.  Signature algorithms are always used
     together with a hash functions.  Different hash functions may be
     used for the RSA algorithm, but only the SHA family for the DSA
     keys.

     You may use 'gnutls_pubkey_get_preferred_hash_algorithm()' to
     determine the hash algorithm.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

 -- Function: int gnutls_privkey_sign_hash (gnutls_privkey_t SIGNER,
          gnutls_digest_algorithm_t HASH_ALGO, unsigned int FLAGS, const
          gnutls_datum_t * HASH_DATA, gnutls_datum_t * SIGNATURE)
     SIGNER: Holds the signer's key

     HASH_ALGO: The hash algorithm used

     FLAGS: Zero or one of 'gnutls_privkey_flags_t'

     HASH_DATA: holds the data to be signed

     SIGNATURE: will contain newly allocated signature

     This function will sign the given hashed data using a signature
     algorithm supported by the private key.  Signature algorithms are
     always used together with a hash functions.  Different hash
     functions may be used for the RSA algorithm, but only SHA-XXX for
     the DSA keys.

     You may use 'gnutls_pubkey_get_preferred_hash_algorithm()' to
     determine the hash algorithm.

     The flags may be 'GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA' or
     'GNUTLS_PRIVKEY_SIGN_FLAG_RSA_PSS' .  In the former case this
     function will ignore 'hash_algo' and perform a raw PKCS1 signature,
     and in the latter an RSA-PSS signature will be generated.

     Note that, not all algorithm support signing already hashed data.
     When signing with Ed25519, 'gnutls_privkey_sign_data()' should be
     used.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

 -- Function: int gnutls_privkey_decrypt_data (gnutls_privkey_t KEY,
          unsigned int FLAGS, const gnutls_datum_t * CIPHERTEXT,
          gnutls_datum_t * PLAINTEXT)
     KEY: Holds the key

     FLAGS: zero for now

     CIPHERTEXT: holds the data to be decrypted

     PLAINTEXT: will contain the decrypted data, allocated with
     'gnutls_malloc()'

     This function will decrypt the given data using the algorithm
     supported by the private key.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

Signing existing structures, such as certificates, CRLs, or certificate
requests, as well as associating public keys with structures is also
possible using the key abstractions.

 -- Function: int gnutls_x509_crq_set_pubkey (gnutls_x509_crq_t CRQ,
          gnutls_pubkey_t KEY)
     CRQ: should contain a 'gnutls_x509_crq_t' type

     KEY: holds a public key

     This function will set the public parameters from the given public
     key to the request.  The 'key' can be deallocated after that.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

 -- Function: int gnutls_x509_crt_set_pubkey (gnutls_x509_crt_t CRT,
          gnutls_pubkey_t KEY)
     CRT: should contain a 'gnutls_x509_crt_t' type

     KEY: holds a public key

     This function will set the public parameters from the given public
     key to the certificate.  The 'key' can be deallocated after that.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0
'INT *note gnutls_x509_crt_privkey_sign:: (gnutls_x509_crt_t CRT, gnutls_x509_crt_t ISSUER, gnutls_privkey_t ISSUER_KEY, gnutls_digest_algorithm_t DIG, unsigned int FLAGS)'
'INT *note gnutls_x509_crl_privkey_sign:: (gnutls_x509_crl_t CRL, gnutls_x509_crt_t ISSUER, gnutls_privkey_t ISSUER_KEY, gnutls_digest_algorithm_t DIG, unsigned int FLAGS)'
'INT *note gnutls_x509_crq_privkey_sign:: (gnutls_x509_crq_t CRQ, gnutls_privkey_t KEY, gnutls_digest_algorithm_t DIG, unsigned int FLAGS)'


File: gnutls.info,  Node: Application-specific keys,  Next: Smart cards and HSMs,  Prev: Abstract key types,  Up: Hardware security modules and abstract key types

5.2 System and application-specific keys
========================================

5.2.1 System-specific keys
--------------------------

In several systems there are keystores which allow to read, store and
use certificates and private keys.  For these systems GnuTLS provides
the system-key API in 'gnutls/system-keys.h'.  That API provides the
ability to iterate through all stored keys, add and delete keys as well
as use these keys using a URL which starts with "system:".  The format
of the URLs is system-specific.  The 'systemkey' tool is also provided
to assist in listing keys and debugging.

The systems supported via this API are the following.
   * Windows Cryptography API (CNG)

 -- Function: int gnutls_system_key_iter_get_info
          (gnutls_system_key_iter_t * ITER, unsigned CERT_TYPE, char **
          CERT_URL, char ** KEY_URL, char ** LABEL, gnutls_datum_t *
          DER, unsigned int FLAGS)
     ITER: an iterator of the system keys (must be set to 'NULL'
     initially)

     CERT_TYPE: A value of gnutls_certificate_type_t which indicates the
     type of certificate to look for

     CERT_URL: The certificate URL of the pair (may be 'NULL' )

     KEY_URL: The key URL of the pair (may be 'NULL' )

     LABEL: The friendly name (if any) of the pair (may be 'NULL' )

     DER: if non-NULL the DER data of the certificate

     FLAGS: should be zero

     This function will return on each call a certificate and key pair
     URLs, as well as a label associated with them, and the DER-encoded
     certificate.  When the iteration is complete it will return
     'GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE' .

     Typically 'cert_type' should be 'GNUTLS_CRT_X509' .

     All values set are allocated and must be cleared using
     'gnutls_free()' ,

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.4.0

'VOID *note gnutls_system_key_iter_deinit:: (gnutls_system_key_iter_t ITER)'
'INT *note gnutls_system_key_add_x509:: (gnutls_x509_crt_t CRT, gnutls_x509_privkey_t PRIVKEY, const char * LABEL, char ** CERT_URL, char ** KEY_URL)'
'INT *note gnutls_system_key_delete:: (const char * CERT_URL, const char * KEY_URL)'

5.2.2 Application-specific keys
-------------------------------

For systems where GnuTLS doesn't provide a system specific store, it may
often be desirable to define a custom class of keys that are identified
via URLs and available to GnuTLS calls such as *note
gnutls_certificate_set_x509_key_file2::.  Such keys can be registered
using the API in 'gnutls/urls.h'.  The function which registers such
keys is *note gnutls_register_custom_url::.

 -- Function: int gnutls_register_custom_url (const gnutls_custom_url_st
          * ST)
     ST: A 'gnutls_custom_url_st' structure

     Register a custom URL. This will affect the following functions:
     'gnutls_url_is_supported()' , 'gnutls_privkey_import_url()' ,
     gnutls_pubkey_import_url, 'gnutls_x509_crt_import_url()' and all
     functions that depend on them, e.g.,
     'gnutls_certificate_set_x509_key_file2()' .

     The provided structure and callback functions must be valid
     throughout the lifetime of the process.  The registration of an
     existing URL type will fail with 'GNUTLS_E_INVALID_REQUEST' .
     Since GnuTLS 3.5.0 this function can be used to override the
     builtin URLs.

     This function is not thread safe.

     *Returns:* returns zero if the given structure was imported or a
     negative value otherwise.

     *Since:* 3.4.0

The input to this function are three callback functions as well as the
prefix of the URL, (e.g., "mypkcs11:") and the length of the prefix.
The types of the callbacks are shown below, and are expected to use the
exported gnutls functions to import the keys and certificates.  E.g., a
typical 'import_key' callback should use *note
gnutls_privkey_import_ext4::.

     typedef int (*gnutls_privkey_import_url_func)(gnutls_privkey_t pkey,
                                                   const char *url,
                                                   unsigned flags);

     typedef int (*gnutls_x509_crt_import_url_func)(gnutls_x509_crt_t pkey,
                                                    const char *url,
                                                    unsigned flags);

     /* The following callbacks are optional */

     /* This is to enable gnutls_pubkey_import_url() */
     typedef int (*gnutls_pubkey_import_url_func)(gnutls_pubkey_t pkey,
     					     const char *url, unsigned flags);

     /* This is to allow constructing a certificate chain. It will be provided
      * the initial certificate URL and the certificate to find its issuer, and must
      * return zero and the DER encoding of the issuer's certificate. If not available,
      * it should return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE. */
     typedef int (*gnutls_get_raw_issuer_func)(const char *url, gnutls_x509_crt_t crt,
     					  gnutls_datum_t *issuer_der, unsigned flags);

     typedef struct custom_url_st {
             const char *name;
             unsigned name_size;
             gnutls_privkey_import_url_func import_key;
             gnutls_x509_crt_import_url_func import_crt;
             gnutls_pubkey_import_url_func import_pubkey;
     	gnutls_get_raw_issuer_func get_issuer;
     } gnutls_custom_url_st;


File: gnutls.info,  Node: Smart cards and HSMs,  Next: Trusted Platform Module,  Prev: Application-specific keys,  Up: Hardware security modules and abstract key types

5.3 Smart cards and HSMs
========================

In this section we present the smart-card and hardware security module
(HSM) support in GnuTLS using PKCS #11 [*note PKCS11::].  Hardware
security modules and smart cards provide a way to store private keys and
perform operations on them without exposing them.  This decouples
cryptographic keys from the applications that use them and provide an
additional security layer against cryptographic key extraction.  Since
this can also be achieved in software components such as in Gnome
keyring, we will use the term security module to describe any
cryptographic key separation subsystem.

PKCS #11 is plugin API allowing applications to access cryptographic
operations on a security module, as well as to objects residing on it.
PKCS #11 modules exist for hardware tokens such as smart cards(1),
cryptographic tokens, as well as for software modules like Gnome
Keyring.  The objects residing on a security module may be certificates,
public keys, private keys or secret keys.  Of those certificates and
public/private key pairs can be used with GnuTLS.  PKCS #11's main
advantage is that it allows operations on private key objects such as
decryption and signing without exposing the key.  In GnuTLS the PKCS #11
functionality is available in 'gnutls/pkcs11.h'.

[image src="pkcs11-vision.png"]



Figure 5.1: PKCS #11 module usage.

* Menu:

* PKCS11 Initialization::
* PKCS11 Manual Initialization::
* Accessing objects that require a PIN::
* Reading objects::
* Writing objects::
* PKCS11 Low Level Access::
* Using a PKCS11 token with TLS::
* Verifying certificates over PKCS11::
* p11tool Invocation::

   ---------- Footnotes ----------

   (1) For example, OpenSC-supported cards.


File: gnutls.info,  Node: PKCS11 Initialization,  Next: PKCS11 Manual Initialization,  Up: Smart cards and HSMs

5.3.1 Initialization
--------------------

To allow all GnuTLS applications to transparently access smart cards and
tokens, PKCS #11 is automatically initialized during the first call of a
PKCS #11 related function, in a thread safe way.  The default
initialization process, utilizes p11-kit configuration, and loads any
appropriate PKCS #11 modules.  The p11-kit configuration files(1) are
typically stored in '/etc/pkcs11/modules/'.  For example a file that
will instruct GnuTLS to load the OpenSC module, could be named
'/etc/pkcs11/modules/opensc.module' and contain the following:

     module: /usr/lib/opensc-pkcs11.so

If you use these configuration files, then there is no need for other
initialization in GnuTLS, except for the PIN and token callbacks (see
next section).  In several cases, however, it is desirable to limit
badly behaving modules (e.g., modules that add an unacceptable delay on
initialization) to single applications.  That can be done using the
"enable-in:" option followed by the base name of applications that this
module should be used.

It is also possible to manually initialize or even disable the PKCS #11
subsystem if the default settings are not desirable or not available
(see *note PKCS11 Manual Initialization:: for more information).

Note that, PKCS #11 modules behave in a peculiar way after a fork; they
require a reinitialization of all the used PKCS #11 resources.  While
GnuTLS automates that process, there are corner cases where it is not
possible to handle it correctly in an automated way(2).  For that, it is
recommended not to mix fork() and PKCS #11 module usage.  It is
recommended to initialize and use any PKCS #11 resources in a single
process.

Older versions of GnuTLS required to call *note gnutls_pkcs11_reinit::
after a fork() call; since 3.3.0 this is no longer required.

   ---------- Footnotes ----------

   (1) <https://p11-glue.github.io/p11-glue/p11-kit.html>

   (2) For example when an open session is to be reinitialized, but the
PIN is not available to GnuTLS (e.g., it was entered at a pinpad).


File: gnutls.info,  Node: PKCS11 Manual Initialization,  Next: Accessing objects that require a PIN,  Prev: PKCS11 Initialization,  Up: Smart cards and HSMs

5.3.2 Manual initialization of user-specific modules
----------------------------------------------------

In systems where one cannot rely on a globally available p11-kit
configuration to be available, it is still possible to utilize PKCS #11
objects.  That can be done by loading directly the PKCS #11 shared
module in the application using *note gnutls_pkcs11_add_provider::,
after having called *note gnutls_pkcs11_init:: specifying the
'GNUTLS_PKCS11_FLAG_MANUAL' flag.

 -- Function: int gnutls_pkcs11_add_provider (const char * NAME, const
          char * PARAMS)
     NAME: The filename of the module

     PARAMS: should be NULL or a known string (see description)

     This function will load and add a PKCS 11 module to the module list
     used in gnutls.  After this function is called the module will be
     used for PKCS 11 operations.

     When loading a module to be used for certificate verification, use
     the string 'trusted' as 'params' .

     Note that this function is not thread safe.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0

In that case, the application will only have access to the modules
explicitly loaded.  If the 'GNUTLS_PKCS11_FLAG_MANUAL' flag is specified
and no calls to *note gnutls_pkcs11_add_provider:: are made, then the
PKCS #11 functionality is effectively disabled.

 -- Function: int gnutls_pkcs11_init (unsigned int FLAGS, const char *
          DEPRECATED_CONFIG_FILE)
     FLAGS: An ORed sequence of 'GNUTLS_PKCS11_FLAG_' *

     DEPRECATED_CONFIG_FILE: either NULL or the location of a deprecated
     configuration file

     This function will initialize the PKCS 11 subsystem in gnutls.  It
     will read configuration files if 'GNUTLS_PKCS11_FLAG_AUTO' is used
     or allow you to independently load PKCS 11 modules using
     'gnutls_pkcs11_add_provider()' if 'GNUTLS_PKCS11_FLAG_MANUAL' is
     specified.

     You don't need to call this function since GnuTLS 3.3.0 because it
     is being called during the first request PKCS 11 operation.  That
     call will assume the 'GNUTLS_PKCS11_FLAG_AUTO' flag.  If another
     flags are required then it must be called independently prior to
     any PKCS 11 operation.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 2.12.0


File: gnutls.info,  Node: Accessing objects that require a PIN,  Next: Reading objects,  Prev: PKCS11 Manual Initialization,  Up: Smart cards and HSMs

5.3.3 Accessing objects that require a PIN
------------------------------------------

Objects stored in token such as a private keys are typically protected
from access by a PIN or password.  This PIN may be required to either
read the object (if allowed) or to perform operations with it.  To allow
obtaining the PIN when accessing a protected object, as well as probe
the user to insert the token the following functions allow to set a
callback.

'VOID *note gnutls_pkcs11_set_token_function:: (gnutls_pkcs11_token_callback_t FN, void * USERDATA)'
'VOID *note gnutls_pkcs11_set_pin_function:: (gnutls_pin_callback_t FN, void * USERDATA)'
'INT *note gnutls_pkcs11_add_provider:: (const char * NAME, const char * PARAMS)'
'GNUTLS_PIN_CALLBACK_T *note gnutls_pkcs11_get_pin_function:: (void ** USERDATA)'

The callback is of type 'gnutls_pin_callback_t' and will have as input
the provided userdata, the PIN attempt number, a URL describing the
token, a label describing the object and flags.  The PIN must be at most
of 'pin_max' size and must be copied to pin variable.  The function must
return 0 on success or a negative error code otherwise.

typedef int (*gnutls_pin_callback_t) (void *userdata, int attempt,
                                      const char *token_url,
                                      const char *token_label,
                                      unsigned int flags,
                                      char *pin, size_t pin_max);

The flags are of 'gnutls_pin_flag_t' type and are explained below.

'GNUTLS_PIN_USER'
     The PIN for the user.
'GNUTLS_PIN_SO'
     The PIN for the security officer (admin).
'GNUTLS_PIN_FINAL_TRY'
     This is the final try before blocking.
'GNUTLS_PIN_COUNT_LOW'
     Few tries remain before token blocks.
'GNUTLS_PIN_CONTEXT_SPECIFIC'
     The PIN is for a specific action and key like signing.
'GNUTLS_PIN_WRONG'
     Last given PIN was not correct.


Figure 5.2: The 'gnutls_pin_flag_t' enumeration.

Note that due to limitations of PKCS #11 there are issues when multiple
libraries are sharing a module.  To avoid this problem GnuTLS uses
p11-kit that provides a middleware to control access to resources over
the multiple users.

To avoid conflicts with multiple registered callbacks for PIN functions,
*note gnutls_pkcs11_get_pin_function:: may be used to check for any
previously set functions.  In addition context specific PIN functions
are allowed, e.g., by using functions below.

'VOID *note gnutls_certificate_set_pin_function:: (gnutls_certificate_credentials_t CRED, gnutls_pin_callback_t FN, void * USERDATA)'
'VOID *note gnutls_pubkey_set_pin_function:: (gnutls_pubkey_t KEY, gnutls_pin_callback_t FN, void * USERDATA)'
'VOID *note gnutls_privkey_set_pin_function:: (gnutls_privkey_t KEY, gnutls_pin_callback_t FN, void * USERDATA)'
'VOID *note gnutls_pkcs11_obj_set_pin_function:: (gnutls_pkcs11_obj_t OBJ, gnutls_pin_callback_t FN, void * USERDATA)'
'VOID *note gnutls_x509_crt_set_pin_function:: (gnutls_x509_crt_t CRT, gnutls_pin_callback_t FN, void * USERDATA)'


File: gnutls.info,  Node: Reading objects,  Next: Writing objects,  Prev: Accessing objects that require a PIN,  Up: Smart cards and HSMs

5.3.4 Reading objects
---------------------

All PKCS #11 objects are referenced by GnuTLS functions by URLs as
described in [*note PKCS11URI::].  This allows for a consistent naming
of objects across systems and applications in the same system.  For
example a public key on a smart card may be referenced as:

     pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315; \
     manufacturer=EnterSafe;object=test1;type=public;\
     id=32f153f3e37990b08624141077ca5dec2d15faed

while the smart card itself can be referenced as:
     pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315;manufacturer=EnterSafe

Objects stored in a PKCS #11 token can typically be extracted if they
are not marked as sensitive.  Usually only private keys are marked as
sensitive and cannot be extracted, while certificates and other data can
be retrieved.  The functions that can be used to enumerate and access
objects are shown below.

'INT *note gnutls_pkcs11_obj_list_import_url4:: (gnutls_pkcs11_obj_t ** P_LIST, unsigned int * N_LIST, const char * URL, unsigned int FLAGS)'
'INT *note gnutls_pkcs11_obj_import_url:: (gnutls_pkcs11_obj_t OBJ, const char * URL, unsigned int FLAGS)'
'INT *note gnutls_pkcs11_obj_export_url:: (gnutls_pkcs11_obj_t OBJ, gnutls_pkcs11_url_type_t DETAILED, char ** URL)'

 -- Function: int gnutls_pkcs11_obj_get_info (gnutls_pkcs11_obj_t OBJ,
          gnutls_pkcs11_obj_info_t ITYPE, void * OUTPUT, size_t *
          OUTPUT_SIZE)
     OBJ: should contain a 'gnutls_pkcs11_obj_t' type

     ITYPE: Denotes the type of information requested

     OUTPUT: where output will be stored

     OUTPUT_SIZE: contains the maximum size of the output buffer and
     will be overwritten with the actual size.

     This function will return information about the PKCS11 certificate
     such as the label, id as well as token information where the key is
     stored.

     When output is text, a null terminated string is written to
     'output' and its string length is written to 'output_size' (without
     null terminator).  If the buffer is too small, 'output_size' will
     contain the expected buffer size (with null terminator for text)
     and return 'GNUTLS_E_SHORT_MEMORY_BUFFER' .

     In versions previously to 3.6.0 this function included the null
     terminator to 'output_size' .  After 3.6.0 the output size doesn't
     include the terminator character.

     *Returns:* 'GNUTLS_E_SUCCESS' (0) on success or a negative error
     code on error.

     *Since:* 2.12.0

'INT *note gnutls_x509_crt_import_pkcs11:: (gnutls_x509_crt_t CRT, gnutls_pkcs11_obj_t PKCS11_CRT)'
'INT *note gnutls_x509_crt_import_url:: (gnutls_x509_crt_t CRT, const char * URL, unsigned int FLAGS)'
'INT *note gnutls_x509_crt_list_import_pkcs11:: (gnutls_x509_crt_t * CERTS, unsigned int CERT_MAX, gnutls_pkcs11_obj_t * const OBJS, unsigned int FLAGS)'

Properties of the physical token can also be accessed and altered with
GnuTLS.  For example data in a token can be erased (initialized), PIN
can be altered, etc.

'INT *note gnutls_pkcs11_token_init:: (const char * TOKEN_URL, const char * SO_PIN, const char * LABEL)'
'INT *note gnutls_pkcs11_token_get_url:: (unsigned int SEQ, gnutls_pkcs11_url_type_t DETAILED, char ** URL)'
'INT *note gnutls_pkcs11_token_get_info:: (const char * URL, gnutls_pkcs11_token_info_t TTYPE, void * OUTPUT, size_t * OUTPUT_SIZE)'
'INT *note gnutls_pkcs11_token_get_flags:: (const char * URL, unsigned int * FLAGS)'
'INT *note gnutls_pkcs11_token_set_pin:: (const char * TOKEN_URL, const char * OLDPIN, const char * NEWPIN, unsigned int FLAGS)'

The following examples demonstrate the usage of the API. The first
example will list all available PKCS #11 tokens in a system and the
latter will list all certificates in a token that have a corresponding
private key.

     int i;
     char* url;

     gnutls_global_init();

     for (i=0;;i++)
       {
         ret = gnutls_pkcs11_token_get_url(i, &url);
         if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
           break;

         if (ret < 0)
           exit(1);

         fprintf(stdout, "Token[%d]: URL: %s\n", i, url);
         gnutls_free(url);
       }
     gnutls_global_deinit();

/* This example code is placed in the public domain. */

#include <config.h>
#include <gnutls/gnutls.h>
#include <gnutls/pkcs11.h>
#include <stdio.h>
#include <stdlib.h>

#define URL "pkcs11:URL"

int main(int argc, char **argv)
{
        gnutls_pkcs11_obj_t *obj_list;
        gnutls_x509_crt_t xcrt;
        unsigned int obj_list_size = 0;
        gnutls_datum_t cinfo;
        int ret;
        unsigned int i;

        ret = gnutls_pkcs11_obj_list_import_url4(&obj_list, &obj_list_size, URL,
                                                GNUTLS_PKCS11_OBJ_FLAG_CRT|
                                                GNUTLS_PKCS11_OBJ_FLAG_WITH_PRIVKEY);
        if (ret < 0)
                return -1;

        /* now all certificates are in obj_list */
        for (i = 0; i < obj_list_size; i++) {

                gnutls_x509_crt_init(&xcrt);

                gnutls_x509_crt_import_pkcs11(xcrt, obj_list[i]);

                gnutls_x509_crt_print(xcrt, GNUTLS_CRT_PRINT_FULL, &cinfo);

                fprintf(stdout, "cert[%d]:\n %s\n\n", i, cinfo.data);

                gnutls_free(cinfo.data);
                gnutls_x509_crt_deinit(xcrt);
        }

        for (i = 0; i < obj_list_size; i++)
                gnutls_pkcs11_obj_deinit(obj_list[i]);
	gnutls_free(obj_list);

        return 0;
}


File: gnutls.info,  Node: Writing objects,  Next: PKCS11 Low Level Access,  Prev: Reading objects,  Up: Smart cards and HSMs

5.3.5 Writing objects
---------------------

With GnuTLS you can copy existing private keys and certificates to a
token.  Note that when copying private keys it is recommended to mark
them as sensitive using the 'GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE' to
prevent its extraction.  An object can be marked as private using the
flag 'GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE', to require PIN to be entered
before accessing the object (for operations or otherwise).

 -- Function: int gnutls_pkcs11_copy_x509_privkey2 (const char *
          TOKEN_URL, gnutls_x509_privkey_t KEY, const char * LABEL,
          const gnutls_datum_t * CID, unsigned int KEY_USAGE, unsigned
          int FLAGS)
     TOKEN_URL: A PKCS '11' URL specifying a token

     KEY: A private key

     LABEL: A name to be used for the stored data

     CID: The CKA_ID to set for the object -if NULL, the ID will be
     derived from the public key

     KEY_USAGE: One of GNUTLS_KEY_*

     FLAGS: One of GNUTLS_PKCS11_OBJ_* flags

     This function will copy a private key into a PKCS '11' token
     specified by a URL.

     Since 3.6.3 the objects are marked as sensitive by default unless
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_SENSITIVE' is specified.

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.4.0

 -- Function: int gnutls_pkcs11_copy_x509_crt2 (const char * TOKEN_URL,
          gnutls_x509_crt_t CRT, const char * LABEL, const
          gnutls_datum_t * CID, unsigned int FLAGS)
     TOKEN_URL: A PKCS '11' URL specifying a token

     CRT: The certificate to copy

     LABEL: The name to be used for the stored data

     CID: The CKA_ID to set for the object -if NULL, the ID will be
     derived from the public key

     FLAGS: One of GNUTLS_PKCS11_OBJ_FLAG_*

     This function will copy a certificate into a PKCS '11' token
     specified by a URL. Valid flags to mark the certificate:
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED' ,
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE' ,
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_CA' ,
     'GNUTLS_PKCS11_OBJ_FLAG_MARK_ALWAYS_AUTH' .

     *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
     otherwise a negative error value.

     *Since:* 3.4.0

 -- Function: int gnutls_pkcs11_delete_url (const char * OBJECT_URL,
          unsigned int FLAGS)
     OBJECT_URL: The URL of the object to delete.

     FLAGS: One of GNUTLS_PKCS11_OBJ_* flags

     This function will delete objects matching the given URL. Note that
     not all tokens support the delete operation.

     *Returns:* On success, the number of objects deleted is returned,
     otherwise a negative error value.

     *Since:* 2.12.0


File: gnutls.info,  Node: PKCS11 Low Level Access,  Next: Using a PKCS11 token with TLS,  Prev: Writing objects,  Up: Smart cards and HSMs

5.3.6 Low Level Access
----------------------

When it is needed to use PKCS#11 functionality which is not wrapped by
GnuTLS, it is possible to extract the PKCS#11 session, object or token
pointers.  That allows an application to still access the low-level
functionality, while at the same time take advantage of the URI
addressing scheme supported by GnuTLS.

 -- Function: int gnutls_pkcs11_token_get_ptr (const char * URL, void **
          PTR, unsigned long * SLOT_ID, unsigned int FLAGS)
     URL: should contain a PKCS'11' URL identifying a token

     PTR: will contain the CK_FUNCTION_LIST_PTR pointer

     SLOT_ID: will contain the slot_id (may be 'NULL' )

     FLAGS: should be zero

     This function will return the function pointer of the specified
     token by the URL. The returned pointers are valid until gnutls is
     deinitialized, c.f.  '_global_deinit()' .

     *Returns:* 'GNUTLS_E_SUCCESS' (0) on success or a negative error
     code on error.

     *Since:* 3.6.3

 -- Function: int gnutls_pkcs11_obj_get_ptr (gnutls_pkcs11_obj_t OBJ,
          void ** PTR, void ** SESSION, void ** OHANDLE, unsigned long *
          SLOT_ID, unsigned int FLAGS)
     OBJ: should contain a 'gnutls_pkcs11_obj_t' type

     PTR: will contain the CK_FUNCTION_LIST_PTR pointer (may be 'NULL' )

     SESSION: will contain the CK_SESSION_HANDLE of the object

     OHANDLE: will contain the CK_OBJECT_HANDLE of the object

     SLOT_ID: the identifier of the slot (may be 'NULL' )

     FLAGS: Or sequence of GNUTLS_PKCS11_OBJ_* flags

     Obtains the PKCS'11' session handles of an object.  'session' and
     'ohandle' must be deinitialized by the caller.  The returned
     pointers are independent of the 'obj' lifetime.

     *Returns:* 'GNUTLS_E_SUCCESS' (0) on success or a negative error
     code on error.

     *Since:* 3.6.3


File: gnutls.info,  Node: Using a PKCS11 token with TLS,  Next: Verifying certificates over PKCS11,  Prev: PKCS11 Low Level Access,  Up: Smart cards and HSMs

5.3.7 Using a PKCS #11 token with TLS
-------------------------------------

It is possible to use a PKCS #11 token to a TLS session, as shown in
*note ex-pkcs11-client::.  In addition the following functions can be
used to load PKCS #11 key and certificates by specifying a PKCS #11 URL
instead of a filename.

'INT *note gnutls_certificate_set_x509_trust_file:: (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)'
'INT *note gnutls_certificate_set_x509_key_file2:: (gnutls_certificate_credentials_t RES, const char * CERTFILE, const char * KEYFILE, gnutls_x509_crt_fmt_t TYPE, const char * PASS, unsigned int FLAGS)'


File: gnutls.info,  Node: Verifying certificates over PKCS11,  Next: p11tool Invocation,  Prev: Using a PKCS11 token with TLS,  Up: Smart cards and HSMs

5.3.8 Verifying certificates over PKCS #11
------------------------------------------

The PKCS #11 API can be used to allow all applications in the same
operating system to access shared cryptographic keys and certificates in
a uniform way, as in *note Figure 5.1: fig-pkcs11-vision.  That way
applications could load their trusted certificate list, as well as user
certificates from a common PKCS #11 module.  Such a provider is the
p11-kit trust storage module(1) and it provides access to the trusted
Root CA certificates in a system.  That provides a more dynamic list of
Root CA certificates, as opposed to a static list in a file or
directory.

That store, allows for blacklisting of CAs or certificates, as well as
categorization of the Root CAs (Web verification, Code signing, etc.),
in addition to restricting their purpose via stapled extensions(2).
GnuTLS will utilize the p11-kit trust module as the default trust store
if configured to; i.e., if '-with-default-trust-store-pkcs11=pkcs11:' is
given to the configure script.

   ---------- Footnotes ----------

   (1) <https://p11-glue.github.io/p11-glue/trust-module.html>

   (2) See the 'Restricting the scope of CA certificates' post at
<https://nmav.gnutls.org/2016/06/restricting-scope-of-ca-certificates.html>


File: gnutls.info,  Node: p11tool Invocation,  Prev: Verifying certificates over PKCS11,  Up: Smart cards and HSMs

5.3.9 Invoking p11tool
----------------------

Program that allows operations on PKCS #11 smart cards and security
modules.

To use PKCS #11 tokens with GnuTLS the p11-kit configuration files need
to be setup.  That is create a .module file in /etc/pkcs11/modules with
the contents 'module: /path/to/pkcs11.so'.  Alternatively the
configuration file /etc/gnutls/pkcs11.conf has to exist and contain a
number of lines of the form 'load=/usr/lib/opensc-pkcs11.so'.

You can provide the PIN to be used for the PKCS #11 operations with the
environment variables GNUTLS_PIN and GNUTLS_SO_PIN.

p11tool help/usage ('-?')
.........................

The text printed is the same whether selected with the 'help' option
('--help') or the 'more-help' option ('--more-help').  'more-help' will
print the usage text by passing it through a pager program.  'more-help'
is disabled on platforms without a working 'fork(2)' function.  The
'PAGER' environment variable is used to select the program, defaulting
to 'more'.  Both will exit with a status code of 0.

     p11tool - GnuTLS PKCS #11 tool
     Usage:  p11tool [ -<flag> [<val>] | --<name>[{=| }<val>] ]... [url]

     None:


     Tokens:

            --list-tokens          List all available tokens
            --list-token-urls      List the URLs available tokens
            --list-mechanisms      List all available mechanisms in a token
            --initialize           Initializes a PKCS #11 token
            --initialize-pin       Initializes/Resets a PKCS #11 token user PIN
            --initialize-so-pin    Initializes/Resets a PKCS #11 token security officer PIN
            --set-pin=str          Specify the PIN to use on token operations
            --set-so-pin=str       Specify the Security Officer's PIN to use on token initialization

     Object listing:

            --list-all             List all available objects in a token
            --list-all-certs       List all available certificates in a token
            --list-certs           List all certificates that have an associated private key
            --list-all-privkeys    List all available private keys in a token
            --list-privkeys        an alias for the 'list-all-privkeys' option
            --list-keys            an alias for the 'list-all-privkeys' option
            --list-all-trusted     List all available certificates marked as trusted
            --export               Export the object specified by the URL
     				- prohibits these options:
     				export-stapled
     				export-chain
     				export-pubkey
            --export-stapled       Export the certificate object specified by the URL
     				- prohibits these options:
     				export
     				export-chain
     				export-pubkey
            --export-chain         Export the certificate specified by the URL and its chain of trust
     				- prohibits these options:
     				export-stapled
     				export
     				export-pubkey
            --export-pubkey        Export the public key for a private key
     				- prohibits these options:
     				export-stapled
     				export
     				export-chain
            --info                 List information on an available object in a token
            --trusted              an alias for the 'mark-trusted' option
            --distrusted           an alias for the 'mark-distrusted' option

     Key generation:

            --generate-privkey=str Generate private-public key pair of given type
            --bits=num             Specify the number of bits for the key generate
            --curve=str            Specify the curve used for EC key generation
            --sec-param=str        Specify the security level

     Writing objects:

            --set-id=str           Set the CKA_ID (in hex) for the specified by the URL object
     				- prohibits the option 'write'
            --set-label=str        Set the CKA_LABEL for the specified by the URL object
     				- prohibits these options:
     				write
     				set-id
            --write                Writes the loaded objects to a PKCS #11 token
            --delete               Deletes the objects matching the given PKCS #11 URL
            --label=str            Sets a label for the write operation
            --id=str               Sets an ID for the write operation
            --mark-wrap            Marks the generated key to be a wrapping key
            --mark-trusted         Marks the object to be written as trusted
     				- prohibits the option 'mark-distrusted'
            --mark-distrusted      When retrieving objects, it requires the objects to be distrusted (blacklisted)
     				- prohibits the option 'mark-trusted'
            --mark-decrypt         Marks the object to be written for decryption
            --mark-sign            Marks the object to be written for signature generation
            --mark-ca              Marks the object to be written as a CA
            --mark-private         Marks the object to be written as private
            --ca                   an alias for the 'mark-ca' option
            --private              an alias for the 'mark-private' option
            --mark-always-authenticate  Marks the object to be written as always authenticate
            --secret-key=str       Provide a hex encoded secret key
            --load-privkey=file    Private key file to use
     				- file must pre-exist
            --load-pubkey=file     Public key file to use
     				- file must pre-exist
            --load-certificate=file Certificate file to use
     				- file must pre-exist

     Other options:

        -d, --debug=num            Enable debugging
     				- it must be in the range:
     				  0 to 9999
            --outfile=str          Output file
            --login                Force (user) login to token
            --so-login             Force security officer login to token
            --admin-login          an alias for the 'so-login' option
            --test-sign            Tests the signature operation of the provided object
            --sign-params=str      Sign with a specific signature algorithm
            --hash=str             Hash algorithm to use for signing
            --generate-random=num  Generate random data
        -8, --pkcs8                Use PKCS #8 format for private keys
            --inder                Use DER/RAW format for input
            --inraw                an alias for the 'inder' option
            --outder               Use DER format for output certificates, private keys, and DH parameters
            --outraw               an alias for the 'outder' option
            --provider=file        Specify the PKCS #11 provider library
            --detailed-url         Print detailed URLs
            --only-urls            Print a compact listing using only the URLs
            --batch                Disable all interaction with the tool

     Version, usage and configuration options:

        -v, --version[=arg]        output version information and exit
        -h, --help                 display extended usage information and exit
        -!, --more-help            extended usage information passed thru pager

     Options are specified by doubled hyphens and their name or by a single
     hyphen and the flag character.
     Operands and options may be intermixed.  They will be reordered.

     Program that allows operations on PKCS #11 smart cards
     and security modules.

     To use PKCS #11 tokens with GnuTLS the p11-kit configuration files need to be setup.
     That is create a .module file in /etc/pkcs11/modules with the contents 'module: /path/to/pkcs11.so'.
     Alternatively the configuration file /etc/gnutls/pkcs11.conf has to exist and contain a number
     of lines of the form 'load=/usr/lib/opensc-pkcs11.so'.

     You can provide the PIN to be used for the PKCS #11 operations with the environment variables
     GNUTLS_PIN and GNUTLS_SO_PIN.


     Please send bug reports to:  <bugs@gnutls.org>


token-related-options options
.............................

Tokens.

list-token-urls option.
.......................

This is the "list the urls available tokens" option.  This is a more
compact version of -list-tokens.

initialize-so-pin option.
.........................

This is the "initializes/resets a pkcs #11 token security officer pin"
option.  This initializes the security officer's PIN. When used
non-interactively use the GNUTLS_NEW_SO_PIN environment variables to
initialize SO's PIN.

set-pin option.
...............

This is the "specify the pin to use on token operations" option.  This
option takes a ArgumentType.STRING argument.  Alternatively the
GNUTLS_PIN environment variable may be used.

set-so-pin option.
..................

This is the "specify the security officer's pin to use on token
initialization" option.  This option takes a ArgumentType.STRING
argument.  Alternatively the GNUTLS_SO_PIN environment variable may be
used.

object-list-related-options options
...................................

Object listing.

list-all option.
................

This is the "list all available objects in a token" option.  All objects
available in the token will be listed.  That includes objects which are
potentially unaccessible using this tool.

list-all-certs option.
......................

This is the "list all available certificates in a token" option.  That
option will also provide more information on the certificates, for
example, expand the attached extensions in a trust token (like
p11-kit-trust).

list-certs option.
..................

This is the "list all certificates that have an associated private key"
option.  That option will only display certificates which have a private
key associated with them (share the same ID).

list-all-privkeys option.
.........................

This is the "list all available private keys in a token" option.  Lists
all the private keys in a token that match the specified URL.

list-privkeys option.
.....................

This is an alias for the 'list-all-privkeys' option, *note the
list-all-privkeys option documentation: p11tool list-all-privkeys.

list-keys option.
.................

This is an alias for the 'list-all-privkeys' option, *note the
list-all-privkeys option documentation: p11tool list-all-privkeys.

export-stapled option.
......................

This is the "export the certificate object specified by the url" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     export, export-chain, export-pubkey.

Exports the certificate specified by the URL while including any
attached extensions to it.  Since attached extensions are a p11-kit
extension, this option is only available on p11-kit registered trust
modules.

export-chain option.
....................

This is the "export the certificate specified by the url and its chain
of trust" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     export-stapled, export, export-pubkey.

Exports the certificate specified by the URL and generates its chain of
trust based on the stored certificates in the module.

export-pubkey option.
.....................

This is the "export the public key for a private key" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     export-stapled, export, export-chain.

Exports the public key for the specified private key

trusted option.
...............

This is an alias for the 'mark-trusted' option, *note the mark-trusted
option documentation: p11tool mark-trusted.

distrusted option.
..................

This is an alias for the 'mark-distrusted' option, *note the
mark-distrusted option documentation: p11tool mark-distrusted.

keygen-related-options options
..............................

Key generation.

generate-privkey option.
........................

This is the "generate private-public key pair of given type" option.
This option takes a ArgumentType.STRING argument.  Generates a
private-public key pair in the specified token.  Acceptable types are
RSA, ECDSA, Ed25519, and DSA. Should be combined with -sec-param or
-bits.

generate-rsa option.
....................

This is the "generate an rsa private-public key pair" option.  Generates
an RSA private-public key pair on the specified token.  Should be
combined with -sec-param or -bits.

*NOTE**: THIS OPTION IS DEPRECATED*

generate-dsa option.
....................

This is the "generate a dsa private-public key pair" option.  Generates
a DSA private-public key pair on the specified token.  Should be
combined with -sec-param or -bits.

*NOTE**: THIS OPTION IS DEPRECATED*

generate-ecc option.
....................

This is the "generate an ecdsa private-public key pair" option.
Generates an ECDSA private-public key pair on the specified token.
Should be combined with -curve, -sec-param or -bits.

*NOTE**: THIS OPTION IS DEPRECATED*

bits option.
............

This is the "specify the number of bits for the key generate" option.
This option takes a ArgumentType.NUMBER argument.  For applications
which have no key-size restrictions the -sec-param option is
recommended, as the sec-param levels will adapt to the acceptable
security levels with the new versions of gnutls.

curve option.
.............

This is the "specify the curve used for ec key generation" option.  This
option takes a ArgumentType.STRING argument.  Supported values are
secp192r1, secp224r1, secp256r1, secp384r1 and secp521r1.

sec-param option.
.................

This is the "specify the security level" option.  This option takes a
ArgumentType.STRING argument 'Security parameter'.  This is alternative
to the bits option.  Available options are [low, legacy, medium, high,
ultra].

write-object-related-options options
....................................

Writing objects.

set-id option.
..............

This is the "set the cka_id (in hex) for the specified by the url
object" option.  This option takes a ArgumentType.STRING argument.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     write.

Modifies or sets the CKA_ID in the specified by the URL object.  The ID
should be specified in hexadecimal format without a '0x' prefix.

set-label option.
.................

This is the "set the cka_label for the specified by the url object"
option.  This option takes a ArgumentType.STRING argument.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     write, set-id.

Modifies or sets the CKA_LABEL in the specified by the URL object

write option.
.............

This is the "writes the loaded objects to a pkcs #11 token" option.  It
can be used to write private, public keys, certificates or secret keys
to a token.  Must be combined with one of -load-privkey, -load-pubkey,
-load-certificate option.

When writing a certificate object, its CKA_ID is set to the same CKA_ID
of the corresponding public key, if it exists on the token; otherwise it
will be derived from the X.509 Subject Key Identifier of the
certificate.  If this behavior is undesired, write the public key to the
token beforehand.

id option.
..........

This is the "sets an id for the write operation" option.  This option
takes a ArgumentType.STRING argument.  Sets the CKA_ID to be set by the
write operation.  The ID should be specified in hexadecimal format
without a '0x' prefix.

mark-wrap option.
.................

This is the "marks the generated key to be a wrapping key" option.
Marks the generated key with the CKA_WRAP flag.

mark-trusted option.
....................

This is the "marks the object to be written as trusted" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     mark-distrusted.
   * can be disabled with -no-mark-trusted.

Marks the object to be generated/written with the CKA_TRUST flag.

mark-distrusted option.
.......................

This is the "when retrieving objects, it requires the objects to be
distrusted (blacklisted)" option.

This option has some usage constraints.  It:
   * must not appear in combination with any of the following options:
     mark-trusted.

Ensures that the objects retrieved have the CKA_X_TRUST flag.  This is
p11-kit trust module extension, thus this flag is only valid with
p11-kit registered trust modules.

mark-decrypt option.
....................

This is the "marks the object to be written for decryption" option.
Marks the object to be generated/written with the CKA_DECRYPT flag set
to true.

mark-sign option.
.................

This is the "marks the object to be written for signature generation"
option.  Marks the object to be generated/written with the CKA_SIGN flag
set to true.

mark-ca option.
...............

This is the "marks the object to be written as a ca" option.  Marks the
object to be generated/written with the CKA_CERTIFICATE_CATEGORY as CA.

mark-private option.
....................

This is the "marks the object to be written as private" option.  Marks
the object to be generated/written with the CKA_PRIVATE flag.  The
written object will require a PIN to be used.

ca option.
..........

This is an alias for the 'mark-ca' option, *note the mark-ca option
documentation: p11tool mark-ca.

private option.
...............

This is an alias for the 'mark-private' option, *note the mark-private
option documentation: p11tool mark-private.

mark-always-authenticate option.
................................

This is the "marks the object to be written as always authenticate"
option.  Marks the object to be generated/written with the
CKA_ALWAYS_AUTHENTICATE flag.  The written object will Mark the object
as requiring authentication (pin entry) before every operation.

secret-key option.
..................

This is the "provide a hex encoded secret key" option.  This option
takes a ArgumentType.STRING argument.  This secret key will be written
to the module if -write is specified.

other-options options
.....................

Other options.

debug option (-d).
..................

This is the "enable debugging" option.  This option takes a
ArgumentType.NUMBER argument.  Specifies the debug level.

so-login option.
................

This is the "force security officer login to token" option.  Forces
login to the token as security officer (admin).

admin-login option.
...................

This is an alias for the 'so-login' option, *note the so-login option
documentation: p11tool so-login.

test-sign option.
.................

This is the "tests the signature operation of the provided object"
option.  It can be used to test the correct operation of the signature
operation.  If both a private and a public key are available this
operation will sign and verify the signed data.

sign-params option.
...................

This is the "sign with a specific signature algorithm" option.  This
option takes a ArgumentType.STRING argument.  This option can be
combined with -test-sign, to sign with a specific signature algorithm
variant.  The only option supported is 'RSA-PSS', and should be
specified in order to use RSA-PSS signature on RSA keys.

hash option.
............

This is the "hash algorithm to use for signing" option.  This option
takes a ArgumentType.STRING argument.  This option can be combined with
test-sign.  Available hash functions are SHA1, RMD160, SHA256, SHA384,
SHA512, SHA3-224, SHA3-256, SHA3-384, SHA3-512.

generate-random option.
.......................

This is the "generate random data" option.  This option takes a
ArgumentType.NUMBER argument.  Asks the token to generate a number of
bytes of random bytes.

inder option.
.............

This is the "use der/raw format for input" option.  Use DER/RAW format
for input certificates and private keys.

inraw option.
.............

This is an alias for the 'inder' option, *note the inder option
documentation: p11tool inder.

outder option.
..............

This is the "use der format for output certificates, private keys, and
dh parameters" option.  The output will be in DER or RAW format.

outraw option.
..............

This is an alias for the 'outder' option, *note the outder option
documentation: p11tool outder.

provider option.
................

This is the "specify the pkcs #11 provider library" option.  This option
takes a ArgumentType.FILE argument.  This will override the default
options in /etc/gnutls/pkcs11.conf

provider-opts option.
.....................

This is the "specify parameters for the pkcs #11 provider library"
option.  This option takes a ArgumentType.STRING argument.  This is a
PKCS#11 internal option used by few modules.  Mainly for testing PKCS#11
modules.

*NOTE**: THIS OPTION IS DEPRECATED*

batch option.
.............

This is the "disable all interaction with the tool" option.  In batch
mode there will be no prompts, all parameters need to be specified on
command line.

version option (-v).
....................

This is the "output version information and exit" option.  This option
takes a ArgumentType.KEYWORD argument.  Output version of program and
exit.  The default mode is 'v', a simple version.  The 'c' mode will
print copyright information and 'n' will print the full copyright
notice.

help option (-h).
.................

This is the "display extended usage information and exit" option.
Display usage information and exit.

more-help option (-!).
......................

This is the "extended usage information passed thru pager" option.  Pass
the extended usage information through a pager.

p11tool exit status
...................

One of the following exit values will be returned:
'0 (EXIT_SUCCESS)'
     Successful program execution.
'1 (EXIT_FAILURE)'
     The operation failed or the command syntax was not valid.

p11tool See Also
................

certtool (1)

p11tool Examples
................

To view all tokens in your system use:
     $ p11tool --list-tokens

To view all objects in a token use:
     $ p11tool --login --list-all "pkcs11:TOKEN-URL"

To store a private key and a certificate in a token run:
     $ p11tool --login --write "pkcs11:URL" --load-privkey key.pem \
               --label "Mykey"
     $ p11tool --login --write "pkcs11:URL" --load-certificate cert.pem \
               --label "Mykey"
Note that some tokens require the same label to be used for the
certificate and its corresponding private key.

To generate an RSA private key inside the token use:
     $ p11tool --login --generate-privkey rsa --bits 1024 --label "MyNewKey" \
               --outfile MyNewKey.pub "pkcs11:TOKEN-URL"
The bits parameter in the above example is explicitly set because some
tokens only support limited choices in the bit length.  The output file
is the corresponding public key.  This key can be used to general a
certificate request with certtool.
     certtool --generate-request --load-privkey "pkcs11:KEY-URL" \
        --load-pubkey MyNewKey.pub --outfile request.pem