summaryrefslogtreecommitdiffstats
path: root/third_party/heimdal/lib/hx509/req.c
blob: c8be1d452bc08b2a1dd9cf7069935d9048d9691b (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
/*
 * Copyright (c) 2006 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "hx_locl.h"
#include <pkcs10_asn1.h>

typedef struct abitstring_s {
    unsigned char *feats;
    size_t feat_bytes;
} *abitstring;

struct hx509_request_data {
    hx509_context context;
    hx509_name name;
    SubjectPublicKeyInfo key;
    KeyUsage ku;
    ExtKeyUsage eku;
    GeneralNames san;
    BasicConstraints bc;
    struct abitstring_s authorized_EKUs;
    struct abitstring_s authorized_SANs;
    uint32_t nunsupported_crit; /* Count of unsupported critical features requested */
    uint32_t nunsupported_opt;  /* Count of unsupported optional features requested */
    uint32_t nauthorized;       /* Count of supported   features authorized */
    uint32_t ca_is_authorized:1;
    uint32_t ku_are_authorized:1;
    uint32_t include_BasicConstraints:1;
};

/**
 * Allocate and initialize an hx509_request structure representing a PKCS#10
 * certificate signing request.
 *
 * @param context An hx509 context.
 * @param req Where to put the new hx509_request object.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_init(hx509_context context, hx509_request *req)
{
    *req = calloc(1, sizeof(**req));
    if (*req == NULL)
	return ENOMEM;

    (*req)->context = context;
    return 0;
}

/**
 * Free a certificate signing request object.
 *
 * @param req A pointer to the hx509_request to free.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION void HX509_LIB_CALL
hx509_request_free(hx509_request *reqp)
{
    hx509_request req = *reqp;

    *reqp = NULL;
    if (req == NULL)
        return;
    if (req->name)
	hx509_name_free(&req->name);
    free(req->authorized_EKUs.feats);
    free(req->authorized_SANs.feats);
    free_SubjectPublicKeyInfo(&req->key);
    free_ExtKeyUsage(&req->eku);
    free_GeneralNames(&req->san);
    free_BasicConstraints(&req->bc);
    memset(req, 0, sizeof(*req));
    free(req);
}

/**
 * Make the CSR request a CA certificate
 *
 * @param context An hx509 context.
 * @param req The hx509_request to alter.
 * @param pathLenConstraint the pathLenConstraint for the BasicConstraints (optional)
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_set_cA(hx509_context context,
                     hx509_request req,
                     unsigned *pathLenConstraint)
{
    req->bc.cA = 1;
    if (pathLenConstraint) {
        if (req->bc.pathLenConstraint == NULL)
            req->bc.pathLenConstraint = malloc(sizeof(*pathLenConstraint));
        if (req->bc.pathLenConstraint == NULL)
            return ENOMEM;
        *req->bc.pathLenConstraint = *pathLenConstraint;
    }
    return 0;
}

/**
 * Make the CSR request an EE (end-entity, i.e., not a CA) certificate
 *
 * @param context An hx509 context.
 * @param req The hx509_request to alter.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION void HX509_LIB_CALL
hx509_request_set_eE(hx509_context context, hx509_request req)
{
    req->bc.cA = 0;
    free(req->bc.pathLenConstraint);
    req->include_BasicConstraints = 1;
    req->ca_is_authorized = 0;
}

/**
 * Set the subjectName of the CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request to alter.
 * @param name The subjectName.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_set_name(hx509_context context,
			hx509_request req,
			hx509_name name)
{
    if (req->name)
	hx509_name_free(&req->name);
    if (name) {
	int ret = hx509_name_copy(context, name, &req->name);
	if (ret)
	    return ret;
    }
    return 0;
}

/**
 * Get the subject name requested by a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param name Where to put the name.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_get_name(hx509_context context,
			hx509_request req,
			hx509_name *name)
{
    if (req->name == NULL) {
	hx509_set_error_string(context, 0, EINVAL, "Request has no name");
	return EINVAL;
    }
    return hx509_name_copy(context, req->name, name);
}

/**
 * Set the subject public key requested by a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param key The public key.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_set_SubjectPublicKeyInfo(hx509_context context,
					hx509_request req,
					const SubjectPublicKeyInfo *key)
{
    free_SubjectPublicKeyInfo(&req->key);
    return copy_SubjectPublicKeyInfo(key, &req->key);
}

/**
 * Get the subject public key requested by a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param key Where to put the key.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_get_SubjectPublicKeyInfo(hx509_context context,
					hx509_request req,
					SubjectPublicKeyInfo *key)
{
    return copy_SubjectPublicKeyInfo(&req->key, key);
}

/**
 * Set the key usage requested by a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param ku The key usage.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_set_ku(hx509_context context, hx509_request req, KeyUsage ku)
{
    uint64_t n = KeyUsage2int(ku);

    if ((KeyUsage2int(req->ku) & n) != n)
        req->ku_are_authorized = 0;
    req->ku = ku;
    return 0;
}

/**
 * Get the key usage requested by a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param ku Where to put the key usage.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_get_ku(hx509_context context, hx509_request req, KeyUsage *ku)
{
    *ku = req->ku;
    return 0;
}

/**
 * Add an extended key usage OID to a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param oid The EKU OID.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_eku(hx509_context context,
                      hx509_request req,
                      const heim_oid *oid)
{
    void *val;
    int ret;

    val = realloc(req->eku.val, sizeof(req->eku.val[0]) * (req->eku.len + 1));
    if (val == NULL)
	return ENOMEM;
    req->eku.val = val;

    ret = der_copy_oid(oid, &req->eku.val[req->eku.len]);
    if (ret)
	return ret;

    req->eku.len += 1;

    return 0;
}

/**
 * Add a GeneralName (Jabber ID) subject alternative name to a CSR.
 *
 * XXX Make this take a heim_octet_string, not a GeneralName*.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param gn The GeneralName object.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_GeneralName(hx509_context context,
                              hx509_request req,
                              const GeneralName *gn)
{
    return add_GeneralNames(&req->san, gn);
}

static int
add_utf8_other_san(hx509_context context,
                   GeneralNames *gns,
                   const heim_oid *oid,
                   const char *s)
{
    const PKIXXmppAddr us = (const PKIXXmppAddr)(uintptr_t)s;
    GeneralName gn;
    size_t size;
    int ret;

    gn.element = choice_GeneralName_otherName;
    gn.u.otherName.type_id.length = 0;
    gn.u.otherName.type_id.components = 0;
    gn.u.otherName.value.data = NULL;
    gn.u.otherName.value.length = 0;
    ret = der_copy_oid(oid, &gn.u.otherName.type_id);
    if (ret == 0)
        ASN1_MALLOC_ENCODE(PKIXXmppAddr, gn.u.otherName.value.data,
                           gn.u.otherName.value.length, &us, &size, ret);
    if (ret == 0 && size != gn.u.otherName.value.length)
        _hx509_abort("internal ASN.1 encoder error");
    if (ret == 0)
        ret = add_GeneralNames(gns, &gn);
    free_GeneralName(&gn);
    if (ret)
        hx509_set_error_string(context, 0, ret, "Out of memory");
    return ret;
}

/**
 * Add an xmppAddr (Jabber ID) subject alternative name to a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param jid The XMPP address.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_xmpp_name(hx509_context context,
                            hx509_request req,
                            const char *jid)
{
    return add_utf8_other_san(context, &req->san,
                              &asn1_oid_id_pkix_on_xmppAddr, jid);
}

/**
 * Add a Microsoft UPN subject alternative name to a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param hostname The XMPP address.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_ms_upn_name(hx509_context context,
                              hx509_request req,
                              const char *upn)
{
    return add_utf8_other_san(context, &req->san, &asn1_oid_id_pkinit_ms_san,
                              upn);
}

/**
 * Add a dNSName (hostname) subject alternative name to a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param hostname The fully-qualified hostname.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_dns_name(hx509_context context,
                           hx509_request req,
                           const char *hostname)
{
    GeneralName name;

    memset(&name, 0, sizeof(name));
    name.element = choice_GeneralName_dNSName;
    name.u.dNSName.data = rk_UNCONST(hostname);
    name.u.dNSName.length = strlen(hostname);

    return add_GeneralNames(&req->san, &name);
}

/**
 * Add a dnsSRV (_service.hostname) subject alternative name to a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param dnssrv The DNS SRV name.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_dns_srv(hx509_context context,
                          hx509_request req,
                          const char *dnssrv)
{
    GeneralName gn;
    SRVName n;
    size_t size;
    int ret;

    memset(&n, 0, sizeof(n));
    memset(&gn, 0, sizeof(gn));
    gn.element = choice_GeneralName_otherName;
    gn.u.otherName.type_id.length = 0;
    gn.u.otherName.type_id.components = 0;
    gn.u.otherName.value.data = NULL;
    gn.u.otherName.value.length = 0;
    n.length = strlen(dnssrv);
    n.data = (void *)(uintptr_t)dnssrv;
    ASN1_MALLOC_ENCODE(SRVName,
                       gn.u.otherName.value.data,
                       gn.u.otherName.value.length, &n, &size, ret);
    if (ret == 0)
        ret = der_copy_oid(&asn1_oid_id_pkix_on_dnsSRV, &gn.u.otherName.type_id);
    if (ret == 0)
        ret = add_GeneralNames(&req->san, &gn);
    free_GeneralName(&gn);
    return ret;
}

/**
 * Add an rfc822Name (e-mail address) subject alternative name to a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param email The e-mail address.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_email(hx509_context context,
                        hx509_request req,
                        const char *email)
{
    GeneralName name;

    memset(&name, 0, sizeof(name));
    name.element = choice_GeneralName_rfc822Name;
    name.u.rfc822Name.data = rk_UNCONST(email);
    name.u.rfc822Name.length = strlen(email);

    return add_GeneralNames(&req->san, &name);
}

/**
 * Add a registeredID (OID) subject alternative name to a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param oid The OID.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_registered(hx509_context context,
                             hx509_request req,
                             heim_oid *oid)
{
    GeneralName name;
    int ret;

    memset(&name, 0, sizeof(name));
    name.element = choice_GeneralName_registeredID;
    ret = der_copy_oid(oid, &name.u.registeredID);
    if (ret)
        return ret;
    ret = add_GeneralNames(&req->san, &name);
    free_GeneralName(&name);
    return ret;
}

/**
 * Add a Kerberos V5 principal subject alternative name to a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param princ The Kerberos principal name.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_add_pkinit(hx509_context context,
                         hx509_request req,
                         const char *princ)
{
    KRB5PrincipalName kn;
    GeneralName gn;
    int ret;

    memset(&kn, 0, sizeof(kn));
    memset(&gn, 0, sizeof(gn));
    gn.element = choice_GeneralName_otherName;
    gn.u.otherName.type_id.length = 0;
    gn.u.otherName.type_id.components = 0;
    gn.u.otherName.value.data = NULL;
    gn.u.otherName.value.length = 0;
    ret = der_copy_oid(&asn1_oid_id_pkinit_san, &gn.u.otherName.type_id);
    if (ret == 0)
        ret = _hx509_make_pkinit_san(context, princ, &gn.u.otherName.value);
    if (ret == 0)
        ret = add_GeneralNames(&req->san, &gn);
    free_GeneralName(&gn);
    return ret;
}

/* XXX Add DNSSRV and other SANs */

