summaryrefslogtreecommitdiff
path: root/lib/x509/pkcs7.c
blob: 0ff55ba04b73ebfb68dad4712d407dc9de120b34 (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
/*
 * Copyright (C) 2003-2015 Free Software Foundation, Inc.
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * Author: Nikos Mavrogiannopoulos
 *
 * This file is part of GnuTLS.
 *
 * The GnuTLS is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>
 *
 */

/* Functions that relate on PKCS7 certificate lists parsing.
 */

#include "gnutls_int.h"
#include <libtasn1.h>

#include <datum.h>
#include <global.h>
#include "errors.h"
#include <common.h>
#include <x509_b64.h>
#include <pkcs7_int.h>
#include <gnutls/abstract.h>
#include <gnutls/pkcs7.h>

#define ATTR_MESSAGE_DIGEST "1.2.840.113549.1.9.4"
#define ATTR_SIGNING_TIME "1.2.840.113549.1.9.5"
#define ATTR_CONTENT_TYPE "1.2.840.113549.1.9.3"

static const uint8_t one = 1;

/* Decodes the PKCS #7 signed data, and returns an ASN1_TYPE,
 * which holds them. If raw is non null then the raw decoded
 * data are copied (they are locally allocated) there.
 */
static int _decode_pkcs7_signed_data(gnutls_pkcs7_t pkcs7)
{
	ASN1_TYPE c2;
	int len, result;
	gnutls_datum_t tmp = {NULL, 0};

	len = MAX_OID_SIZE - 1;
	result = asn1_read_value(pkcs7->pkcs7, "contentType", pkcs7->encap_data_oid, &len);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		return _gnutls_asn2err(result);
	}

	if (strcmp(pkcs7->encap_data_oid, SIGNED_DATA_OID) != 0) {
		gnutls_assert();
		_gnutls_debug_log("Unknown PKCS7 Content OID '%s'\n", pkcs7->encap_data_oid);
		return GNUTLS_E_UNKNOWN_PKCS_CONTENT_TYPE;
	}

	if ((result = asn1_create_element
	     (_gnutls_get_pkix(), "PKIX1.pkcs-7-SignedData",
	      &c2)) != ASN1_SUCCESS) {
		gnutls_assert();
		return _gnutls_asn2err(result);
	}

	/* the Signed-data has been created, so
	 * decode them.
	 */
	result = _gnutls_x509_read_value(pkcs7->pkcs7, "content", &tmp);
	if (result < 0) {
		gnutls_assert();
		goto cleanup;
	}

	/* Step 1. In case of a signed structure extract certificate set.
	 */

	result = asn1_der_decoding(&c2, tmp.data, tmp.size, NULL);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	/* read the encapsulated content */
	len = MAX_OID_SIZE - 1;
	result =
	    asn1_read_value(c2, "encapContentInfo.eContentType", pkcs7->encap_data_oid, &len);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	if (strcmp(pkcs7->encap_data_oid, DATA_OID) != 0
	    && strcmp(pkcs7->encap_data_oid, DIGESTED_DATA_OID) != 0) {
		_gnutls_debug_log
		    ("Unknown PKCS#7 Encapsulated Content OID '%s'; treating as raw data\n",
		     pkcs7->encap_data_oid);

	}

	/* Try reading as octet string according to rfc5652. If that fails, attempt
	 * a raw read according to rfc2315 */
	result = _gnutls_x509_read_string(c2, "encapContentInfo.eContent", &pkcs7->der_signed_data, ASN1_ETYPE_OCTET_STRING, 1);
	if (result < 0) {
		result = _gnutls_x509_read_value(c2, "encapContentInfo.eContent", &pkcs7->der_signed_data);
		if (result < 0) {
			pkcs7->der_signed_data.data = NULL;
			pkcs7->der_signed_data.size = 0;
		} else {
			int tag_len, len_len;
			unsigned char cls;
			unsigned long tag;

			/* we skip the embedded element's tag and length - uncharted territorry - used by MICROSOFT_CERT_TRUST_LIST */
			result = asn1_get_tag_der(pkcs7->der_signed_data.data, pkcs7->der_signed_data.size, &cls, &tag_len, &tag);
			if (result != ASN1_SUCCESS) {
				gnutls_assert();
				result = _gnutls_asn2err(result);
				goto cleanup;
			}

			result = asn1_get_length_ber(pkcs7->der_signed_data.data+tag_len, pkcs7->der_signed_data.size-tag_len, &len_len);
			if (result < 0) {
				gnutls_assert();
				result = GNUTLS_E_ASN1_DER_ERROR;
				goto cleanup;
			}

			tag_len += len_len;
			memmove(pkcs7->der_signed_data.data, &pkcs7->der_signed_data.data[tag_len], pkcs7->der_signed_data.size-tag_len);
			pkcs7->der_signed_data.size-=tag_len;
		}
	}

	pkcs7->signed_data = c2;
	gnutls_free(tmp.data);

	return 0;

 cleanup:
	gnutls_free(tmp.data);
	if (c2)
		asn1_delete_structure(&c2);
	return result;
}

static int pkcs7_reinit(gnutls_pkcs7_t pkcs7)
{
	int result;

	asn1_delete_structure(&pkcs7->pkcs7);

	result = asn1_create_element(_gnutls_get_pkix(),
				     "PKIX1.pkcs-7-ContentInfo", &pkcs7->pkcs7);
	if (result != ASN1_SUCCESS) {
		result = _gnutls_asn2err(result);
		gnutls_assert();
		return result;
	}

	return 0;
}

/**
 * gnutls_pkcs7_init:
 * @pkcs7: A pointer to the type to be initialized
 *
 * This function will initialize a PKCS7 structure. PKCS7 structures
 * usually contain lists of X.509 Certificates and X.509 Certificate
 * revocation lists.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_init(gnutls_pkcs7_t * pkcs7)
{
	*pkcs7 = gnutls_calloc(1, sizeof(gnutls_pkcs7_int));

	if (*pkcs7) {
		int result = pkcs7_reinit(*pkcs7);
		if (result < 0) {
			gnutls_assert();
			gnutls_free(*pkcs7);
			return result;
		}
		return 0;	/* success */
	}
	return GNUTLS_E_MEMORY_ERROR;
}

/**
 * gnutls_pkcs7_deinit:
 * @pkcs7: the type to be deinitialized
 *
 * This function will deinitialize a PKCS7 type.
 **/
void gnutls_pkcs7_deinit(gnutls_pkcs7_t pkcs7)
{
	if (!pkcs7)
		return;

	if (pkcs7->pkcs7)
		asn1_delete_structure(&pkcs7->pkcs7);

	if (pkcs7->signed_data)
		asn1_delete_structure(&pkcs7->signed_data);

	_gnutls_free_datum(&pkcs7->der_signed_data);

	gnutls_free(pkcs7);
}

/**
 * gnutls_pkcs7_import:
 * @pkcs7: The data to store the parsed PKCS7.
 * @data: The DER or PEM encoded PKCS7.
 * @format: One of DER or PEM
 *
 * This function will convert the given DER or PEM encoded PKCS7 to
 * the native #gnutls_pkcs7_t format.  The output will be stored in
 * @pkcs7.
 *
 * If the PKCS7 is PEM encoded it should have a header of "PKCS7".
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int
gnutls_pkcs7_import(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * data,
		    gnutls_x509_crt_fmt_t format)
{
	int result = 0, need_free = 0;
	gnutls_datum_t _data;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	_data.data = data->data;
	_data.size = data->size;

	/* If the PKCS7 is in PEM format then decode it
	 */
	if (format == GNUTLS_X509_FMT_PEM) {
		result =
		    _gnutls_fbase64_decode(PEM_PKCS7, data->data,
					   data->size, &_data);

		if (result < 0) {
			gnutls_assert();
			return result;
		}

		need_free = 1;
	}

	if (pkcs7->expanded) {
		result = pkcs7_reinit(pkcs7);
		if (result < 0) {
			gnutls_assert();
			goto cleanup;
		}
	}
	pkcs7->expanded = 1;

	result = asn1_der_decoding(&pkcs7->pkcs7, _data.data, _data.size, NULL);
	if (result != ASN1_SUCCESS) {
		result = _gnutls_asn2err(result);
		gnutls_assert();
		goto cleanup;
	}

	/* Decode the signed data.
	 */
	result = _decode_pkcs7_signed_data(pkcs7);
	if (result < 0) {
		gnutls_assert();
		goto cleanup;
	}

	result = 0;

 cleanup:
	if (need_free)
		_gnutls_free_datum(&_data);
	return result;
}

