summaryrefslogtreecommitdiff
path: root/lib/x509/pkcs7.c
blob: 781d21b3506231555334819f17a38d58ca9f7858 (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
/*
 * Copyright (C) 2003-2012 Free Software Foundation, 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 <http://www.gnu.org/licenses/>
 *
 */

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

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

#include <gnutls_datum.h>
#include <gnutls_global.h>
#include <gnutls_errors.h>
#include <common.h>
#include <x509_b64.h>
#include <gnutls/abstract.h>
#include <gnutls/pkcs7.h>

#define SIGNED_DATA_OID "1.2.840.113549.1.7.2"
#define PLAIN_DATA_OID "1.2.840.113549.1.7.1"
#define DIGESTED_DATA_OID "1.2.840.113549.1.7.5"

#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"


/* 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(ASN1_TYPE pkcs7, ASN1_TYPE * sdata)
{
	char oid[MAX_OID_SIZE];
	ASN1_TYPE c2;
	gnutls_datum_t tmp = {NULL, 0};
	int len, result;

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

	if (strcmp(oid, SIGNED_DATA_OID) != 0) {
		gnutls_assert();
		_gnutls_debug_log("Unknown PKCS7 Content OID '%s'\n", 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, "content", &tmp);
	if (result < 0) {
		gnutls_assert();
		goto cleanup;
	}

	/* tmp, tmp_size hold the data and the size of the CertificateSet structure
	 * actually the ANY stuff.
	 */

	/* 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 = sizeof(oid) - 1;
	result = asn1_read_value(c2, "encapContentInfo.eContentType", oid, &len);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		return _gnutls_asn2err(result);
	}

	if (strcmp(oid, PLAIN_DATA_OID) != 0) {
		gnutls_assert();
		_gnutls_debug_log("Unknown or unexpected PKCS7 Encapsulated Content OID '%s'\n", oid);
		return GNUTLS_E_UNKNOWN_PKCS_CONTENT_TYPE;
	}

	*sdata = c2;

	return 0;

      cleanup:
	if (c2)
		asn1_delete_structure(&c2);
	gnutls_free(tmp.data);
	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(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->pkcs7, &pkcs7->signed_data);
	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
 * @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.
 *
 * Since: 3.4.2
 **/
int
gnutls_pkcs7_get_crt_raw2(gnutls_pkcs7_t pkcs7,
			 int indx, gnutls_datum_t *cert)
{
	int result, len;
	char root2[ASN1_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,
			 int 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 certifcates in the PKCS7
 * or RFC2630 certificate set.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) 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);
	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_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;
	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_x509_oid2sign_algorithm(oid);
	if (sig == GNUTLS_SIGN_UNKNOWN) {
		/* great PKCS #7 allows to only specify a public key algo */
		pk = _gnutls_x509_oid2pk_algorithm(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_x509_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;
		}

		if (strcmp(oid, ATTR_SIGNING_TIME) == 0) {
			snprintf(root, sizeof(root), "signerInfos.?%u.signedAttrs.?%u.values.?1", idx+1, i+1);
			info->signing_time = parse_time(pkcs7, root);
		}
	}
 	return 0;
 fail:
	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) {
		ret = _gnutls_x509_read_value(pkcs7->signed_data, "encapContentInfo.eContent", &tmp);
		if (ret < 0) {
			if (ret == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND)
				ret = GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE;
			gnutls_assert();
			return ret;
		}
		data = &tmp;
	}

	ret = gnutls_hash_fast(hash, data->data, data->size, hash_output);

	gnutls_free(tmp.data);
	tmp.data = NULL;

	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 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);
	 	tmp.data = NULL;
	 	gnutls_free(tmp2.data);
	 	tmp2.data = NULL;
	}

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

 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) {
		ret = _gnutls_x509_read_value(pkcs7->signed_data, "encapContentInfo.eContent", sigdata);
		if (ret < 0) {
			gnutls_assert();
			return gnutls_assert_val(ret);
		}
		return 0;
	}

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