static int
get_exts(hx509_context context,
         const hx509_request req,
         Extensions *exts)
{
    size_t size;
    int ret = 0;

    exts->val = NULL;
    exts->len = 0;

    if (req->bc.cA || req->include_BasicConstraints) {
        Extension e;

        /*
         * If `!req->bc.cA' then we don't include BasicConstraints unless
         * hx509_request_set_eE() was called on this request, and in that case
         * we make this extension non-critical.  We do this to emulate Dell
         * iDRAC CSR-making software.
         *
         * If `req->bc.cA' then we make the BasicConstraints critical,
         * obviously.
         */
        memset(&e, 0, sizeof(e));
        e.critical = req->bc.cA ? 1 : 0;
        if (ret == 0)
            ASN1_MALLOC_ENCODE(BasicConstraints, e.extnValue.data, e.extnValue.length,
                               &req->bc, &size, ret);
        if (ret == 0)
            ret = der_copy_oid(&asn1_oid_id_x509_ce_basicConstraints, &e.extnID);
        if (ret == 0)
            ret = add_Extensions(exts, &e);
        free_Extension(&e);
    }
    if (KeyUsage2int(req->ku)) {
        Extension e;

        memset(&e, 0, sizeof(e));
        /* The critical field needs to be made DEFAULT FALSE... */
        e.critical = 1;
        if (ret == 0)
            ASN1_MALLOC_ENCODE(KeyUsage, e.extnValue.data, e.extnValue.length,
                               &req->ku, &size, ret);
        if (ret == 0)
            ret = der_copy_oid(&asn1_oid_id_x509_ce_keyUsage, &e.extnID);
        if (ret == 0)
            ret = add_Extensions(exts, &e);
        free_Extension(&e);
    }
    if (ret == 0 && req->eku.len) {
        Extension e;

        memset(&e, 0, sizeof(e));
        e.critical = 1;
        if (ret == 0)
            ASN1_MALLOC_ENCODE(ExtKeyUsage,
                               e.extnValue.data, e.extnValue.length,
                               &req->eku, &size, ret);
        if (ret == 0)
            ret = der_copy_oid(&asn1_oid_id_x509_ce_extKeyUsage, &e.extnID);
        if (ret == 0)
            ret = add_Extensions(exts, &e);
        free_Extension(&e);
    }
    if (ret == 0 && req->san.len) {
        Extension e;

        memset(&e, 0, sizeof(e));
        /*
         * SANs are critical when the subject Name is empty.
         *
         * The empty DN check could probably stand to be a function we export.
         */
        e.critical = FALSE;
        if (req->name &&
            req->name->der_name.element == choice_Name_rdnSequence &&
            req->name->der_name.u.rdnSequence.len == 0)
            e.critical = 1;
        if (ret == 0)
            ASN1_MALLOC_ENCODE(GeneralNames,
                               e.extnValue.data, e.extnValue.length,
                               &req->san,
                               &size, ret);
        if (ret == 0)
            ret = der_copy_oid(&asn1_oid_id_x509_ce_subjectAltName, &e.extnID);
        if (ret == 0)
            ret = add_Extensions(exts, &e);
        free_Extension(&e);
    }

    return ret;
}