/**
 * gnutls_pkcs7_get_crt_raw2:
 * @pkcs7: should contain a gnutls_pkcs7_t type
 * @indx: contains the index of the certificate to extract
 * @cert: will hold the contents of the certificate; must be deallocated with gnutls_free()
 *
 * This function will return a certificate of the PKCS7 or RFC2630
 * certificate set.
 *
 * After the last certificate has been read
 * %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.  If the provided buffer is not long enough,
 *   then @certificate_size is updated and
 *   %GNUTLS_E_SHORT_MEMORY_BUFFER is returned.
 *
 * Since: 3.4.2
 **/
int
gnutls_pkcs7_get_crt_raw2(gnutls_pkcs7_t pkcs7,
			  unsigned indx, gnutls_datum_t * cert)
{
	int result, len;
	char root2[MAX_NAME_SIZE];
	char oid[MAX_OID_SIZE];
	gnutls_datum_t tmp = { NULL, 0 };

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	/* Step 2. Parse the CertificateSet
	 */
	snprintf(root2, sizeof(root2), "certificates.?%u", indx + 1);

	len = sizeof(oid) - 1;

	result = asn1_read_value(pkcs7->signed_data, root2, oid, &len);

	if (result == ASN1_VALUE_NOT_FOUND) {
		result = GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE;
		goto cleanup;
	}

	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	/* if 'Certificate' is the choice found:
	 */
	if (strcmp(oid, "certificate") == 0) {
		int start, end;

		result = _gnutls_x509_read_value(pkcs7->pkcs7, "content", &tmp);
		if (result < 0) {
			gnutls_assert();
			goto cleanup;
		}

		result =
		    asn1_der_decoding_startEnd(pkcs7->signed_data, tmp.data,
					       tmp.size, root2, &start, &end);

		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			result = _gnutls_asn2err(result);
			goto cleanup;
		}

		end = end - start + 1;

		result = _gnutls_set_datum(cert, &tmp.data[start], end);
	} else {
		result = GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE;
	}

 cleanup:
	_gnutls_free_datum(&tmp);
	return result;
}

/**
 * gnutls_pkcs7_get_crt_raw:
 * @pkcs7: should contain a gnutls_pkcs7_t type
 * @indx: contains the index of the certificate to extract
 * @certificate: the contents of the certificate will be copied
 *   there (may be null)
 * @certificate_size: should hold the size of the certificate
 *
 * This function will return a certificate of the PKCS7 or RFC2630
 * certificate set.
 *
 * After the last certificate has been read
 * %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.  If the provided buffer is not long enough,
 *   then @certificate_size is updated and
 *   %GNUTLS_E_SHORT_MEMORY_BUFFER is returned.
 **/
int
gnutls_pkcs7_get_crt_raw(gnutls_pkcs7_t pkcs7,
			 unsigned indx, void *certificate,
			 size_t * certificate_size)
{
	int ret;
	gnutls_datum_t tmp = { NULL, 0 };

	ret = gnutls_pkcs7_get_crt_raw2(pkcs7, indx, &tmp);
	if (ret < 0)
		return gnutls_assert_val(ret);

	if ((unsigned)tmp.size > *certificate_size) {
		*certificate_size = tmp.size;
		ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
		goto cleanup;
	}

	*certificate_size = tmp.size;
	if (certificate)
		memcpy(certificate, tmp.data, tmp.size);

 cleanup:
	_gnutls_free_datum(&tmp);
	return ret;
}

/**
 * gnutls_pkcs7_get_crt_count:
 * @pkcs7: should contain a #gnutls_pkcs7_t type
 *
 * This function will return the number of certificates in the PKCS7
 * or RFC2630 certificate set.
 *
 * Returns: On success, a positive number is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_get_crt_count(gnutls_pkcs7_t pkcs7)
{
	int result, count;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	/* Step 2. Count the CertificateSet */

	result =
	    asn1_number_of_elements(pkcs7->signed_data, "certificates", &count);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		return 0;	/* no certificates */
	}

	return count;
}

/**
 * gnutls_pkcs7_signature_info_deinit:
 * @info: should point to a #gnutls_pkcs7_signature_info_st structure
 *
 * This function will deinitialize any allocated value in the
 * provided #gnutls_pkcs7_signature_info_st.
 *
 * Since: 3.4.2
 **/
void gnutls_pkcs7_signature_info_deinit(gnutls_pkcs7_signature_info_st * info)
{
	gnutls_free(info->sig.data);
	gnutls_free(info->issuer_dn.data);
	gnutls_free(info->signer_serial.data);
	gnutls_free(info->issuer_keyid.data);
	gnutls_pkcs7_attrs_deinit(info->signed_attrs);
	gnutls_pkcs7_attrs_deinit(info->unsigned_attrs);
	memset(info, 0, sizeof(*info));
}

static time_t parse_time(gnutls_pkcs7_t pkcs7, const char *root)
{
	char tval[128];
	ASN1_TYPE c2 = ASN1_TYPE_EMPTY;
	time_t ret;
	int result, len;

	result = asn1_create_element(_gnutls_get_pkix(), "PKIX1.Time", &c2);
	if (result != ASN1_SUCCESS) {
		ret = -1;
		gnutls_assert();
		goto cleanup;
	}

	len = sizeof(tval);
	result = asn1_read_value(pkcs7->signed_data, root, tval, &len);
	if (result != ASN1_SUCCESS) {
		ret = -1;
		gnutls_assert();
		goto cleanup;
	}

	result = _asn1_strict_der_decode(&c2, tval, len, NULL);
	if (result != ASN1_SUCCESS) {
		ret = -1;
		gnutls_assert();
		goto cleanup;
	}

	ret = _gnutls_x509_get_time(c2, "", 0);

 cleanup:
	asn1_delete_structure(&c2);
	return ret;
}

/**
 * gnutls_pkcs7_get_signature_count:
 * @pkcs7: should contain a #gnutls_pkcs7_t type
 *
 * This function will return the number of signatures in the PKCS7
 * structure.
 *
 * Returns: On success, a positive number is returned, otherwise a
 *   negative error value.
 *
 * Since: 3.4.3
 **/
int gnutls_pkcs7_get_signature_count(gnutls_pkcs7_t pkcs7)
{
	int ret, count;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	ret =
	    asn1_number_of_elements(pkcs7->signed_data, "signerInfos", &count);
	if (ret != ASN1_SUCCESS) {
		gnutls_assert();
		return 0;
	}

	return count;
}

/**
 * gnutls_pkcs7_get_signature_info:
 * @pkcs7: should contain a #gnutls_pkcs7_t type
 * @idx: the index of the signature info to check
 * @info: will contain the output signature
 *
 * This function will return information about the signature identified
 * by idx in the provided PKCS #7 structure. The information should be
 * deinitialized using gnutls_pkcs7_signature_info_deinit().
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 *
 * Since: 3.4.2
 **/
