Linux Audio

Check our new training course

Embedded Linux Audio

Check our new training course
with Creative Commons CC-BY-SA
lecture materials

Bootlin logo

Elixir Cross Referencer

Loading...
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
// SPDX-License-Identifier: BSD-2-Clause
/*
 * Copyright (c) 2017-2020, Linaro Limited
 */

#include <assert.h>
#include <inttypes.h>
#include <pkcs11_ta.h>
#include <stdlib.h>
#include <string_ext.h>
#include <tee_internal_api_extensions.h>
#include <tee_internal_api.h>
#include <trace.h>
#include <util.h>

#include "attributes.h"
#include "handle.h"
#include "pkcs11_attributes.h"
#include "pkcs11_helpers.h"
#include "pkcs11_token.h"
#include "sanitize_object.h"
#include "serializer.h"
#include "token_capabilities.h"

static uint32_t pkcs11_func2ckfm(enum processing_func function)
{
	switch (function) {
	case PKCS11_FUNCTION_DIGEST:
		return PKCS11_CKFM_DIGEST;
	case PKCS11_FUNCTION_GENERATE:
		return PKCS11_CKFM_GENERATE;
	case PKCS11_FUNCTION_GENERATE_PAIR:
		return PKCS11_CKFM_GENERATE_KEY_PAIR;
	case PKCS11_FUNCTION_DERIVE:
		return PKCS11_CKFM_DERIVE;
	case PKCS11_FUNCTION_WRAP:
		return PKCS11_CKFM_WRAP;
	case PKCS11_FUNCTION_UNWRAP:
		return PKCS11_CKFM_UNWRAP;
	case PKCS11_FUNCTION_ENCRYPT:
		return PKCS11_CKFM_ENCRYPT;
	case PKCS11_FUNCTION_DECRYPT:
		return PKCS11_CKFM_DECRYPT;
	case PKCS11_FUNCTION_SIGN:
		return PKCS11_CKFM_SIGN;
	case PKCS11_FUNCTION_VERIFY:
		return PKCS11_CKFM_VERIFY;
	case PKCS11_FUNCTION_SIGN_RECOVER:
		return PKCS11_CKFM_SIGN_RECOVER;
	case PKCS11_FUNCTION_VERIFY_RECOVER:
		return PKCS11_CKFM_VERIFY_RECOVER;
	default:
		return 0;
	}
}

enum pkcs11_rc
check_mechanism_against_processing(struct pkcs11_session *session,
				   enum pkcs11_mechanism_id mechanism_type,
				   enum processing_func function,
				   enum processing_step step)
{
	bool allowed = false;

	switch (step) {
	case PKCS11_FUNC_STEP_INIT:
		switch (function) {
		case PKCS11_FUNCTION_IMPORT:
		case PKCS11_FUNCTION_COPY:
		case PKCS11_FUNCTION_MODIFY:
		case PKCS11_FUNCTION_DESTROY:
			return PKCS11_CKR_OK;
		default:
			break;
		}
		/*
		 * Check that the returned PKCS11_CKFM_* flag from
		 * pkcs11_func2ckfm() is among the ones from
		 * mechanism_supported_flags().
		 */
		allowed = mechanism_supported_flags(mechanism_type) &
			  pkcs11_func2ckfm(function);
		break;

	case PKCS11_FUNC_STEP_ONESHOT:
		if (session->processing->always_authen &&
		    !session->processing->relogged)
			return PKCS11_CKR_USER_NOT_LOGGED_IN;

		if (session->processing->step == PKCS11_FUNC_STEP_UPDATE ||
		    session->processing->step == PKCS11_FUNC_STEP_FINAL) {
			EMSG("Cannot perform one-shot on active processing");
			return PKCS11_CKR_OPERATION_ACTIVE;
		}

		allowed = true;
		break;

	case PKCS11_FUNC_STEP_UPDATE:
		if (session->processing->always_authen &&
		    !session->processing->relogged)
			return PKCS11_CKR_USER_NOT_LOGGED_IN;

		if (session->processing->step == PKCS11_FUNC_STEP_ONESHOT ||
		    session->processing->step == PKCS11_FUNC_STEP_FINAL) {
			EMSG("Cannot perform update on finalized processing");
			return PKCS11_CKR_OPERATION_ACTIVE;
		}

		allowed = !mechanism_is_one_shot_only(mechanism_type);
		break;

	case PKCS11_FUNC_STEP_UPDATE_KEY:
		assert(function == PKCS11_FUNCTION_DIGEST);

		if (session->processing->always_authen &&
		    !session->processing->relogged)
			return PKCS11_CKR_USER_NOT_LOGGED_IN;

		allowed = true;
		break;

	case PKCS11_FUNC_STEP_FINAL:
		if (session->processing->always_authen &&
		    !session->processing->relogged)
			return PKCS11_CKR_USER_NOT_LOGGED_IN;

		if (session->processing->step == PKCS11_FUNC_STEP_ONESHOT) {
			EMSG("Cannot perform final on oneshot processing");
			return PKCS11_CKR_OPERATION_ACTIVE;
		}
		return PKCS11_CKR_OK;

	default:
		TEE_Panic(step);
		break;
	}

	if (!allowed) {
		EMSG("Processing %#x/%s not permitted (%u/%u)",
		     (unsigned int)mechanism_type, id2str_proc(mechanism_type),
		     function, step);
		return PKCS11_CKR_MECHANISM_INVALID;
	}

	return PKCS11_CKR_OK;
}

/*
 * Object default boolean attributes as per PKCS#11
 */
static uint8_t *pkcs11_object_default_boolprop(uint32_t attribute)
{
	static const uint8_t bool_true = 1;
	static const uint8_t bool_false;

	switch (attribute) {
	/* As per PKCS#11 default value */
	case PKCS11_CKA_MODIFIABLE:
	case PKCS11_CKA_COPYABLE:
	case PKCS11_CKA_DESTROYABLE:
		return (uint8_t *)&bool_true;
	case PKCS11_CKA_TOKEN:
	case PKCS11_CKA_PRIVATE:
	case PKCS11_CKA_WRAP_WITH_TRUSTED:
	case PKCS11_CKA_ALWAYS_AUTHENTICATE:
	case PKCS11_CKA_SENSITIVE:
		return (uint8_t *)&bool_false;
	/* Token specific default value */
	case PKCS11_CKA_SIGN:
	case PKCS11_CKA_VERIFY:
	case PKCS11_CKA_DERIVE:
	case PKCS11_CKA_ENCRYPT:
	case PKCS11_CKA_DECRYPT:
	case PKCS11_CKA_SIGN_RECOVER:
	case PKCS11_CKA_VERIFY_RECOVER:
	case PKCS11_CKA_WRAP:
	case PKCS11_CKA_UNWRAP:
	case PKCS11_CKA_EXTRACTABLE:
	case PKCS11_CKA_TRUSTED:
		return (uint8_t *)&bool_false;
	default:
		DMSG("No default for boolprop attribute %#"PRIx32, attribute);
		return NULL;
	}
}

/*
 * Object expects several boolean attributes to be set to a default value
 * or to a validate client configuration value. This function append the input
 * attribute (id/size/value) in the serialized object.
 */
static enum pkcs11_rc pkcs11_import_object_boolprop(struct obj_attrs **out,
						    struct obj_attrs *templ,
						    uint32_t attribute)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;
	uint8_t bbool = 0;
	uint32_t size = sizeof(uint8_t);
	void *attr = NULL;

	rc = get_attribute(templ, attribute, &bbool, &size);
	if (rc) {
		if (rc != PKCS11_RV_NOT_FOUND)
			return rc;
		attr = pkcs11_object_default_boolprop(attribute);
		if (!attr)
			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
	} else {
		attr = &bbool;
	}

	/* Boolean attributes are 1byte in the ABI, no alignment issue */
	return add_attribute(out, attribute, attr, sizeof(uint8_t));
}

static enum pkcs11_rc set_mandatory_boolprops(struct obj_attrs **out,
					      struct obj_attrs *temp,
					      uint32_t const *bp,
					      size_t bp_count)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;
	size_t n = 0;

	for (n = 0; n < bp_count; n++) {
		rc = pkcs11_import_object_boolprop(out, temp, bp[n]);
		if (rc)
			return rc;
	}

	return rc;
}

static enum pkcs11_rc set_mandatory_attributes(struct obj_attrs **out,
					       struct obj_attrs *temp,
					       uint32_t const *attrs,
					       size_t attrs_count)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;
	size_t n = 0;

	for (n = 0; n < attrs_count; n++) {
		uint32_t size = 0;
		void *value = NULL;

		if (get_attribute_ptr(temp, attrs[n], &value, &size))
			return PKCS11_CKR_TEMPLATE_INCOMPLETE;

		rc = add_attribute(out, attrs[n], value, size);
		if (rc)
			return rc;
	}

	return rc;
}

static enum pkcs11_rc get_default_value(enum pkcs11_attr_id id, void **value,
					uint32_t *size)
{
	/* should have been taken care of already */
	assert(!pkcs11_attr_is_boolean(id));

	/* All other attributes have an empty default value */
	*value = NULL;
	*size = 0;
	return PKCS11_CKR_OK;
}

static enum pkcs11_rc set_optional_attributes_with_def(struct obj_attrs **out,
						       struct obj_attrs *temp,
						       uint32_t const *attrs,
						       size_t attrs_count,
						       bool default_to_null)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;
	size_t n = 0;

	for (n = 0; n < attrs_count; n++) {
		uint32_t size = 0;
		void *value = NULL;

		rc = get_attribute_ptr(temp, attrs[n], &value, &size);
		if (rc == PKCS11_RV_NOT_FOUND) {
			if (default_to_null) {
				rc = get_default_value(attrs[n], &value, &size);
			} else {
				rc = PKCS11_CKR_OK;
				continue;
			}
		}
		if (rc)
			return rc;

		rc = add_attribute(out, attrs[n], value, size);
		if (rc)
			return rc;
	}

	return rc;
}