/**
 * Get the KU/EKUs/SANs set on a request as a DER-encoding of Extensions.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param exts_der Where to put the DER-encoded Extensions.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_get_exts(hx509_context context,
                       const hx509_request req,
                       heim_octet_string *exts_der)
{
    Extensions exts;
    size_t size;
    int ret;

    exts_der->data = NULL;
    exts_der->length = 0;
    ret = get_exts(context, req, &exts);
    if (ret == 0 && exts.len /* Extensions has a min size constraint of 1 */)
        ASN1_MALLOC_ENCODE(Extensions, exts_der->data, exts_der->length,
                           &exts, &size, ret);
    free_Extensions(&exts);
    return ret;
}

/* XXX Add PEM */

/**
 * Encode a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param signer The private key corresponding to the CSR's subject public key.
 * @param request Where to put the DER-encoded CSR.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_to_pkcs10(hx509_context context,
                        const hx509_request req,
                        const hx509_private_key signer,
                        heim_octet_string *request)
{
    CertificationRequest r;
    Extensions exts;
    heim_octet_string data;
    size_t size;
    int ret;

    request->data = NULL;
    request->length = 0;

    data.length = 0;
    data.data = NULL;

    if (req->name == NULL) {
	hx509_set_error_string(context, 0, EINVAL,
			       "PKCS10 needs to have a subject");
	return EINVAL;
    }

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

    /* Setup CSR */
    r.certificationRequestInfo.version = pkcs10_v1;
    ret = copy_Name(&req->name->der_name,
		    &r.certificationRequestInfo.subject);
    if (ret == 0)
        ret = copy_SubjectPublicKeyInfo(&req->key,
                                        &r.certificationRequestInfo.subjectPKInfo);

    /* Encode extReq attribute with requested Certificate Extensions */

    if (ret == 0)
        ret = get_exts(context, req, &exts);
    if (ret == 0 && exts.len) {
        Attribute *a = NULL; /* Quiet VC */
        heim_any extns;

        extns.data = NULL;
        extns.length = 0;
        r.certificationRequestInfo.attributes =
            calloc(1, sizeof(r.certificationRequestInfo.attributes[0]));
        if (r.certificationRequestInfo.attributes == NULL)
            ret = ENOMEM;
        if (ret == 0) {
            r.certificationRequestInfo.attributes[0].len = 1;
            r.certificationRequestInfo.attributes[0].val =
                calloc(1, sizeof(r.certificationRequestInfo.attributes[0].val[0]));
            if (r.certificationRequestInfo.attributes[0].val == NULL)
                ret = ENOMEM;
            if (ret == 0)
                a = r.certificationRequestInfo.attributes[0].val;
        }
        if (ret == 0)
            ASN1_MALLOC_ENCODE(Extensions, extns.data, extns.length,
                               &exts, &size, ret);
        if (ret == 0 && a)
            ret = der_copy_oid(&asn1_oid_id_pkcs9_extReq, &a->type);
        if (ret == 0)
            ret = add_AttributeValues(&a->value, &extns);
        free_heim_any(&extns);
    }

    /* Encode CSR body for signing */
    if (ret == 0)
        ASN1_MALLOC_ENCODE(CertificationRequestInfo, data.data, data.length,
                           &r.certificationRequestInfo, &size, ret);
    if (ret == 0 && data.length != size)
	abort();

    /* Self-sign CSR body */
    if (ret == 0) {
        ret = _hx509_create_signature_bitstring(context, signer,
                                                _hx509_crypto_default_sig_alg,
                                                &data,
                                                &r.signatureAlgorithm,
                                                &r.signature);
    }
    free(data.data);

    /* Encode CSR */
    if (ret == 0)
        ASN1_MALLOC_ENCODE(CertificationRequest, request->data, request->length,
                           &r, &size, ret);
    if (ret == 0 && request->length != size)
	abort();

    free_CertificationRequest(&r);
    free_Extensions(&exts);
    return ret;
}