int gnutls_pkcs7_get_signature_info(gnutls_pkcs7_t pkcs7, unsigned idx,
				    gnutls_pkcs7_signature_info_st * info)
{
	int ret, count, len;
	char root[256];
	char oid[MAX_OID_SIZE];
	gnutls_pk_algorithm_t pk;
	gnutls_sign_algorithm_t sig;
	gnutls_datum_t tmp = { NULL, 0 };
	unsigned i;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	memset(info, 0, sizeof(*info));
	info->signing_time = -1;

	ret =
	    asn1_number_of_elements(pkcs7->signed_data, "signerInfos", &count);
	if (ret != ASN1_SUCCESS || idx + 1 > (unsigned)count) {
		gnutls_assert();
		return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE;
	}
	snprintf(root, sizeof(root),
		 "signerInfos.?%u.signatureAlgorithm.algorithm", idx + 1);

	len = sizeof(oid) - 1;
	ret = asn1_read_value(pkcs7->signed_data, root, oid, &len);
	if (ret != ASN1_SUCCESS) {
		gnutls_assert();
		goto unsupp_algo;
	}

	sig = gnutls_oid_to_sign(oid);
	if (sig == GNUTLS_SIGN_UNKNOWN) {
		/* great PKCS #7 allows to only specify a public key algo */
		pk = gnutls_oid_to_pk(oid);
		if (pk == GNUTLS_PK_UNKNOWN) {
			gnutls_assert();
			goto unsupp_algo;
		}

		/* use the digests algorithm */
		snprintf(root, sizeof(root),
			 "signerInfos.?%u.digestAlgorithm.algorithm", idx + 1);

		len = sizeof(oid) - 1;
		ret = asn1_read_value(pkcs7->signed_data, root, oid, &len);
		if (ret != ASN1_SUCCESS) {
			gnutls_assert();
			goto unsupp_algo;
		}

		ret = gnutls_oid_to_digest(oid);
		if (ret == GNUTLS_DIG_UNKNOWN) {
			gnutls_assert();
			goto unsupp_algo;
		}

		sig = gnutls_pk_to_sign(pk, ret);
		if (sig == GNUTLS_SIGN_UNKNOWN) {
			gnutls_assert();
			goto unsupp_algo;
		}
	}

	info->algo = sig;

	snprintf(root, sizeof(root), "signerInfos.?%u.signature", idx + 1);
	/* read the signature */
	ret = _gnutls_x509_read_value(pkcs7->signed_data, root, &info->sig);
	if (ret < 0) {
		gnutls_assert();
		goto fail;
	}

	/* read the issuer info */
	snprintf(root, sizeof(root),
		 "signerInfos.?%u.sid.issuerAndSerialNumber.issuer.rdnSequence",
		 idx + 1);
	/* read the signature */
	ret =
	    _gnutls_x509_get_raw_field(pkcs7->signed_data, root,
				       &info->issuer_dn);
	if (ret >= 0) {
		snprintf(root, sizeof(root),
			 "signerInfos.?%u.sid.issuerAndSerialNumber.serialNumber",
			 idx + 1);
		/* read the signature */
		ret =
		    _gnutls_x509_read_value(pkcs7->signed_data, root,
					    &info->signer_serial);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}
	} else {		/* keyid */
		snprintf(root, sizeof(root),
			 "signerInfos.?%u.sid.subjectKeyIdentifier", idx + 1);
		/* read the signature */
		ret =
		    _gnutls_x509_read_value(pkcs7->signed_data, root,
					    &info->issuer_keyid);
		if (ret < 0) {
			gnutls_assert();
		}
	}

	if (info->issuer_keyid.data == NULL && info->issuer_dn.data == NULL) {
		ret = gnutls_assert_val(GNUTLS_E_PARSING_ERROR);
		goto fail;
	}

	/* read the signing time */
	for (i = 0;; i++) {
		snprintf(root, sizeof(root),
			 "signerInfos.?%u.signedAttrs.?%u.type", idx + 1,
			 i + 1);
		len = sizeof(oid) - 1;
		ret = asn1_read_value(pkcs7->signed_data, root, oid, &len);
		if (ret != ASN1_SUCCESS) {
			break;
		}

		snprintf(root, sizeof(root),
			 "signerInfos.?%u.signedAttrs.?%u.values.?1", idx + 1,
			 i + 1);
		ret = _gnutls_x509_read_value(pkcs7->signed_data, root, &tmp);
		if (ret == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND) {
			tmp.data = NULL;
			tmp.size = 0;
		} else if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		ret = gnutls_pkcs7_add_attr(&info->signed_attrs, oid, &tmp, 0);
		gnutls_free(tmp.data);

		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		if (strcmp(oid, ATTR_SIGNING_TIME) == 0) {
			info->signing_time = parse_time(pkcs7, root);
		}
	}

	/* read the unsigned attrs */
	for (i = 0;; i++) {
		snprintf(root, sizeof(root),
			 "signerInfos.?%u.unsignedAttrs.?%u.type", idx + 1,
			 i + 1);
		len = sizeof(oid) - 1;
		ret = asn1_read_value(pkcs7->signed_data, root, oid, &len);
		if (ret != ASN1_SUCCESS) {
			break;
		}

		snprintf(root, sizeof(root),
			 "signerInfos.?%u.unsignedAttrs.?%u.values.?1", idx + 1,
			 i + 1);
		ret = _gnutls_x509_read_value(pkcs7->signed_data, root, &tmp);
		if (ret == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND) {
			tmp.data = NULL;
			tmp.size = 0;
		} else if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		ret =
		    gnutls_pkcs7_add_attr(&info->unsigned_attrs, oid, &tmp, 0);
		gnutls_free(tmp.data);

		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}
	}

	return 0;
 fail:
	gnutls_free(tmp.data);
	gnutls_pkcs7_signature_info_deinit(info);
	return ret;
 unsupp_algo:
	return GNUTLS_E_UNKNOWN_ALGORITHM;
}

/* Verifies that the hash attribute ATTR_MESSAGE_DIGEST is present
 * and matches our calculated hash */
static int verify_hash_attr(gnutls_pkcs7_t pkcs7, const char *root,
			    gnutls_sign_algorithm_t algo,
			    const gnutls_datum_t *data)
{
	unsigned hash;
	gnutls_datum_t tmp = { NULL, 0 };
	gnutls_datum_t tmp2 = { NULL, 0 };
	uint8_t hash_output[MAX_HASH_SIZE];
	unsigned hash_size, i;
	char oid[MAX_OID_SIZE];
	char name[256];
	unsigned msg_digest_ok = 0;
	unsigned num_cont_types = 0;
	int ret;

	hash = gnutls_sign_get_hash_algorithm(algo);

	/* hash the data */
	if (hash == GNUTLS_DIG_UNKNOWN)
		return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);

	hash_size = gnutls_hash_get_len(hash);

	if (data == NULL || data->data == NULL) {
		data = &pkcs7->der_signed_data;
	}

	if (data->size == 0) {
		return gnutls_assert_val(GNUTLS_E_NO_EMBEDDED_DATA);
	}

	ret = gnutls_hash_fast(hash, data->data, data->size, hash_output);
	if (ret < 0)
		return gnutls_assert_val(ret);

	/* now verify that hash matches */
	for (i = 0;; i++) {
		snprintf(name, sizeof(name), "%s.signedAttrs.?%u", root, i + 1);

		ret = _gnutls_x509_decode_and_read_attribute(pkcs7->signed_data,
							     name, oid,
							     sizeof(oid), &tmp,
							     1, 0);
		if (ret < 0) {
			if (ret == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND)
				break;
			return gnutls_assert_val(ret);
		}

		if (strcmp(oid, ATTR_MESSAGE_DIGEST) == 0) {
			ret =
			    _gnutls_x509_decode_string(ASN1_ETYPE_OCTET_STRING,
						       tmp.data, tmp.size,
						       &tmp2, 0);
			if (ret < 0) {
				gnutls_assert();
				goto cleanup;
			}

			if (tmp2.size == hash_size
			    && memcmp(hash_output, tmp2.data, tmp2.size) == 0) {
				msg_digest_ok = 1;
			} else {
				gnutls_assert();
			}
		} else if (strcmp(oid, ATTR_CONTENT_TYPE) == 0) {
			if (num_cont_types > 0) {
				gnutls_assert();
				ret = GNUTLS_E_PARSING_ERROR;
				goto cleanup;
			}

			num_cont_types++;

			/* check if it matches */
			ret =
			    _gnutls_x509_get_raw_field(pkcs7->signed_data,
						       "encapContentInfo.eContentType",
						       &tmp2);
			if (ret < 0) {
				gnutls_assert();
				goto cleanup;
			}

			if (tmp2.size != tmp.size
			    || memcmp(tmp.data, tmp2.data, tmp2.size) != 0) {
				gnutls_assert();
				ret = GNUTLS_E_PARSING_ERROR;
				goto cleanup;
			}
		}

		gnutls_free(tmp.data);
		gnutls_free(tmp2.data);
	}

	if (msg_digest_ok)
		ret = 0;
	else
		ret = gnutls_assert_val(GNUTLS_E_PK_SIG_VERIFY_FAILED);

 cleanup:
	gnutls_free(tmp.data);
	gnutls_free(tmp2.data);
	return ret;
}

/* Returns the data to be used for signature verification. PKCS #7
 * decided that this should not be an easy task.
 */
static int figure_pkcs7_sigdata(gnutls_pkcs7_t pkcs7, const char *root,
				const gnutls_datum_t * data,
				gnutls_sign_algorithm_t algo,
				gnutls_datum_t * sigdata)
{
	int ret;
	char name[256];

	snprintf(name, sizeof(name), "%s.signedAttrs", root);
	/* read the signature */
	ret = _gnutls_x509_get_raw_field(pkcs7->signed_data, name, sigdata);
	if (ret == 0) {
		/* verify that hash matches */
		ret = verify_hash_attr(pkcs7, root, algo, data);
		if (ret < 0)
			return gnutls_assert_val(ret);

		if (sigdata->size > 0)
			sigdata->data[0] = 0x31;

		return 0;
	}

	/* We have no signedAttrs. Use the provided data, or the encapsulated */
	if (data == NULL || data->data == NULL) {
		return _gnutls_set_datum(sigdata, pkcs7->der_signed_data.data, pkcs7->der_signed_data.size);
	}

	return _gnutls_set_datum(sigdata, data->data, data->size);
}