static enum pkcs11_rc set_attributes_opt_or_null(struct obj_attrs **out,
						 struct obj_attrs *temp,
						 uint32_t const *attrs,
						 size_t attrs_count)
{
	return set_optional_attributes_with_def(out, temp, attrs, attrs_count,
						true /* defaults to empty */);
}

static enum pkcs11_rc set_optional_attributes(struct obj_attrs **out,
					      struct obj_attrs *temp,
					      uint32_t const *attrs,
					      size_t attrs_count)
{
	return set_optional_attributes_with_def(out, temp, attrs, attrs_count,
						false /* no default value */);
}

/*
 * Below are listed the mandated or optional expected attributes for
 * PKCS#11 storage objects.
 *
 * Note: boolprops (mandated boolean attributes) PKCS11_CKA_ALWAYS_SENSITIVE,
 * and PKCS11_CKA_NEVER_EXTRACTABLE are set by the token, not provided
 * in the client template.
 */

/* PKCS#11 specification for any object (session/token) of the storage */
static const uint32_t any_object_boolprops[] = {
	PKCS11_CKA_TOKEN, PKCS11_CKA_PRIVATE,
	PKCS11_CKA_MODIFIABLE, PKCS11_CKA_COPYABLE, PKCS11_CKA_DESTROYABLE,
};

static const uint32_t any_object_opt_or_null[] = {
	PKCS11_CKA_LABEL,
};

/* PKCS#11 specification for raw data object (+any_object_xxx) */
const uint32_t raw_data_opt_or_null[] = {
	PKCS11_CKA_OBJECT_ID, PKCS11_CKA_APPLICATION, PKCS11_CKA_VALUE,
};

/* PKCS#11 specification for certificate object (+pkcs11_any_object_xxx) */
static const uint32_t pkcs11_certificate_mandated[] = {
	PKCS11_CKA_CERTIFICATE_TYPE,
};

static const uint32_t pkcs11_certificate_boolprops[] = {
	PKCS11_CKA_TRUSTED,
};

static const uint32_t pkcs11_certificate_optional[] = {
	PKCS11_CKA_CERTIFICATE_CATEGORY, PKCS11_CKA_CHECK_VALUE,
	PKCS11_CKA_START_DATE, PKCS11_CKA_END_DATE, PKCS11_CKA_PUBLIC_KEY_INFO,
};

/*
 * PKCS#11 specification for X.509 certificate object (+pkcs11_certificate_xxx)
 */
static const uint32_t pkcs11_x509_certificate_mandated[] = {
	PKCS11_CKA_SUBJECT,
};

static const uint32_t pkcs11_x509_certificate_optional[] = {
	PKCS11_CKA_ID, PKCS11_CKA_ISSUER, PKCS11_CKA_SERIAL_NUMBER,
	PKCS11_CKA_VALUE, PKCS11_CKA_URL,
	PKCS11_CKA_HASH_OF_SUBJECT_PUBLIC_KEY,
	PKCS11_CKA_HASH_OF_ISSUER_PUBLIC_KEY,
	PKCS11_CKA_JAVA_MIDP_SECURITY_DOMAIN, PKCS11_CKA_NAME_HASH_ALGORITHM,
};

/* PKCS#11 specification for any key object (+any_object_xxx) */
static const uint32_t any_key_boolprops[] = {
	PKCS11_CKA_DERIVE,
};

static const uint32_t any_key_opt_or_null[] = {
	PKCS11_CKA_ID,
	PKCS11_CKA_START_DATE, PKCS11_CKA_END_DATE,
};

static const uint32_t any_key_optional[] = {
	PKCS11_CKA_ALLOWED_MECHANISMS,
};

/* PKCS#11 specification for any symmetric key (+any_key_xxx) */
static const uint32_t symm_key_boolprops[] = {
	PKCS11_CKA_ENCRYPT, PKCS11_CKA_DECRYPT,
	PKCS11_CKA_SIGN, PKCS11_CKA_VERIFY,
	PKCS11_CKA_WRAP, PKCS11_CKA_UNWRAP,
	PKCS11_CKA_SENSITIVE, PKCS11_CKA_EXTRACTABLE,
	PKCS11_CKA_WRAP_WITH_TRUSTED, PKCS11_CKA_TRUSTED,
};

static const uint32_t symm_key_opt_or_null[] = {
	PKCS11_CKA_WRAP_TEMPLATE, PKCS11_CKA_UNWRAP_TEMPLATE,
	PKCS11_CKA_DERIVE_TEMPLATE, PKCS11_CKA_VALUE,
};

static const uint32_t symm_key_optional[] = {
	PKCS11_CKA_VALUE_LEN,
};

/* PKCS#11 specification for any asymmetric public key (+any_key_xxx) */
static const uint32_t public_key_boolprops[] = {
	PKCS11_CKA_ENCRYPT, PKCS11_CKA_VERIFY, PKCS11_CKA_VERIFY_RECOVER,
	PKCS11_CKA_WRAP,
	PKCS11_CKA_TRUSTED,
};

static const uint32_t public_key_mandated[] = {
};

static const uint32_t public_key_opt_or_null[] = {
	PKCS11_CKA_SUBJECT, PKCS11_CKA_WRAP_TEMPLATE,
	PKCS11_CKA_PUBLIC_KEY_INFO,
};

/* PKCS#11 specification for any asymmetric private key (+any_key_xxx) */
static const uint32_t private_key_boolprops[] = {
	PKCS11_CKA_DECRYPT, PKCS11_CKA_SIGN, PKCS11_CKA_SIGN_RECOVER,
	PKCS11_CKA_UNWRAP,
	PKCS11_CKA_SENSITIVE, PKCS11_CKA_EXTRACTABLE,
	PKCS11_CKA_WRAP_WITH_TRUSTED, PKCS11_CKA_ALWAYS_AUTHENTICATE,
};

static const uint32_t private_key_mandated[] = {
};

static const uint32_t private_key_opt_or_null[] = {
	PKCS11_CKA_SUBJECT, PKCS11_CKA_UNWRAP_TEMPLATE,
	PKCS11_CKA_PUBLIC_KEY_INFO,
};

/* PKCS#11 specification for any RSA key (+public/private_key_xxx) */
static const uint32_t rsa_pub_key_gen_mand[] = {
	PKCS11_CKA_MODULUS_BITS,
};

static const uint32_t rsa_pub_key_create_mand[] = {
	PKCS11_CKA_MODULUS, PKCS11_CKA_PUBLIC_EXPONENT,
};

static const uint32_t rsa_pub_key_gen_opt_or_null[] = {
	PKCS11_CKA_PUBLIC_EXPONENT,
};

static const uint32_t rsa_priv_key_opt_or_null[] = {
	PKCS11_CKA_MODULUS, PKCS11_CKA_PUBLIC_EXPONENT,
	PKCS11_CKA_PRIVATE_EXPONENT,
	PKCS11_CKA_PRIME_1, PKCS11_CKA_PRIME_2,
	PKCS11_CKA_EXPONENT_1, PKCS11_CKA_EXPONENT_2, PKCS11_CKA_COEFFICIENT,
};

/* PKCS#11 specification for any EC key (+public/private_key_xxx) */
static const uint32_t ec_public_key_mandated[] = {
	PKCS11_CKA_EC_PARAMS,
};

static const uint32_t ec_public_key_opt_or_null[] = {
	PKCS11_CKA_EC_POINT,
};

static const uint32_t ec_private_key_mandated[] = {
};

static const uint32_t ec_private_key_opt_or_null[] = {
	PKCS11_CKA_EC_PARAMS,
	PKCS11_CKA_VALUE,
};

static enum pkcs11_rc create_storage_attributes(struct obj_attrs **out,
						struct obj_attrs *temp)
{
	enum pkcs11_class_id class = PKCS11_CKO_UNDEFINED_ID;
	enum pkcs11_rc rc = PKCS11_CKR_OK;

	rc = init_attributes_head(out);
	if (rc)
		return rc;

	/* Object class is mandatory */
	class = get_class(temp);
	if (class == PKCS11_CKO_UNDEFINED_ID) {
		EMSG("Class attribute not found");

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}
	rc = add_attribute(out, PKCS11_CKA_CLASS, &class, sizeof(uint32_t));
	if (rc)
		return rc;

	rc = set_mandatory_boolprops(out, temp, any_object_boolprops,
				     ARRAY_SIZE(any_object_boolprops));
	if (rc)
		return rc;

	return set_attributes_opt_or_null(out, temp, any_object_opt_or_null,
					  ARRAY_SIZE(any_object_opt_or_null));
}

static enum pkcs11_rc create_genkey_attributes(struct obj_attrs **out,
					       struct obj_attrs *temp)
{
	uint32_t type = PKCS11_CKO_UNDEFINED_ID;
	enum pkcs11_rc rc = PKCS11_CKR_OK;

	rc = create_storage_attributes(out, temp);
	if (rc)
		return rc;

	type = get_key_type(temp);
	if (type == PKCS11_CKK_UNDEFINED_ID) {
		EMSG("Key type attribute not found");

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}
	rc = add_attribute(out, PKCS11_CKA_KEY_TYPE, &type, sizeof(uint32_t));
	if (rc)
		return rc;

	rc = set_mandatory_boolprops(out, temp, any_key_boolprops,
				     ARRAY_SIZE(any_key_boolprops));
	if (rc)
		return rc;

	rc = set_attributes_opt_or_null(out, temp, any_key_opt_or_null,
					ARRAY_SIZE(any_key_opt_or_null));
	if (rc)
		return rc;

	return set_optional_attributes(out, temp, any_key_optional,
				       ARRAY_SIZE(any_key_optional));

}