/**
 * Parse an encoded CSR and verify its self-signature.
 *
 * @param context An hx509 context.
 * @param der The DER-encoded CSR.
 * @param req Where to put request object.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_parse_der(hx509_context context,
                        heim_octet_string *der,
                        hx509_request *req)
{
    CertificationRequestInfo *rinfo = NULL;
    CertificationRequest r;
    hx509_cert signer = NULL;
    Extensions exts;
    size_t i, size;
    int ret;

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

    /* Initial setup and decoding of CSR */
    ret = hx509_request_init(context, req);
    if (ret)
        return ret;
    ret = decode_CertificationRequest(der->data, der->length, &r, &size);
    if (ret) {
        hx509_set_error_string(context, 0, ret, "Failed to decode CSR");
        free(*req);
        *req = NULL;
        return ret;
    }
    rinfo = &r.certificationRequestInfo;

    /*
     * Setup a 'signer' for verifying the self-signature for proof of
     * possession.
     *
     * Sadly we need a "certificate" here because _hx509_verify_signature_*()
     * functions want one as a signer even though all the verification
     * functions that use the signer argument only ever use the spki of the
     * signer certificate.
     *
     * FIXME Change struct signature_alg's verify_signature's prototype to use
     *       an spki instead of an hx509_cert as the signer!  The we won't have
     *       to do this.
     */
    if (ret == 0) {
        Certificate c;
        memset(&c, 0, sizeof(c));
        c.tbsCertificate.subjectPublicKeyInfo = rinfo->subjectPKInfo;
        if ((signer = hx509_cert_init(context, &c, NULL)) == NULL)
            ret = ENOMEM;
    }

    /* Verify the signature */
    if (ret == 0)
        ret = _hx509_verify_signature_bitstring(context, signer,
                                                &r.signatureAlgorithm,
                                                &rinfo->_save,
                                                &r.signature);
    if (ret)
        hx509_set_error_string(context, 0, ret,
                               "CSR signature verification failed");
    hx509_cert_free(signer);

    /* Populate the hx509_request */
    if (ret == 0)
        ret = hx509_request_set_SubjectPublicKeyInfo(context, *req,
                                                     &rinfo->subjectPKInfo);
    if (ret == 0)
        ret = _hx509_name_from_Name(&rinfo->subject, &(*req)->name);

    /* Extract KUs, EKUs, and SANs from the CSR's attributes */
    if (ret || !rinfo->attributes || !rinfo->attributes[0].len)
        goto out;

    for (i = 0; ret == 0 && i < rinfo->attributes[0].len; i++) {
        Attribute *a = &rinfo->attributes[0].val[i];
        heim_any *av = NULL;

        /* We only support Extensions request attributes */
        if (der_heim_oid_cmp(&a->type, &asn1_oid_id_pkcs9_extReq) != 0) {
            char *oidstr = NULL;

            /*
             * We need an HX509_TRACE facility for this sort of warning.
             *
             * We'd put the warning in the context and then allow the caller to
             * extract and reset the warning.
             *
             * FIXME
             */
            der_print_heim_oid(&a->type, '.', &oidstr);
            warnx("Unknown or unsupported CSR attribute %s",
                  oidstr ? oidstr : "<error decoding OID>");
            free(oidstr);
            continue;
        }
        if (!a->value.val)
            continue;

        av = a->value.val;
        ret = decode_Extensions(av->data, av->length, &exts, NULL);
        if (ret) {
            hx509_set_error_string(context, 0, ret,
                                   "CSR signature verification failed "
                                   "due to invalid extReq attribute");
            goto out;
        }
    }
    for (i = 0; ret == 0 && i < exts.len; i++) {
        const char *what = "";
        Extension *e = &exts.val[i];

        if (der_heim_oid_cmp(&e->extnID,
                             &asn1_oid_id_x509_ce_keyUsage) == 0) {
            ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length,
                                  &(*req)->ku, NULL);
            what = "keyUsage";
            /*
             * Count all KUs as one requested extension to be authorized,
             * though the caller will have to check the KU values individually.
             */
            if (KeyUsage2int((*req)->ku) & ~KeyUsage2int(int2KeyUsage(~0ULL))) {
                if (e->critical)
                    (*req)->nunsupported_crit++;
                else
                    (*req)->nunsupported_opt++;
            }
        } else if (der_heim_oid_cmp(&e->extnID,
                                    &asn1_oid_id_x509_ce_extKeyUsage) == 0) {
            ret = decode_ExtKeyUsage(e->extnValue.data, e->extnValue.length,
                                     &(*req)->eku, NULL);
            what = "extKeyUsage";

            /*
             * Count each EKU as a separate requested extension to be
             * authorized.
             */
        } else if (der_heim_oid_cmp(&e->extnID,
                                    &asn1_oid_id_x509_ce_subjectAltName) == 0) {
            ret = decode_GeneralNames(e->extnValue.data, e->extnValue.length,
                                      &(*req)->san, NULL);
            what = "subjectAlternativeName";

            /*
             * Count each SAN as a separate requested extension to be
             * authorized.
             */
        } else if (der_heim_oid_cmp(&e->extnID,
                                    &asn1_oid_id_x509_ce_basicConstraints) == 0) {
            (*req)->include_BasicConstraints = 1;
            ret = decode_BasicConstraints(e->extnValue.data, e->extnValue.length,
                                          &(*req)->bc, NULL);
        } else {
            char *oidstr = NULL;

            if (e->critical)
                (*req)->nunsupported_crit++;
            else
                (*req)->nunsupported_opt++;

            /*
             * We need an HX509_TRACE facility for this sort of warning.
             *
             * We'd put the warning in the context and then allow the caller to
             * extract and reset the warning.
             *
             * FIXME
             */
            der_print_heim_oid(&e->extnID, '.', &oidstr);
            warnx("Unknown or unsupported CSR extension request %s",
                  oidstr ? oidstr : "<error decoding OID>");
            free(oidstr);
        }
        if (ret) {
            hx509_set_error_string(context, 0, ret,
                                   "CSR signature verification failed "
                                   "due to invalid %s extension", what);
            break;
        }
    }