/**
 * gnutls_pkcs7_get_embedded_data:
 * @pkcs7: should contain a gnutls_pkcs7_t type
 * @flags: must be zero or %GNUTLS_PKCS7_EDATA_GET_RAW
 * @data: will hold the embedded data in the provided structure
 *
 * This function will return the data embedded in the signature of
 * the PKCS7 structure. If no data are available then
 * %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned.
 *
 * The returned data must be de-allocated using gnutls_free().
 *
 * Note, that this function returns the exact same data that are
 * authenticated. If the %GNUTLS_PKCS7_EDATA_GET_RAW flag is provided,
 * the returned data will be including the wrapping tag/value as
 * they are encoded in the structure.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 *
 * Since: 3.4.8
 **/
int
gnutls_pkcs7_get_embedded_data(gnutls_pkcs7_t pkcs7, unsigned flags,
			       gnutls_datum_t *data)
{
	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	if (pkcs7->der_signed_data.size == 0)
		return gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);

	if (flags & GNUTLS_PKCS7_EDATA_GET_RAW) {
		if (pkcs7->signed_data == NULL)
			return gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);

		return _gnutls_x509_read_value(pkcs7->signed_data, "encapContentInfo.eContent", data);
	} else {
		return _gnutls_set_datum(data, pkcs7->der_signed_data.data, pkcs7->der_signed_data.size);
	}
}

/**
 * gnutls_pkcs7_get_embedded_data_oid:
 * @pkcs7: should contain a gnutls_pkcs7_t type
 *
 * This function will return the OID of the data embedded in the signature of
 * the PKCS7 structure. If no data are available then %NULL will be
 * returned. The returned value will be valid during the lifetime
 * of the @pkcs7 structure.
 *
 * Returns: On success, a pointer to an OID string, %NULL on error.
 *
 * Since: 3.5.5
 **/
const char *
gnutls_pkcs7_get_embedded_data_oid(gnutls_pkcs7_t pkcs7)
{
	if (pkcs7 == NULL || pkcs7->encap_data_oid[0] == 0)
		return NULL;

	return pkcs7->encap_data_oid;
}

/**
 * gnutls_pkcs7_verify_direct:
 * @pkcs7: should contain a #gnutls_pkcs7_t type
 * @signer: the certificate believed to have signed the structure
 * @idx: the index of the signature info to check
 * @data: The data to be verified or %NULL
 * @flags: Zero or an OR list of #gnutls_certificate_verify_flags
 *
 * This function will verify the provided data against the signature
 * present in the SignedData of the PKCS #7 structure. If the data
 * provided are NULL then the data in the encapsulatedContent field
 * will be used instead.
 *
 * Note that, unlike gnutls_pkcs7_verify() this function does not
 * verify the key purpose of the signer. It is expected for the caller
 * to verify the intended purpose of the %signer -e.g., via gnutls_x509_crt_get_key_purpose_oid(),
 * or gnutls_x509_crt_check_key_purpose().
 *
 * Note also, that since GnuTLS 3.5.6 this function introduces checks in the
 * end certificate (@signer), including time checks and key usage checks.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value. A verification error results to a
 *   %GNUTLS_E_PK_SIG_VERIFY_FAILED and the lack of encapsulated data
 *   to verify to a %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE.
 *
 * Since: 3.4.2
 **/
int gnutls_pkcs7_verify_direct(gnutls_pkcs7_t pkcs7,
			       gnutls_x509_crt_t signer,
			       unsigned idx,
			       const gnutls_datum_t *data, unsigned flags)
{
	int count, ret;
	gnutls_datum_t tmpdata = { NULL, 0 };
	gnutls_pkcs7_signature_info_st info;
	gnutls_datum_t sigdata = { NULL, 0 };
	char root[128];

	memset(&info, 0, sizeof(info));

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	ret =
	    asn1_number_of_elements(pkcs7->signed_data, "signerInfos", &count);
	if (ret != ASN1_SUCCESS || idx + 1 > (unsigned)count) {
		gnutls_assert();
		return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE;
	}

	ret = gnutls_pkcs7_get_signature_info(pkcs7, idx, &info);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	snprintf(root, sizeof(root), "signerInfos.?%u", idx + 1);
	ret = figure_pkcs7_sigdata(pkcs7, root, data, info.algo, &sigdata);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	ret =
	    gnutls_x509_crt_verify_data2(signer, info.algo, flags, &sigdata,
					 &info.sig);
	if (ret < 0) {
		gnutls_assert();
	}

 cleanup:
	gnutls_free(tmpdata.data);
	gnutls_free(sigdata.data);
	gnutls_pkcs7_signature_info_deinit(&info);

	return ret;
}

/* Finds the issuer of the given certificate (@cert) in the
 * included in PKCS#7 list of certificates */
static gnutls_x509_crt_t find_verified_issuer_of(gnutls_pkcs7_t pkcs7,
					gnutls_x509_crt_t cert,
					const char *purpose,
					unsigned vflags)
{
	gnutls_x509_crt_t issuer = NULL;
	int ret, count;
	gnutls_datum_t tmp = { NULL, 0 };
	unsigned i, vtmp;

	count = gnutls_pkcs7_get_crt_count(pkcs7);
	if (count < 0) {
		gnutls_assert();
		return NULL;
	}

	for (i = 0; i < (unsigned)count; i++) {
		/* Try to find the signer in the appended list. */
		ret = gnutls_pkcs7_get_crt_raw2(pkcs7, i, &tmp);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		ret = gnutls_x509_crt_init(&issuer);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		ret = gnutls_x509_crt_import(issuer, &tmp, GNUTLS_X509_FMT_DER);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		if (!gnutls_x509_crt_check_issuer(cert, issuer)) {
			gnutls_assert();
			goto skip;
		}

		ret = gnutls_x509_crt_verify(cert, &issuer, 1, vflags|GNUTLS_VERIFY_DO_NOT_ALLOW_SAME, &vtmp);
		if (ret < 0 || vtmp != 0 ||
		    (purpose != NULL && !_gnutls_check_key_purpose(issuer, purpose, 0))) {
			gnutls_assert();	/* maybe next one is trusted */
			_gnutls_cert_log("failed verification with", issuer);
 skip:
			gnutls_x509_crt_deinit(issuer);
			issuer = NULL;
			gnutls_free(tmp.data);
			continue;
		}

		_gnutls_cert_log("issued by", issuer);

		/* we found a signer we trust. let's return it */
		break;
	}

	if (issuer == NULL) {
		gnutls_assert();
		return NULL;
	}
	goto cleanup;

 fail:
	if (issuer) {
		gnutls_x509_crt_deinit(issuer);
		issuer = NULL;
	}

 cleanup:
	gnutls_free(tmp.data);

	return issuer;
}

/* Finds a certificate that is issued by @issuer -if given-, and matches
 * either the serial number or the key ID (both in @info) .
 */
static gnutls_x509_crt_t find_child_of_with_serial(gnutls_pkcs7_t pkcs7,
						   gnutls_x509_crt_t issuer,
						   const char *purpose,
						   gnutls_pkcs7_signature_info_st *info)
{
	gnutls_x509_crt_t crt = NULL;
	int ret, count;
	uint8_t tmp[128];
	size_t tmp_size;
	gnutls_datum_t tmpdata = { NULL, 0 };
	unsigned i;

	count = gnutls_pkcs7_get_crt_count(pkcs7);
	if (count < 0) {
		gnutls_assert();
		return NULL;
	}

	for (i = 0; i < (unsigned)count; i++) {
		/* Try to find the crt in the appended list. */
		ret = gnutls_pkcs7_get_crt_raw2(pkcs7, i, &tmpdata);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		ret = gnutls_x509_crt_init(&crt);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		ret = gnutls_x509_crt_import(crt, &tmpdata, GNUTLS_X509_FMT_DER);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		if (issuer != NULL) {
			if (!gnutls_x509_crt_check_issuer(crt, issuer)) {
				gnutls_assert();
				goto skip;
			}
		}

		if (purpose) {
			ret =
			    _gnutls_check_key_purpose(crt, purpose, 0);
			if (ret == 0) {
				_gnutls_cert_log("key purpose unacceptable", crt);
				goto skip;
			}
		}

		if (info->signer_serial.size > 0) {
			tmp_size = sizeof(tmp);
			ret = gnutls_x509_crt_get_serial(crt, tmp, &tmp_size);
			if (ret < 0) {
				gnutls_assert();
				goto skip;
			}

			if (tmp_size != info->signer_serial.size
			    || memcmp(info->signer_serial.data, tmp,
				      tmp_size) != 0) {
				_gnutls_cert_log("doesn't match serial", crt);
				gnutls_assert();
				goto skip;
			}
		} else if (info->issuer_keyid.size > 0) {
			tmp_size = sizeof(tmp);
			ret = gnutls_x509_crt_get_subject_key_id(crt, tmp, &tmp_size, NULL);
			if (ret < 0) {
				gnutls_assert();
				goto skip;
			}

			if (tmp_size != info->issuer_keyid.size
			    || memcmp(info->issuer_keyid.data, tmp,
				      tmp_size) != 0) {
				_gnutls_cert_log("doesn't match key ID", crt);
				gnutls_assert();
 skip:
				gnutls_x509_crt_deinit(crt);
				crt = NULL;
				gnutls_free(tmpdata.data);
				continue;
			}
		} else {
			gnutls_assert();
			crt = NULL;
			goto fail;
		}

		_gnutls_cert_log("signer is", crt);

		/* we found the child with the given serial or key ID */
		break;
	}

	if (crt == NULL) {
		gnutls_assert();
		return NULL;
	}

	goto cleanup;
 fail:
	if (crt) {
		gnutls_x509_crt_deinit(crt);
		crt = NULL;
	}

 cleanup:
	gnutls_free(tmpdata.data);

	return crt;
}