static enum pkcs11_rc create_symm_key_attributes(struct obj_attrs **out,
						 struct obj_attrs *temp)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;

	assert(get_class(temp) == PKCS11_CKO_SECRET_KEY);

	rc = create_genkey_attributes(out, temp);
	if (rc)
		return rc;

	assert(get_class(*out) == PKCS11_CKO_SECRET_KEY);

	switch (get_key_type(*out)) {
	case PKCS11_CKK_GENERIC_SECRET:
	case PKCS11_CKK_AES:
	case PKCS11_CKK_MD5_HMAC:
	case PKCS11_CKK_SHA_1_HMAC:
	case PKCS11_CKK_SHA256_HMAC:
	case PKCS11_CKK_SHA384_HMAC:
	case PKCS11_CKK_SHA512_HMAC:
	case PKCS11_CKK_SHA224_HMAC:
		break;
	default:
		EMSG("Invalid key type %#"PRIx32"/%s",
		     get_key_type(*out), id2str_key_type(get_key_type(*out)));

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	rc = set_mandatory_boolprops(out, temp, symm_key_boolprops,
				     ARRAY_SIZE(symm_key_boolprops));
	if (rc)
		return rc;

	rc = set_attributes_opt_or_null(out, temp, symm_key_opt_or_null,
					ARRAY_SIZE(symm_key_opt_or_null));
	if (rc)
		return rc;

	return set_optional_attributes(out, temp, symm_key_optional,
				       ARRAY_SIZE(symm_key_optional));
}

static enum pkcs11_rc create_data_attributes(struct obj_attrs **out,
					     struct obj_attrs *temp)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;

	assert(get_class(temp) == PKCS11_CKO_DATA);

	rc = create_storage_attributes(out, temp);
	if (rc)
		return rc;

	assert(get_class(*out) == PKCS11_CKO_DATA);

	return set_attributes_opt_or_null(out, temp, raw_data_opt_or_null,
					  ARRAY_SIZE(raw_data_opt_or_null));
}

static enum pkcs11_rc create_certificate_attributes(struct obj_attrs **out,
						    struct obj_attrs *temp)
{
	uint32_t const *mandated = NULL;
	uint32_t const *optional = NULL;
	size_t mandated_count = 0;
	size_t optional_count = 0;
	void *attr_value = NULL;
	uint32_t attr_size = 0;
	uint32_t default_cert_category =
		PKCS11_CK_CERTIFICATE_CATEGORY_UNSPECIFIED;
	uint32_t default_name_hash_alg = PKCS11_CKM_SHA_1;
	uint32_t cert_category = 0;
	enum pkcs11_rc rc = PKCS11_CKR_OK;

	assert(get_class(temp) == PKCS11_CKO_CERTIFICATE);

	rc = create_storage_attributes(out, temp);
	if (rc)
		return rc;

	assert(get_class(*out) == PKCS11_CKO_CERTIFICATE);

	rc = set_mandatory_boolprops(out, temp, pkcs11_certificate_boolprops,
				     ARRAY_SIZE(pkcs11_certificate_boolprops));
	if (rc)
		return rc;

	rc = set_mandatory_attributes(out, temp, pkcs11_certificate_mandated,
				      ARRAY_SIZE(pkcs11_certificate_mandated));
	if (rc)
		return rc;

	rc = set_optional_attributes(out, temp, pkcs11_certificate_optional,
				     ARRAY_SIZE(pkcs11_certificate_optional));
	if (rc)
		return rc;