out:
    free_CertificationRequest(&r);
    free_Extensions(&exts);
    if (ret)
        hx509_request_free(req);
    return ret;
}

/**
 * Parse an encoded CSR and verify its self-signature.
 *
 * @param context An hx509 context.
 * @param csr The name of a store containing the CSR ("PKCS10:/path/to/file")
 * @param req Where to put request object.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_parse(hx509_context context,
                    const char *csr,
                    hx509_request *req)
{
    heim_octet_string d;
    int ret;

    /* XXX Add support for PEM */
    if (strncmp(csr, "PKCS10:", 7) != 0) {
	hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,
                               "CSR location does not start with \"PKCS10:\": %s",
                               csr);
	return HX509_UNSUPPORTED_OPERATION;
    }

    ret = rk_undumpdata(csr + 7, &d.data, &d.length);
    if (ret) {
	hx509_set_error_string(context, 0, ret, "Could not read %s", csr);
	return ret;
    }

    ret = hx509_request_parse_der(context, &d, req);
    free(d.data);
    if (ret)
        hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
                               " (while parsing CSR from %s)", csr);
    return ret;
}

/**
 * Get some EKU from a CSR.  Usable as an iterator.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param idx The index of the EKU (0 for the first) to return
 * @param out A pointer to a char * variable where the OID will be placed
 *            (caller must free with free())
 *
 * @return Zero on success, HX509_NO_ITEM if no such item exists (denoting
 *         iteration end), or an error.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_get_eku(hx509_request req,
                      size_t idx,
                      char **out)
{
    *out = NULL;
    if (idx >= req->eku.len)
        return HX509_NO_ITEM;
    return der_print_heim_oid(&req->eku.val[idx], '.', out);
}

static int
abitstring_check(abitstring a, size_t n, int idx)
{
    size_t bytes;

    if (idx >= n)
        return HX509_NO_ITEM;

    bytes = (idx + 1) / CHAR_BIT + (((idx + 1) % CHAR_BIT) ? 1 : 0);
    if (a->feat_bytes < bytes)
        return 0;

    return !!(a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)));
}

/*
 * Sets and returns 0 if not already set, -1 if already set.  Positive return
 * values are system errors.
 */
static int
abitstring_set(abitstring a, size_t n, int idx)
{
    size_t bytes;

    if (idx >= n)
        return HX509_NO_ITEM;

    bytes = n / CHAR_BIT + ((n % CHAR_BIT) ? 1 : 0);
    if (a->feat_bytes < bytes) {
        unsigned char *tmp;

        if ((tmp = realloc(a->feats, bytes)) == NULL)
            return ENOMEM;
        memset(tmp + a->feat_bytes, 0, bytes - a->feat_bytes);
        a->feats = tmp;
        a->feat_bytes = bytes;
    }

    if (!(a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)))) {
        a->feats[idx / CHAR_BIT] |= 1UL<<(idx % CHAR_BIT);
        return 0;
    }
    return -1;
}

/*
 * Resets and returns 0 if not already reset, -1 if already reset.  Positive
 * return values are system errors.
 */
static int
abitstring_reset(abitstring a, size_t n, int idx)
{
    size_t bytes;

    if (idx >= n)
        return HX509_NO_ITEM;

    bytes = (idx + 1) / CHAR_BIT + (((idx + 1) % CHAR_BIT) ? 1 : 0);
    if (a->feat_bytes >= bytes &&
        (a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)))) {
        a->feats[idx / CHAR_BIT] &= ~(1UL<<(idx % CHAR_BIT));
        return 0;
    }
    return -1;
}