static
gnutls_x509_crt_t find_signer(gnutls_pkcs7_t pkcs7, gnutls_x509_trust_list_t tl,
			      gnutls_typed_vdata_st * vdata,
			      unsigned vdata_size,
			      unsigned vflags,
			      gnutls_pkcs7_signature_info_st * info)
{
	gnutls_x509_crt_t issuer = NULL;
	gnutls_x509_crt_t signer = NULL;
	int ret;
	gnutls_datum_t tmp = { NULL, 0 };
	unsigned i, vtmp;
	const char *purpose = NULL;

	if (info->issuer_keyid.data) {
		ret =
		    gnutls_x509_trust_list_get_issuer_by_subject_key_id(tl,
									NULL,
									&info->
									issuer_keyid,
									&signer,
									0);
		if (ret < 0) {
			gnutls_assert();
			signer = NULL;
		}
	}

	/* get key purpose */
	for (i = 0; i < vdata_size; i++) {
		if (vdata[i].type == GNUTLS_DT_KEY_PURPOSE_OID) {
			purpose = (char *)vdata[i].data;
			break;
		}
	}

	/* this will give us the issuer of the signer (wtf) */
	if (info->issuer_dn.data && signer == NULL) {
		ret =
		    gnutls_x509_trust_list_get_issuer_by_dn(tl,
							    &info->issuer_dn,
							    &issuer, 0);
		if (ret < 0) {
			gnutls_assert();
			signer = NULL;
		}

		if (issuer) {
			/* try to find the actual signer in the list of
			 * certificates */
			signer = find_child_of_with_serial(pkcs7, issuer, purpose, info);
			if (signer == NULL) {
				gnutls_assert();
				goto fail;
			}

			gnutls_x509_crt_deinit(issuer);
			issuer = NULL;
		}
	}

	if (signer == NULL) {
		/* get the signer from the pkcs7 list; the one that matches serial
		 * or key ID */
		signer = find_child_of_with_serial(pkcs7, NULL, purpose, info);
		if (signer == NULL) {
			gnutls_assert();
			goto fail;
		}

		/* if the signer cannot be verified from our trust list, make a chain of certificates
		 * starting from the identified signer, to a root we know. */
		ret = gnutls_x509_trust_list_verify_crt2(tl, &signer, 1, vdata, vdata_size, vflags, &vtmp, NULL);
		if (ret < 0 || vtmp != 0) {
			gnutls_x509_crt_t prev = NULL;

			issuer = signer;
			/* construct a chain */
			do {
				if (prev && prev != signer) {
					gnutls_x509_crt_deinit(prev);
				}
				prev = issuer;

				issuer = find_verified_issuer_of(pkcs7, issuer, purpose, vflags);

				if (issuer != NULL && gnutls_x509_crt_check_issuer(issuer, issuer)) {
					if (prev) gnutls_x509_crt_deinit(prev);
					prev = issuer;
					break;
				}
			} while(issuer != NULL);

			issuer = prev; /* the last we have seen */

			if (issuer == NULL) {
				gnutls_assert();
				goto fail;
			}

			ret = gnutls_x509_trust_list_verify_crt2(tl, &issuer, 1, vdata, vdata_size, vflags, &vtmp, NULL);
			if (ret < 0 || vtmp != 0) {
				/* could not construct a valid chain */
				_gnutls_reason_log("signer's chain failed trust list verification", vtmp);
				gnutls_assert();
				goto fail;
			}
		}
	} else {
		/* verify that the signer we got is trusted */
		ret = gnutls_x509_trust_list_verify_crt2(tl, &signer, 1, vdata, vdata_size, vflags, &vtmp, NULL);
		if (ret < 0 || vtmp != 0) {
			/* could not construct a valid chain */
			_gnutls_reason_log("signer failed trust list verification", vtmp);
			gnutls_assert();
			goto fail;
		}
	}

	if (signer == NULL) {
		gnutls_assert();
		goto fail;
	}

	goto cleanup;

 fail:
	if (signer != NULL) {
		if (issuer == signer)
			issuer = NULL;
		gnutls_x509_crt_deinit(signer);
		signer = NULL;
	}

 cleanup:
	if (issuer != NULL) {
		gnutls_x509_crt_deinit(issuer);
		issuer = NULL;
	}
	gnutls_free(tmp.data);

	return signer;
}

/**
 * gnutls_pkcs7_verify:
 * @pkcs7: should contain a #gnutls_pkcs7_t type
 * @tl: A list of trusted certificates
 * @vdata: an array of typed data
 * @vdata_size: the number of data elements
 * @idx: the index of the signature info to check
 * @data: The data to be verified or %NULL
 * @flags: Zero or an OR list of #gnutls_certificate_verify_flags
 *
 * This function will verify the provided data against the signature
 * present in the SignedData of the PKCS #7 structure. If the data
 * provided are NULL then the data in the encapsulatedContent field
 * will be used instead.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value. A verification error results to a
 *   %GNUTLS_E_PK_SIG_VERIFY_FAILED and the lack of encapsulated data
 *   to verify to a %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE.
 *
 * Since: 3.4.2
 **/
int gnutls_pkcs7_verify(gnutls_pkcs7_t pkcs7,
			gnutls_x509_trust_list_t tl,
			gnutls_typed_vdata_st *vdata,
			unsigned int vdata_size,
			unsigned idx,
			const gnutls_datum_t *data, unsigned flags)
{
	int count, ret;
	gnutls_datum_t tmpdata = { NULL, 0 };
	gnutls_pkcs7_signature_info_st info;
	gnutls_x509_crt_t signer;
	gnutls_datum_t sigdata = { NULL, 0 };
	char root[128];

	memset(&info, 0, sizeof(info));

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	ret =
	    asn1_number_of_elements(pkcs7->signed_data, "signerInfos", &count);
	if (ret != ASN1_SUCCESS || idx + 1 > (unsigned)count) {
		gnutls_assert();
		return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE;
	}

	/* read data */
	ret = gnutls_pkcs7_get_signature_info(pkcs7, idx, &info);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	snprintf(root, sizeof(root), "signerInfos.?%u", idx + 1);
	ret = figure_pkcs7_sigdata(pkcs7, root, data, info.algo, &sigdata);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	signer = find_signer(pkcs7, tl, vdata, vdata_size, flags, &info);
	if (signer) {
		ret =
		    gnutls_x509_crt_verify_data3(signer, info.algo, vdata, vdata_size,
						 &sigdata, &info.sig, flags);
		if (ret < 0) {
			_gnutls_cert_log("failed struct verification with", signer);
			gnutls_assert();
		}
		gnutls_x509_crt_deinit(signer);
	} else {
		gnutls_assert();
		ret = GNUTLS_E_PK_SIG_VERIFY_FAILED;
	}

 cleanup:
	gnutls_free(tmpdata.data);
	gnutls_free(sigdata.data);
	gnutls_pkcs7_signature_info_deinit(&info);

	return ret;
}

static void disable_opt_fields(gnutls_pkcs7_t pkcs7)
{
	int result;
	int count;

	/* disable the optional fields */
	result = asn1_number_of_elements(pkcs7->signed_data, "crls", &count);
	if (result != ASN1_SUCCESS || count == 0) {
		(void)asn1_write_value(pkcs7->signed_data, "crls", NULL, 0);
	}

	result =
	    asn1_number_of_elements(pkcs7->signed_data, "certificates", &count);
	if (result != ASN1_SUCCESS || count == 0) {
		(void)asn1_write_value(pkcs7->signed_data, "certificates", NULL, 0);
	}

	return;
}