/**
 * gnutls_pkcs7_verify_direct:
 * @pkcs7: should contain a #gnutls_pkcs7_t type
 * @signer: the certificate believe to have signed the structure
 * @idx: the index of the signature info to check
 * @data: The data to be verified or %NULL
 * @flags: Should be zero
 *
 * 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_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) {
		return gnutls_assert_val(ret);
	}

	ret = gnutls_x509_crt_verify_data2(signer, info.algo, 0, &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;
}

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,
			      gnutls_pkcs7_signature_info_st *info)
{
	gnutls_x509_crt_t issuer = NULL, crt = NULL;
	int ret, count;
	uint8_t serial[128];
	size_t serial_size;
	gnutls_datum_t tmp = {NULL, 0};
	unsigned i, vtmp;

	if (info->issuer_dn.data) {
		ret = gnutls_x509_trust_list_get_issuer_by_dn(tl, &info->issuer_dn, &issuer, 0);
		if (ret < 0) {
			gnutls_assert();
			issuer = NULL;
		}
	}

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

	if (issuer == NULL) {
		/* the issuer of the signer is not trusted. Too bad. */
		return NULL;
	}

	/* check issuer's key purpose */
	for (i=0;i<vdata_size;i++) {
		if (vdata[i].type == GNUTLS_DT_KEY_PURPOSE_OID) {
			ret = _gnutls_check_key_purpose(issuer, (char*)vdata[i].data, 0);
			if (ret == 0) {
				gnutls_assert();
				goto fail;
			} else {
				break;
			}
		}
	}

	/* if the serial number of the issuer matches the one in the cert,
	 * then the issuer is the signer */
	if (info->signer_serial.data) {
		serial_size = sizeof(serial);
		ret = gnutls_x509_crt_get_serial(issuer, serial, &serial_size);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		if (serial_size == info->signer_serial.size && memcmp(info->signer_serial.data, serial, serial_size) == 0) {
			/* issuer == signer */
			return issuer;
		}
	}

	count = gnutls_pkcs7_get_crt_count(pkcs7);
	if (count < 0) {
		gnutls_assert();
		goto fail;
	}

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

		serial_size = sizeof(serial);
		ret = gnutls_x509_crt_get_serial(crt, serial, &serial_size);
		if (ret < 0) {
			gnutls_assert();
			goto fail;
		}

		if (serial_size != info->signer_serial.size || memcmp(info->signer_serial.data, serial, serial_size) != 0) {
			gnutls_assert();
			goto skip;
		}

		ret = gnutls_x509_trust_list_verify_crt2(tl, &crt, 1, vdata, vdata_size, 0, &vtmp, NULL);
		if (ret < 0 || vtmp != 0) {
			gnutls_assert(); /* maybe next one is trusted */
 skip:
			gnutls_x509_crt_deinit(crt);
			crt = NULL;
			gnutls_free(tmp.data);
			tmp.data = NULL;
			continue;
		}

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

	/* ok a trusted certificate was found. This is the signer */
	goto cleanup;

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

 cleanup:
	gnutls_free(tmp.data);
	if (issuer)
		gnutls_x509_crt_deinit(issuer);
 
	return crt;
}

/**
 * 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: Should be zero
 *
 * 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) {
		return gnutls_assert_val(ret);
	}

	signer = find_signer(pkcs7, tl, vdata, vdata_size, &info);
	if (signer) {
		ret = gnutls_x509_crt_verify_data2(signer, info.algo, 0, &sigdata, &info.sig);
		if (ret < 0) {
			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;
}

/**
 * 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)
{
	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	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)
{
	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	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)
{
	uint8_t one = 1;
	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.
	 */

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

	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;
	}

	/* Step 3. Replace the old content with the new
	 */
	result =
	    _gnutls_x509_der_encode_and_copy(pkcs7->signed_data, "", pkcs7->pkcs7,
					     "content", 0);
	if (result < 0) {
		gnutls_assert();
		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)
{
	ASN1_TYPE c2 = ASN1_TYPE_EMPTY;
	int result;
	char root2[ASN1_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(c2, root2, NULL, 0);
	if (result != ASN1_SUCCESS) {
		gnutls_assert();
		result = _gnutls_asn2err(result);
		goto cleanup;
	}

	/* Step 3. Replace the old content with the new
	 */
	result =
	    _gnutls_x509_der_encode_and_copy(c2, "", pkcs7->pkcs7,
					     "content", 0);
	if (result < 0) {
		gnutls_assert();
		goto cleanup;
	}

	asn1_delete_structure(&c2);

	return 0;

      cleanup:
	if (c2)
		asn1_delete_structure(&c2);
	return result;
}

/* Read and write CRLs
 */

/**
 * 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,
			 int indx, void *crl, size_t * crl_size)
{
	int result;
	char root2[ASN1_MAX_NAME_SIZE];
	gnutls_datum_t tmp = { NULL, 0 };
	int start, end;

	if (pkcs7 == NULL || crl_size == 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;

	if ((unsigned) end > *crl_size) {
		*crl_size = end;
		result = GNUTLS_E_SHORT_MEMORY_BUFFER;
		goto cleanup;
	}

	if (crl)
		memcpy(crl, &tmp.data[start], end);

	*crl_size = end;

	result = 0;

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

/**
 * gnutls_pkcs7_get_crl_count:
 * @pkcs7: The pkcs7 type
 *
 * This function will return the number of certifcates 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;
	}

	/* Step 3. Replace the old content with the new
	 */
	result =
	    _gnutls_x509_der_encode_and_copy(pkcs7->signed_data, "", pkcs7->pkcs7,
					     "content", 0);
	if (result < 0) {
		gnutls_assert();
		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[ASN1_MAX_NAME_SIZE];

	if (pkcs7 == NULL)
		return GNUTLS_E_INVALID_REQUEST;

	/* Step 2. 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;
	}

	/* Step 3. Replace the old content with the new
	 */
	result =
	    _gnutls_x509_der_encode_and_copy(pkcs7->signed_data, "", pkcs7->pkcs7,
					     "content", 0);
	if (result < 0) {
		gnutls_assert();
		goto cleanup;
	}

	return 0;

      cleanup:
	return result;
}