static int
authorize_feat(hx509_request req, abitstring a, size_t n, int idx)
{
    int ret;

    ret = abitstring_set(a, n, idx);
    switch (ret) {
    case 0:
        req->nauthorized++;
        HEIM_FALLTHROUGH;
    case -1:
        return 0;
    default:
        return ret;
    }
}

static int
reject_feat(hx509_request req, abitstring a, size_t n, int idx)
{
    int ret;

    ret = abitstring_reset(a, n, idx);
    switch (ret) {
    case 0:
        req->nauthorized--;
        HEIM_FALLTHROUGH;
    case -1:
        return 0;
    default:
        return ret;
    }
}

/**
 * Authorize issuance of a CA certificate as requested.
 *
 * @param req The hx509_request object.
 * @param pathLenConstraint the pathLenConstraint for the BasicConstraints (optional)
 *
 * @return an hx509 or system error.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_authorize_cA(hx509_request req, unsigned *pathLenConstraint)
{
    int ret;

    ret = hx509_request_set_cA(NULL, req, pathLenConstraint);
    req->ca_is_authorized++;
    return ret;
}

/**
 * Filter the requested KeyUsage and mark it authorized.
 *
 * @param req The hx509_request object.
 * @param ku Permitted KeyUsage
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION void HX509_LIB_CALL
hx509_request_authorize_ku(hx509_request req, KeyUsage ku)
{
    (void) hx509_request_set_ku(NULL, req, ku);
    req->ku = int2KeyUsage(KeyUsage2int(req->ku) & KeyUsage2int(ku));
    if (KeyUsage2int(ku))
        req->ku_are_authorized = 1;
}

/**
 * Mark a requested EKU as authorized.
 *
 * @param req The hx509_request object.
 * @param idx The index of an EKU that can be fetched with
 *            hx509_request_get_eku()
 *
 * @return Zero on success, an error otherwise.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_authorize_eku(hx509_request req, size_t idx)
{
    return authorize_feat(req, &req->authorized_EKUs, req->eku.len, idx);
}

/**
 * Mark a requested EKU as not authorized.
 *
 * @param req The hx509_request object.
 * @param idx The index of an EKU that can be fetched with
 *            hx509_request_get_eku()
 *
 * @return Zero on success, an error otherwise.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_reject_eku(hx509_request req, size_t idx)
{
    return reject_feat(req, &req->authorized_EKUs, req->eku.len, idx);
}

/**
 * Check if an EKU has been marked authorized.
 *
 * @param req The hx509_request object.
 * @param idx The index of an EKU that can be fetched with
 *            hx509_request_get_eku()
 *
 * @return Non-zero if authorized, zero if not.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_eku_authorized_p(hx509_request req, size_t idx)
{
    return abitstring_check(&req->authorized_EKUs, req->eku.len, idx);
}

/**
 * Mark a requested SAN as authorized.
 *
 * @param req The hx509_request object.
 * @param idx The cursor as modified by a SAN iterator.
 *
 * @return Zero on success, an error otherwise.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_authorize_san(hx509_request req, size_t idx)
{
    return authorize_feat(req, &req->authorized_SANs, req->san.len, idx);
}

/**
 * Mark a requested SAN as not authorized.
 *
 * @param req The hx509_request object.
 * @param idx The cursor as modified by a SAN iterator.
 *
 * @return Zero on success, an error otherwise.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_reject_san(hx509_request req, size_t idx)
{
    return reject_feat(req, &req->authorized_SANs, req->san.len, idx);
}

/**
 * Check if a SAN has been marked authorized.
 *
 * @param req The hx509_request object.
 * @param idx The index of a SAN that can be fetched with
 *            hx509_request_get_san()
 *
 * @return Non-zero if authorized, zero if not.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_san_authorized_p(hx509_request req, size_t idx)
{
    return abitstring_check(&req->authorized_SANs, req->san.len, idx);
}

/**
 * Return the count of unsupported requested certificate extensions.
 *
 * @param req The hx509_request object.
 * @return The number of unsupported certificate extensions requested.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION size_t HX509_LIB_CALL
hx509_request_count_unsupported(hx509_request req)
{
    return req->nunsupported_crit;
}

/**
 * Return the count of as-yet unauthorized certificate extensions requested.
 *
 * @param req The hx509_request object.
 * @return The number of as-yet unauthorized certificate extensions requested.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION size_t HX509_LIB_CALL
hx509_request_count_unauthorized(hx509_request req)
{
    size_t nrequested = req->eku.len + req->san.len +
        (KeyUsage2int(req->ku) ? 1 : 0) + !!req->bc.cA +
        req->nunsupported_crit;

    return nrequested - (req->nauthorized + req->ku_are_authorized + req->ca_is_authorized);
}

static hx509_san_type
san_map_type(GeneralName *san)
{
    static const struct {
        const heim_oid *oid;
        hx509_san_type type;
    } map[] = {
        { &asn1_oid_id_pkix_on_dnsSRV, HX509_SAN_TYPE_DNSSRV },
        { &asn1_oid_id_pkinit_san, HX509_SAN_TYPE_PKINIT },
        { &asn1_oid_id_pkix_on_xmppAddr, HX509_SAN_TYPE_XMPP },
        { &asn1_oid_id_pkinit_ms_san, HX509_SAN_TYPE_MS_UPN },
        { &asn1_oid_id_pkix_on_permanentIdentifier, HX509_SAN_TYPE_PERMANENT_ID },
        { &asn1_oid_id_on_hardwareModuleName, HX509_SAN_TYPE_HW_MODULE },
    };
    size_t i;

    switch (san->element) {
    case choice_GeneralName_rfc822Name:    return HX509_SAN_TYPE_EMAIL;
    case choice_GeneralName_dNSName:       return HX509_SAN_TYPE_DNSNAME;
    case choice_GeneralName_directoryName: return HX509_SAN_TYPE_DN;
    case choice_GeneralName_registeredID:  return HX509_SAN_TYPE_REGISTERED_ID;
    case choice_GeneralName_otherName: {
        for (i = 0; i < sizeof(map)/sizeof(map[0]); i++)
            if (der_heim_oid_cmp(&san->u.otherName.type_id, map[i].oid) == 0)
                return map[i].type;
    }
        HEIM_FALLTHROUGH;
    default:                               return HX509_SAN_TYPE_UNSUPPORTED;
    }
}

/**
 * Return the count of as-yet unauthorized certificate extensions requested.
 *
 * @param req The hx509_request object.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION size_t HX509_LIB_CALL
hx509_request_get_san(hx509_request req,
                      size_t idx,
                      hx509_san_type *type,
                      char **out)
{
    struct rk_strpool *pool = NULL;
    GeneralName *san;

    *out = NULL;
    if (idx >= req->san.len)
        return HX509_NO_ITEM;

    san = &req->san.val[idx];
    switch ((*type = san_map_type(san))) {
    case HX509_SAN_TYPE_UNSUPPORTED: return 0;
    case HX509_SAN_TYPE_EMAIL:
        *out = strndup(san->u.rfc822Name.data,
                       san->u.rfc822Name.length);
        break;
    case HX509_SAN_TYPE_DNSNAME:
        *out = strndup(san->u.dNSName.data,
                       san->u.dNSName.length);
        break;
    case HX509_SAN_TYPE_DNSSRV: {
        SRVName name;
        size_t size;
        int ret;

        ret = decode_SRVName(san->u.otherName.value.data,
                             san->u.otherName.value.length, &name, &size);
        if (ret)
            return ret;
        *out = strndup(name.data, name.length);
        break;
    }
    case HX509_SAN_TYPE_PERMANENT_ID: {
        PermanentIdentifier pi;
        size_t size;
        char *s = NULL;
        int ret;

        ret = decode_PermanentIdentifier(san->u.otherName.value.data,
                                         san->u.otherName.value.length,
                                         &pi, &size);
        if (ret == 0 && pi.assigner) {
            ret = der_print_heim_oid(pi.assigner, '.', &s);
            if (ret == 0 &&
                (pool = rk_strpoolprintf(NULL, "%s", s)) == NULL)
                ret = ENOMEM;
        } else if (ret == 0) {
            pool = rk_strpoolprintf(NULL, "-");
        }
        if (ret == 0 &&
            (pool = rk_strpoolprintf(pool, "%s%s",
                                     *pi.identifierValue ? " " : "",
                                     *pi.identifierValue ? *pi.identifierValue : "")) == NULL)
            ret = ENOMEM;
        if (ret == 0 && (*out = rk_strpoolcollect(pool)) == NULL)
            ret = ENOMEM;
        free_PermanentIdentifier(&pi);
        free(s);
        return ret;
    }
    case HX509_SAN_TYPE_HW_MODULE: {
        HardwareModuleName hn;
        size_t size;
        char *s = NULL;
        int ret;

        ret = decode_HardwareModuleName(san->u.otherName.value.data,
                                        san->u.otherName.value.length,
                                        &hn, &size);
        if (ret == 0 && hn.hwSerialNum.length > 256)
            hn.hwSerialNum.length = 256;
        if (ret == 0)
            ret = der_print_heim_oid(&hn.hwType, '.', &s);
        if (ret == 0)
            pool = rk_strpoolprintf(NULL, "%s", s);
        if (ret == 0 && pool)
            pool = rk_strpoolprintf(pool, " %.*s",
                                    (int)hn.hwSerialNum.length,
                                    (char *)hn.hwSerialNum.data);
        if (ret == 0 &&
            (pool == NULL || (*out = rk_strpoolcollect(pool)) == NULL))
            ret = ENOMEM;
        free_HardwareModuleName(&hn);
        return ret;
    }
    case HX509_SAN_TYPE_DN: {
        Name name;

        if (san->u.directoryName.element == choice_Name_rdnSequence) {
            name.element = choice_Name_rdnSequence;
            name.u.rdnSequence = san->u.directoryName.u.rdnSequence;
            return _hx509_Name_to_string(&name, out);
        }
        *type = HX509_SAN_TYPE_UNSUPPORTED;
        return 0;
    }
    case HX509_SAN_TYPE_REGISTERED_ID:
        return der_print_heim_oid(&san->u.registeredID, '.', out);
    case HX509_SAN_TYPE_XMPP:
        HEIM_FALLTHROUGH;
    case HX509_SAN_TYPE_MS_UPN: {
        int ret;

        ret = _hx509_unparse_utf8_string_name(req->context, &pool,
                                              &san->u.otherName.value);
        if ((*out = rk_strpoolcollect(pool)) == NULL)
            return hx509_enomem(req->context);
        return ret;
    }
    case HX509_SAN_TYPE_PKINIT: {
        int ret;

        ret = _hx509_unparse_KRB5PrincipalName(req->context, &pool,
                                               &san->u.otherName.value);
        if ((*out = rk_strpoolcollect(pool)) == NULL)
            return hx509_enomem(req->context);
        return ret;
    }
    default:
        *type = HX509_SAN_TYPE_UNSUPPORTED;
        return 0;
    }
    if (*out == NULL)
        return ENOMEM;
    return 0;
}

/**
 * Indicate if a CSR requested a CA certificate.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 *
 * @return 1 if the CSR requested CA certificate, 0 otherwise.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_get_cA(hx509_context context,
                     hx509_request req)
{
    return req->bc.cA;
}

/**
 * Return the CSR's requested BasicConstraints pathLenConstraint.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 *
 * @return -1 if no pathLenConstraint was requested (or the BasicConstraints
 * does not request a CA certificate), or the actual requested
 * pathLenConstraint.
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_get_cA_pathLenConstraint(hx509_context context,
                                       hx509_request req)
{
    if (req->bc.cA && req->bc.pathLenConstraint &&
        *req->bc.pathLenConstraint < INT_MAX)
        return *req->bc.pathLenConstraint;
    return -1;
}

/**
 * Display a CSR.
 *
 * @param context An hx509 context.
 * @param req The hx509_request object.
 * @param f A FILE * to print the CSR to.
 *
 * @return An hx509 error code, see hx509_get_error_string().
 *
 * @ingroup hx509_request
 */