	switch (get_certificate_type(*out)) {
	case PKCS11_CKC_X_509:
		mandated = pkcs11_x509_certificate_mandated;
		optional = pkcs11_x509_certificate_optional;
		mandated_count = ARRAY_SIZE(pkcs11_x509_certificate_mandated);
		optional_count = ARRAY_SIZE(pkcs11_x509_certificate_optional);
		break;
	default:
		EMSG("Invalid certificate type %#"PRIx32"/%s",
		     get_certificate_type(*out),
		     id2str_certificate_type(get_certificate_type(*out)));

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	rc = set_mandatory_attributes(out, temp, mandated, mandated_count);
	if (rc)
		return rc;

	rc = set_optional_attributes(out, temp, optional, optional_count);
	if (rc)
		return rc;

	attr_size = 0;
	rc = get_attribute_ptr(*out, PKCS11_CKA_CERTIFICATE_CATEGORY,
			       &attr_value, &attr_size);
	if (rc == PKCS11_CKR_OK && attr_size == sizeof(cert_category)) {
		/* Sanitize certificate category */
		TEE_MemMove(&cert_category, attr_value, sizeof(cert_category));

		switch (cert_category) {
		case PKCS11_CK_CERTIFICATE_CATEGORY_UNSPECIFIED:
		case PKCS11_CK_CERTIFICATE_CATEGORY_TOKEN_USER:
		case PKCS11_CK_CERTIFICATE_CATEGORY_AUTHORITY:
		case PKCS11_CK_CERTIFICATE_CATEGORY_OTHER_ENTITY:
			break;
		default:
			EMSG("Invalid certificate category %#"PRIx32,
			     cert_category);

			return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
		}
	} else if (rc == PKCS11_RV_NOT_FOUND) {
		/* Set default category when missing */
		rc = set_attribute(out, PKCS11_CKA_CERTIFICATE_CATEGORY,
				   &default_cert_category,
				   sizeof(default_cert_category));
		if (rc)
			return rc;
	} else {
		/* All other cases are errors */
		EMSG("Invalid certificate category");

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	attr_size = 0;
	rc = get_attribute_ptr(*out, PKCS11_CKA_NAME_HASH_ALGORITHM, NULL,
			       &attr_size);
	if (rc == PKCS11_CKR_OK && attr_size == sizeof(uint32_t)) {
		/* We accept any algorithm what caller wanted to specify */
	} else if (rc == PKCS11_RV_NOT_FOUND) {
		/* Set default hash algorithm when missing */
		rc = set_attribute(out, PKCS11_CKA_NAME_HASH_ALGORITHM,
				   &default_name_hash_alg,
				   sizeof(default_name_hash_alg));
		if (rc)
			return rc;
	} else {
		/* All other cases are errors */
		EMSG("Invalid name hash algorithm");

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	return rc;
}

static enum pkcs11_rc create_pub_key_attributes(struct obj_attrs **out,
						struct obj_attrs *temp,
						enum processing_func function)
{
	uint32_t const *mandated = NULL;
	uint32_t const *oon = NULL;
	size_t mandated_count = 0;
	size_t oon_count = 0;
	enum pkcs11_rc rc = PKCS11_CKR_OK;

	assert(get_class(temp) == PKCS11_CKO_PUBLIC_KEY);

	rc = create_genkey_attributes(out, temp);
	if (rc)
		return rc;

	assert(get_class(*out) == PKCS11_CKO_PUBLIC_KEY);

	rc = set_mandatory_boolprops(out, temp, public_key_boolprops,
				     ARRAY_SIZE(public_key_boolprops));
	if (rc)
		return rc;

	rc = set_mandatory_attributes(out, temp, public_key_mandated,
				      ARRAY_SIZE(public_key_mandated));
	if (rc)
		return rc;

	rc = set_attributes_opt_or_null(out, temp,
					public_key_opt_or_null,
					ARRAY_SIZE(public_key_opt_or_null));
	if (rc)
		return rc;

	switch (get_key_type(*out)) {
	case PKCS11_CKK_RSA:
		switch (function) {
		case PKCS11_FUNCTION_GENERATE_PAIR:
			mandated = rsa_pub_key_gen_mand;
			oon = rsa_pub_key_gen_opt_or_null;
			mandated_count = ARRAY_SIZE(rsa_pub_key_gen_mand);
			oon_count = ARRAY_SIZE(rsa_pub_key_gen_opt_or_null);
			break;
		case PKCS11_FUNCTION_IMPORT:
			mandated = rsa_pub_key_create_mand;
			mandated_count = ARRAY_SIZE(rsa_pub_key_create_mand);
			break;
		default:
			EMSG("Unsupported function %#"PRIx32"/%s", function,
			     id2str_function(function));

			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
		}
		break;
	case PKCS11_CKK_EC:
		mandated = ec_public_key_mandated;
		oon = ec_public_key_opt_or_null;
		mandated_count = ARRAY_SIZE(ec_public_key_mandated);
		oon_count = ARRAY_SIZE(ec_public_key_opt_or_null);
		break;
	default:
		EMSG("Invalid key type %#"PRIx32"/%s",
		     get_key_type(*out), id2str_key_type(get_key_type(*out)));

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	rc = set_mandatory_attributes(out, temp, mandated, mandated_count);
	if (rc)
		return rc;

	return set_attributes_opt_or_null(out, temp, oon, oon_count);
}

static enum pkcs11_rc create_priv_key_attributes(struct obj_attrs **out,
						 struct obj_attrs *temp)
{
	uint32_t const *mandated = NULL;
	uint32_t const *oon = NULL;
	size_t mandated_count = 0;
	size_t oon_count = 0;
	enum pkcs11_rc rc = PKCS11_CKR_OK;

	assert(get_class(temp) == PKCS11_CKO_PRIVATE_KEY);

	rc = create_genkey_attributes(out, temp);
	if (rc)
		return rc;

	assert(get_class(*out) == PKCS11_CKO_PRIVATE_KEY);

	rc = set_mandatory_boolprops(out, temp, private_key_boolprops,
				     ARRAY_SIZE(private_key_boolprops));
	if (rc)
		return rc;

	rc = set_mandatory_attributes(out, temp, private_key_mandated,
				      ARRAY_SIZE(private_key_mandated));
	if (rc)
		return rc;

	rc = set_attributes_opt_or_null(out, temp, private_key_opt_or_null,
					ARRAY_SIZE(private_key_opt_or_null));
	if (rc)
		return rc;

	switch (get_key_type(*out)) {
	case PKCS11_CKK_RSA:
		oon = rsa_priv_key_opt_or_null;
		oon_count = ARRAY_SIZE(rsa_priv_key_opt_or_null);
		break;
	case PKCS11_CKK_EC:
		mandated = ec_private_key_mandated;
		oon = ec_private_key_opt_or_null;
		mandated_count = ARRAY_SIZE(ec_private_key_mandated);
		oon_count = ARRAY_SIZE(ec_private_key_opt_or_null);
		break;
	default:
		EMSG("Invalid key type %#"PRIx32"/%s",
		     get_key_type(*out), id2str_key_type(get_key_type(*out)));

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	rc = set_mandatory_attributes(out, temp, mandated, mandated_count);
	if (rc)
		return rc;

	return set_attributes_opt_or_null(out, temp, oon, oon_count);
}

static enum pkcs11_rc
sanitize_symm_key_attributes(struct obj_attrs **temp,
			     enum processing_func function)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;
	uint32_t a_size = 0;

	assert(get_class(*temp) == PKCS11_CKO_SECRET_KEY);

	rc = get_attribute_ptr(*temp, PKCS11_CKA_VALUE, NULL, &a_size);

	switch (get_key_type(*temp)) {
	case PKCS11_CKK_GENERIC_SECRET:
	case PKCS11_CKK_AES:
	case PKCS11_CKK_MD5_HMAC:
	case PKCS11_CKK_SHA_1_HMAC:
	case PKCS11_CKK_SHA256_HMAC:
	case PKCS11_CKK_SHA384_HMAC:
	case PKCS11_CKK_SHA512_HMAC:
	case PKCS11_CKK_SHA224_HMAC:
		switch (function) {
		case PKCS11_FUNCTION_IMPORT:
			/* CKA_VALUE is a mandatory with C_CreateObject */
			if (rc || a_size == 0)
				return PKCS11_CKR_TEMPLATE_INCONSISTENT;

			if (get_attribute_ptr(*temp, PKCS11_CKA_VALUE_LEN, NULL,
					      NULL) != PKCS11_RV_NOT_FOUND)
				return PKCS11_CKR_TEMPLATE_INCONSISTENT;

			return add_attribute(temp, PKCS11_CKA_VALUE_LEN,
					     &a_size, sizeof(uint32_t));
		case PKCS11_FUNCTION_GENERATE:
			if (rc != PKCS11_RV_NOT_FOUND)
				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
			break;
		default:
			break;
		}
		break;
	default:
		EMSG("Invalid key type %#"PRIx32"/%s",
		     get_key_type(*temp), id2str_key_type(get_key_type(*temp)));

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	return PKCS11_CKR_OK;
}

/*
 * Create an attribute list for a new object from a template and a parent
 * object (optional) for an object generation function (generate, copy,
 * derive...).
 *
 * PKCS#11 directives on the supplied template and expected return value:
 * - template has an invalid attribute ID: ATTRIBUTE_TYPE_INVALID
 * - template has an invalid value for an attribute: ATTRIBUTE_VALID_INVALID
 * - template has value for a read-only attribute: ATTRIBUTE_READ_ONLY
 * - template+default+parent => still miss an attribute: TEMPLATE_INCONSISTENT
 *
 * INFO on PKCS11_CMD_COPY_OBJECT:
 * - parent PKCS11_CKA_COPYIABLE=false => return ACTION_PROHIBITED.
 * - template can specify PKCS11_CKA_TOKEN, PKCS11_CKA_PRIVATE,
 *   PKCS11_CKA_MODIFIABLE, PKCS11_CKA_DESTROYABLE.
 * - SENSITIVE can change from false to true, not from true to false.
 * - LOCAL is the parent LOCAL
 */
enum pkcs11_rc
create_attributes_from_template(struct obj_attrs **out, void *template,
				size_t template_size,
				struct obj_attrs *parent,
				enum processing_func function,
				enum pkcs11_mechanism_id mecha,
				enum pkcs11_class_id template_class)
{
	struct obj_attrs *temp = NULL;
	struct obj_attrs *attrs = NULL;
	enum pkcs11_rc rc = PKCS11_CKR_OK;
	uint8_t local = 0;
	uint8_t always_sensitive = 0;
	uint8_t never_extract = 0;
	uint8_t extractable = 0;
	uint32_t class = PKCS11_UNDEFINED_ID;
	uint32_t type = PKCS11_UNDEFINED_ID;
	uint32_t mechanism_id = PKCS11_CKM_UNDEFINED_ID;
	struct obj_attrs *req_attrs = NULL;
	uint32_t size = 0;
	uint32_t indirect_template = PKCS11_CKA_UNDEFINED_ID;

#ifdef DEBUG	/* Sanity: check function argument */
	trace_attributes_from_api_head("template", template, template_size);
	switch (function) {
	case PKCS11_FUNCTION_GENERATE:
	case PKCS11_FUNCTION_GENERATE_PAIR:
	case PKCS11_FUNCTION_IMPORT:
	case PKCS11_FUNCTION_MODIFY:
	case PKCS11_FUNCTION_DERIVE:
	case PKCS11_FUNCTION_UNWRAP:
	case PKCS11_FUNCTION_COPY:
		break;
	default:
		TEE_Panic(TEE_ERROR_NOT_SUPPORTED);
	}
#endif

	/*
	 * For PKCS11_FUNCTION_GENERATE, find the class and type
	 * based on the mechanism. These will be passed as hint
	 * sanitize_client_object() and added in temp if not
	 * already present
	 */
	if (function == PKCS11_FUNCTION_GENERATE) {
		switch (mecha) {
		case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
			class = PKCS11_CKO_SECRET_KEY;
			type = PKCS11_CKK_GENERIC_SECRET;
			break;
		case PKCS11_CKM_AES_KEY_GEN:
			class = PKCS11_CKO_SECRET_KEY;
			type = PKCS11_CKK_AES;
			break;
		default:
			TEE_Panic(TEE_ERROR_NOT_SUPPORTED);
		}
	}

	/*
	 * For PKCS11_FUNCTION_GENERATE_PAIR, find the class and type
	 * based on the mechanism. These will be passed as hint
	 * sanitize_client_object() and added in temp if not
	 * already present
	 */
	if (function == PKCS11_FUNCTION_GENERATE_PAIR) {
		switch (mecha) {
		case PKCS11_CKM_EC_KEY_PAIR_GEN:
			class = template_class;
			type = PKCS11_CKK_EC;
			break;
		case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
			class = template_class;
			type = PKCS11_CKK_RSA;
			break;
		default:
			TEE_Panic(TEE_ERROR_NOT_SUPPORTED);
		}
	}

	/*
	 * Check and remove duplicates if any and create a new temporary
	 * template
	 */
	rc = sanitize_client_object(&temp, template, template_size, class,
				    type);
	if (rc)
		goto out;

	/*
	 * For function type modify and copy return the created template
	 * from here. Rest of the code below is for creating objects
	 * or generating keys.
	 */
	switch (function) {
	case PKCS11_FUNCTION_MODIFY:
	case PKCS11_FUNCTION_COPY:
		*out = temp;
		return rc;
	case PKCS11_FUNCTION_DERIVE:
	case PKCS11_FUNCTION_UNWRAP:
		if (function == PKCS11_FUNCTION_UNWRAP)
			indirect_template = PKCS11_CKA_UNWRAP_TEMPLATE;
		else
			indirect_template = PKCS11_CKA_DERIVE_TEMPLATE;

		rc = get_attribute_ptr(parent, indirect_template,
				       (void *)&req_attrs, &size);
		if (rc == PKCS11_CKR_OK && size != 0) {
			rc = attributes_match_add_reference(&temp, req_attrs);
			if (rc)
				goto out;
		}
		break;
	default:
		break;
	}

	/*
	 * Check if class and type in temp are consistent with the mechanism
	 */
	switch (mecha) {
	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
		if (get_class(temp) != PKCS11_CKO_SECRET_KEY ||
		    get_key_type(temp) != PKCS11_CKK_GENERIC_SECRET) {
			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
			goto out;
		}
		break;
	case PKCS11_CKM_AES_KEY_GEN:
		if (get_class(temp) != PKCS11_CKO_SECRET_KEY ||
		    get_key_type(temp) != PKCS11_CKK_AES) {
			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
			goto out;
		}
		break;
	case PKCS11_CKM_EC_KEY_PAIR_GEN:
		if ((get_class(temp) != PKCS11_CKO_PUBLIC_KEY &&
		     get_class(temp) != PKCS11_CKO_PRIVATE_KEY) ||
		    get_key_type(temp) != PKCS11_CKK_EC) {
			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
			goto out;
		}
		break;
	case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
		if ((get_class(temp) != PKCS11_CKO_PUBLIC_KEY &&
		     get_class(temp) != PKCS11_CKO_PRIVATE_KEY) ||
		    get_key_type(temp) != PKCS11_CKK_RSA) {
			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
			goto out;
		}
		break;
	default:
		break;
	}

	if (!sanitize_consistent_class_and_type(temp)) {
		EMSG("Inconsistent class/type");
		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
		goto out;
	}

	/*
	 * TBD - Add a check to see if temp contains any attribute which
	 * is not consistent with the object class or type and return error.
	 * In current implementation such attributes are ignored and not
	 * added to final object while PKCS#11 specification expects a
	 * failure and an error code be returned.
	 */

	switch (get_class(temp)) {
	case PKCS11_CKO_DATA:
		rc = create_data_attributes(&attrs, temp);
		break;
	case PKCS11_CKO_CERTIFICATE:
		rc = create_certificate_attributes(&attrs, temp);
		break;
	case PKCS11_CKO_SECRET_KEY:
		rc = sanitize_symm_key_attributes(&temp, function);
		if (rc)
			goto out;
		rc = create_symm_key_attributes(&attrs, temp);
		break;
	case PKCS11_CKO_PUBLIC_KEY:
		rc = create_pub_key_attributes(&attrs, temp, function);
		break;
	case PKCS11_CKO_PRIVATE_KEY:
		rc = create_priv_key_attributes(&attrs, temp);
		break;
	default:
		DMSG("Invalid object class %#"PRIx32"/%s",
		     get_class(temp), id2str_class(get_class(temp)));

		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
		break;
	}
	if (rc)
		goto out;

	if (get_attribute_ptr(temp, PKCS11_CKA_LOCAL, NULL, NULL) !=
	    PKCS11_RV_NOT_FOUND) {
		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
		goto out;
	}

	if (get_attribute_ptr(temp, PKCS11_CKA_KEY_GEN_MECHANISM, NULL, NULL) !=
	    PKCS11_RV_NOT_FOUND) {
		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
		goto out;
	}

	switch (function) {
	case PKCS11_FUNCTION_GENERATE:
	case PKCS11_FUNCTION_GENERATE_PAIR:
		local = PKCS11_TRUE;
		break;
	case PKCS11_FUNCTION_IMPORT:
	case PKCS11_FUNCTION_DERIVE:
	case PKCS11_FUNCTION_UNWRAP:
	default:
		local = PKCS11_FALSE;
		break;
	}
	rc = add_attribute(&attrs, PKCS11_CKA_LOCAL, &local, sizeof(local));
	if (rc)
		goto out;

	switch (get_class(attrs)) {
	case PKCS11_CKO_SECRET_KEY:
	case PKCS11_CKO_PRIVATE_KEY:
	case PKCS11_CKO_PUBLIC_KEY:
		always_sensitive = PKCS11_FALSE;
		never_extract = PKCS11_FALSE;

		switch (function) {
		case PKCS11_FUNCTION_DERIVE:
			always_sensitive =
				get_bool(parent, PKCS11_CKA_ALWAYS_SENSITIVE) &&
				get_bool(attrs, PKCS11_CKA_SENSITIVE);
			never_extract =
			       get_bool(parent, PKCS11_CKA_NEVER_EXTRACTABLE) &&
			       !get_bool(attrs, PKCS11_CKA_EXTRACTABLE);
			break;
		case PKCS11_FUNCTION_UNWRAP:
			always_sensitive = PKCS11_FALSE;
			never_extract = PKCS11_FALSE;
			extractable = PKCS11_TRUE;

			/*
			 * Check if template passed by user has CKA_EXTRACTABLE.
			 * If not, by default value of CKA_EXTRACTABLE is set as
			 * TRUE.
			 */
			if (get_attribute_ptr(temp, PKCS11_CKA_EXTRACTABLE,
					      NULL,
					      NULL) == PKCS11_RV_NOT_FOUND) {
				rc = set_attribute(&attrs,
						   PKCS11_CKA_EXTRACTABLE,
						   &extractable,
						   sizeof(extractable));
				if (rc)
					goto out;
			}
			break;
		case PKCS11_FUNCTION_GENERATE:
		case PKCS11_FUNCTION_GENERATE_PAIR:
			always_sensitive = get_bool(attrs,
						    PKCS11_CKA_SENSITIVE);
			never_extract = !get_bool(attrs,
						  PKCS11_CKA_EXTRACTABLE);
			break;
		default:
			break;
		}

		rc = add_attribute(&attrs, PKCS11_CKA_ALWAYS_SENSITIVE,
				   &always_sensitive, sizeof(always_sensitive));
		if (rc)
			goto out;

		rc = add_attribute(&attrs, PKCS11_CKA_NEVER_EXTRACTABLE,
				   &never_extract, sizeof(never_extract));
		if (rc)
			goto out;

		/* Keys mandate attribute PKCS11_CKA_KEY_GEN_MECHANISM */
		if (local)
			mechanism_id = mecha;
		else
			mechanism_id = PKCS11_CK_UNAVAILABLE_INFORMATION;

		rc = add_attribute(&attrs, PKCS11_CKA_KEY_GEN_MECHANISM,
				   &mechanism_id, sizeof(mechanism_id));
		if (rc)
			goto out;
		break;

	default:
		break;
	}

	*out = attrs;

#ifdef DEBUG
	trace_attributes("object", attrs);
#endif

out:
	TEE_Free(temp);
	if (rc)
		TEE_Free(attrs);

	return rc;
}

static enum pkcs11_rc check_attrs_misc_integrity(struct obj_attrs *head)
{
	if (get_bool(head, PKCS11_CKA_NEVER_EXTRACTABLE) &&
	    get_bool(head, PKCS11_CKA_EXTRACTABLE)) {
		DMSG("Never/Extractable attributes mismatch %d/%d",
		     get_bool(head, PKCS11_CKA_NEVER_EXTRACTABLE),
		     get_bool(head, PKCS11_CKA_EXTRACTABLE));

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	if (get_bool(head, PKCS11_CKA_ALWAYS_SENSITIVE) &&
	    !get_bool(head, PKCS11_CKA_SENSITIVE)) {
		DMSG("Sensitive/always attributes mismatch %d/%d",
		     get_bool(head, PKCS11_CKA_SENSITIVE),
		     get_bool(head, PKCS11_CKA_ALWAYS_SENSITIVE));

		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	return PKCS11_CKR_OK;
}

bool object_is_private(struct obj_attrs *head)
{
	return get_bool(head, PKCS11_CKA_PRIVATE);
}

bool object_is_token(struct obj_attrs *head)
{
	return get_bool(head, PKCS11_CKA_TOKEN);
}

bool object_is_modifiable(struct obj_attrs *head)
{
	return get_bool(head, PKCS11_CKA_MODIFIABLE);
}

bool object_is_copyable(struct obj_attrs *head)
{
	return get_bool(head, PKCS11_CKA_COPYABLE);
}

/*
 * Check access to object against authentication to token
 */
enum pkcs11_rc check_access_attrs_against_token(struct pkcs11_session *session,
						struct obj_attrs *head)
{
	bool private = true;

	switch (get_class(head)) {
	case PKCS11_CKO_SECRET_KEY:
	case PKCS11_CKO_PRIVATE_KEY:
	case PKCS11_CKO_PUBLIC_KEY:
	case PKCS11_CKO_DATA:
	case PKCS11_CKO_CERTIFICATE:
		private = object_is_private(head);
		break;
	default:
		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
	}

	if (private && (pkcs11_session_is_public(session) ||
			pkcs11_session_is_so(session))) {
		DMSG("Private object access from a public or SO session");

		return PKCS11_CKR_USER_NOT_LOGGED_IN;
	}

	return PKCS11_CKR_OK;
}

/*
 * Check the attributes of a to-be-created object matches the token state
 */
enum pkcs11_rc check_created_attrs_against_token(struct pkcs11_session *session,
						 struct obj_attrs *head)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;

	rc = check_attrs_misc_integrity(head);
	if (rc)
		return rc;

	if (get_bool(head, PKCS11_CKA_TRUSTED) &&
	    !pkcs11_session_is_so(session)) {
		DMSG("Can't create trusted object");

		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
	}

	if (get_bool(head, PKCS11_CKA_TOKEN) &&
	    !pkcs11_session_is_read_write(session)) {
		DMSG("Can't create persistent object");

		return PKCS11_CKR_SESSION_READ_ONLY;
	}

	/*
	 * TODO: START_DATE and END_DATE: complies with current time?
	 */
	return PKCS11_CKR_OK;
}

#define DMSG_BAD_BBOOL(attr, proc, head)				\
	do {								\
		uint32_t __maybe_unused _attr = (attr);			\
		uint8_t __maybe_unused _bvalue = 0;			\
		enum pkcs11_rc __maybe_unused _rc = PKCS11_CKR_OK;	\
									\
		_rc = get_attribute((head), _attr, &_bvalue, NULL);	\
		DMSG("%s issue for %s: %sfound, value %"PRIu8,		\
		     id2str_attr(_attr), id2str_proc((proc)),		\
		     _rc ? "not " : "", _bvalue);			\
	} while (0)

static bool __maybe_unused check_attr_bval(uint32_t proc_id __maybe_unused,
					   struct obj_attrs *head,
					   uint32_t attribute, bool val)
{
	uint8_t bbool = 0;
	uint32_t sz = sizeof(bbool);

	if (!get_attribute(head, attribute, &bbool, &sz) && !!bbool == val)
		return true;

	DMSG_BAD_BBOOL(attribute, proc_id, head);
	return false;
}

/*
 * Check the attributes of a new secret match the processing/mechanism
 * used to create it.
 *
 * @proc_id - PKCS11_CKM_xxx
 * @head - head of the attributes of the to-be-created object.
 */
enum pkcs11_rc check_created_attrs_against_processing(uint32_t proc_id,
						      struct obj_attrs *head)
{
	/*
	 * Processings that do not create secrets are not expected to call
	 * this function which would panic.
	 */
	switch (proc_id) {
	case PKCS11_PROCESSING_IMPORT:
	case PKCS11_CKM_ECDH1_DERIVE:
	case PKCS11_CKM_AES_ECB:
	case PKCS11_CKM_AES_CBC:
	case PKCS11_CKM_AES_ECB_ENCRYPT_DATA:
	case PKCS11_CKM_AES_CBC_ENCRYPT_DATA:
		assert(check_attr_bval(proc_id, head, PKCS11_CKA_LOCAL, false));
		break;
	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
	case PKCS11_CKM_AES_KEY_GEN:
	case PKCS11_CKM_EC_KEY_PAIR_GEN:
	case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
		assert(check_attr_bval(proc_id, head, PKCS11_CKA_LOCAL, true));
		break;
	default:
		TEE_Panic(proc_id);
		break;
	}

	switch (proc_id) {
	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
		assert(get_key_type(head) == PKCS11_CKK_GENERIC_SECRET);
		break;
	case PKCS11_CKM_AES_KEY_GEN:
		assert(get_key_type(head) == PKCS11_CKK_AES);
		break;
	case PKCS11_CKM_EC_KEY_PAIR_GEN:
		assert(get_key_type(head) == PKCS11_CKK_EC);
		break;
	case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
		assert(get_key_type(head) == PKCS11_CKK_RSA);
		break;
	case PKCS11_PROCESSING_IMPORT:
	case PKCS11_CKM_ECDH1_DERIVE:
	default:
		break;
	}

	return PKCS11_CKR_OK;
}

/* Return min and max key size supported for a key_type in bytes */
static void get_key_min_max_sizes(enum pkcs11_key_type key_type,
				  uint32_t *min_key_size,
				  uint32_t *max_key_size)
{
	enum pkcs11_mechanism_id mechanism = PKCS11_CKM_UNDEFINED_ID;

	switch (key_type) {
	case PKCS11_CKK_GENERIC_SECRET:
		mechanism = PKCS11_CKM_GENERIC_SECRET_KEY_GEN;
		break;
	case PKCS11_CKK_AES:
		mechanism = PKCS11_CKM_AES_KEY_GEN;
		break;
	case PKCS11_CKK_MD5_HMAC:
		mechanism = PKCS11_CKM_MD5_HMAC;
		break;
	case PKCS11_CKK_SHA_1_HMAC:
		mechanism = PKCS11_CKM_SHA_1_HMAC;
		break;
	case PKCS11_CKK_SHA224_HMAC:
		mechanism = PKCS11_CKM_SHA224_HMAC;
		break;
	case PKCS11_CKK_SHA256_HMAC:
		mechanism = PKCS11_CKM_SHA256_HMAC;
		break;
	case PKCS11_CKK_SHA384_HMAC:
		mechanism = PKCS11_CKM_SHA384_HMAC;
		break;
	case PKCS11_CKK_SHA512_HMAC:
		mechanism = PKCS11_CKM_SHA512_HMAC;
		break;
	case PKCS11_CKK_EC:
		mechanism = PKCS11_CKM_EC_KEY_PAIR_GEN;
		break;
	case PKCS11_CKK_RSA:
		mechanism = PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN;
		break;
	default:
		TEE_Panic(key_type);
		break;
	}

	mechanism_supported_key_sizes_bytes(mechanism, min_key_size,
					    max_key_size);
}

enum pkcs11_rc check_created_attrs(struct obj_attrs *key1,
				   struct obj_attrs *key2)
{
	enum pkcs11_rc rc = PKCS11_CKR_OK;
	struct obj_attrs *secret = NULL;
	struct obj_attrs *private = NULL;
	struct obj_attrs *public = NULL;
	uint32_t max_key_size = 0;
	uint32_t min_key_size = 0;
	uint32_t key_length = 0;

	switch (get_class(key1)) {
	case PKCS11_CKO_SECRET_KEY:
		secret = key1;
		break;
	case PKCS11_CKO_PUBLIC_KEY:
		public = key1;
		break;
	case PKCS11_CKO_PRIVATE_KEY:
		private = key1;
		break;
	default:
		return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
	}

	if (key2) {
		switch (get_class(key2)) {
		case PKCS11_CKO_PUBLIC_KEY:
			public = key2;
			if (private == key1)
				break;

			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
		case PKCS11_CKO_PRIVATE_KEY:
			private = key2;
			if (public == key1)
				break;

			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
		default:
			return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
		}

		if (get_key_type(private) != get_key_type(public))
			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
	}

	if (secret) {
		switch (get_key_type(secret)) {
		case PKCS11_CKK_AES:
		case PKCS11_CKK_GENERIC_SECRET:
		case PKCS11_CKK_MD5_HMAC:
		case PKCS11_CKK_SHA_1_HMAC:
		case PKCS11_CKK_SHA224_HMAC:
		case PKCS11_CKK_SHA256_HMAC:
		case PKCS11_CKK_SHA384_HMAC:
		case PKCS11_CKK_SHA512_HMAC:
			break;
		default:
			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
		}

		/* Get key size */
		rc = get_u32_attribute(secret, PKCS11_CKA_VALUE_LEN,
				       &key_length);
		if (rc)
			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
	}
	if (public) {
		switch (get_key_type(public)) {
		case PKCS11_CKK_RSA:
			/* Get key size */
			rc = get_u32_attribute(public, PKCS11_CKA_MODULUS_BITS,
					       &key_length);
			if (rc)
				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
			key_length = ROUNDUP(key_length, 8) / 8;
			break;
		case PKCS11_CKK_EC:
			break;
		default:
			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
		}
	}
	if (private) {
		switch (get_key_type(private)) {
		case PKCS11_CKK_RSA:
		case PKCS11_CKK_EC:
			break;
		default:
			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
		}
	}

	/*
	 * Check key size for symmetric keys and RSA keys
	 * EC is bound to domains, no need to check here.
	 */
	switch (get_key_type(key1)) {
	case PKCS11_CKK_EC:
		return PKCS11_CKR_OK;
	default:
		break;
	}

	get_key_min_max_sizes(get_key_type(key1), &min_key_size, &max_key_size);
	if (key_length < min_key_size || key_length > max_key_size) {
		EMSG("Length %"PRIu32" vs range [%"PRIu32" %"PRIu32"]",
		     key_length, min_key_size, max_key_size);

		return PKCS11_CKR_KEY_SIZE_RANGE;
	}

	if (secret && get_key_type(secret) == PKCS11_CKK_AES) {
		if (key_length != 16 && key_length != 24 && key_length != 32)
			return PKCS11_CKR_KEY_SIZE_RANGE;
	}

	return PKCS11_CKR_OK;
}

/* Check processing ID against attribute ALLOWED_MECHANISMS if any */
static bool parent_key_complies_allowed_processings(uint32_t proc_id,
						    struct obj_attrs *head)
{
	char *attr = NULL;
	uint32_t size = 0;
	uint32_t proc = 0;
	size_t count = 0;
	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;

	rc = get_attribute_ptr(head, PKCS11_CKA_ALLOWED_MECHANISMS,
			       (void *)&attr, &size);
	if (rc == PKCS11_RV_NOT_FOUND)
		return true;
	if (rc) {
		EMSG("unexpected attributes state");
		TEE_Panic(TEE_ERROR_BAD_STATE);
	}

	for (count = size / sizeof(uint32_t); count; count--) {
		TEE_MemMove(&proc, attr, sizeof(uint32_t));
		attr += sizeof(uint32_t);

		if (proc == proc_id)
			return true;
	}

	DMSG("can't find %s in allowed list", id2str_proc(proc_id));
	return false;
}

static enum pkcs11_attr_id func_to_attr(enum processing_func func)
{
	switch (func) {
	case PKCS11_FUNCTION_ENCRYPT:
		return PKCS11_CKA_ENCRYPT;
	case PKCS11_FUNCTION_DECRYPT:
		return PKCS11_CKA_DECRYPT;
	case PKCS11_FUNCTION_SIGN:
		return PKCS11_CKA_SIGN;
	case PKCS11_FUNCTION_VERIFY:
		return PKCS11_CKA_VERIFY;
	case PKCS11_FUNCTION_WRAP:
		return PKCS11_CKA_WRAP;
	case PKCS11_FUNCTION_UNWRAP:
		return PKCS11_CKA_UNWRAP;
	case PKCS11_FUNCTION_DERIVE:
		return PKCS11_CKA_DERIVE;
	default:
		return PKCS11_CKA_UNDEFINED_ID;
	}
}

enum pkcs11_rc
check_parent_attrs_against_processing(enum pkcs11_mechanism_id proc_id,
				      enum processing_func function,
				      struct obj_attrs *head)
{
	enum pkcs11_class_id key_class = get_class(head);
	enum pkcs11_key_type key_type = get_key_type(head);
	enum pkcs11_attr_id attr = func_to_attr(function);

	if (!get_bool(head, attr)) {
		DMSG("%s not permitted", id2str_attr(attr));
		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
	}

	/* Check processing complies with parent key family */
	switch (proc_id) {
	case PKCS11_CKM_AES_ECB:
	case PKCS11_CKM_AES_CBC:
	case PKCS11_CKM_AES_CTS:
	case PKCS11_CKM_AES_CTR:
	case PKCS11_CKM_AES_CMAC:
	case PKCS11_CKM_AES_CMAC_GENERAL:
		if (key_class == PKCS11_CKO_SECRET_KEY &&
		    key_type == PKCS11_CKK_AES)
			break;

		DMSG("%s invalid key %s/%s", id2str_proc(proc_id),
		     id2str_class(key_class), id2str_key_type(key_type));

		if (function == PKCS11_FUNCTION_WRAP)
			return PKCS11_CKR_WRAPPING_KEY_TYPE_INCONSISTENT;
		else if (function == PKCS11_FUNCTION_UNWRAP)
			return PKCS11_CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT;
		else
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;

	case PKCS11_CKM_AES_ECB_ENCRYPT_DATA:
	case PKCS11_CKM_AES_CBC_ENCRYPT_DATA:
		if (key_class != PKCS11_CKO_SECRET_KEY &&
		    key_type != PKCS11_CKK_AES)
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;

		if (get_bool(head, PKCS11_CKA_ENCRYPT)) {
			/*
			 * Intentionally refuse to proceed despite
			 * PKCS#11 specifications v2.40 and v3.0 not expecting
			 * this behavior to avoid potential security issue
			 * where keys derived by these mechanisms can be
			 * revealed by doing data encryption using parent key.
			 */
			return PKCS11_CKR_FUNCTION_FAILED;
		}

		break;
	case PKCS11_CKM_MD5_HMAC:
	case PKCS11_CKM_SHA_1_HMAC:
	case PKCS11_CKM_SHA224_HMAC:
	case PKCS11_CKM_SHA256_HMAC:
	case PKCS11_CKM_SHA384_HMAC:
	case PKCS11_CKM_SHA512_HMAC:
	case PKCS11_CKM_MD5_HMAC_GENERAL:
	case PKCS11_CKM_SHA_1_HMAC_GENERAL:
	case PKCS11_CKM_SHA224_HMAC_GENERAL:
	case PKCS11_CKM_SHA256_HMAC_GENERAL:
	case PKCS11_CKM_SHA384_HMAC_GENERAL:
	case PKCS11_CKM_SHA512_HMAC_GENERAL:
		if (key_class != PKCS11_CKO_SECRET_KEY)
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;

		if (key_type == PKCS11_CKK_GENERIC_SECRET)
			break;

		switch (proc_id) {
		case PKCS11_CKM_MD5_HMAC:
		case PKCS11_CKM_MD5_HMAC_GENERAL:
			if (key_type == PKCS11_CKK_MD5_HMAC)
				break;
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		case PKCS11_CKM_SHA_1_HMAC:
		case PKCS11_CKM_SHA_1_HMAC_GENERAL:
			if (key_type == PKCS11_CKK_SHA_1_HMAC)
				break;
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		case PKCS11_CKM_SHA224_HMAC:
		case PKCS11_CKM_SHA224_HMAC_GENERAL:
			if (key_type == PKCS11_CKK_SHA224_HMAC)
				break;
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		case PKCS11_CKM_SHA256_HMAC:
		case PKCS11_CKM_SHA256_HMAC_GENERAL:
			if (key_type == PKCS11_CKK_SHA256_HMAC)
				break;
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		case PKCS11_CKM_SHA384_HMAC:
		case PKCS11_CKM_SHA384_HMAC_GENERAL:
			if (key_type == PKCS11_CKK_SHA384_HMAC)
				break;
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		case PKCS11_CKM_SHA512_HMAC:
		case PKCS11_CKM_SHA512_HMAC_GENERAL:
			if (key_type == PKCS11_CKK_SHA512_HMAC)
				break;
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		default:
			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		}
		break;

	case PKCS11_CKM_ECDSA:
	case PKCS11_CKM_ECDSA_SHA1:
	case PKCS11_CKM_ECDSA_SHA224:
	case PKCS11_CKM_ECDSA_SHA256:
	case PKCS11_CKM_ECDSA_SHA384:
	case PKCS11_CKM_ECDSA_SHA512:
	case PKCS11_CKM_ECDH1_DERIVE:
		if (key_type != PKCS11_CKK_EC) {
			EMSG("Invalid key %s for mechanism %s",
			     id2str_type(key_type, key_class),
			     id2str_proc(proc_id));

			return PKCS11_CKR_KEY_TYPE_INCONSISTENT;
		}
		if (key_class != PKCS11_CKO_PUBLIC_KEY &&
		    key_class != PKCS11_CKO_PRIVATE_KEY) {
			EMSG("Invalid key class for mechanism %s",
			     id2str_proc(proc_id));

			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		}
		break;
	case PKCS11_CKM_RSA_PKCS:
	case PKCS11_CKM_MD5_RSA_PKCS:
	case PKCS11_CKM_SHA1_RSA_PKCS:
	case PKCS11_CKM_SHA224_RSA_PKCS:
	case PKCS11_CKM_SHA256_RSA_PKCS:
	case PKCS11_CKM_SHA384_RSA_PKCS:
	case PKCS11_CKM_SHA512_RSA_PKCS:
	case PKCS11_CKM_RSA_PKCS_OAEP:
	case PKCS11_CKM_RSA_PKCS_PSS:
	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
		if (key_type != PKCS11_CKK_RSA) {
			EMSG("Invalid key %s for mechanism %s",
			     id2str_type(key_type, key_class),
			     id2str_proc(proc_id));

			return PKCS11_CKR_KEY_TYPE_INCONSISTENT;
		}
		if (key_class != PKCS11_CKO_PUBLIC_KEY &&
		    key_class != PKCS11_CKO_PRIVATE_KEY) {
			EMSG("Invalid key class for mechanism %s",
			     id2str_proc(proc_id));

			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
		}
		break;
	default:
		DMSG("Invalid processing %#"PRIx32"/%s", proc_id,
		     id2str_proc(proc_id));

		return PKCS11_CKR_MECHANISM_INVALID;
	}

	if (!parent_key_complies_allowed_processings(proc_id, head)) {
		DMSG("Allowed mechanism failed");
		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
	}

	return PKCS11_CKR_OK;
}

bool attribute_is_exportable(struct pkcs11_attribute_head *req_attr,
			     struct pkcs11_object *obj)
{
	uint8_t boolval = 0;
	uint32_t boolsize = 0;
	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
	enum pkcs11_class_id key_class = get_class(obj->attributes);

	if (key_class != PKCS11_CKO_SECRET_KEY &&
	    key_class != PKCS11_CKO_PRIVATE_KEY)
		return true;

	switch (req_attr->id) {
	case PKCS11_CKA_PRIVATE_EXPONENT:
	case PKCS11_CKA_PRIME_1:
	case PKCS11_CKA_PRIME_2:
	case PKCS11_CKA_EXPONENT_1:
	case PKCS11_CKA_EXPONENT_2:
	case PKCS11_CKA_COEFFICIENT:
	case PKCS11_CKA_VALUE:
		boolsize = sizeof(boolval);
		rc = get_attribute(obj->attributes, PKCS11_CKA_EXTRACTABLE,
				   &boolval, &boolsize);
		if (rc || boolval == PKCS11_FALSE)
			return false;

		boolsize = sizeof(boolval);
		rc = get_attribute(obj->attributes, PKCS11_CKA_SENSITIVE,
				   &boolval, &boolsize);
		if (rc || boolval == PKCS11_TRUE)
			return false;
		break;
	default:
		break;
	}

	return true;
}

static bool attr_is_modifiable_any_key(struct pkcs11_attribute_head *attr)
{
	switch (attr->id) {
	case PKCS11_CKA_ID:
	case PKCS11_CKA_START_DATE:
	case PKCS11_CKA_END_DATE:
	case PKCS11_CKA_DERIVE:
		return true;
	default:
		return false;
	}
}

static bool attr_is_modifiable_secret_key(struct pkcs11_attribute_head *attr,
					  struct pkcs11_session *session,
					  struct pkcs11_object *obj)
{
	switch (attr->id) {
	case PKCS11_CKA_ENCRYPT:
	case PKCS11_CKA_DECRYPT:
	case PKCS11_CKA_SIGN:
	case PKCS11_CKA_VERIFY:
	case PKCS11_CKA_WRAP:
	case PKCS11_CKA_UNWRAP:
		return true;
	/* Can't be modified once set to CK_FALSE - 12 in Table 10 */
	case PKCS11_CKA_EXTRACTABLE:
		return get_bool(obj->attributes, attr->id);
	/* Can't be modified once set to CK_TRUE - 11 in Table 10 */
	case PKCS11_CKA_SENSITIVE:
	case PKCS11_CKA_WRAP_WITH_TRUSTED:
		return !get_bool(obj->attributes, attr->id);
	/* Change in CKA_TRUSTED can only be done by SO */
	case PKCS11_CKA_TRUSTED:
		return pkcs11_session_is_so(session);
	case PKCS11_CKA_NEVER_EXTRACTABLE:
	case PKCS11_CKA_ALWAYS_SENSITIVE:
		return false;
	default:
		return false;
	}
}

static bool attr_is_modifiable_public_key(struct pkcs11_attribute_head *attr,
					  struct pkcs11_session *session,
					  struct pkcs11_object *obj __unused)
{
	switch (attr->id) {
	case PKCS11_CKA_SUBJECT:
	case PKCS11_CKA_ENCRYPT:
	case PKCS11_CKA_VERIFY:
	case PKCS11_CKA_VERIFY_RECOVER:
	case PKCS11_CKA_WRAP:
		return true;
	case PKCS11_CKA_TRUSTED:
		/* Change in CKA_TRUSTED can only be done by SO */
		return pkcs11_session_is_so(session);
	default:
		return false;
	}
}

static bool attr_is_modifiable_private_key(struct pkcs11_attribute_head *attr,
					   struct pkcs11_session *sess __unused,
					   struct pkcs11_object *obj)
{
	switch (attr->id) {
	case PKCS11_CKA_SUBJECT:
	case PKCS11_CKA_DECRYPT:
	case PKCS11_CKA_SIGN:
	case PKCS11_CKA_SIGN_RECOVER:
	case PKCS11_CKA_UNWRAP:
	/*
	 * TBD: Revisit if we don't support PKCS11_CKA_PUBLIC_KEY_INFO
	 * Specification mentions that if this attribute is
	 * supplied as part of a template for C_CreateObject, C_CopyObject or
	 * C_SetAttributeValue for a private key, the token MUST verify
	 * correspondence between the private key data and the public key data
	 * as supplied in CKA_PUBLIC_KEY_INFO. This needs to be
	 * taken care of when this object type will be implemented
	 */
	case PKCS11_CKA_PUBLIC_KEY_INFO:
		return true;
	/* Can't be modified once set to CK_FALSE - 12 in Table 10 */
	case PKCS11_CKA_EXTRACTABLE:
		return get_bool(obj->attributes, attr->id);
	/* Can't be modified once set to CK_TRUE - 11 in Table 10 */
	case PKCS11_CKA_SENSITIVE:
	case PKCS11_CKA_WRAP_WITH_TRUSTED:
		return !get_bool(obj->attributes, attr->id);
	case PKCS11_CKA_NEVER_EXTRACTABLE:
	case PKCS11_CKA_ALWAYS_SENSITIVE:
		return false;
	default:
		return false;
	}
}

static bool attr_is_modifiable_certificate(struct pkcs11_attribute_head *attr,
					   struct pkcs11_session *session,
					   struct pkcs11_object *obj)
{
	uint8_t boolval = 0;
	uint32_t boolsize = 0;
	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;

	/* Trusted certificates cannot be modified. */
	rc = get_attribute(obj->attributes, PKCS11_CKA_TRUSTED,
			   &boolval, &boolsize);
	if (rc || boolval == PKCS11_TRUE)
		return false;

	/* Common certificate attributes */
	switch (attr->id) {
	case PKCS11_CKA_TRUSTED:
		/*
		 * The CKA_TRUSTED attribute cannot be set to CK_TRUE by an
		 * application. It MUST be set by a token initialization
		 * application or by the token’s SO.
		 */
		return pkcs11_session_is_so(session);
	case PKCS11_CKA_CERTIFICATE_TYPE:
	case PKCS11_CKA_CERTIFICATE_CATEGORY:
		return false;
	default:
		break;
	}

	/* Certificate type specific attributes */
	switch (get_certificate_type(obj->attributes)) {
	case PKCS11_CKC_X_509:
		/*
		 * Only the CKA_ID, CKA_ISSUER, and CKA_SERIAL_NUMBER
		 * attributes may be modified after the object is created.
		 */
		switch (attr->id) {
		case PKCS11_CKA_ID:
		case PKCS11_CKA_ISSUER:
		case PKCS11_CKA_SERIAL_NUMBER:
			return true;
		default:
			break;
		}
		break;
	default:
		/* Unsupported certificate type */
		break;
	}

	return false;
}

static bool attribute_is_modifiable(struct pkcs11_session *session,
				    struct pkcs11_attribute_head *req_attr,
				    struct pkcs11_object *obj,
				    enum pkcs11_class_id class,
				    enum processing_func function)
{
	/* Check modifiable attributes common to any object */
	switch (req_attr->id) {
	case PKCS11_CKA_LABEL:
		return true;
	case PKCS11_CKA_TOKEN:
	case PKCS11_CKA_MODIFIABLE:
	case PKCS11_CKA_DESTROYABLE:
	case PKCS11_CKA_PRIVATE:
		return function == PKCS11_FUNCTION_COPY;
	case PKCS11_CKA_COPYABLE:
		/*
		 * Specification mentions that if the attribute value is false
		 * it can't be set to true. Reading this we assume that it
		 * should be possible to modify this attribute even though this
		 * is not marked as modifiable in Table 10 if done in right
		 * direction i.e from TRUE -> FALSE.
		 */
		return get_bool(obj->attributes, req_attr->id);
	default:
		break;
	}

	/* Attribute checking based on class type */
	switch (class) {
	case PKCS11_CKO_SECRET_KEY:
	case PKCS11_CKO_PUBLIC_KEY:
	case PKCS11_CKO_PRIVATE_KEY:
		if (attr_is_modifiable_any_key(req_attr))
			return true;
		if (class == PKCS11_CKO_SECRET_KEY &&
		    attr_is_modifiable_secret_key(req_attr, session, obj))
			return true;
		if (class == PKCS11_CKO_PUBLIC_KEY &&
		    attr_is_modifiable_public_key(req_attr, session, obj))
			return true;
		if (class == PKCS11_CKO_PRIVATE_KEY &&
		    attr_is_modifiable_private_key(req_attr, session, obj))
			return true;
		break;
	case PKCS11_CKO_DATA:
		/* None of the data object attributes are modifiable */
		return false;
	case PKCS11_CKO_CERTIFICATE:
		return attr_is_modifiable_certificate(req_attr, session, obj);
	default:
		break;
	}

	return false;
}

enum pkcs11_rc check_attrs_against_modification(struct pkcs11_session *session,
						struct obj_attrs *head,
						struct pkcs11_object *obj,
						enum processing_func function)
{
	enum pkcs11_class_id class = PKCS11_CKO_UNDEFINED_ID;
	char *cur = NULL;
	char *end = NULL;
	size_t len = 0;

	class = get_class(obj->attributes);

	cur = (char *)head + sizeof(struct obj_attrs);
	end = cur + head->attrs_size;

	for (; cur < end; cur += len) {
		/* Structure aligned copy of the pkcs11_ref in the object */
		struct pkcs11_attribute_head cli_ref = { };

		TEE_MemMove(&cli_ref, cur, sizeof(cli_ref));
		len = sizeof(cli_ref) + cli_ref.size;

		/*
		 * Check 1 - Check if attribute belongs to the object
		 * The obj->attributes has all the attributes in
		 * it which are allowed for an object.
		 */
		if (get_attribute_ptr(obj->attributes, cli_ref.id, NULL,
				      NULL) == PKCS11_RV_NOT_FOUND)
			return PKCS11_CKR_ATTRIBUTE_TYPE_INVALID;

		/* Check 2 - Is attribute modifiable */
		if (!attribute_is_modifiable(session, &cli_ref, obj, class,
					     function))
			return PKCS11_CKR_ATTRIBUTE_READ_ONLY;

		/*
		 * Checks for modification in PKCS11_CKA_TOKEN and
		 * PKCS11_CKA_PRIVATE are required for PKCS11_FUNCTION_COPY
		 * only, so skip them for PKCS11_FUNCTION_MODIFY.
		 */
		if (function == PKCS11_FUNCTION_MODIFY)
			continue;

		/*
		 * An attempt to copy an object to a token will fail for
		 * RO session
		 */
		if (cli_ref.id == PKCS11_CKA_TOKEN &&
		    get_bool(head, PKCS11_CKA_TOKEN)) {
			if (!pkcs11_session_is_read_write(session)) {
				DMSG("Can't copy to token in a RO session");
				return PKCS11_CKR_SESSION_READ_ONLY;
			}
		}

		if (cli_ref.id == PKCS11_CKA_PRIVATE) {
			bool parent_priv =
				get_bool(obj->attributes, cli_ref.id);
			bool obj_priv = get_bool(head, cli_ref.id);

			/*
			 * If PKCS11_CKA_PRIVATE is being set to TRUE from
			 * FALSE, user has to be logged in
			 */
			if (!parent_priv && obj_priv) {
				if ((pkcs11_session_is_public(session) ||
				     pkcs11_session_is_so(session)))
					return PKCS11_CKR_USER_NOT_LOGGED_IN;
			}

			/*
			 * Restriction added - Even for Copy, do not allow
			 * modification of CKA_PRIVATE from TRUE to FALSE
			 */
			if (parent_priv && !obj_priv)
				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
		}
	}

	return PKCS11_CKR_OK;
}

static enum pkcs11_rc set_secret_key_data(struct obj_attrs **head, void *data,
					  size_t key_size)
{
	uint32_t size = sizeof(uint32_t);
	uint32_t key_length = 0;
	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;

	/* Get key size if present in template */
	rc = get_attribute(*head, PKCS11_CKA_VALUE_LEN, &key_length, &size);
	if (rc && rc != PKCS11_RV_NOT_FOUND)
		return rc;

	if (key_length) {
		if (key_size < key_length)
			return PKCS11_CKR_DATA_LEN_RANGE;
	} else {
		key_length = key_size;
		rc = set_attribute(head, PKCS11_CKA_VALUE_LEN, &key_length,
				   sizeof(uint32_t));
		if (rc)
			return rc;
	}

	/* Now we can check the VALUE_LEN field */
	rc = check_created_attrs(*head, NULL);
	if (rc)
		return rc;

	/* Remove the default empty value attribute if found */
	rc = remove_empty_attribute(head, PKCS11_CKA_VALUE);
	if (rc != PKCS11_CKR_OK && rc != PKCS11_RV_NOT_FOUND)
		return PKCS11_CKR_GENERAL_ERROR;

	return add_attribute(head, PKCS11_CKA_VALUE, data, key_length);
}

enum pkcs11_rc set_key_data(struct obj_attrs **head, void *data,
			    size_t key_size)
{
	switch (get_class(*head)) {
	case PKCS11_CKO_SECRET_KEY:
		return set_secret_key_data(head, data, key_size);
	default:
		return PKCS11_CKR_GENERAL_ERROR;
	}
}

enum pkcs11_rc get_key_data_to_wrap(struct obj_attrs *head, void **data,
				    uint32_t *sz)
{
	switch (get_class(head)) {
	case PKCS11_CKO_SECRET_KEY:
		if (get_attribute_ptr(head, PKCS11_CKA_VALUE, data, sz))
			return PKCS11_CKR_ARGUMENTS_BAD;
		break;
	default:
		return PKCS11_CKR_GENERAL_ERROR;
	}

	return PKCS11_CKR_OK;
}

enum pkcs11_rc add_missing_attribute_id(struct obj_attrs **pub_head,
					struct obj_attrs **priv_head)
{
	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
	void *id1 = NULL;
	uint32_t id1_size = 0;
	void *id2 = NULL;
	uint32_t id2_size = 0;

	assert(pub_head);
	assert(priv_head);

	rc = get_attribute_ptr(*pub_head, PKCS11_CKA_ID, &id1, &id1_size);
	if (rc) {
		if (rc != PKCS11_RV_NOT_FOUND)
			return rc;
		id1 = NULL;
	} else if (!id1_size) {
		id1 = NULL;
	}

	rc = get_attribute_ptr(*priv_head, PKCS11_CKA_ID, &id2, &id2_size);
	if (rc) {
		if (rc != PKCS11_RV_NOT_FOUND)
			return rc;
		id2 = NULL;
	} else if (!id2_size) {
		id2 = NULL;
	}

	/* Both have value -- let them be what caller has specified them */
	if (id1 && id2)
		return PKCS11_CKR_OK;

	/* Both are empty -- leave empty values */
	if (!id1 && !id2)
		return PKCS11_CKR_OK;

	/* Cross copy CKA_ID value */
	if (id1)
		return set_attribute(priv_head, PKCS11_CKA_ID, id1, id1_size);
	else
		return set_attribute(pub_head, PKCS11_CKA_ID, id2, id2_size);
}