static int reencode(gnutls_pkcs7_t pkcs7)
{
	int result;

	if (pkcs7->signed_data != ASN1_TYPE_EMPTY) {
		disable_opt_fields(pkcs7);

		/* Replace the old content with the new
		 */
		result =
		    _gnutls_x509_der_encode_and_copy(pkcs7->signed_data, "",
						     pkcs7->pkcs7, "content",
						     0);
		if (result < 0) {
			return gnutls_assert_val(result);
		}

		/* Write the content type of the signed data
		 */
		result =
		    asn1_write_value(pkcs7->pkcs7, "contentType",
				     SIGNED_DATA_OID, 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			return _gnutls_asn2err(result);
		}
	}
	return 0;
}

/**
 * gnutls_pkcs7_export:
 * @pkcs7: The pkcs7 type
 * @format: the format of output params. One of PEM or DER.
 * @output_data: will contain a structure PEM or DER encoded
 * @output_data_size: holds the size of output_data (and will be
 *   replaced by the actual size of parameters)
 *
 * This function will export the pkcs7 structure to DER or PEM format.
 *
 * 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.
 *
 * If the structure is PEM encoded, it will have a header
 * of "BEGIN PKCS7".
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int
gnutls_pkcs7_export(gnutls_pkcs7_t pkcs7,
		    gnutls_x509_crt_fmt_t format, void *output_data,
		    size_t * output_data_size)
{
	int ret;
	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	if ((ret = reencode(pkcs7)) < 0)
		return gnutls_assert_val(ret);

	return _gnutls_x509_export_int(pkcs7->pkcs7, format, PEM_PKCS7,
				       output_data, output_data_size);
}

/**
 * gnutls_pkcs7_export2:
 * @pkcs7: The pkcs7 type
 * @format: the format of output params. One of PEM or DER.
 * @out: will contain a structure PEM or DER encoded
 *
 * This function will export the pkcs7 structure to DER or PEM format.
 *
 * The output buffer is allocated using gnutls_malloc().
 *
 * If the structure is PEM encoded, it will have a header
 * of "BEGIN PKCS7".
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 *
 * Since: 3.1.3
 **/
int
gnutls_pkcs7_export2(gnutls_pkcs7_t pkcs7,
		     gnutls_x509_crt_fmt_t format, gnutls_datum_t * out)
{
	int ret;
	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	if ((ret = reencode(pkcs7)) < 0)
		return gnutls_assert_val(ret);

	return _gnutls_x509_export_int2(pkcs7->pkcs7, format, PEM_PKCS7, out);
}

/* Creates an empty signed data structure in the pkcs7
 * structure and returns a handle to the signed data.
 */
static int create_empty_signed_data(ASN1_TYPE pkcs7, ASN1_TYPE * sdata)
{
	int result;

	*sdata = ASN1_TYPE_EMPTY;

	if ((result = asn1_create_element
	     (_gnutls_get_pkix(), "PKIX1.pkcs-7-SignedData",
	      sdata)) != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	/* Use version 1
	 */
	result = asn1_write_value(*sdata, "version", &one, 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	/* Use no digest algorithms
	 */

	/* id-data */
	result =
	    asn1_write_value(*sdata, "encapContentInfo.eContentType",
			     DIGESTED_DATA_OID, 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	result = asn1_write_value(*sdata, "encapContentInfo.eContent", NULL, 0);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	/* Add no certificates.
	 */

	/* Add no crls.
	 */

	/* Add no signerInfos.
	 */

	return 0;

 cleanup:
	asn1_delete_structure(sdata);
	return result;

}

/**
 * gnutls_pkcs7_set_crt_raw:
 * @pkcs7: The pkcs7 type
 * @crt: the DER encoded certificate to be added
 *
 * This function will add a certificate to the PKCS7 or RFC2630
 * certificate set.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_set_crt_raw(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * crt)
{
	int result;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	/* If the signed data are uninitialized
	 * then create them.
	 */
	if (pkcs7->signed_data == ASN1_TYPE_EMPTY) {
		/* The pkcs7 structure is new, so create the
		 * signedData.
		 */
		result =
		    create_empty_signed_data(pkcs7->pkcs7, &pkcs7->signed_data);
		if (result < 0) {
			gnutls_assert();
			return result;
		}
	}

	/* Step 2. Append the new certificate.
	 */

	result = asn1_write_value(pkcs7->signed_data, "certificates", "NEW", 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	result =
	    asn1_write_value(pkcs7->signed_data, "certificates.?LAST",
			     "certificate", 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	result =
	    asn1_write_value(pkcs7->signed_data,
			     "certificates.?LAST.certificate", crt->data,
			     crt->size);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	result = 0;

 cleanup:
	return result;
}

/**
 * gnutls_pkcs7_set_crt:
 * @pkcs7: The pkcs7 type
 * @crt: the certificate to be copied.
 *
 * This function will add a parsed certificate to the PKCS7 or
 * RFC2630 certificate set.  This is a wrapper function over
 * gnutls_pkcs7_set_crt_raw() .
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_set_crt(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_t crt)
{
	int ret;
	gnutls_datum_t data;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	ret = _gnutls_x509_der_encode(crt->cert, "", &data, 0);
	if (ret < 0) {
		gnutls_assert();
		return ret;
	}

	ret = gnutls_pkcs7_set_crt_raw(pkcs7, &data);

	_gnutls_free_datum(&data);

	if (ret < 0) {
		gnutls_assert();
		return ret;
	}

	return 0;
}

/**
 * gnutls_pkcs7_delete_crt:
 * @pkcs7: The pkcs7 type
 * @indx: the index of the certificate to delete
 *
 * This function will delete a certificate from a PKCS7 or RFC2630
 * certificate set.  Index starts from 0. Returns 0 on success.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_delete_crt(gnutls_pkcs7_t pkcs7, int indx)
{
	int result;
	char root2[MAX_NAME_SIZE];

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	/* Step 2. Delete the certificate.
	 */

	snprintf(root2, sizeof(root2), "certificates.?%u", indx + 1);

	result = asn1_write_value(pkcs7->signed_data, root2, NULL, 0);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	return 0;

 cleanup:
	return result;
}

/* Read and write CRLs
 */

/**
 * gnutls_pkcs7_get_crl_raw2:
 * @pkcs7: The pkcs7 type
 * @indx: contains the index of the crl to extract
 * @crl: will contain the contents of the CRL in an allocated buffer
 *
 * This function will return a DER encoded CRL of the PKCS7 or RFC2630 crl set.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.  After the last crl has been read
 *   %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned.
 *
 * Since: 3.4.2
 **/
int
gnutls_pkcs7_get_crl_raw2(gnutls_pkcs7_t pkcs7,
			  unsigned indx, gnutls_datum_t * crl)
{
	int result;
	char root2[MAX_NAME_SIZE];
	gnutls_datum_t tmp = { NULL, 0 };
	int start, end;

	if (pkcs7 == NULL || crl == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	result = _gnutls_x509_read_value(pkcs7->pkcs7, "content", &tmp);
	if (result < 0) {
		gnutls_assert();
		goto cleanup;
	}

	/* Step 2. Parse the CertificateSet
	 */

	snprintf(root2, sizeof(root2), "crls.?%u", indx + 1);

	/* Get the raw CRL
	 */
	result =
	    asn1_der_decoding_startEnd(pkcs7->signed_data, tmp.data, tmp.size,
				       root2, &start, &end);

	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	end = end - start + 1;

	result = _gnutls_set_datum(crl, &tmp.data[start], end);

 cleanup:
	_gnutls_free_datum(&tmp);
	return result;
}

/**
 * gnutls_pkcs7_get_crl_raw:
 * @pkcs7: The pkcs7 type
 * @indx: contains the index of the crl to extract
 * @crl: the contents of the crl will be copied there (may be null)
 * @crl_size: should hold the size of the crl
 *
 * This function will return a crl of the PKCS7 or RFC2630 crl set.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.  If the provided buffer is not long enough,
 *   then @crl_size is updated and %GNUTLS_E_SHORT_MEMORY_BUFFER is
 *   returned.  After the last crl has been read
 *   %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned.
 **/
int
gnutls_pkcs7_get_crl_raw(gnutls_pkcs7_t pkcs7,
			 unsigned indx, void *crl, size_t * crl_size)
{
	int ret;
	gnutls_datum_t tmp = { NULL, 0 };

	ret = gnutls_pkcs7_get_crl_raw2(pkcs7, indx, &tmp);
	if (ret < 0)
		return gnutls_assert_val(ret);

	if ((unsigned)tmp.size > *crl_size) {
		*crl_size = tmp.size;
		ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
		goto cleanup;
	}

	assert(tmp.data != NULL);

	*crl_size = tmp.size;
	if (crl)
		memcpy(crl, tmp.data, tmp.size);

 cleanup:
	_gnutls_free_datum(&tmp);
	return ret;
}

/**
 * gnutls_pkcs7_get_crl_count:
 * @pkcs7: The pkcs7 type
 *
 * This function will return the number of certificates in the PKCS7
 * or RFC2630 crl set.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_get_crl_count(gnutls_pkcs7_t pkcs7)
{
	int result, count;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	/* Step 2. Count the CertificateSet */

	result = asn1_number_of_elements(pkcs7->signed_data, "crls", &count);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		return 0;	/* no crls */
	}

	return count;

}

/**
 * gnutls_pkcs7_set_crl_raw:
 * @pkcs7: The pkcs7 type
 * @crl: the DER encoded crl to be added
 *
 * This function will add a crl to the PKCS7 or RFC2630 crl set.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_set_crl_raw(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * crl)
{
	int result;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	/* If the signed data are uninitialized
	 * then create them.
	 */
	if (pkcs7->signed_data == ASN1_TYPE_EMPTY) {
		/* The pkcs7 structure is new, so create the
		 * signedData.
		 */
		result =
		    create_empty_signed_data(pkcs7->pkcs7, &pkcs7->signed_data);
		if (result < 0) {
			gnutls_assert();
			return result;
		}
	}

	/* Step 2. Append the new crl.
	 */

	result = asn1_write_value(pkcs7->signed_data, "crls", "NEW", 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	result =
	    asn1_write_value(pkcs7->signed_data, "crls.?LAST", crl->data,
			     crl->size);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	result = 0;

 cleanup:
	return result;
}

/**
 * gnutls_pkcs7_set_crl:
 * @pkcs7: The pkcs7 type
 * @crl: the DER encoded crl to be added
 *
 * This function will add a parsed CRL to the PKCS7 or RFC2630 crl
 * set.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_set_crl(gnutls_pkcs7_t pkcs7, gnutls_x509_crl_t crl)
{
	int ret;
	gnutls_datum_t data;

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	ret = _gnutls_x509_der_encode(crl->crl, "", &data, 0);
	if (ret < 0) {
		gnutls_assert();
		return ret;
	}

	ret = gnutls_pkcs7_set_crl_raw(pkcs7, &data);

	_gnutls_free_datum(&data);

	if (ret < 0) {
		gnutls_assert();
		return ret;
	}

	return 0;
}

/**
 * gnutls_pkcs7_delete_crl:
 * @pkcs7: The pkcs7 type
 * @indx: the index of the crl to delete
 *
 * This function will delete a crl from a PKCS7 or RFC2630 crl set.
 * Index starts from 0. Returns 0 on success.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 **/
int gnutls_pkcs7_delete_crl(gnutls_pkcs7_t pkcs7, int indx)
{
	int result;
	char root2[MAX_NAME_SIZE];

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	/* Delete the crl.
	 */

	snprintf(root2, sizeof(root2), "crls.?%u", indx + 1);

	result = asn1_write_value(pkcs7->signed_data, root2, NULL, 0);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	return 0;

 cleanup:
	return result;
}

static int write_signer_id(ASN1_TYPE c2, const char *root,
			   gnutls_x509_crt_t signer, unsigned flags)
{
	int result;
	size_t serial_size;
	uint8_t serial[128];
	char name[256];

	if (flags & GNUTLS_PKCS7_WRITE_SPKI) {
		const uint8_t ver = 3;

		snprintf(name, sizeof(name), "%s.version", root);
		result = asn1_write_value(c2, name, &ver, 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			return _gnutls_asn2err(result);
		}

		snprintf(name, sizeof(name), "%s.sid", root);
		result = asn1_write_value(c2, name, "subjectKeyIdentifier", 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			return _gnutls_asn2err(result);
		}

		serial_size = sizeof(serial);
		result =
		    gnutls_x509_crt_get_subject_key_id(signer, serial,
						       &serial_size, NULL);
		if (result < 0)
			return gnutls_assert_val(result);

		snprintf(name, sizeof(name), "%s.subjectKeyIdentifier", root);
		result = asn1_write_value(c2, name, serial, serial_size);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			return _gnutls_asn2err(result);
		}
	} else {
		serial_size = sizeof(serial);
		result =
		    gnutls_x509_crt_get_serial(signer, serial, &serial_size);
		if (result < 0)
			return gnutls_assert_val(result);

		snprintf(name, sizeof(name), "%s.sid", root);
		result = asn1_write_value(c2, name, "issuerAndSerialNumber", 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			return _gnutls_asn2err(result);
		}

		snprintf(name, sizeof(name),
			 "%s.sid.issuerAndSerialNumber.serialNumber", root);
		result = asn1_write_value(c2, name, serial, serial_size);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			return _gnutls_asn2err(result);
		}

		snprintf(name, sizeof(name),
			 "%s.sid.issuerAndSerialNumber.issuer", root);
		result =
		    asn1_copy_node(c2, name, signer->cert,
				   "tbsCertificate.issuer");
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			return _gnutls_asn2err(result);
		}
	}

	return 0;
}