HX509_LIB_FUNCTION int HX509_LIB_CALL
hx509_request_print(hx509_context context, hx509_request req, FILE *f)
{
    uint64_t ku_num;
    size_t i;
    char *s = NULL;
    int ret = 0;

    /*
     * It's really unformatunate that we can't reuse more of the
     * lib/hx509/print.c infrastructure here, as it's too focused on
     * Certificates.
     *
     * For that matter, it's really annoying that CSRs don't more resemble
     * Certificates.  Indeed, an ideal CSR would look like this:
     *
     *      CSRInfo ::= {
     *          desiredTbsCertificate TBSCertificate,
     *          attributes [1] SEQUENCE OF Attribute OPTIONAL,
     *      }
     *      CSR :: = {
     *          csrInfo CSRInfo,
     *          sigAlg AlgorithmIdentifier,
     *          signature BIT STRING
     *      }
     *
     * with everything related to the desired certificate in
     * desiredTbsCertificate and anything not related to the CSR's contents in
     * the 'attributes' field.
     *
     * That wouldn't allow one to have optional desired TBSCertificate
     * features, but hey.  One could express "gimme all or gimme nothing" as an
     * attribute, or "gimme what you can", then check what one got.
     */
    fprintf(f, "PKCS#10 CertificationRequest:\n");

    if (req->include_BasicConstraints) {
        fprintf(f, "  cA: %s\n", req->bc.cA ? "yes" : "no");
        if (req->bc.pathLenConstraint)
            fprintf(f, "  pathLenConstraint: %u\n", *req->bc.pathLenConstraint);
        else
            fprintf(f, "  pathLenConstraint: unspecified\n");
    }
    if (req->name) {
	char *subject;
	ret = hx509_name_to_string(req->name, &subject);
	if (ret) {
	    hx509_set_error_string(context, 0, ret, "Failed to print name");
	    return ret;
	}
        fprintf(f, "  name: %s\n", subject);
	free(subject);
    }
    /* XXX Use hx509_request_get_ku() accessor */
    if ((ku_num = KeyUsage2int(req->ku))) {
        const struct units *u;
        const char *first = " ";

        fprintf(f, "  key usage:");
        for (u = asn1_KeyUsage_units(); u->name; ++u) {
            if ((ku_num & u->mult)) {
                fprintf(f, "%s%s", first, u->name);
                first = ", ";
                ku_num &= ~u->mult;
            }
        }
        if (ku_num)
            fprintf(f, "%s<unknown-KeyUsage-value(s)>", first);
        fprintf(f, "\n");
    }
    if (req->eku.len) {
        const char *first = " ";

        fprintf(f, "  eku:");
        for (i = 0; ret == 0; i++) {
            free(s); s = NULL;
            ret = hx509_request_get_eku(req, i, &s);
            if (ret)
                break;
            fprintf(f, "%s{%s}", first, s);
            first = ", ";
        }
        fprintf(f, "\n");
    }
    free(s); s = NULL;
    if (ret == HX509_NO_ITEM)
        ret = 0;
    for (i = 0; ret == 0; i++) {
        hx509_san_type san_type;

        free(s); s = NULL;
        ret = hx509_request_get_san(req, i, &san_type, &s);
        if (ret)
            break;
        switch (san_type) {
        case HX509_SAN_TYPE_EMAIL:
            fprintf(f, "  san: rfc822Name: %s\n", s);
            break;
        case HX509_SAN_TYPE_DNSNAME:
            fprintf(f, "  san: dNSName: %s\n", s);
            break;
        case HX509_SAN_TYPE_DN:
            fprintf(f, "  san: dn: %s\n", s);
            break;
        case HX509_SAN_TYPE_REGISTERED_ID:
            fprintf(f, "  san: registeredID: %s\n", s);
            break;
        case HX509_SAN_TYPE_XMPP:
            fprintf(f, "  san: xmpp: %s\n", s);
            break;
        case HX509_SAN_TYPE_PKINIT:
            fprintf(f, "  san: pkinit: %s\n", s);
            break;
        case HX509_SAN_TYPE_MS_UPN:
            fprintf(f, "  san: ms-upn: %s\n", s);
            break;
        default:
            fprintf(f, "  san: <SAN type not supported>\n");
            break;
        }
    }
    if (req->nunsupported_crit) {
        fprintf(f, "  unsupported_critical_extensions_count: %u\n",
                (unsigned)req->nunsupported_crit);
    }
    if (req->nunsupported_crit) {
        fprintf(f, "  unsupported_optional_extensions_count: %u\n",
                (unsigned)req->nunsupported_opt);
    }
    free(s); s = NULL;
    if (ret == HX509_NO_ITEM)
        ret = 0;
    return ret;
}