static int add_attrs(ASN1_TYPE c2, const char *root, gnutls_pkcs7_attrs_t attrs,
		     unsigned already_set)
{
	char name[256];
	gnutls_pkcs7_attrs_st *p = attrs;
	int result;

	if (attrs == NULL) {
		/* if there are no other attributes delete that field */
		if (already_set == 0)
			(void)asn1_write_value(c2, root, NULL, 0);
	} else {
		while (p != NULL) {
			result = asn1_write_value(c2, root, "NEW", 1);
			if (result != ASN1_SUCCESS) {
				gnutls_assert();
				return _gnutls_asn2err(result);
			}

			snprintf(name, sizeof(name), "%s.?LAST.type", root);
			result = asn1_write_value(c2, name, p->oid, 1);
			if (result != ASN1_SUCCESS) {
				gnutls_assert();
				return _gnutls_asn2err(result);
			}

			snprintf(name, sizeof(name), "%s.?LAST.values", root);
			result = asn1_write_value(c2, name, "NEW", 1);
			if (result != ASN1_SUCCESS) {
				gnutls_assert();
				return _gnutls_asn2err(result);
			}

			snprintf(name, sizeof(name), "%s.?LAST.values.?1",
				 root);
			result =
			    asn1_write_value(c2, name, p->data.data,
					     p->data.size);
			if (result != ASN1_SUCCESS) {
				gnutls_assert();
				return _gnutls_asn2err(result);
			}

			p = p->next;
		}
	}

	return 0;
}

static int write_attributes(ASN1_TYPE c2, const char *root,
			    const gnutls_datum_t * data,
			    const mac_entry_st * me,
			    gnutls_pkcs7_attrs_t other_attrs, unsigned flags)
{
	char name[256];
	int result, ret;
	uint8_t digest[MAX_HASH_SIZE];
	gnutls_datum_t tmp = { NULL, 0 };
	unsigned digest_size;
	unsigned already_set = 0;

	if (flags & GNUTLS_PKCS7_INCLUDE_TIME) {
		if (data == NULL || data->data == NULL) {
			gnutls_assert();
			return GNUTLS_E_INVALID_REQUEST;
		}

		/* Add time */
		result = asn1_write_value(c2, root, "NEW", 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			return ret;
		}

		snprintf(name, sizeof(name), "%s.?LAST.type", root);
		result = asn1_write_value(c2, name, ATTR_SIGNING_TIME, 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			return ret;
		}

		snprintf(name, sizeof(name), "%s.?LAST.values", root);
		result = asn1_write_value(c2, name, "NEW", 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			return ret;
		}

		snprintf(name, sizeof(name), "%s.?LAST.values.?1", root);
		ret = _gnutls_x509_set_raw_time(c2, name, gnutls_time(0));
		if (ret < 0) {
			gnutls_assert();
			return ret;
		}

		already_set = 1;
	}

	ret = add_attrs(c2, root, other_attrs, already_set);
	if (ret < 0) {
		gnutls_assert();
		return ret;
	}

	if (already_set != 0 || other_attrs != NULL) {
		/* Add content type */
		result = asn1_write_value(c2, root, "NEW", 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			return ret;
		}

		snprintf(name, sizeof(name), "%s.?LAST.type", root);
		result = asn1_write_value(c2, name, ATTR_CONTENT_TYPE, 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			return ret;
		}

		snprintf(name, sizeof(name), "%s.?LAST.values", root);
		result = asn1_write_value(c2, name, "NEW", 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			return ret;
		}

		ret =
		    _gnutls_x509_get_raw_field(c2,
					       "encapContentInfo.eContentType",
					       &tmp);
		if (ret < 0) {
			gnutls_assert();
			return ret;
		}

		snprintf(name, sizeof(name), "%s.?LAST.values.?1", root);
		result = asn1_write_value(c2, name, tmp.data, tmp.size);
		gnutls_free(tmp.data);

		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			return ret;
		}

		/* If we add any attribute we should add them all */
		/* Add hash */
		digest_size = _gnutls_hash_get_algo_len(me);
		ret = gnutls_hash_fast(MAC_TO_DIG(me->id), data->data, data->size, digest);
		if (ret < 0) {
			gnutls_assert();
			return ret;
		}

		result = asn1_write_value(c2, root, "NEW", 1);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			return ret;
		}

		snprintf(name, sizeof(name), "%s.?LAST", root);
		ret =
		    _gnutls_x509_encode_and_write_attribute(ATTR_MESSAGE_DIGEST,
							    c2, name, digest,
							    digest_size, 1);
		if (ret < 0) {
			gnutls_assert();
			return ret;
		}
	}

	return 0;
}

/**
 * gnutls_pkcs7_sign:
 * @pkcs7: should contain a #gnutls_pkcs7_t type
 * @signer: the certificate to sign the structure
 * @signer_key: the key to sign the structure
 * @data: The data to be signed or %NULL if the data are already embedded
 * @signed_attrs: Any additional attributes to be included in the signed ones (or %NULL)
 * @unsigned_attrs: Any additional attributes to be included in the unsigned ones (or %NULL)
 * @dig: The digest algorithm to use for signing
 * @flags: Should be zero or one of %GNUTLS_PKCS7 flags
 *
 * This function will add a signature in the provided PKCS #7 structure
 * for the provided data. Multiple signatures can be made with different
 * signers.
 *
 * The available flags are:
 *  %GNUTLS_PKCS7_EMBED_DATA, %GNUTLS_PKCS7_INCLUDE_TIME, %GNUTLS_PKCS7_INCLUDE_CERT,
 *  and %GNUTLS_PKCS7_WRITE_SPKI. They are explained in the #gnutls_pkcs7_sign_flags
 *  definition.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 *
 * Since: 3.4.2
 **/
int gnutls_pkcs7_sign(gnutls_pkcs7_t pkcs7,
		      gnutls_x509_crt_t signer,
		      gnutls_privkey_t signer_key,
		      const gnutls_datum_t *data,
		      gnutls_pkcs7_attrs_t signed_attrs,
		      gnutls_pkcs7_attrs_t unsigned_attrs,
		      gnutls_digest_algorithm_t dig, unsigned flags)
{
	int ret, result;
	gnutls_datum_t sigdata = { NULL, 0 };
	gnutls_datum_t signature = { NULL, 0 };
	const mac_entry_st *me = hash_to_entry(dig);
	unsigned pk, sigalgo;
	gnutls_x509_spki_st key_params, params;
	const gnutls_sign_entry_st *se;

	if (pkcs7 == NULL || me == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	if (pkcs7->signed_data == ASN1_TYPE_EMPTY) {
		result =
		    asn1_create_element(_gnutls_get_pkix(),
					"PKIX1.pkcs-7-SignedData",
					&pkcs7->signed_data);
		if (result != ASN1_SUCCESS) {
			gnutls_assert();
			ret = _gnutls_asn2err(result);
			goto cleanup;
		}

		if (!(flags & GNUTLS_PKCS7_EMBED_DATA)) {
			(void)asn1_write_value(pkcs7->signed_data,
					 "encapContentInfo.eContent", NULL, 0);
		}
	}

	result = asn1_write_value(pkcs7->signed_data, "version", &one, 1);
	if (result != ASN1_SUCCESS) {
		ret = _gnutls_asn2err(result);
		goto cleanup;
	}

	result =
	    asn1_write_value(pkcs7->signed_data,
			     "encapContentInfo.eContentType", DATA_OID,
			     0);
	if (result != ASN1_SUCCESS) {
		ret = _gnutls_asn2err(result);
		goto cleanup;
	}

	if ((flags & GNUTLS_PKCS7_EMBED_DATA) && data->data) {	/* embed data */
		ret =
		    _gnutls_x509_write_string(pkcs7->signed_data,
				     "encapContentInfo.eContent", data,
				     ASN1_ETYPE_OCTET_STRING);
		if (ret < 0) {
			goto cleanup;
		}
	}

	if (flags & GNUTLS_PKCS7_INCLUDE_CERT) {
		ret = gnutls_pkcs7_set_crt(pkcs7, signer);
		if (ret < 0) {
			gnutls_assert();
			goto cleanup;
		}
	}

	/* append digest info algorithm */
	result =
	    asn1_write_value(pkcs7->signed_data, "digestAlgorithms", "NEW", 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		ret = _gnutls_asn2err(result);
		goto cleanup;
	}

	result =
	    asn1_write_value(pkcs7->signed_data,
			     "digestAlgorithms.?LAST.algorithm",
			     _gnutls_x509_digest_to_oid(me), 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		ret = _gnutls_asn2err(result);
		goto cleanup;
	}

	(void)asn1_write_value(pkcs7->signed_data,
			 "digestAlgorithms.?LAST.parameters", NULL, 0);

	/* append signer's info */
	result = asn1_write_value(pkcs7->signed_data, "signerInfos", "NEW", 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		ret = _gnutls_asn2err(result);
		goto cleanup;
	}

	result =
	    asn1_write_value(pkcs7->signed_data, "signerInfos.?LAST.version",
			     &one, 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		ret = _gnutls_asn2err(result);
		goto cleanup;
	}

	result =
	    asn1_write_value(pkcs7->signed_data,
			     "signerInfos.?LAST.digestAlgorithm.algorithm",
			     _gnutls_x509_digest_to_oid(me), 1);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		ret = _gnutls_asn2err(result);
		goto cleanup;
	}

	(void)asn1_write_value(pkcs7->signed_data,
			 "signerInfos.?LAST.digestAlgorithm.parameters", NULL,
			 0);

	ret =
	    write_signer_id(pkcs7->signed_data, "signerInfos.?LAST", signer,
			    flags);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	ret =
	    add_attrs(pkcs7->signed_data, "signerInfos.?LAST.unsignedAttrs",
		      unsigned_attrs, 0);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	ret =
	    write_attributes(pkcs7->signed_data,
			     "signerInfos.?LAST.signedAttrs", data, me,
			     signed_attrs, flags);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	disable_opt_fields(pkcs7);

	/* write the signature algorithm */
	pk = gnutls_x509_crt_get_pk_algorithm(signer, NULL);

	ret = _gnutls_privkey_get_spki_params(signer_key, &key_params);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	ret = _gnutls_x509_crt_get_spki_params(signer, &key_params, &params);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	ret = _gnutls_privkey_update_spki_params(signer_key, pk, dig, 0,
						  &params);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	se = _gnutls_pk_to_sign_entry(params.pk, dig);
	if (se == NULL) {
		ret = gnutls_assert_val(GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM);
		goto cleanup;
	}

	/* RFC5652 is silent on what the values would be and initially I assumed that
	 * typical signature algorithms should be set. However RFC2315 (PKCS#7) mentions
	 * that a generic RSA OID should be used. We switch to this "unexpected" value
	 * because some implementations cannot cope with the "expected" signature values.
	 */
	params.legacy = 1;
	ret =
	    _gnutls_x509_write_sign_params(pkcs7->signed_data,
					   "signerInfos.?LAST.signatureAlgorithm",
					   se, &params);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	sigalgo = se->id;

	/* sign the data */
	ret =
	    figure_pkcs7_sigdata(pkcs7, "signerInfos.?LAST", data, sigalgo,
				 &sigdata);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	FIX_SIGN_PARAMS(params, flags, dig);

	ret = privkey_sign_and_hash_data(signer_key, se,
					 &sigdata, &signature, &params);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	result =
	    asn1_write_value(pkcs7->signed_data, "signerInfos.?LAST.signature",
			     signature.data, signature.size);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		ret = _gnutls_asn2err(result);
		goto cleanup;
	}

	ret = 0;

 cleanup:
	gnutls_free(sigdata.data);
	gnutls_free(signature.data);
	return ret;
}