summaryrefslogtreecommitdiffstats
path: root/src/tpm12/tpm_migration.c
blob: 62c59b6ca441b210bc6005f69d95f5fa9df9a77d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
/********************************************************************************/
/*										*/
/*				TPM Migration					*/
/*			     Written by Ken Goldman				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*	      $Id: tpm_migration.c 4526 2011-03-24 21:14:42Z kgoldman $		*/
/*										*/
/* (c) Copyright IBM Corporation 2006, 2010.					*/
/*										*/
/* All rights reserved.								*/
/* 										*/
/* Redistribution and use in source and binary forms, with or without		*/
/* modification, are permitted provided that the following conditions are	*/
/* met:										*/
/* 										*/
/* Redistributions of source code must retain the above copyright notice,	*/
/* this list of conditions and the following disclaimer.			*/
/* 										*/
/* 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.		*/
/* 										*/
/* Neither the names of the IBM Corporation 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 COPYRIGHT HOLDERS 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 COPYRIGHT		*/
/* HOLDER 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 <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "tpm_auth.h"
#include "tpm_crypto.h"
#include "tpm_cryptoh.h"
#include "tpm_debug.h"
#include "tpm_digest.h"
#include "tpm_error.h"
#include "tpm_io.h"
#include "tpm_key.h"
#include "tpm_memory.h"
#include "tpm_nonce.h"
#include "tpm_permanent.h"
#include "tpm_process.h"
#include "tpm_secret.h"

#include "tpm_migration.h"

/*
  TPM_MIGRATIONKEYAUTH
*/
  
/* TPM_Migrationkeyauth_Init()

   sets members to default values
   sets all pointers to NULL and sizes to 0
   always succeeds - no return code
*/

void TPM_Migrationkeyauth_Init(TPM_MIGRATIONKEYAUTH *tpm_migrationkeyauth)
{
    printf(" TPM_Migrationkeyauth_Init:\n");
    TPM_Pubkey_Init(&(tpm_migrationkeyauth->migrationKey));
    tpm_migrationkeyauth->migrationScheme = 0; 
    TPM_Digest_Init(tpm_migrationkeyauth->digest); 
    return;
}

/* TPM_Migrationkeyauth_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes
   
   Before use, call TPM_Migrationkeyauth_Init()
   After use, call TPM_Migrationkeyauth_Delete() to free memory
*/

TPM_RESULT TPM_Migrationkeyauth_Load(TPM_MIGRATIONKEYAUTH *tpm_migrationkeyauth,
				     unsigned char **stream,
				     uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_Migrationkeyauth_Load:\n");
    /* load migrationKey */
    if (rc == 0) {
	rc = TPM_Pubkey_Load(&(tpm_migrationkeyauth->migrationKey), stream, stream_size);
    }
    /* load migrationScheme */
    if (rc == 0) {
	rc = TPM_Load16(&(tpm_migrationkeyauth->migrationScheme), stream, stream_size);
    }
    /* load digest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_migrationkeyauth->digest, stream, stream_size);
    }
    return rc;
}

/* TPM_Migrationkeyauth_Store()
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_Migrationkeyauth_Store(TPM_STORE_BUFFER *sbuffer,
				      TPM_MIGRATIONKEYAUTH *tpm_migrationkeyauth)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_Migrationkeyauth_Store:\n");
    /* store migrationKey */
    if (rc == 0) {
	rc = TPM_Pubkey_Store(sbuffer, &(tpm_migrationkeyauth->migrationKey));
    }
    /* store migrationScheme */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append16(sbuffer, tpm_migrationkeyauth->migrationScheme);
    }
    /* store digest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_migrationkeyauth->digest);
    }
    return rc;
}

/* TPM_Migrationkeyauth_Delete()

   No-OP if the parameter is NULL, else:
   frees memory allocated for the object
   sets pointers to NULL
   calls TPM_Migrationkeyauth_Init to set members back to default values
   The object itself is not freed
*/   

void TPM_Migrationkeyauth_Delete(TPM_MIGRATIONKEYAUTH *tpm_migrationkeyauth)
{
    printf(" TPM_Migrationkeyauth_Delete:\n");
    if (tpm_migrationkeyauth != NULL) {
	TPM_Pubkey_Delete(&(tpm_migrationkeyauth->migrationKey));
	TPM_Migrationkeyauth_Init(tpm_migrationkeyauth);
    }
    return;
}

/*
  TPM_MSA_COMPOSITE
*/

/* TPM_MsaComposite_Init()

   sets members to default values
   sets all pointers to NULL and sizes to 0
   always succeeds - no return code
*/

void TPM_MsaComposite_Init(TPM_MSA_COMPOSITE *tpm_msa_composite)
{
    printf(" TPM_MsaComposite_Init:\n");
    tpm_msa_composite->MSAlist = 0;
    tpm_msa_composite->migAuthDigest = NULL;
    return;
}

/* TPM_MsaComposite_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes
   
   Before use, call TPM_MsaComposite_Init()
   After use, call TPM_MsaComposite_Delete() to free memory
*/

TPM_RESULT TPM_MsaComposite_Load(TPM_MSA_COMPOSITE *tpm_msa_composite,
				 unsigned char **stream,
				 uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;
    uint32_t		i;

    printf(" TPM_MsaComposite_Load:\n");
    /* load MSAlist */
    if (rc == 0) {
	rc = TPM_Load32(&(tpm_msa_composite->MSAlist), stream, stream_size);
    }
    /* MSAlist MUST be one (1) or greater. */
    if (rc == 0) {
	if (tpm_msa_composite->MSAlist == 0) {
	    printf("TPM_MsaComposite_Load: Error, MSAlist is zero\n");
	    rc = TPM_INVALID_STRUCTURE;
	}
    }
    /* FIXME add MSAlist limit */
    /* allocate memory for the migAuthDigest array */
    if (rc == 0) {
	rc = TPM_Malloc((unsigned char **)&(tpm_msa_composite->migAuthDigest),
			(tpm_msa_composite->MSAlist) * TPM_DIGEST_SIZE);
    }
    /* load migAuthDigest array */
    for (i = 0 ; (rc == 0) && (i < tpm_msa_composite->MSAlist) ; i++) {
	rc = TPM_Digest_Load(tpm_msa_composite->migAuthDigest[i], stream, stream_size);
    }
    return rc;
}

/* TPM_MsaComposite_Store()
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_MsaComposite_Store(TPM_STORE_BUFFER *sbuffer,
				  const TPM_MSA_COMPOSITE *tpm_msa_composite)
{
    TPM_RESULT		rc = 0;
    uint32_t		i;

    printf(" TPM_MsaComposite_Store:\n");
    /* store MSAlist */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append32(sbuffer, tpm_msa_composite->MSAlist);
    }
    /* store migAuthDigest array */
    for (i = 0 ; (rc == 0) && (i < tpm_msa_composite->MSAlist) ; i++) {
	rc = TPM_Digest_Store(sbuffer, tpm_msa_composite->migAuthDigest[i]);
    }
    return rc;
}

/* TPM_MsaComposite_Delete()

   No-OP if the parameter is NULL, else:
   frees memory allocated for the object
   sets pointers to NULL
   calls TPM_MsaComposite_Init to set members back to default values
   The object itself is not freed
*/   

void TPM_MsaComposite_Delete(TPM_MSA_COMPOSITE *tpm_msa_composite)
{
    printf(" TPM_MsaComposite_Delete:\n");
    if (tpm_msa_composite != NULL) {
	free(tpm_msa_composite->migAuthDigest);
	TPM_MsaComposite_Init(tpm_msa_composite);
    }
    return;
}

TPM_RESULT TPM_MsaComposite_CheckMigAuthDigest(TPM_DIGEST tpm_digest, /* value to check vs list */
					       TPM_MSA_COMPOSITE *tpm_msa_composite)
{
    TPM_RESULT		rc = 0;
    uint32_t		n;		/* count through msaList */
    TPM_BOOL		match;

    printf(" TPM_MsaComposite_CheckMigAuthDigest:\n");
    for (n = 0 , match = FALSE ; (n < tpm_msa_composite->MSAlist) && !match ; n++) {
	rc = TPM_Digest_Compare(tpm_digest, tpm_msa_composite->migAuthDigest[n]);
	if (rc == 0) {
	    match = TRUE;
	}
    }
    if (match) {
	rc = TPM_SUCCESS;
    }
    else {
	printf("TPM_MsaComposite_CheckMigAuthDigest: Error, no match to msaList\n");
	rc = TPM_MA_TICKET_SIGNATURE;
    }
    return rc;
}

/* TPM_MsaComposite_CheckSigTicket()

   i. Verify that for one of the n=1 to n=(msaList -> MSAlist) values of msaList ->
      migAuthDigest[n], sigTicket == HMAC (V1) using tpmProof as the secret where V1 is a
      TPM_CMK_SIGTICKET structure such that:

      (1) V1 -> verKeyDigest = msaList -> migAuthDigest[n]
      (2) V1 -> signedData = SHA1[restrictTicket]
*/

TPM_RESULT TPM_MsaComposite_CheckSigTicket(TPM_DIGEST sigTicket, /* expected HMAC */
					   TPM_SECRET tpmProof,	  /* HMAC key */
					   TPM_MSA_COMPOSITE *tpm_msa_composite,
					   TPM_CMK_SIGTICKET *tpm_cmk_sigticket)
{
    TPM_RESULT		rc = 0;
    uint32_t		n;		/* count through msaList */
    TPM_BOOL		match;
    TPM_STORE_BUFFER	sbuffer;
    const unsigned char *buffer;	
    uint32_t		length;
    
    printf(" TPM_MsaComposite_CheckSigTicket: TPM_MSA_COMPOSITE length %u\n",
	   tpm_msa_composite->MSAlist);
    TPM_Sbuffer_Init(&sbuffer);		/* freed @1 */
    for (n = 0 , match = FALSE ;
	 (rc == 0) && (n < tpm_msa_composite->MSAlist) && !match ; n++) {

	if (rc == 0) {
	    /* verKeyDigest = msaList -> migAuthDigest[n].  The rest of the structure is initialized
	       by the caller */
	    TPM_PrintFour("  TPM_MsaComposite_CheckSigTicket: Checking migAuthDigest: ",
			  tpm_msa_composite->migAuthDigest[n]);
	    TPM_Digest_Copy(tpm_cmk_sigticket->verKeyDigest, tpm_msa_composite->migAuthDigest[n]);
	    /* serialize the TPM_CMK_SIGTICKET structure */
	    TPM_Sbuffer_Clear(&sbuffer);	/* reset pointers without free */
	    rc = TPM_CmkSigticket_Store(&sbuffer, tpm_cmk_sigticket);
	    TPM_Sbuffer_Get(&sbuffer, &buffer, &length);
	}
	if (rc == 0) {
	    rc = TPM_HMAC_Check(&match,
				sigTicket,	/* expected */
				tpmProof,	/* HMAC key*/
				length, buffer, /* TPM_CMK_SIGTICKET */
				0, NULL);
	}
    }
    if (rc == 0) {
	    if (!match) {
	    printf("TPM_MsaComposite_CheckSigTicket: Error, no match to msaList\n");
	    rc = TPM_MA_TICKET_SIGNATURE;
	}
    }
    TPM_Sbuffer_Delete(&sbuffer);	/* @1 */
    return rc;
}

/*
  TPM_CMK_AUTH
*/

/* TPM_CmkAuth_Init()

   sets members to default values
   sets all pointers to NULL and sizes to 0
   always succeeds - no return code
*/

void TPM_CmkAuth_Init(TPM_CMK_AUTH *tpm_cmk_auth)
{
    printf(" TPM_CmkAuth_Init:\n");
    TPM_Digest_Init(tpm_cmk_auth->migrationAuthorityDigest);
    TPM_Digest_Init(tpm_cmk_auth->destinationKeyDigest);
    TPM_Digest_Init(tpm_cmk_auth->sourceKeyDigest);
    return;
}

/* TPM_CmkAuth_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes
   
   Before use, call TPM_CmkAuth_Init()
   After use, call TPM_CmkAuth_Delete() to free memory
*/

TPM_RESULT TPM_CmkAuth_Load(TPM_CMK_AUTH *tpm_cmk_auth,
			    unsigned char **stream,
			    uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_CmkAuth_Load:\n");
    /* load migrationAuthorityDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_cmk_auth->migrationAuthorityDigest, stream, stream_size);
    }
    /* load destinationKeyDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_cmk_auth->destinationKeyDigest, stream, stream_size);
    }
    /* load sourceKeyDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_cmk_auth->sourceKeyDigest, stream, stream_size);
    }
    return rc;
}

/* TPM_CmkAuth_Store()
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_CmkAuth_Store(TPM_STORE_BUFFER *sbuffer,
			     const TPM_CMK_AUTH *tpm_cmk_auth)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_CmkAuth_Store:\n");
    /* store migrationAuthorityDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_cmk_auth->migrationAuthorityDigest);
    }
    /* store destinationKeyDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_cmk_auth->destinationKeyDigest);
    }
    /* store sourceKeyDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_cmk_auth->sourceKeyDigest);
    }
    return rc;
}

/* TPM_CmkAuth_Delete()

   No-OP if the parameter is NULL, else:
   frees memory allocated for the object
   sets pointers to NULL
   calls TPM_CmkAuth_Init to set members back to default values
   The object itself is not freed
*/   

void TPM_CmkAuth_Delete(TPM_CMK_AUTH *tpm_cmk_auth)
{
    printf(" TPM_CmkAuth_Delete:\n");
    if (tpm_cmk_auth != NULL) {
	TPM_CmkAuth_Init(tpm_cmk_auth);
    }
    return;
}

/*
  TPM_CMK_MIGAUTH
*/

/* TPM_CmkMigauth_Init()

   sets members to default values
   sets all pointers to NULL and sizes to 0
   always succeeds - no return code
*/

void TPM_CmkMigauth_Init(TPM_CMK_MIGAUTH *tpm_cmk_migauth)
{
    printf(" TPM_CmkMigauth_Init:\n");
    TPM_Digest_Init(tpm_cmk_migauth->msaDigest);
    TPM_Digest_Init(tpm_cmk_migauth->pubKeyDigest);
    return;
}

/* TPM_CmkMigauth_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes
   
   Before use, call TPM_CmkMigauth_Init()
   After use, call TPM_CmkMigauth_Delete() to free memory
*/

TPM_RESULT TPM_CmkMigauth_Load(TPM_CMK_MIGAUTH *tpm_cmk_migauth,
			       unsigned char **stream,
			       uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_CmkMigauth_Load:\n");
    /* check tag */
    if (rc == 0) {	
	rc = TPM_CheckTag(TPM_TAG_CMK_MIGAUTH, stream, stream_size);
    }
    /* load msaDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_cmk_migauth->msaDigest , stream, stream_size);
    }
    /* load pubKeyDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_cmk_migauth->pubKeyDigest , stream, stream_size);
    }
    return rc;
}

/* TPM_CmkMigauth_Store()
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_CmkMigauth_Store(TPM_STORE_BUFFER *sbuffer,
				const TPM_CMK_MIGAUTH *tpm_cmk_migauth)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_CmkMigauth_Store:\n");
    /* store tag */
    if (rc == 0) {	
	rc = TPM_Sbuffer_Append16(sbuffer, TPM_TAG_CMK_MIGAUTH); 
    }
    /* store msaDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_cmk_migauth->msaDigest);
    }
    /* store pubKeyDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_cmk_migauth->pubKeyDigest);
    }
    return rc;
}

/* TPM_CmkMigauth_Delete()

   No-OP if the parameter is NULL, else:
   frees memory allocated for the object
   sets pointers to NULL
   calls TPM_CmkMigauth_Init to set members back to default values
   The object itself is not freed
*/   

void TPM_CmkMigauth_Delete(TPM_CMK_MIGAUTH *tpm_cmk_migauth)
{
    printf(" TPM_CmkMigauth_Delete:\n");
    if (tpm_cmk_migauth != NULL) {
	TPM_CmkMigauth_Init(tpm_cmk_migauth);
    }
    return;
}

/* TPM_CmkMigauth_CheckHMAC() checks an HMAC of a TPM_CMK_MIGAUTH object.

   It serializes the structure and HMAC's the result.  The common function cannot be used because
   'tpm_hmac' is not part of the structure and cannot be NULL'ed.
*/

TPM_RESULT TPM_CmkMigauth_CheckHMAC(TPM_BOOL *valid,			/* result */
				    TPM_HMAC tpm_hmac,			/* expected */
				    TPM_SECRET tpm_hmac_key,		/* key */
				    TPM_CMK_MIGAUTH *tpm_cmk_migauth)	/* data */
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	sbuffer;	/* serialized TPM_CMK_MIGAUTH */

    printf(" TPM_CmkMigauth_CheckHMAC:\n");
    TPM_Sbuffer_Init(&sbuffer);				/* freed @1 */
    /* Serialize the TPM_CMK_MIGAUTH structure */
    if (rc == 0) {
	rc = TPM_CmkMigauth_Store(&sbuffer, tpm_cmk_migauth);
    }	 
    /* verify the HMAC of the serialized structure */
    if (rc == 0) {
	rc = TPM_HMAC_CheckSbuffer(valid,		/* result */
				   tpm_hmac,		/* expected */
				   tpm_hmac_key,	/* key */
				   &sbuffer);		/* data stream */
    }
    TPM_Sbuffer_Delete(&sbuffer);			/* @1 */
    return rc;
}

/*
  TPM_CMK_SIGTICKET
*/

/* TPM_CmkSigticket_Init()

   sets members to default values
   sets all pointers to NULL and sizes to 0
   always succeeds - no return code
*/

void TPM_CmkSigticket_Init(TPM_CMK_SIGTICKET *tpm_cmk_sigticket)
{
    printf(" TPM_CmkSigticket_Init:\n");
    TPM_Digest_Init(tpm_cmk_sigticket->verKeyDigest);
    TPM_Digest_Init(tpm_cmk_sigticket->signedData);
    return;
}

/* TPM_CmkSigticket_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes
   
   Before use, call TPM_CmkSigticket_Init()
   After use, call TPM_CmkSigticket_Delete() to free memory
*/

TPM_RESULT TPM_CmkSigticket_Load(TPM_CMK_SIGTICKET *tpm_cmk_sigticket,
				 unsigned char **stream,
				 uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_CmkSigticket_Load:\n");
    /* check tag */
    if (rc == 0) {	
	rc = TPM_CheckTag(TPM_TAG_CMK_SIGTICKET, stream, stream_size);
    }
    /* load verKeyDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_cmk_sigticket->verKeyDigest , stream, stream_size);
    }
    /* load signedData */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_cmk_sigticket->signedData , stream, stream_size);
    }
    return rc;
}

/* TPM_CmkSigticket_Store()
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_CmkSigticket_Store(TPM_STORE_BUFFER *sbuffer,
				  const TPM_CMK_SIGTICKET *tpm_cmk_sigticket)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_CmkSigticket_Store:\n");
    /* store tag */
    if (rc == 0) {	
	rc = TPM_Sbuffer_Append16(sbuffer, TPM_TAG_CMK_SIGTICKET); 
    }
    /* store verKeyDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_cmk_sigticket->verKeyDigest);
    }
    /* store signedData */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_cmk_sigticket->signedData);
    }
    return rc;
}

/* TPM_CmkSigticket_Delete()

   No-OP if the parameter is NULL, else:
   frees memory allocated for the object
   sets pointers to NULL
   calls TPM_CmkSigticket_Init to set members back to default values
   The object itself is not freed
*/   

void TPM_CmkSigticket_Delete(TPM_CMK_SIGTICKET *tpm_cmk_sigticket)
{
    printf(" TPM_CmkSigticket_Delete:\n");
    if (tpm_cmk_sigticket != NULL) {
	TPM_CmkSigticket_Init(tpm_cmk_sigticket);
    }
    return;
}

/*
  TPM_CMK_MA_APPROVAL
*/

/* TPM_CmkMaApproval_Init()

   sets members to default values
   sets all pointers to NULL and sizes to 0
   always succeeds - no return code
*/

void TPM_CmkMaApproval_Init(TPM_CMK_MA_APPROVAL *tpm_cmk_ma_approval)
{
    printf(" TPM_CmkMaApproval_Init:\n");
    TPM_Digest_Init(tpm_cmk_ma_approval->migrationAuthorityDigest);
    return;
}

/* TPM_CmkMaApproval_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes
   
   Before use, call TPM_CmkMaApproval_Init()
   After use, call TPM_CmkMaApproval_Delete() to free memory
*/

TPM_RESULT TPM_CmkMaApproval_Load(TPM_CMK_MA_APPROVAL *tpm_cmk_ma_approval,
				  unsigned char **stream,
				  uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_CmkMaApproval_Load:\n");
    /* check tag */
    if (rc == 0) {	
	rc = TPM_CheckTag(TPM_TAG_CMK_MA_APPROVAL, stream, stream_size);
    }
    /* load migrationAuthorityDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_cmk_ma_approval->migrationAuthorityDigest, stream, stream_size);
    }
    return rc;
}

/* TPM_CmkMaApproval_Store()
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_CmkMaApproval_Store(TPM_STORE_BUFFER *sbuffer,
				   const TPM_CMK_MA_APPROVAL *tpm_cmk_ma_approval)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_CmkMaApproval_Store:\n");
    /* store tag */
    if (rc == 0) {	
	rc = TPM_Sbuffer_Append16(sbuffer, TPM_TAG_CMK_MA_APPROVAL); 
    }
    /* store migrationAuthorityDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_cmk_ma_approval->migrationAuthorityDigest);
    }
    return rc;
}

/* TPM_CmkMaApproval_Delete()

   No-OP if the parameter is NULL, else:
   frees memory allocated for the object
   sets pointers to NULL
   calls TPM_CmkMaApproval_Init to set members back to default values
   The object itself is not freed
*/   

void TPM_CmkMaApproval_Delete(TPM_CMK_MA_APPROVAL *tpm_cmk_ma_approval)
{
    printf(" TPM_CmkMaApproval_Delete:\n");
    if (tpm_cmk_ma_approval != NULL) {
	TPM_CmkMaApproval_Init(tpm_cmk_ma_approval);
    }
    return;
}

/* TPM_CmkMaApproval_CheckHMAC() generates an HMAC of a TPM_CMK_MIGAUTH object

   It serializes the structure and HMAC's the result.The common function cannot be used because
   'tpm_hmac' is not part of the structure and cannot be NULL'ed.
*/

TPM_RESULT TPM_CmkMaApproval_CheckHMAC(TPM_BOOL *valid,			/* result */
				       TPM_HMAC tpm_hmac,		/* expected */
				       TPM_SECRET tpm_hmac_key,		/* key */
				       TPM_CMK_MA_APPROVAL *tpm_cmk_ma_approval) /* data */
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	sbuffer;	/* serialized TPM_CMK_MA_APPROVAL */

    printf(" TPM_CmkMaApproval_CheckHMAC:\n");
    TPM_Sbuffer_Init(&sbuffer);				/* freed @1 */
    /* Serialize the TPM_CMK_MA_APPROVAL structure */
    if (rc == 0) {
	rc = TPM_CmkMaApproval_Store(&sbuffer, tpm_cmk_ma_approval);
    }	 
    /* verify the HMAC of the serialized structure */
    if (rc == 0) {
	rc = TPM_HMAC_CheckSbuffer(valid,		/* result */
				   tpm_hmac,		/* expected */
				   tpm_hmac_key,	/* key */
				   &sbuffer);		/* data stream */
    }
    TPM_Sbuffer_Delete(&sbuffer);			/* @1 */
    return rc;
}

/*
  Processing functions
*/

/* TPM_CreateBlobCommon() does the steps common to TPM_CreateMigrationBlob and
   TPM_CMK_CreateBlob
   
   It takes a TPM_STORE_ASYMKEY, and
	- splits the TPM_STORE_PRIVKEY into k1 (20) and k2 (112)
	- builds a TPM_MIGRATE_ASYMKEY using
		'payload_type'
		TPM_STORE_ASYMKEY usageAuth, pubDataDigest
		k2 as partPrivKey
	- serializes the TPM_MIGRATE_ASYMKEY
	- OAEP encode using
		'phash'
		k1 as seed
*/

TPM_RESULT TPM_CreateBlobCommon(TPM_SIZED_BUFFER *outData,	/* The modified, encrypted
								   entity. */
				TPM_STORE_ASYMKEY *d1AsymKey,
				TPM_DIGEST pHash,		/* for OAEP padding */
				TPM_PAYLOAD_TYPE payload_type,
				TPM_SIZED_BUFFER *random,	/* String used for xor encryption */
				TPM_PUBKEY *migrationKey)	/* public key of the migration
								   facility */
{
    TPM_RESULT		rc = 0;
    uint32_t		o1_size;
    BYTE		*o1;
    BYTE		*r1;
    BYTE		*x1;

    printf("TPM_CreateBlobCommon:\n");
    o1 = NULL;		/* freed @1 */
    r1 = NULL;		/* freed @2 */
    x1 = NULL;		/* freed @3 */
    if (rc == 0) {
	TPM_StoreAsymkey_GetO1Size(&o1_size, d1AsymKey);
    }
    if (rc == 0) {
	rc = TPM_Malloc(&o1, o1_size);
    }
    if (rc == 0) {
	rc = TPM_Malloc(&r1, o1_size);
    }
    if (rc == 0) {
	rc = TPM_Malloc(&x1, o1_size);
    }
    if (rc == 0) {
	rc = TPM_StoreAsymkey_StoreO1(o1,
				      o1_size,
				      d1AsymKey,
				      pHash,
				      payload_type,
				      d1AsymKey->usageAuth);
    }
    /* NOTE Comments from TPM_CreateMigrationBlob rev 81 */
    /* d. Create r1 a random value from the TPM RNG. The size of r1 MUST be the size of o1. Return
       r1 in the Random parameter. */
    if (rc == 0) {
	rc = TPM_Random(r1, o1_size);
    }
    /* e. Create x1 by XOR of o1 with r1 */
    if (rc == 0) {
	TPM_PrintFourLimit("TPM_CreateBlobCommon: r1 -", r1, o1_size);
	TPM_XOR(x1, o1, r1, o1_size);
	TPM_PrintFourLimit("TPM_CreateBlobCommon: x1 -", x1, o1_size);
	/* f. Copy r1 into the output field "random".*/
	rc = TPM_SizedBuffer_Set(random, o1_size, r1);
    }
    /* g. Encrypt x1 with the migration public key included in migrationKeyAuth. */
    if (rc == 0) {
	rc = TPM_RSAPublicEncrypt_Pubkey(outData,
					 x1,
					 o1_size,
					 migrationKey);
	TPM_PrintFour("TPM_CreateBlobCommon: outData", outData->buffer);
    }
    free(o1);		/* @1 */
    free(r1);		/* @2 */
    free(x1);		/* @3 */
    return rc;
}

/* 11.1 TPM_CreateMigrationBlob rev 109

   The TPM_CreateMigrationBlob command implements the first step in the process of moving a
   migratable key to a new parent or platform. Execution of this command requires knowledge of the
   migrationAuth field of the key to be migrated.

   Migrate mode is generally used to migrate keys from one TPM to another for backup, upgrade or to
   clone a key on another platform. To do this, the TPM needs to create a data blob that another TPM
   can deal with.  This is done by loading in a backup public key that will be used by the TPM to
   create a new data blob for a migratable key.

   The TPM Owner does the selection and authorization of migration public keys at any time prior to
   the execution of TPM_CreateMigrationBlob by performing the TPM_AuthorizeMigrationKey command.

   IReWrap mode is used to directly move the key to a new parent (either on this platform or
   another). The TPM simply re-encrypts the key using a new parent, and outputs a normal encrypted
   element that can be subsequently used by a TPM_LoadKey command.

   TPM_CreateMigrationBlob implicitly cannot be used to migrate a non-migratory key. No explicit
   check is required. Only the TPM knows tpmProof. Therefore it is impossible for the caller to
   submit an authorization value equal to tpmProof and migrate a non-migratory key.
*/

TPM_RESULT TPM_Process_CreateMigrationBlob(tpm_state_t *tpm_state,
					   TPM_STORE_BUFFER *response,
					   TPM_TAG tag,
					   uint32_t paramSize,
					   TPM_COMMAND_CODE ordinal,
					   unsigned char *command,
					   TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;				/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_KEY_HANDLE parentHandle;	/* Handle of the parent key that can decrypt encData. */
    TPM_MIGRATE_SCHEME migrationType;	/* The migration type, either MIGRATE or REWRAP */
    TPM_MIGRATIONKEYAUTH migrationKeyAuth;	/* Migration public key and its authorization
						   digest. */
    TPM_SIZED_BUFFER encData;		/* The encrypted entity that is to be modified. */
    TPM_AUTHHANDLE parentAuthHandle;	/* The authorization handle used for the parent key. */
    TPM_NONCE nonceOdd;			/* Nonce generated by system associated with
					   parentAuthHandle */
    TPM_BOOL continueAuthSession;	/* Continue use flag for parent session */
    TPM_AUTHDATA parentAuth;		/* Authorization HMAC key: parentKey.usageAuth. */
    TPM_AUTHHANDLE entityAuthHandle;	/* The authorization handle used for the encrypted
					   entity. */
    TPM_NONCE entitynonceOdd;		/* Nonce generated by system associated with
					   entityAuthHandle */
    TPM_BOOL continueEntitySession = TRUE;	/* Continue use flag for entity session */
    TPM_AUTHDATA entityAuth;		/* Authorization HMAC key: entity.migrationAuth. */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			parentAuthHandleValid = FALSE;
    TPM_BOOL			entityAuthHandleValid = FALSE;
    TPM_AUTH_SESSION_DATA	*parent_auth_session_data = NULL;	/* session data for
									   parentAuthHandle */
    TPM_AUTH_SESSION_DATA	*entity_auth_session_data = NULL;	/* session data for
									   entityAuthHandle */
    TPM_SECRET			*hmacKey;
    TPM_SECRET			*entityHmacKey;
    TPM_KEY			*parentKey;
    TPM_BOOL			parentPCRStatus;
    TPM_SECRET			*parentUsageAuth;
    unsigned char		*d1Decrypt;	       	/* decryption of encData */
    uint32_t			d1DecryptLength = 0;   	/* actual valid data */
    unsigned char		*stream;		/* for deserializing decrypted encData */
    uint32_t			stream_size;
    TPM_STORE_ASYMKEY		d1AsymKey;		/* structure from decrypted encData */
    TPM_STORE_BUFFER		mka_sbuffer;		/* serialized migrationKeyAuth */
    const unsigned char		*mka_buffer;	
    uint32_t			mka_length;
    
    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_SIZED_BUFFER	random;		/* String used for xor encryption */
    TPM_SIZED_BUFFER	outData;	/* The modified, encrypted entity. */

    printf("TPM_Process_CreateMigrationBlob: Ordinal Entry\n");
    TPM_Migrationkeyauth_Init(&migrationKeyAuth);	/* freed @1 */
    TPM_SizedBuffer_Init(&encData);			/* freed @2 */
    TPM_SizedBuffer_Init(&random);			/* freed @3 */
    TPM_SizedBuffer_Init(&outData);			/* freed @4 */
    d1Decrypt = NULL;					/* freed @5 */
    TPM_StoreAsymkey_Init(&d1AsymKey);			/* freed @6 */
    TPM_Sbuffer_Init(&mka_sbuffer);			/* freed @7 */
    /*
      get inputs
    */
    /* get parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get migrationType */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateMigrationBlob: parentHandle %08x\n", parentHandle); 
	returnCode = TPM_Load16(&migrationType, &command, &paramSize);
    }
    /* get migrationKeyAuth */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Migrationkeyauth_Load(&migrationKeyAuth, &command, &paramSize);
    }
    /* get encData */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&encData, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag21(tag);
    }
    /* get the optional 'below the line' authorization parameters */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	returnCode = TPM_AuthParams_Get(&parentAuthHandle,
					&parentAuthHandleValid,
					nonceOdd,
					&continueAuthSession,
					parentAuth,
					&command, &paramSize);
    }
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	printf("TPM_Process_CreateMigrationBlob: parentAuthHandle %08x\n", parentAuthHandle);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&entityAuthHandle,
					&entityAuthHandleValid,
					entitynonceOdd,
					&continueEntitySession,
					entityAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateMigrationBlob: entityAuthHandle %08x\n", entityAuthHandle); 
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CreateMigrationBlob: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	parentAuthHandleValid = FALSE;
	entityAuthHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* The TPM does not check the PCR values when migrating values locked to a PCR. */
    /* get the key associated with parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&parentKey, &parentPCRStatus,
						 tpm_state, parentHandle,
						 FALSE,		/* read-only, do not check PCR's */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get parentHandle -> usageAuth */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	returnCode = TPM_Key_GetUsageAuth(&parentUsageAuth, parentKey);
    }	 
    /* get the session data */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	returnCode = TPM_AuthSessions_GetData(&parent_auth_session_data,
					      &hmacKey,
					      tpm_state,
					      parentAuthHandle,
					      TPM_PID_NONE,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      parentKey,
					      parentUsageAuth,			/* OIAP */
					      parentKey->tpm_store_asymkey->pubDataDigest); /*OSAP*/
    }
    /* 1. Validate that parentAuth authorizes the use of the key pointed to by parentHandle. */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					parent_auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					parentAuth);		/* Authorization digest for input */
    }
    /* if there is no parent authorization, check that the parent authDataUsage is TPM_AUTH_NEVER */
    if ((returnCode == TPM_SUCCESS) && (tag != TPM_TAG_RQU_AUTH2_COMMAND)) {
	if (parentKey->authDataUsage != TPM_AUTH_NEVER) {
	    printf("TPM_Process_CreateMigrationBlob: Error, parent key authorization required\n");
	    returnCode = TPM_AUTHFAIL;
	}
    }
    /* 2. Validate that parentHandle -> keyUsage is TPM_KEY_STORAGE, if not return
       TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_CreateMigrationBlob: Error, keyUsage %04hx is invalid\n",
		   parentKey->keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 3. Create d1 a TPM_STORE_ASYMKEY structure by decrypting encData using the key pointed to by
       parentHandle. */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateMigrationBlob: Decrypting encData\n");
	/* decrypt with the parent key to a stream */
	returnCode = TPM_RSAPrivateDecryptMalloc(&d1Decrypt,	       /* decrypted data */
						 &d1DecryptLength,     /* actual size of d1 data */
						 encData.buffer,/* encrypted data */
						 encData.size,	/* encrypted data size */
						 parentKey);
    }
    /* deserialize the stream to a TPM_STORE_ASYMKEY d1AsymKey */
    if (returnCode == TPM_SUCCESS) {
	stream = d1Decrypt;
	stream_size = d1DecryptLength;
	returnCode = TPM_StoreAsymkey_Load(&d1AsymKey, FALSE,
					   &stream, &stream_size,
					   NULL,	/* TPM_KEY_PARMS */
					   NULL);	/* TPM_SIZED_BUFFER pubKey */
    }	 
    /* a. Verify that d1 -> payload is TPM_PT_ASYM. */
    if (returnCode == TPM_SUCCESS) {
	if (d1AsymKey.payload != TPM_PT_ASYM) {
	    printf("TPM_Process_CreateMigrationBlob: Error, bad payload %02x\n",
		   d1AsymKey.payload);
	    returnCode = TPM_BAD_MIGRATION;
	}
    }
    /* 4. Validate that entityAuth authorizes the migration of d1. The validation MUST use d1 ->
       migrationAuth as the secret. */
    /* get the second session data */
    /* The second authorisation session (using entityAuth) MUST be OIAP because OSAP does not have a
       suitable entityType */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&entity_auth_session_data,
					      &entityHmacKey,
					      tpm_state,
					      entityAuthHandle,
					      TPM_PID_OIAP,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      NULL,
					      &(d1AsymKey.migrationAuth),
					      NULL);
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Auth2data_Check(tpm_state,
					 *entityHmacKey,		/* HMAC key */
					 inParamDigest,
					 entity_auth_session_data,	/* authorization session */
					 entitynonceOdd,		/* Nonce generated by system
									   associated with authHandle */
					 continueEntitySession,
					 entityAuth);		/* Authorization digest for input */
    }
    /* 5.  Validate that migrationKeyAuth -> digest is the SHA-1 hash of (migrationKeyAuth ->
       migrationKey || migrationKeyAuth -> migrationScheme || TPM_PERMANENT_DATA -> tpmProof). */
    /* first serialize the TPM_PUBKEY migrationKeyAuth -> migrationKey */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateMigrationBlob: Verifying migrationKeyAuth\n");
	returnCode = TPM_Pubkey_Store(&mka_sbuffer, &(migrationKeyAuth.migrationKey));
    }
    if (returnCode == TPM_SUCCESS) {
	/* get the serialization result */
	TPM_Sbuffer_Get(&mka_sbuffer, &mka_buffer, &mka_length);
	/* compare to migrationKeyAuth -> digest */
	returnCode = TPM_SHA1_Check(migrationKeyAuth.digest,
				    mka_length, mka_buffer,	/* serialized migrationKey */
				    sizeof(TPM_MIGRATE_SCHEME), &(migrationKeyAuth.migrationScheme),
				    TPM_SECRET_SIZE, tpm_state->tpm_permanent_data.tpmProof,
				    0, NULL);
    }
    /* 6. If migrationType == TPM_MS_MIGRATE the TPM SHALL perform the following actions: */
    if ((returnCode == TPM_SUCCESS) && (migrationType == TPM_MS_MIGRATE)) {
	printf("TPM_Process_CreateMigrationBlob: migrationType TPM_MS_MIGRATE\n");
	/* a. Build two byte arrays, K1 and K2: */
	/* i. K1 = d1.privKey[0..19] (d1.privKey.keyLength + 16 bytes of d1.privKey.key), sizeof(K1)
	   = 20 */
	/* ii. K2 = d1.privKey[20..131] (position 16-127 of TPM_STORE_ASYMKEY. privKey.key)
	   (position 16-127 of d1 . privKey.key), sizeof(K2) = 112 */
	/* b. Build M1 a TPM_MIGRATE_ASYMKEY structure */
	/* i. TPM_MIGRATE_ASYMKEY.payload = TPM_PT_MIGRATE */
	/* ii. TPM_MIGRATE_ASYMKEY.usageAuth = d1.usageAuth */
	/* iii. TPM_MIGRATE_ASYMKEY.pubDataDigest = d1.pubDataDigest */
	/* iv. TPM_MIGRATE_ASYMKEY.partPrivKeyLen = 112 - 127. */
	/* v. TPM_MIGRATE_ASYMKEY.partPrivKey = K2 */
	/* c. Create o1 (which SHALL be 198 bytes for a 2048 bit RSA key) by performing the OAEP
	   encoding of m using OAEP parameters of */
	/* i. m = M1 the TPM_MIGRATE_ASYMKEY structure */
	/* ii. pHash = d1->migrationAuth */
	/* iii. seed = s1 = K1 */
	/* d. Create r1 a random value from the TPM RNG. The size of r1 MUST be the size of
	   o1. Return r1 in the Random parameter. */
	/* e. Create x1 by XOR of o1 with r1*/
	/* f. Copy r1 into the output field "random".*/
	/* g. Encrypt x1 with the migration public key included in migrationKeyAuth.*/
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_CreateBlobCommon(&outData,			/* output */
					      &d1AsymKey,		/* TPM_STORE_ASYMKEY */
					      d1AsymKey.migrationAuth,	/* pHash */
					      TPM_PT_MIGRATE,		/* payload type */
					      &random,		/* string for XOR encryption */
					      &(migrationKeyAuth.migrationKey)); /* TPM_PUBKEY */
	}
    }
    /* 7. If migrationType == TPM_MS_REWRAP the TPM SHALL perform the following actions: */
    else if ((returnCode == TPM_SUCCESS) && (migrationType == TPM_MS_REWRAP)) {
	printf("TPM_Process_CreateMigrationBlob: migrationType TPM_MS_REWRAP\n");
	/* a. Rewrap the key using the public key in migrationKeyAuth, keeping the existing contents
	   of that key. */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_RSAPublicEncrypt_Pubkey(&outData,
						     d1Decrypt,	/* decrypted encData parameter */
						     d1DecryptLength,
						     &(migrationKeyAuth.migrationKey));
	}
	/* b. Set randomSize to 0 in the output parameter array */
	/* NOTE Done by TPM_SizedBuffer_Init() */
    }
    /* 8. Else */
    /* a. Return TPM_BAD_PARAMETER */
    else if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateMigrationBlob: Error, illegal migrationType %04hx\n",
	       migrationType);
	returnCode = TPM_BAD_PARAMETER;
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CreateMigrationBlob: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* return random */
	    returnCode = TPM_SizedBuffer_Store(response, &random);
	}
	if (returnCode == TPM_SUCCESS) {
	    /* return outData */
	    returnCode = TPM_SizedBuffer_Store(response, &outData);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* HMAC key */
					    parent_auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *entityHmacKey,	/* HMAC key */
					    entity_auth_session_data,
					    outParamDigest,
					    entitynonceOdd,
					    continueEntitySession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession)
	&& parentAuthHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions,
					 parentAuthHandle);
    }
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueEntitySession) &&
	entityAuthHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions,
					 entityAuthHandle);
    }
    /*
      cleanup
    */
    TPM_Migrationkeyauth_Delete(&migrationKeyAuth);	/* @1 */
    TPM_SizedBuffer_Delete(&encData);			/* @2 */
    TPM_SizedBuffer_Delete(&random);			/* @3 */
    TPM_SizedBuffer_Delete(&outData);			/* @4 */
    free(d1Decrypt);					/* @5 */
    TPM_StoreAsymkey_Delete(&d1AsymKey);		/* @6 */
    TPM_Sbuffer_Delete(&mka_sbuffer);			/* @7 */
    return rcf;
}



/* 11.2 TPM_ConvertMigrationBlob rev 87

   This command takes a migration blob and creates a normal wrapped blob. The migrated blob must be
   loaded into the TPM using the normal TPM_LoadKey function.

   Note that the command migrates private keys, only. The migration of the associated public keys is
   not specified by TPM because they are not security sensitive. Migration of the associated public
   keys may be specified in a platform specific specification. A TPM_KEY structure must be recreated
   before the migrated key can be used by the target TPM in a LoadKey command.
*/

/* The relationship between Create and Convert parameters are:

   Create:	k1 || k2 = privKey
		m = TPM_MIGRATE_ASYMKEY, partPrivKey = k2
		o1 = OAEP (m), seed = k1
		x1 = o1 ^ r1
		out = pub (x1)
   Convert:
		d1 = priv (in)
		o1 = d1 ^ r1
		m1, seed = OAEP (o1)
		k1 = seed || partPrivKey
*/

TPM_RESULT TPM_Process_ConvertMigrationBlob(tpm_state_t *tpm_state,
					    TPM_STORE_BUFFER *response,
					    TPM_TAG tag,
					    uint32_t paramSize,
					    TPM_COMMAND_CODE ordinal,
					    unsigned char *command,
					    TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_KEY_HANDLE parentHandle;	/* Handle of a loaded key that can decrypt keys. */
    TPM_SIZED_BUFFER inData;		/* The XOR'd and encrypted key */
    TPM_SIZED_BUFFER random;		/* Random value used to hide key data. */
    TPM_AUTHHANDLE authHandle;		/* The authorization handle used for keyHandle. */
    TPM_NONCE nonceOdd;			/* Nonce generated by system associated with authHandle */
    TPM_BOOL continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   handle */
    TPM_AUTHDATA parentAuth;		/* The authorization digest that authorizes the inputs and
					   the migration of the key in parentHandle. HMAC key:
					   parentKey.usageAuth */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			authHandleValid = FALSE;
    TPM_SECRET			*hmacKey;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_KEY			*parentKey = NULL;	/* the key specified by parentHandle */
    TPM_BOOL			parentPCRStatus;
    TPM_SECRET			*parentUsageAuth;
    unsigned char		*d1Decrypt;
    uint32_t			d1DecryptLength = 0;		/* actual valid data */
    BYTE			*o1Oaep;
    TPM_STORE_ASYMKEY		d2AsymKey;
    TPM_STORE_BUFFER		d2_sbuffer;

    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_SIZED_BUFFER	outData;	/* The encrypted private key that can be loaded with
					   TPM_LoadKey */

    printf("TPM_Process_ConvertMigrationBlob: Ordinal Entry\n");
    TPM_SizedBuffer_Init(&inData);		/* freed @1 */
    TPM_SizedBuffer_Init(&random);		/* freed @2 */
    TPM_SizedBuffer_Init(&outData);		/* freed @3 */
    d1Decrypt = NULL;				/* freed @4 */
    o1Oaep = NULL;				/* freed @5 */
    TPM_StoreAsymkey_Init(&d2AsymKey);		/* freed @6 */
    TPM_Sbuffer_Init(&d2_sbuffer);		/* freed @7 */
    /*
      get inputs
    */
    /* get parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get inData */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_ConvertMigrationBlob: parentHandle %08x\n", parentHandle);
	returnCode = TPM_SizedBuffer_Load(&inData, &command, &paramSize);
    }
    /* get random */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&random, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag10(tag);
    }
    /* get the optional 'below the line' authorization parameters */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					parentAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_ConvertMigrationBlob: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* Verify that parentHandle points to a valid key.	Get the TPM_KEY associated with parentHandle
     */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&parentKey, &parentPCRStatus,
						 tpm_state, parentHandle,
						 FALSE,		/* not r/o, using to decrypt */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* check TPM_AUTH_DATA_USAGE authDataUsage */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_COMMAND)) {
	if (parentKey->authDataUsage != TPM_AUTH_NEVER) {
	    printf("TPM_Process_ConvertMigrationBlob: Error, parent key authorization required\n");
	    returnCode = TPM_AUTHFAIL;
	}
    }
    /* get parentHandle -> usageAuth */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_Key_GetUsageAuth(&parentUsageAuth, parentKey);
    }	 
    /* get the session data */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      parentKey,
					      parentUsageAuth,			/* OIAP */
					      parentKey->tpm_store_asymkey->pubDataDigest); /*OSAP*/
    }
    /* 1. Validate the authorization to use the key in parentHandle */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					parentAuth);		/* Authorization digest for input */
    }
    /* 2. If the keyUsage field of the key referenced by parentHandle does not have the value
       TPM_KEY_STORAGE, the TPM must return the error code TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_ConvertMigrationBlob: Error, "
		   "parentHandle -> keyUsage should be TPM_KEY_STORAGE, is %04x\n",
		   parentKey->keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 3. Create d1 by decrypting the inData area using the key in parentHandle */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_ConvertMigrationBlob: Decrypting inData\n");
	TPM_PrintFourLimit("TPM_Process_ConvertMigrationBlob: inData", inData.buffer, inData.size);
	returnCode = TPM_RSAPrivateDecryptMalloc(&d1Decrypt,		/* decrypted data */
						 &d1DecryptLength,	/* actual size of d1 data */
						 inData.buffer,		/* encrypted data */
						 inData.size,
						 parentKey);
    }
    /* the random input parameter must be the same length as the decrypted data */
    if (returnCode == TPM_SUCCESS) {
	if (d1DecryptLength != random.size) {
	    printf("TPM_Process_ConvertMigrationBlob: Error "
		   "decrypt data length %u random size %u\n",
		   d1DecryptLength, random.size);
	    returnCode = TPM_BAD_PARAMETER;
	}
    }
    /* allocate memory for o1 */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Malloc(&o1Oaep, d1DecryptLength);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_ConvertMigrationBlob: d1 length %u\n", d1DecryptLength);
	TPM_PrintFourLimit("TPM_Process_ConvertMigrationBlob: d1 -", d1Decrypt, d1DecryptLength);
	/* 4. Create o1 by XOR d1 and random parameter */
	TPM_XOR(o1Oaep, d1Decrypt, random.buffer, d1DecryptLength);
	/* 5. Create m1 a TPM_MIGRATE_ASYMKEY structure, seed and pHash by OAEP decoding o1 */
	/* NOTE TPM_StoreAsymkey_LoadO1() extracts TPM_STORE_ASYMKEY from the OAEP encoded
	   TPM_MIGRATE_ASYMKEY. */
	returnCode = TPM_StoreAsymkey_LoadO1(&d2AsymKey, o1Oaep, d1DecryptLength);
    }
    /* 6. Create k1 by combining seed and the TPM_MIGRATE_ASYMKEY -> partPrivKey field */
    /* NOTE Done by TPM_StoreAsymkey_LoadO1 () */
    /* 7. Create d2 a TPM_STORE_ASYMKEY structure */
    if (returnCode == TPM_SUCCESS) {
	/* a. Verify that m1 -> payload == TPM_PT_MIGRATE */
	/* NOTE TPM_StoreAsymkey_LoadO1() copied TPM_MIGRATE_ASYMKEY -> payload to TPM_STORE_ASYMKEY
	   -> payload */
	if (d2AsymKey.payload != TPM_PT_MIGRATE) {
	    printf("TPM_Process_ConvertMigrationBlob: Error, invalid payload %02x\n",
		   d2AsymKey.payload);
	    returnCode = TPM_BAD_MIGRATION;
	}
    }
    if (returnCode == TPM_SUCCESS) {
	/* b. Set d2 -> payload = TPM_PT_ASYM */
	d2AsymKey.payload = TPM_PT_ASYM;  
	/* c. Set d2 -> usageAuth to m1 -> usageAuth */
	/* d. Set d2 -> migrationAuth to pHash */
	/* e. Set d2 -> pubDataDigest to m1 -> pubDataDigest */
	/* f. Set d2 -> privKey field to k1 */
	/* NOTE Done by TPM_StoreAsymkey_LoadO1() */
	/* 9. Create outData using the key in parentHandle to perform the encryption */
	/* serialize d2key  to d2 */
	returnCode = TPM_StoreAsymkey_Store(&d2_sbuffer, FALSE, &d2AsymKey);
    }
    /* encrypt d2 with parentKey */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_RSAPublicEncryptSbuffer_Key(&outData, &d2_sbuffer, parentKey);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_ConvertMigrationBlob: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* return the outData */
	    returnCode = TPM_SizedBuffer_Store(response, &outData);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    TPM_SizedBuffer_Delete(&inData);		/* @1 */
    TPM_SizedBuffer_Delete(&random);		/* @2 */
    TPM_SizedBuffer_Delete(&outData);		/* @3 */
    free(d1Decrypt);				/* @4 */
    free(o1Oaep);				/* @5 */
    TPM_StoreAsymkey_Delete(&d2AsymKey);	/* @6 */
    TPM_Sbuffer_Delete(&d2_sbuffer);		/* @7 */
    return rcf;
}

/* 11.3 TPM_AuthorizeMigrationKey rev 114

   This command creates an authorization blob, to allow the TPM owner to specify which migration
   facility they will use and allow users to migrate information without further involvement with
   the TPM owner.

   It is the responsibility of the TPM Owner to determine whether migrationKey is appropriate for
   migration. The TPM checks just the cryptographic strength of migrationKey.
*/

TPM_RESULT TPM_Process_AuthorizeMigrationKey(tpm_state_t *tpm_state,
					     TPM_STORE_BUFFER *response,
					     TPM_TAG tag,
					     uint32_t paramSize,
					     TPM_COMMAND_CODE ordinal,
					     unsigned char *command,
					     TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;				/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_MIGRATE_SCHEME migrationScheme; /* Type of migration operation that is to be permitted for
					   this key. */
    TPM_PUBKEY migrationKey;		/* The public key to be authorized. */
    TPM_AUTHHANDLE authHandle;		/* The authorization handle used for owner authorization. */
    TPM_NONCE nonceOdd;			/* Nonce generated by system associated with authHandle */
    TPM_BOOL continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   handle */
    TPM_AUTHDATA ownerAuth;		/* The authorization digest for inputs and owner
					   authorization. HMAC key: ownerAuth. */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			authHandleValid = FALSE;
    TPM_SECRET			*hmacKey;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_RSA_KEY_PARMS		*rsa_key_parms;			/* for migrationKey */
    TPM_STORE_BUFFER		sbuffer;
    const unsigned char		*buffer;
    uint32_t			length;
    
    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_MIGRATIONKEYAUTH outData;	/* (f1) Returned public key and authorization digest. */

    printf("TPM_Process_AuthorizeMigrationKey: Ordinal Entry\n");
    TPM_Pubkey_Init(&migrationKey);		/* freed @1 */
    TPM_Migrationkeyauth_Init(&outData);	/* freed @2 */
    TPM_Sbuffer_Init(&sbuffer);			/* freed @3 */
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get migrationScheme */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load16(&migrationScheme, &command, &paramSize);
    }
    /* get migrationKey */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Pubkey_Load(&migrationKey, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					ownerAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_AuthorizeMigrationKey: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Check that the cryptographic strength of migrationKey is at least that of a 2048 bit RSA
       key. If migrationKey is an RSA key, this means that migrationKey MUST be 2048 bits or greater
       and MUST use the default exponent. */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyParms_GetRSAKeyParms(&rsa_key_parms,
						 &(migrationKey.algorithmParms));
    }
    if (returnCode == TPM_SUCCESS) {
	if (rsa_key_parms->keyLength < 2048) {
	    printf("TPM_Process_AuthorizeMigrationKey: Error, "
		   "migrationKey length %u less than 2048\n",
		   rsa_key_parms->keyLength);
	    returnCode = TPM_BAD_KEY_PROPERTY;
	}
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyParams_CheckDefaultExponent(&(rsa_key_parms->exponent));
    }
    /* 2. Validate the AuthData to use the TPM by the TPM Owner */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_OWNER,
					      ordinal,
					      NULL,
					      &(tpm_state->tpm_permanent_data.ownerAuth), /* OIAP */
					      tpm_state->tpm_permanent_data.ownerAuth);	  /* OSAP */
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* owner HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					ownerAuth);		/* Authorization digest for input */
    }
    /* 3. Create a f1 a TPM_MIGRATIONKEYAUTH  structure */
    /* NOTE: This is outData */
    /* 4. Verify that migrationKey-> algorithmParms -> encScheme is TPM_ES_RSAESOAEP_SHA1_MGF1, and
       return the error code TPM_INAPPROPRIATE_ENC if it is not */
    if (returnCode == TPM_SUCCESS) {
	if (migrationKey.algorithmParms.encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) {
	    printf("TPM_Process_AuthorizeMigrationKey: Error, "
		   "migrationKey encScheme %04hx must be TPM_ES_RSAESOAEP_SHA1_MGF1\n",
		   migrationKey.algorithmParms.encScheme);
	    returnCode = TPM_INAPPROPRIATE_ENC;
	}
    }
    /* 5. Set f1 -> migrationKey to the input migrationKey */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Pubkey_Copy(&(outData.migrationKey), &(migrationKey));
    }
    if (returnCode == TPM_SUCCESS) {
	/* 6. Set f1 -> migrationScheme to the input migrationScheme */
	outData.migrationScheme = migrationScheme;
	/* 7. Create v1 by concatenating (migrationKey || migrationScheme || TPM_PERMANENT_DATA ->
	   tpmProof) */
	/* 8. Create h1 by performing a SHA-1 hash of v1 */
	/* first serialize the TPM_PUBKEY migrationKey */
	returnCode = TPM_Pubkey_Store(&sbuffer, &migrationKey);
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_Sbuffer_Get(&sbuffer, &buffer, &length);
	/* 9. Set f1 -> digest to h1 */
	returnCode = TPM_SHA1(outData.digest,
			      length, buffer,		/* serialized migrationKey */
			      sizeof(TPM_MIGRATE_SCHEME), &(migrationScheme),
			      TPM_SECRET_SIZE, tpm_state->tpm_permanent_data.tpmProof,
			      0, NULL);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_AuthorizeMigrationKey: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* 10. Return f1 as outData */
	    returnCode = TPM_Migrationkeyauth_Store(response, &outData);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* owner HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    TPM_Pubkey_Delete(&migrationKey);		/* @1 */
    TPM_Migrationkeyauth_Delete(&outData);	/* @2 */
    TPM_Sbuffer_Delete(&sbuffer);		/* @3 */
    return rcf;
}

/* 11.4 TPM_MigrateKey rev 87

   The TPM_MigrateKey command performs the function of a migration authority.

   The command is relatively simple; it just decrypts the input packet (coming from
   TPM_CreateMigrationBlob or TPM_CMK_CreateBlob) and then re-encrypts it with the input public
   key. The output of this command would then be sent to TPM_ConvertMigrationBlob or
   TPM_CMK_ConvertMigration on the target TPM.
   
   TPM_MigrateKey does not make ANY assumptions about the contents of the encrypted blob. Since it
   does not have the XOR string, it cannot actually determine much about the key that is being
   migrated.
  
   This command exists to permit the TPM to be a migration authority. If used in this way, it is
   expected that the physical security of the system containing the TPM and the AuthData value for
   the MA key would be tightly controlled.

   To prevent the execution of this command using any other key as a parent key, this command works
   only if keyUsage for maKeyHandle is TPM_KEY_MIGRATE.
*/

TPM_RESULT TPM_Process_MigrateKey(tpm_state_t *tpm_state,
				  TPM_STORE_BUFFER *response,
				  TPM_TAG tag,
				  uint32_t paramSize,
				  TPM_COMMAND_CODE ordinal,
				  unsigned char *command,
				  TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;				/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_KEY_HANDLE maKeyHandle;		/* Handle of the key to be used to migrate the key. */
    TPM_PUBKEY pubKey;			/* Public key to which the blob is to be migrated */
    TPM_SIZED_BUFFER inData;		/* The input blob */

    TPM_AUTHHANDLE maAuthHandle;	/* The authorization session handle used for maKeyHandle. */
    TPM_NONCE nonceOdd;		/* Nonce generated by system associated with certAuthHandle */
    TPM_BOOL continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   session handle */
    TPM_AUTHDATA keyAuth;	/* The authorization session digest for the inputs and key to be
				   signed. HMAC key: maKeyHandle.usageAuth. */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			maAuthHandleValid = FALSE;
    TPM_SECRET			*hmacKey;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_KEY			*maKey = NULL;		/* the key specified by maKeyHandle */
    TPM_RSA_KEY_PARMS		*tpm_rsa_key_parms;	/* for maKey */
    TPM_SECRET			*maKeyUsageAuth;
    TPM_BOOL			maPCRStatus;
    uint32_t			decrypt_data_size;	/* resulting decrypted data size */
    BYTE			*decrypt_data = NULL;	/* The resulting decrypted data. */

    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_SIZED_BUFFER	outData;	/* The re-encrypted blob */

    printf("TPM_Process_MigrateKey: Ordinal Entry\n");
    TPM_SizedBuffer_Init(&inData);	/* freed @1 */
    TPM_SizedBuffer_Init(&outData);	/* freed @2 */
    TPM_Pubkey_Init(&pubKey);		/* freed @4 */
    /*
      get inputs
    */
    /* get maKeyHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&maKeyHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get pubKey */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_MigrateKey: maKeyHandle %08x\n", maKeyHandle); 
	returnCode = TPM_Pubkey_Load(&pubKey, &command, &paramSize);
    }
    /* get encData */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&inData, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag10(tag);
    }
    /* get the optional 'below the line' authorization parameters */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthParams_Get(&maAuthHandle,
					&maAuthHandleValid,
					nonceOdd,
					&continueAuthSession,
					keyAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_MigrateKey: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	maAuthHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Validate that keyAuth authorizes the use of the key pointed to by maKeyHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&maKey, &maPCRStatus, tpm_state, maKeyHandle,
						 FALSE,		/* not read-only */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get maKeyHandle -> usageAuth */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_Key_GetUsageAuth(&maKeyUsageAuth, maKey);
    }	 
    /* get the session data */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	printf("TPM_Process_MigrateKey: maAuthHandle %08x\n", maAuthHandle); 
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      maAuthHandle,
					      TPM_PID_NONE,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      maKey,
					      maKeyUsageAuth,		/* OIAP */
					      maKey->tpm_store_asymkey->pubDataDigest); /* OSAP */
    }
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					keyAuth);		/* Authorization digest for input */
    }
    /* check TPM_AUTH_DATA_USAGE authDataUsage */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_COMMAND)) {
	if (maKey->authDataUsage != TPM_AUTH_NEVER) {
	    printf("TPM_Process_MigrateKey: Error, authorization required\n");
	    returnCode = TPM_AUTHFAIL;
	}
    }
    /* 2. The TPM validates that the key pointed to by maKeyHandle has a key usage value of
       TPM_KEY_MIGRATE, and that the allowed encryption scheme is TPM_ES_RSAESOAEP_SHA1_MGF1. */
    if (returnCode == TPM_SUCCESS) {
	if (maKey->keyUsage != TPM_KEY_MIGRATE) {
	    printf("TPM_Process_MigrateKey: Error, keyUsage %04hx not TPM_KEY_MIGRATE\n",
		   maKey->keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
	else if (maKey->algorithmParms.encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) {
	    printf("TPM_Process_MigrateKey: Error, encScheme %04hx not TPM_ES_RSAESOAEP_SHA_MGF1\n",
		   maKey->algorithmParms.encScheme);
	    returnCode = TPM_BAD_KEY_PROPERTY;
	}
    }
    /* 3. The TPM validates that pubKey is of a size supported by the TPM and that its size is
       consistent with the input blob and maKeyHandle. */
    /* NOTE: Let the encryption step do this step */
    /* 4. The TPM decrypts inData and re-encrypts it using pubKey. */
    /* get the TPM_RSA_KEY_PARMS associated with maKey */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyParms_GetRSAKeyParms(&tpm_rsa_key_parms, &(maKey->algorithmParms));
    }	     
    /* decrypt using maKey */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_MigrateKey: Decrypt using maKey\n");
	returnCode =
	    TPM_RSAPrivateDecryptMalloc(&decrypt_data,		/* decrypted data, freed @3 */
					&decrypt_data_size,	/* actual size of decrypt data */
					inData.buffer,
					inData.size,
					maKey);
	
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_MigrateKey: Encrypt using pubKey\n");
	returnCode = TPM_RSAPublicEncrypt_Pubkey(&outData,	/* encrypted data */
						 decrypt_data,
						 decrypt_data_size,
						 &pubKey);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_MigrateKey: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* return outData */
	    returnCode = TPM_SizedBuffer_Store(response, &outData);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	maAuthHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, maAuthHandle);
    }
    /*
      cleanup
    */
    TPM_SizedBuffer_Delete(&inData);	/* @1 */
    TPM_SizedBuffer_Delete(&outData);	/* @2 */
    free(decrypt_data);			/* @3 */
    TPM_Pubkey_Delete(&pubKey);		/* @4 */
    return rcf;
}
     
/* 11.7 TPM_CMK_CreateKey rev 114

   The TPM_CMK_CreateKey command both generates and creates a secure storage bundle for asymmetric
   keys whose migration is controlled by a migration authority.

   TPM_CMK_CreateKey is very similar to TPM_CreateWrapKey, but: (1) the resultant key must be a
   migratable key and can be migrated only by TPM_CMK_CreateBlob; (2) the command is Owner
   authorized via a ticket.

   TPM_CMK_CreateKey creates an otherwise normal migratable key except that (1) migrationAuth is an
   HMAC of the migration authority and the new key's public key, signed by tpmProof (instead of
   being tpmProof); (2) the migrationAuthority bit is set TRUE; (3) the payload type is
   TPM_PT_MIGRATE_RESTRICTED.
     
   The migration-selection/migration authority is specified by passing in a public key (actually the
   digests of one or more public keys, so more than one migration authority can be specified).
*/

TPM_RESULT TPM_Process_CMK_CreateKey(tpm_state_t *tpm_state,
				     TPM_STORE_BUFFER *response,
				     TPM_TAG tag,
				     uint32_t paramSize,
				     TPM_COMMAND_CODE ordinal,
				     unsigned char *command,
				     TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;				/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_KEY_HANDLE parentHandle;	/* Handle of a loaded key that can perform key wrapping. */
    TPM_ENCAUTH dataUsageAuth;		/* Encrypted usage authorization data for the key. */
    TPM_KEY keyInfo;			/* Information about key to be created, pubkey.keyLength and
					   keyInfo.encData elements are 0. MUST be TPM_KEY12 */
    TPM_HMAC migrationAuthorityApproval;/* A ticket, created by the TPM Owner using
					   TPM_CMK_ApproveMA, approving a TPM_MSA_COMPOSITE
					   structure */
    TPM_DIGEST migrationAuthorityDigest;/* The digest of a TPM_MSA_COMPOSITE structure */

    TPM_AUTHHANDLE authHandle;		/* The authorization handle used for parent key
					   authorization. Must be an OSAP session. */
    TPM_NONCE nonceOdd;			/* Nonce generated by system associated with authHandle */
    TPM_BOOL continueAuthSession = TRUE;	/* Ignored */
    TPM_AUTHDATA pubAuth;		/* The authorization session digest that authorizes the use
					   of the public key in parentHandle. HMAC key:
					   parentKey.usageAuth.*/

    /* processing parameters */
    unsigned char *		inParamStart;			/* starting point of inParam's */
    unsigned char *		inParamEnd;			/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			authHandleValid = FALSE;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for entityAuthHandle
								 */
    TPM_SECRET			*hmacKey;
    TPM_KEY			*parentKey = NULL;	/* the key specified by parentHandle */
    TPM_BOOL			parentPCRStatus;
    TPM_BOOL			hmacValid;			/* for migrationAuthorityApproval */
    TPM_SECRET			du1DecryptAuth;
    TPM_STORE_ASYMKEY		*wrappedStoreAsymkey;		/* substructure of wrappedKey */
    TPM_CMK_MA_APPROVAL		m1CmkMaApproval;
    TPM_CMK_MIGAUTH		m2CmkMigauth;
    int				ver;

    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_KEY		wrappedKey;	/* The TPM_KEY structure which includes the public and
					   encrypted private key. MUST be TPM_KEY12 */

    printf("TPM_Process_CMK_CreateKey: Ordinal Entry\n");
    TPM_Key_Init(&keyInfo);			/* freed @1 */
    TPM_Key_Init(&wrappedKey);			/* freed @2 */
    TPM_CmkMaApproval_Init(&m1CmkMaApproval);	/* freed @3 */
    TPM_CmkMigauth_Init(&m2CmkMigauth);		/* freed @4 */
    /*
      get inputs
    */
    /* get parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get dataUsageAuth */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateKey: parentHandle %08x\n", parentHandle);
	returnCode = TPM_Authdata_Load(dataUsageAuth, &command, &paramSize);
    }
    /* get keyInfo */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_Load(&keyInfo, &command, &paramSize);
    }
    /* get migrationAuthorityApproval */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Digest_Load(migrationAuthorityApproval, &command, &paramSize);
    }
    /* get migrationAuthorityDigest */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Digest_Load(migrationAuthorityDigest, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					pubAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateKey: authHandle %08x\n", authHandle); 
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CMK_CreateKey: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Validate the authorization to use the key pointed to by parentHandle. Return TPM_AUTHFAIL
       on any error. */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&parentKey, &parentPCRStatus,
						 tpm_state, parentHandle,
						 FALSE,		/* not r/o, using to encrypt */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get the session data */
    /* 2. Validate the session type for parentHandle is OSAP. */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_OSAP,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      parentKey,
					      NULL,			/* OIAP */
					      parentKey->tpm_store_asymkey->pubDataDigest); /*OSAP*/
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					pubAuth);		/* Authorization digest for input */
    }
    /* 3. If the TPM is not designed to create a key of the type requested in keyInfo, return the
       error code TPM_BAD_KEY_PROPERTY */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_CheckProperties(&ver, &keyInfo, 0,
					     tpm_state->tpm_permanent_flags.FIPS);
	printf("TPM_Process_CMK_CreateKey: key parameters v = %d\n", ver);
    }
    /* 4. Verify that parentHandle->keyUsage equals TPM_KEY_STORAGE */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateKey: Checking parent key\n");
	if (parentKey->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_CMK_CreateKey: Error, parent keyUsage not TPM_KEY_STORAGE\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }	 
    /* 5. Verify that parentHandle-> keyFlags-> migratable == FALSE */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyFlags & TPM_MIGRATABLE) {
	    printf("TPM_Process_CMK_CreateKey: Error, parent migratable\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 6. If keyInfo -> keyFlags -> migratable is FALSE then return TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateKey: Checking key flags\n");
	if (!(keyInfo.keyFlags & TPM_MIGRATABLE)) {
	    printf("TPM_Process_CMK_CreateKey: Error, keyInfo migratable is FALSE\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 7. If keyInfo -> keyFlags -> migrateAuthority is FALSE , return TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if (!(keyInfo.keyFlags & TPM_MIGRATEAUTHORITY)) {
	    printf("TPM_Process_CMK_CreateKey: Error, keyInfo migrateauthority is FALSE\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 8. Verify that the migration authority is authorized */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateKey: Checking migration authority authorization\n");
	/* a. Create M1 a TPM_CMK_MA_APPROVAL structure */
	/* NOTE Done by TPM_CmkMaApproval_Init() */
	/* i. Set M1 ->migrationAuthorityDigest to migrationAuthorityDigest */
	TPM_Digest_Copy(m1CmkMaApproval.migrationAuthorityDigest, migrationAuthorityDigest);
	/* b. Verify that migrationAuthorityApproval == HMAC(M1) using tpmProof as the secret and
	   return error TPM_MA_AUTHORITY on mismatch */
	returnCode =
	    TPM_CmkMaApproval_CheckHMAC(&hmacValid,
					migrationAuthorityApproval,		/* expect */
					tpm_state->tpm_permanent_data.tpmProof, /* HMAC key */
					&m1CmkMaApproval);
	if (!hmacValid) {
	    printf("TPM_Process_CMK_CreateKey: Error, Invalid migrationAuthorityApproval\n");
	    returnCode = TPM_MA_AUTHORITY;
	}
    }
    /* 9. Validate key parameters */
    /* a. keyInfo -> keyUsage MUST NOT be TPM_KEY_IDENTITY or TPM_KEY_AUTHCHANGE. If it is, return
       TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateKey: Checking key usage\n");
	if ((keyInfo.keyUsage == TPM_KEY_IDENTITY) ||
	    (keyInfo.keyUsage == TPM_KEY_AUTHCHANGE)) {
	    printf("TPM_Process_CMK_CreateKey: Error, invalid keyInfo -> keyUsage %04hx\n",
		   keyInfo.keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 10. If TPM_PERMANENT_FLAGS -> FIPS is TRUE then */
    /* a. If keyInfo -> keySize is less than 1024 return TPM_NOTFIPS */
    /* b. If keyInfo -> authDataUsage specifies TPM_AUTH_NEVER return TPM_NOTFIPS */
    /* c. If keyInfo -> keyUsage specifies TPM_KEY_LEGACY return TPM_NOTFIPS */
    /* NOTE Done by TPM_Key_CheckProperties() */
    /* 11. If keyInfo -> keyUsage equals TPM_KEY_STORAGE or TPM_KEY_MIGRATE */
    /* a. algorithmID MUST be TPM_ALG_RSA */
    /* b. encScheme MUST be TPM_ES_RSAESOAEP_SHA1_MGF1 */
    /* c. sigScheme MUST be TPM_SS_NONE */
    /* d. key size MUST be 2048 */
    /* e. exponentSize MUST be 0 */
    /* NOTE Done by TPM_Key_CheckProperties() */
    /* 12. If keyInfo -> tag is NOT TPM_TAG_KEY12 return TPM_INVALID_STRUCTURE */
    if (returnCode == TPM_SUCCESS) {
	if (ver != 2) {
	    printf("TPM_Process_CMK_CreateKey: Error, keyInfo must be TPM_TAG_KEY12\n");
	    returnCode = TPM_INVALID_STRUCTURE;
	}
    }
    /* 13. Map wrappedKey to a TPM_KEY12 structure */
    /* NOTE: Not required.  TPM_KEY functions handle TPM_KEY12 subclass */
    /* 14. Create DU1 by decrypting dataUsageAuth according to the ADIP indicated by authHandle. */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessionData_Decrypt(du1DecryptAuth,
						 NULL,
						 dataUsageAuth,
						 auth_session_data,
						 NULL,
						 NULL,
						 FALSE);	/* even and odd */
    }
    if (returnCode == TPM_SUCCESS) {
	/* 15. Set continueAuthSession to FALSE */
	continueAuthSession = FALSE;
	/* 16. Generate asymmetric key according to algorithm information in keyInfo */
	/* 17. Fill in the wrappedKey structure with information from the newly generated key.	*/
	printf("TPM_Process_CMK_CreateKey: Generating key\n");
	returnCode = TPM_Key_GenerateRSA(&wrappedKey,
					 tpm_state,
					 parentKey,
					 tpm_state->tpm_stclear_data.PCRS,	/* PCR array */
					 ver,				/* TPM_KEY12 */
					 keyInfo.keyUsage,
					 keyInfo.keyFlags,
					 keyInfo.authDataUsage,		/* TPM_AUTH_DATA_USAGE */
					 &(keyInfo.algorithmParms),	/* TPM_KEY_PARMS */
					 keyInfo.tpm_pcr_info,		/* TPM_PCR_INFO */
					 keyInfo.tpm_pcr_info_long);	/* TPM_PCR_INFO_LONG */
    }	 
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_GetStoreAsymkey(&wrappedStoreAsymkey,
					     &wrappedKey);
    }	 
    if (returnCode == TPM_SUCCESS) {
	/* a. Set wrappedKey -> encData -> usageAuth to DU1 */
	TPM_Secret_Copy(wrappedStoreAsymkey->usageAuth, du1DecryptAuth);
	/* b. Set wrappedKey -> encData -> payload to TPM_PT_MIGRATE_RESTRICTED */
	wrappedStoreAsymkey->payload = TPM_PT_MIGRATE_RESTRICTED;
	/* c. Create thisPubKey, a TPM_PUBKEY structure containing wrappedKey's public key. */
	/* NOTE All that is really needed is its digest, which is calculated directly */
    }
    if (returnCode == TPM_SUCCESS) {
	/* d. Create M2 a TPM_CMK_MIGAUTH structure */
	/* NOTE Done by TPM_CmkMigauth_Init() */
	/* i. Set M2 -> msaDigest to migrationAuthorityDigest */
	TPM_Digest_Copy(m2CmkMigauth.msaDigest, migrationAuthorityDigest);
	/* ii. Set M2 -> pubKeyDigest to SHA-1 (thisPubKey) */
	returnCode = TPM_Key_GeneratePubkeyDigest(m2CmkMigauth.pubKeyDigest, &wrappedKey);
	/* e. Set wrappedKey -> encData -> migrationAuth equal to HMAC(M2), using tpmProof as the
	   shared secret */
	returnCode = TPM_HMAC_GenerateStructure
		     (wrappedStoreAsymkey->migrationAuth,	/* HMAC */
		      tpm_state->tpm_permanent_data.tpmProof,	/* HMAC key */
		      &m2CmkMigauth,				/* structure */
		      (TPM_STORE_FUNCTION_T)TPM_CmkMigauth_Store);	/* store function */
    }
    /* 18. If keyInfo->PCRInfoSize is non-zero */
    /* a. Set wrappedKey -> pcrInfo to a TPM_PCR_INFO_LONG structure */
    /* b. Set wrappedKey -> pcrInfo to keyInfo -> pcrInfo  */
    /* b. Set wrappedKey -> digestAtCreation to the TPM_COMPOSITE_HASH indicated by
       creationPCRSelection */
    /* c. Set wrappedKey -> localityAtCreation to TPM_STANY_FLAGS -> localityModifier */
    /* NOTE This is done during TPM_Key_GenerateRSA() */
    /* 19. Encrypt the private portions of the wrappedKey structure using the key in parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_GenerateEncData(&wrappedKey, parentKey);
    }	 
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CMK_CreateKey: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* 20. Return the newly generated key in the wrappedKey parameter */
	    returnCode = TPM_Key_Store(response, &wrappedKey);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,	/* HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    TPM_Key_Delete(&keyInfo);			/* @1 */
    TPM_Key_Delete(&wrappedKey);		/* @2 */
    TPM_CmkMaApproval_Delete(&m1CmkMaApproval); /* @3 */
    TPM_CmkMigauth_Delete(&m2CmkMigauth);	/* @4 */
    return rcf;
}


/* 11.5 TPM_CMK_CreateTicket rev 101

   The TPM_verifySignature command uses a public key to verify the signature over a digest.

   TPM_verifySignature returns a ticket that can be used to prove to the same TPM that signature
   verification with a particular public key was successful.
*/

TPM_RESULT TPM_Process_CMK_CreateTicket(tpm_state_t *tpm_state,
					TPM_STORE_BUFFER *response,
					TPM_TAG tag,
					uint32_t paramSize,
					TPM_COMMAND_CODE ordinal,
					unsigned char *command,
					TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_PUBKEY verificationKey;		/* The public key to be used to check signatureValue */
    TPM_DIGEST signedData;		/* The data to be verified */
    TPM_SIZED_BUFFER signatureValue;	/* The signatureValue to be verified */
    TPM_AUTHHANDLE authHandle;		/* The authorization handle used for owner authorization. */
    TPM_NONCE nonceOdd;			/* Nonce generated by system associated with authHandle */
    TPM_BOOL continueAuthSession = TRUE;	/* Ignored */
    TPM_AUTHDATA pubAuth;		/* The authorization digest for inputs and owner. HMAC key:
					   ownerAuth. */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			authHandleValid = FALSE;
    TPM_SECRET			*hmacKey;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_CMK_SIGTICKET		m2CmkSigticket;
    
    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_HMAC		sigTicket;	/* Ticket that proves digest created on this TPM */

    printf("TPM_Process_CMK_CreateTicket: Ordinal Entry\n");
    TPM_Pubkey_Init(&verificationKey);		/* freed @1 */
    TPM_SizedBuffer_Init(&signatureValue);	/* freed @2 */
    TPM_CmkSigticket_Init(&m2CmkSigticket);	/* freed @3 */
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get verificationKey */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Pubkey_Load(&verificationKey, &command, &paramSize);
    }
    /* get signedData */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Digest_Load(signedData, &command, &paramSize);
    }
    /* get signatureValue */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&signatureValue, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					pubAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CMK_CreateTicket: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Validate the TPM Owner authorization to use the command */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_OWNER,
					      ordinal,
					      NULL,
					      &(tpm_state->tpm_permanent_data.ownerAuth), /* OIAP */
					      tpm_state->tpm_permanent_data.ownerAuth);	  /* OSAP */
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* owner HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					pubAuth);		/* Authorization digest for input */
    }
    /* 2. Validate that the key type and algorithm are correct */
    /* a. Validate that verificationKey -> algorithmParms -> algorithmID == TPM_ALG_RSA */
    if (returnCode == TPM_SUCCESS) {
	if (verificationKey.algorithmParms.algorithmID != TPM_ALG_RSA) {
	    printf("TPM_Process_CMK_CreateTicket: Error, incorrect algorithmID %08x\n",
		   verificationKey.algorithmParms.algorithmID);
	    returnCode = TPM_BAD_KEY_PROPERTY;
	}
    }
    /* b. Validate that verificationKey -> algorithmParms ->encScheme == TPM_ES_NONE */
    if (returnCode == TPM_SUCCESS) {
	if (verificationKey.algorithmParms.encScheme != TPM_ES_NONE) {
	    printf("TPM_Process_CMK_CreateTicket: Error, incorrect encScheme %04hx\n",
		   verificationKey.algorithmParms.encScheme);
	    returnCode = TPM_INAPPROPRIATE_ENC;
	}
    }
    /* c. Validate that verificationKey ->algorithmParms ->sigScheme is
       TPM_SS_RSASSAPKCS1v15_SHA1 or TPM_SS_RSASSAPKCS1v15_INFO */
    if (returnCode == TPM_SUCCESS) {
	if ((verificationKey.algorithmParms.sigScheme != TPM_SS_RSASSAPKCS1v15_SHA1) &&
	    (verificationKey.algorithmParms.sigScheme != TPM_SS_RSASSAPKCS1v15_INFO)) {
	    printf("TPM_Process_CMK_CreateTicket: Error, incorrect sigScheme %04hx\n",
		   verificationKey.algorithmParms.sigScheme);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 3. Use verificationKey to verify that signatureValue is a valid signature on signedData, and
       return error TPM_BAD_SIGNATURE on mismatch */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateTicket: Verifying signature\n");
	returnCode = TPM_RSAVerifyH(&signatureValue,		/* signature */
				    signedData,			/* data that was signed */
				    TPM_DIGEST_SIZE,		/* size of signed data */
				    &verificationKey);		/* TPM_PUBKEY public key */
	if (returnCode != TPM_SUCCESS) {
	    printf("TPM_Process_CMK_CreateTicket: Error verifying signature\n");
	}
    }
    /* 4. Create M2 a TPM_CMK_SIGTICKET */
    /* NOTE Done by TPM_CmkSigticket_Init() */
    /* a. Set M2 -> verKeyDigest to the SHA-1 (verificationKey) */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SHA1_GenerateStructure(m2CmkSigticket.verKeyDigest, &verificationKey,
						(TPM_STORE_FUNCTION_T)TPM_Pubkey_Store);
    }
    if (returnCode == TPM_SUCCESS) {
	/* b. Set M2 -> signedData to signedData */
	TPM_Digest_Copy(m2CmkSigticket.signedData, signedData);
	/* 5. Set sigTicket = HMAC(M2) signed by using tpmProof as the secret */
	returnCode = TPM_HMAC_GenerateStructure
		     (sigTicket,				/* HMAC */
		      tpm_state->tpm_permanent_data.tpmProof,	/* HMAC key */
		      &m2CmkSigticket,				/* structure */
		      (TPM_STORE_FUNCTION_T)TPM_CmkSigticket_Store);	/* store function */
    }
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CMK_CreateTicket: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* return sigTicket */
	    returnCode = TPM_Digest_Store(response, sigTicket);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* owner HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    TPM_Pubkey_Delete(&verificationKey);	/* @1 */
    TPM_SizedBuffer_Delete(&signatureValue);	/* @2 */
    TPM_CmkSigticket_Delete(&m2CmkSigticket);	/* @3 */
    return rcf;
}


/* 11.9 TPM_CMK_CreateBlob rev 114

   TPM_CMK_CreateBlob command is very similar to TPM_CreateMigrationBlob, except that it: (1) uses
   an extra ticket (restrictedKeyAuth) instead of a migrationAuth authorization session; (2) uses
   the migration options TPM_MS_RESTRICT_MIGRATE or TPM_MS_RESTRICT_APPROVE; (3) produces a wrapped
   key blob whose migrationAuth is independent of tpmProof.

   If the destination (parent) public key is the MA, migration is implicitly permitted. Further
   checks are required if the MA is not the destination (parent) public key, and merely selects a
   migration destination: (1) sigTicket must prove that restrictTicket was signed by the MA; (2)
   restrictTicket must vouch that the target public key is approved for migration to the destination
   (parent) public key. (Obviously, this more complex method may also be used by an MA to approve
   migration to that MA.) In both cases, the MA must be one of the MAs implicitly listed in the
   migrationAuth of the target key-to-be-migrated.
   
   When the migrationType is TPM_MS_RESTRICT_MIGRATE, restrictTicket and sigTicket are unused.	The
   TPM may test that the corresponding sizes are zero, so the caller should set them to zero for
   interoperability.
*/

TPM_RESULT TPM_Process_CMK_CreateBlob(tpm_state_t *tpm_state,
				      TPM_STORE_BUFFER *response,
				      TPM_TAG tag,
				      uint32_t paramSize,
				      TPM_COMMAND_CODE ordinal,
				      unsigned char *command,
				      TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_KEY_HANDLE parentHandle;	/* Handle of the parent key that can decrypt encData. */
    TPM_MIGRATE_SCHEME migrationType;	/* The migration type, either TPM_MS_RESTRICT_MIGRATE or
					   TPM_MS_RESTRICT_APPROVE
					   NOTE Never used */
    TPM_MIGRATIONKEYAUTH migrationKeyAuth;	/* Migration public key and its authorization
						   session digest. */
    TPM_DIGEST pubSourceKeyDigest;	/* The digest of the TPM_PUBKEY of the entity to be migrated
					   */
    TPM_SIZED_BUFFER msaListBuffer;	/* One or more digests of public keys belonging to migration
					   authorities */
    TPM_SIZED_BUFFER restrictTicketBuffer;	/* If migrationType is TPM_MS_RESTRICT_APPROVE, a
						   TPM_CMK_AUTH structure, containing the digests of
						   the public keys belonging to the Migration
						   Authority, the destination parent key and the
						   key-to-be-migrated. */
    TPM_SIZED_BUFFER sigTicketBuffer;	/* If migrationType is TPM_MS_RESTRICT_APPROVE, a TPM_HMAC
					   structure, generated by the TPM, signaling a valid
					   signature over restrictTicket */
    TPM_SIZED_BUFFER encData;		/* The encrypted entity that is to be modified. */
    TPM_AUTHHANDLE parentAuthHandle;	/* The authorization handle used for the parent key. */
    TPM_NONCE nonceOdd;			/* Nonce generated by system associated with
					   parentAuthHandle */
    TPM_BOOL continueAuthSession;	/* Continue use flag for parent session */
    TPM_AUTHDATA parentAuth;		/* The authorization digest for inputs and
					   parentHandle. HMAC key: parentKey.usageAuth. */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			authHandleValid = FALSE;
    TPM_SECRET			*hmacKey;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_KEY			*parentKey;
    TPM_BOOL			parentPCRStatus;
    TPM_SECRET			*parentUsageAuth;
    unsigned char		*d1Decrypt;		/* decryption of encData */
    uint32_t			d1DecryptLength = 0;	/* actual valid data */
    TPM_STORE_ASYMKEY		d1AsymKey;	/* structure from decrypted encData */
    unsigned char		*stream;	/* for deserializing structures */
    uint32_t			stream_size;
    TPM_STORE_BUFFER		mka_sbuffer;	/* serialized migrationKeyAuth.migrationKey */
    const unsigned char		*mka_buffer;	
    uint32_t			mka_length;
    TPM_DIGEST			migrationKeyDigest;  /* digest of migrationKeyAuth.migrationKey */
    TPM_DIGEST			pHash;
    TPM_CMK_MIGAUTH		m2CmkMigauth;
    TPM_BOOL			valid;
    TPM_MSA_COMPOSITE		msaList;
    TPM_DIGEST			sigTicket;
    TPM_CMK_AUTH		restrictTicket;
    TPM_CMK_SIGTICKET		v1CmkSigticket;

    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_SIZED_BUFFER	random;		/* String used for xor encryption */
    TPM_SIZED_BUFFER	outData;	/* The modified, encrypted entity. */

    printf("TPM_Process_CMK_CreateBlob: Ordinal Entry\n");
    d1Decrypt = NULL;					/* freed @1 */
    TPM_Migrationkeyauth_Init(&migrationKeyAuth);	/* freed @2 */
    TPM_SizedBuffer_Init(&msaListBuffer);		/* freed @3 */
    TPM_SizedBuffer_Init(&restrictTicketBuffer);	/* freed @4 */
    TPM_SizedBuffer_Init(&sigTicketBuffer);		/* freed @5 */
    TPM_SizedBuffer_Init(&encData);			/* freed @6 */
    TPM_SizedBuffer_Init(&random);			/* freed @7 */
    TPM_SizedBuffer_Init(&outData);			/* freed @8 */
    TPM_Sbuffer_Init(&mka_sbuffer);			/* freed @9 */
    TPM_StoreAsymkey_Init(&d1AsymKey);			/* freed @10 */
    TPM_MsaComposite_Init(&msaList);			/* freed @11 */
    TPM_CmkAuth_Init(&restrictTicket);			/* freed @12 */
    TPM_CmkMigauth_Init(&m2CmkMigauth);			/* freed @13 */
    TPM_CmkSigticket_Init(&v1CmkSigticket);		/* freed @14 */
    /*
      get inputs
    */
    /* get parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get migrationType */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load16(&migrationType, &command, &paramSize);
    }
    /* get migrationKeyAuth */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Migrationkeyauth_Load(&migrationKeyAuth, &command, &paramSize);
    }
    /* get pubSourceKeyDigest */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Digest_Load(pubSourceKeyDigest, &command, &paramSize);
    }
    /* get msaListBuffer */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&msaListBuffer, &command, &paramSize);
    }
    /* deserialize to msaList */
    if (returnCode == TPM_SUCCESS) {
	stream = msaListBuffer.buffer;
	stream_size = msaListBuffer.size;
	returnCode = TPM_MsaComposite_Load(&msaList, &stream, &stream_size);
    }
    /* get restrictTicket */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&restrictTicketBuffer, &command, &paramSize);
    }
    /* get sigTicket */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&sigTicketBuffer, &command, &paramSize);
    }
    /* get encData */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&encData, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&parentAuthHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					parentAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CMK_CreateBlob: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /*
      The TPM does not check the PCR values when migrating values locked to a PCR. */
    /* get the key associated with parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&parentKey, &parentPCRStatus,
						 tpm_state, parentHandle,
						 FALSE,		/* do not check PCR's */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get parentHandle -> usageAuth */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_GetUsageAuth(&parentUsageAuth, parentKey);
    }	 
    /* get the session data */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      parentAuthHandle,
					      TPM_PID_NONE,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      parentKey,
					      parentUsageAuth,			/* OIAP */
					      parentKey->tpm_store_asymkey->pubDataDigest); /*OSAP*/
    }
    /* 1. Validate that parentAuth authorizes the use of the key pointed to by parentHandle. */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,	
					parentAuth);		/* Authorization digest for input */
   }
    /* 2.The TPM MAY verify that migrationType == migrationKeyAuth -> migrationScheme and return
	 TPM_BAD_MODE on error.
       a.The TPM MAY ignore migrationType. */
    /* 3. Verify that parentHandle-> keyFlags-> migratable == FALSE */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyFlags & TPM_MIGRATABLE) {
	    printf("TPM_Process_CMK_CreateBlob: Error, parent migratable\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* Validate that parentHandle -> keyUsage is TPM_KEY_STORAGE, if not return the error code
       TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_CMK_CreateBlob: Error, keyUsage %04hx is invalid\n",
		   parentKey->keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 4. Create d1 by decrypting encData using the key pointed to by parentHandle. */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateBlob: Decrypting encData\n");
	/* decrypt with the parent key to a stream */
	returnCode = TPM_RSAPrivateDecryptMalloc(&d1Decrypt,	/* decrypted data, freed @1 */
						 &d1DecryptLength,	/* actual size of d1 data */
						 encData.buffer,/* encrypted data */
						 encData.size,	/* encrypted data size */
						 parentKey);
    }
    /* deserialize the stream to a TPM_STORE_ASYMKEY d1AsymKey */
    if (returnCode == TPM_SUCCESS) {
	stream = d1Decrypt;
	stream_size = d1DecryptLength;
	returnCode = TPM_StoreAsymkey_Load(&d1AsymKey, FALSE,
					   &stream, &stream_size,
					   NULL,	/* TPM_KEY_PARMS */
					   NULL);	/* TPM_SIZED_BUFFER pubKey */
    }	 
    /* 5. Verify that the digest within migrationKeyAuth is legal for this TPM and public key */
    /* NOTE Presumably, this reverses the steps from TPM_AuthorizeMigrationKey */
    /* create h1 by concatenating (migrationKey || migrationScheme || TPM_PERMANENT_DATA ->
       tpmProof) */
    /* first serialize the TPM_PUBKEY migrationKeyAuth -> migrationKey */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateBlob: Verifying migrationKeyAuth\n");
	returnCode = TPM_Pubkey_Store(&mka_sbuffer, &(migrationKeyAuth.migrationKey));
    }
    if (returnCode == TPM_SUCCESS) {
	/* get the serialization result */
	TPM_Sbuffer_Get(&mka_sbuffer, &mka_buffer, &mka_length);
	/* then create the hash.  tpmProof indicates that the input knew ownerAuth in
	   TPM_AuthorizeMigrationKey */
	/* compare to migrationKeyAuth -> digest */	
	returnCode = TPM_SHA1_Check(migrationKeyAuth.digest,
				    mka_length, mka_buffer,	/* serialized migrationKey */
				    sizeof(TPM_MIGRATE_SCHEME), &(migrationKeyAuth.migrationScheme),
				    TPM_SECRET_SIZE, tpm_state->tpm_permanent_data.tpmProof,
				    0, NULL);
    }	
    /* 6. Verify that d1 -> payload == TPM_PT_MIGRATE_RESTRICTED or TPM_PT_MIGRATE_EXTERNAL */
    if (returnCode == TPM_SUCCESS) {
	if ((d1AsymKey.payload != TPM_PT_MIGRATE_RESTRICTED) &&
	    (d1AsymKey.payload != TPM_PT_MIGRATE_EXTERNAL)) {
	    printf("TPM_Process_CMK_CreateBlob: Error, invalid payload %02x\n", d1AsymKey.payload);
	    returnCode = TPM_INVALID_STRUCTURE;
	}
    }
    /* 7. Verify that the migration authorities in msaList are authorized to migrate this key */
    /* a. Create M2 a TPM_CMK_MIGAUTH structure */
    /* NOTE Done by TPM_CmkMigauth_Init() */
    /* i. Set M2 -> msaDigest to SHA-1[msaList] */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SHA1_GenerateStructure(m2CmkMigauth.msaDigest, &msaList,
						(TPM_STORE_FUNCTION_T)TPM_MsaComposite_Store);
    }
    if (returnCode == TPM_SUCCESS) {
	/* ii. Set M2 -> pubKeyDigest to pubSourceKeyDigest */
	TPM_Digest_Copy(m2CmkMigauth.pubKeyDigest, pubSourceKeyDigest);
	/* b. Verify that d1 -> migrationAuth == HMAC(M2) using tpmProof as the secret and return
	   error TPM_MA_AUTHORITY on mismatch */
	returnCode = TPM_CmkMigauth_CheckHMAC(&valid,
					      d1AsymKey.migrationAuth,		/* expected */
					      tpm_state->tpm_permanent_data.tpmProof, /* HMAC key*/
					      &m2CmkMigauth);
	if (!valid) {
	    printf("TPM_Process_CMK_CreateBlob: Error validating migrationAuth\n");
	    returnCode = TPM_MA_AUTHORITY;
	}	    
    }
    /* SHA-1[migrationKeyAuth -> migrationKey] is required below */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SHA1(migrationKeyDigest,
			      mka_length, mka_buffer,	/* serialized migrationKey */
			      0, NULL);
    }
    /* 8. If migrationKeyAuth -> migrationScheme == TPM_MS_RESTRICT_MIGRATE */
    if ((returnCode == TPM_SUCCESS) &&
	(migrationKeyAuth.migrationScheme == TPM_MS_RESTRICT_MIGRATE)) {
	/* a. Verify that intended migration destination is an MA: */
	if (returnCode == TPM_SUCCESS) {
	    printf("TPM_Process_CMK_CreateBlob: migrationScheme is TPM_MS_RESTRICT_MIGRATE\n");
	    /* i. For one of n=1 to n=(msaList -> MSAlist), verify that SHA-1[migrationKeyAuth ->
	       migrationKey] == msaList -> migAuthDigest[n] */
	    returnCode = TPM_MsaComposite_CheckMigAuthDigest(migrationKeyDigest, &msaList);
	}
	/* b. Validate that the MA key is the correct type */
	/* i. Validate that migrationKeyAuth -> migrationKey -> algorithmParms -> algorithmID ==
	   TPM_ALG_RSA */
	if (returnCode == TPM_SUCCESS) {
	    if (migrationKeyAuth.migrationKey.algorithmParms.algorithmID != TPM_ALG_RSA) {
		printf("TPM_Process_CMK_CreateBlob: Error, algorithmID %08x not TPM_ALG_RSA\n",
		       migrationKeyAuth.migrationKey.algorithmParms.algorithmID);
		returnCode = TPM_BAD_KEY_PROPERTY;
	    }
	}
	/* ii. Validate that migrationKeyAuth -> migrationKey -> algorithmParms -> encScheme is an
	   encryption scheme supported by the TPM */
	if (returnCode == TPM_SUCCESS) {
	    if (migrationKeyAuth.migrationKey.algorithmParms.encScheme !=
		TPM_ES_RSAESOAEP_SHA1_MGF1) {

		printf("TPM_Process_CMK_CreateBlob: Error, "
		       "encScheme %04hx not TPM_ES_RSAESOAEP_SHA1_MGF1\n",
		       migrationKeyAuth.migrationKey.algorithmParms.encScheme );
		returnCode = TPM_INAPPROPRIATE_ENC;
	    }
	}
	/* iii. Validate that migrationKeyAuth -> migrationKey ->algorithmParms -> sigScheme is
	   TPM_SS_NONE */
	if (returnCode == TPM_SUCCESS) {
	    if (migrationKeyAuth.migrationKey.algorithmParms.sigScheme != TPM_SS_NONE) {
		printf("TPM_Process_CMK_CreateBlob: Error, sigScheme %04hx not TPM_SS_NONE\n",
		       migrationKeyAuth.migrationKey.algorithmParms.sigScheme);
		returnCode = TPM_INVALID_KEYUSAGE;
	    }
	}
	/* c. The TPM MAY validate that restrictTicketSize is zero. */
	if (returnCode == TPM_SUCCESS) {
	    if (restrictTicketBuffer.size != 0) {
		printf("TPM_Process_CMK_CreateBlob: Error, "
		       "TPM_MS_RESTRICT_MIGRATE and restrictTicketSize %u not zero\n",
		       restrictTicketBuffer.size);
		returnCode = TPM_BAD_PARAMETER;
	    }
	}
	/* d. The TPM MAY validate that sigTicketSize is zero. */
	if (returnCode == TPM_SUCCESS) {
	    if (sigTicketBuffer.size != 0) {
		printf("TPM_Process_CMK_CreateBlob: Error, "
		       "TPM_MS_RESTRICT_MIGRATE and sigTicketSize %u not zero\n",
		       sigTicketBuffer.size);
		returnCode = TPM_BAD_PARAMETER;
	    }
	}
    }
    /* 9. If migrationKeyAuth -> migrationScheme == TPM_MS_RESTRICT_APPROVE */
    else if ((returnCode == TPM_SUCCESS) &&
	     (migrationKeyAuth.migrationScheme == TPM_MS_RESTRICT_APPROVE)) {
	/* a. Verify that the intended migration destination has been approved by the MSA: */
	/* i. Verify that for one of the n=1 to n=(msaList -> MSAlist) values of msaList ->
	   migAuthDigest[n], sigTicket == HMAC (V1) using tpmProof as the secret where V1 is a
	   TPM_CMK_SIGTICKET structure such that: */
	/* (1) V1 -> verKeyDigest = msaList -> migAuthDigest[n] */
	/* (2) V1 -> signedData = SHA-1[restrictTicket] */
	printf("TPM_Process_CMK_CreateBlob: migrationScheme is TPM_MS_RESTRICT_APPROVE_DOUBLE\n");
	/* deserialize the sigTicket TPM_HMAC */
	if (returnCode == TPM_SUCCESS) {
	    stream = sigTicketBuffer.buffer;
	    stream_size = sigTicketBuffer.size;
	    returnCode = TPM_Digest_Load(sigTicket, &stream, &stream_size);
	}
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_SHA1(v1CmkSigticket.signedData,
				  restrictTicketBuffer.size, restrictTicketBuffer.buffer,
				  0, NULL);
	}
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_MsaComposite_CheckSigTicket(sigTicket,
							 tpm_state->tpm_permanent_data.tpmProof,
							 &msaList,
							 &v1CmkSigticket);
	}
	/* ii. If [restrictTicket -> destinationKeyDigest] != SHA-1[migrationKeyAuth ->
	   migrationKey], return error TPM_MA_DESTINATION */
	/* deserialize the restrictTicket structure */
	if (returnCode == TPM_SUCCESS) {
	    stream = restrictTicketBuffer.buffer;
	    stream_size = restrictTicketBuffer.size;
	    returnCode = TPM_CmkAuth_Load(&restrictTicket, &stream, &stream_size);
	}
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_Digest_Compare(migrationKeyDigest,
					    restrictTicket.destinationKeyDigest);
	    if (returnCode != TPM_SUCCESS) {
		printf("TPM_Process_CMK_CreateBlob: Error, no match to destinationKeyDigest\n");
		returnCode = TPM_MA_DESTINATION;
	    }
	}
	/* iii. If [restrictTicket -> sourceKeyDigest] != pubSourceKeyDigest, return error
	   TPM_MA_SOURCE */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_Digest_Compare(pubSourceKeyDigest, restrictTicket.sourceKeyDigest);
	    if (returnCode != TPM_SUCCESS) {
		printf("TPM_Process_CMK_CreateBlob: Error, no match to sourceKeyDigest\n");
		returnCode = TPM_MA_SOURCE;
	    }
	}
    }
    /* 10. Else return with error TPM_BAD_PARAMETER. */
    else if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_CreateBlob: Error, Illegal migrationScheme %04hx\n",
	       migrationKeyAuth.migrationScheme);
	returnCode = TPM_BAD_PARAMETER;
    }
    /* 11. Build two bytes array, K1 and K2, using d1: */
    /* a. K1 = TPM_STORE_ASYMKEY.privKey[0..19] (TPM_STORE_ASYMKEY.privKey.keyLength + 16 bytes of
       TPM_STORE_ASYMKEY.privKey.key), sizeof(K1) = 20 */
    /* b. K2 = TPM_STORE_ASYMKEY.privKey[20..131] (position 16-127 of
       TPM_STORE_ASYMKEY.privKey.key), sizeof(K2) = 112 */
    /* 12. Build M1 a TPM_MIGRATE_ASYMKEY structure */
    /* a. TPM_MIGRATE_ASYMKEY.payload = TPM_PT_CMK_MIGRATE */
    /* b. TPM_MIGRATE_ASYMKEY.usageAuth = TPM_STORE_ASYMKEY.usageAuth */
    /* c. TPM_MIGRATE_ASYMKEY.pubDataDigest = TPM_STORE_ASYMKEY.pubDataDigest */
    /* d. TPM_MIGRATE_ASYMKEY.partPrivKeyLen = 112 - 127.  */
    /* e. TPM_MIGRATE_ASYMKEY.partPrivKey = K2 */
    /* 13. Create o1 (which SHALL be 198 bytes for a 2048 bit RSA key) by performing the OAEP
       encoding of m using OAEP parameters m, pHash, and seed */
    /* a. m is the previously created M1 */
    /* b. pHash = SHA-1( SHA-1[msaList] || pubSourceKeyDigest) */
    /* c. seed = s1 = the previously created K1 */
    /* 14. Create r1 a random value from the TPM RNG. The size of r1 MUST be the size of o1. Return
       r1 in the */
    /* random parameter */
    /* 15. Create x1 by XOR of o1 with r1 */
    /* 16. Copy r1 into the output field "random" */
    /* 17. Encrypt x1 with the migrationKeyAuth-> migrationKey */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SHA1(pHash,
			      TPM_DIGEST_SIZE, m2CmkMigauth.msaDigest,
			      TPM_DIGEST_SIZE, pubSourceKeyDigest,
			      0, NULL);
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CreateBlobCommon(&outData,
					  &d1AsymKey,
					  pHash,
					  TPM_PT_CMK_MIGRATE,
					  &random,
					  &(migrationKeyAuth.migrationKey));
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CMK_CreateBlob: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* return random */
	    returnCode = TPM_SizedBuffer_Store(response, &random);
	}
	if (returnCode == TPM_SUCCESS) {
	    /* return outData */
	    returnCode = TPM_SizedBuffer_Store(response, &outData);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* owner HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions,
					 parentAuthHandle);
    }
    /*
      cleanup
    */
    free(d1Decrypt);					/* @1 */
    TPM_Migrationkeyauth_Delete(&migrationKeyAuth);	/* @2 */
    TPM_SizedBuffer_Delete(&msaListBuffer);		/* @3 */
    TPM_SizedBuffer_Delete(&restrictTicketBuffer);	/* @4 */
    TPM_SizedBuffer_Delete(&sigTicketBuffer);		/* @5 */
    TPM_SizedBuffer_Delete(&encData);			/* @6 */
    TPM_SizedBuffer_Delete(&random);			/* @7 */
    TPM_SizedBuffer_Delete(&outData);			/* @8 */
    TPM_Sbuffer_Delete(&mka_sbuffer);			/* @9 */
    TPM_StoreAsymkey_Delete(&d1AsymKey);		/* @10 */
    TPM_MsaComposite_Delete(&msaList);			/* @11 */
    TPM_CmkAuth_Delete(&restrictTicket);		/* @12 */
    TPM_CmkMigauth_Delete(&m2CmkMigauth);		/* @13 */
    TPM_CmkSigticket_Delete(&v1CmkSigticket);		/* @14 */
    return rcf;
}

/* 11.7 TPM_CMK_SetRestrictions rev 96

   This command is used by the Owner to dictate the usage of a certified-migration key with
   delegated authorisation (authorisation other than actual Owner authorisation).

   This command is provided for privacy reasons and must not itself be delegated, because a
   certified-migration-key may involve a contractual relationship between the Owner and an external
   entity.

   Since restrictions are validated at DSAP session use, there is no need to invalidate DSAP
   sessions when the restriction value changes.
*/

TPM_RESULT TPM_Process_CMK_SetRestrictions(tpm_state_t *tpm_state,
					   TPM_STORE_BUFFER *response,
					   TPM_TAG tag,
					   uint32_t paramSize,
					   TPM_COMMAND_CODE ordinal,
					   unsigned char *command,
					   TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_CMK_DELEGATE restriction;	/* The bit mask of how to set the restrictions on CMK keys
					   */
    TPM_AUTHHANDLE authHandle;		/* The authorization handle TPM Owner authorization */
    TPM_NONCE nonceOdd;			/* Nonce generated by system associated with authHandle */
    TPM_BOOL continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   handle */
    TPM_AUTHDATA ownerAuth;		/* The authorization digest. HMAC key: TPM Owner Auth */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			authHandleValid = FALSE;
    TPM_SECRET			*hmacKey;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */

    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;

    printf("TPM_Process_CMK_SetRestrictions: Ordinal Entry\n");
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get restriction */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&restriction, &command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_SetRestrictions: restriction %08x\n", restriction);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters  */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					ownerAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CMK_SetRestrictions: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Validate the ordinal and parameters using TPM Owner authorization, return TPM_AUTHFAIL on
	  error */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_OWNER,
					      ordinal,
					      NULL,
					      &(tpm_state->tpm_permanent_data.ownerAuth), /* OIAP */
					      tpm_state->tpm_permanent_data.ownerAuth);	  /* OSAP */
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_PrintFour("TPM_Process_CMK_SetRestrictions: ownerAuth secret", *hmacKey);
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,	/* owner HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,	/* Nonce generated by system
							   associated with authHandle */
					continueAuthSession,
					ownerAuth);	/* Authorization digest for input */
    }
    /*	2. Set TPM_PERMANENT_DATA -> TPM_CMK_DELEGATE -> restrictDelegate = restriction */
    if (returnCode == TPM_SUCCESS) {
	/* only update NVRAM if the value is changing */
	if (tpm_state->tpm_permanent_data.restrictDelegate != restriction) {
	    tpm_state->tpm_permanent_data.restrictDelegate = restriction;
	    /* Store the permanent data back to NVRAM */
	    printf("TPM_Process_CMK_SetRestrictions: Storing permanent data\n");
	    returnCode = TPM_PermanentAll_NVStore(tpm_state,
						  TRUE,	/* write NV */
						  0);	/* no roll back */
	}
	else {
	    printf("TPM_Process_CMK_SetRestrictions: No change to value\n");
	}
    }
    /*	3. Return TPM_SUCCESS */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CMK_SetRestrictions: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* owner HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    return rcf;
}

/* 11.6 TPM_CMK_ApproveMA 87

  This command creates an authorization ticket, to allow the TPM owner to specify which Migration
  Authorities they approve and allow users to create certified-migration-keys without further
  involvement with the TPM owner.

  It is the responsibility of the TPM Owner to determine whether a particular Migration Authority is
  suitable to control migration.
*/
  
TPM_RESULT TPM_Process_CMK_ApproveMA(tpm_state_t *tpm_state,
				     TPM_STORE_BUFFER *response,
				     TPM_TAG tag,
				     uint32_t paramSize,
				     TPM_COMMAND_CODE ordinal,
				     unsigned char *command,
				     TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_DIGEST migrationAuthorityDigest;	/* A digest of a TPM_MSA_COMPOSITE structure (itself
						   one or more digests of public keys belonging to
						   migration authorities) */
    TPM_AUTHHANDLE authHandle;		/* The authorization session handle used for owner
					   authentication. */
    TPM_NONCE nonceOdd;			/* Nonce generated by system associated with authHandle */
    TPM_BOOL continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   session handle */
    TPM_AUTHDATA ownerAuth;		/* Authorization HMAC, key: ownerAuth. */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			authHandleValid = FALSE;
    TPM_SECRET			*hmacKey;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_CMK_MA_APPROVAL		m2CmkMaApproval;

    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_HMAC		outData;	/* HMAC of migrationAuthorityDigest */

    printf("TPM_Process_CMK_ApproveMA: Ordinal Entry\n");
    TPM_CmkMaApproval_Init(&m2CmkMaApproval);	/* freed @1 */
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get migrationAuthorityDigest */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Digest_Load(migrationAuthorityDigest, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					ownerAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CMK_ApproveMA: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Validate the AuthData to use the TPM by the TPM Owner */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_OWNER,
					      ordinal,
					      NULL,
					      &(tpm_state->tpm_permanent_data.ownerAuth), /* OIAP */
					      tpm_state->tpm_permanent_data.ownerAuth);	  /* OSAP */
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* owner HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					ownerAuth);		/* Authorization digest for input */
    }
    if (returnCode == TPM_SUCCESS) {
	/* 2. Create M2 a TPM_CMK_MA_APPROVAL structure */
	/* NOTE Done by TPM_CmkMaApproval_Init() */
	/* a. Set M2 ->migrationAuthorityDigest to migrationAuthorityDigest */
	TPM_Digest_Copy(m2CmkMaApproval.migrationAuthorityDigest, migrationAuthorityDigest);
	/* 3. Set outData = HMAC(M2) using tpmProof as the secret */
	returnCode = TPM_HMAC_GenerateStructure
		     (outData,					/* HMAC */
		      tpm_state->tpm_permanent_data.tpmProof,	/* HMAC key */
		      &m2CmkMaApproval,				/* structure */
		      (TPM_STORE_FUNCTION_T)TPM_CmkMaApproval_Store);	/* store function */
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CMK_ApproveMA: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* return the outData */
	    returnCode = TPM_Digest_Store(response, outData);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    TPM_CmkMaApproval_Delete(&m2CmkMaApproval); /* @1 */
    return rcf;
}

/* 11.10 TPM_CMK_ConvertMigration rev 106

   TPM_CMK_ConvertMigration completes the migration of certified migration blobs.

   This command takes a certified migration blob and creates a normal wrapped blob with payload type
   TPM_PT_MIGRATE_EXTERNAL. The migrated blob must be loaded into the TPM using the normal
   TPM_LoadKey function.

   Note that the command migrates private keys, only. The migration of the associated public keys is
   not specified by TPM because they are not security sensitive. Migration of the associated public
   keys may be specified in a platform specific specification. A TPM_KEY structure must be recreated
   before the migrated key can be used by the target TPM in a LoadKey command.

   TPM_CMK_ConvertMigration checks that one of the MAs implicitly listed in the migrationAuth of the
   target key has approved migration of the target key to the destination (parent) key, and that the
   settings (flags etc.) in the target key are those of a CMK.
*/

TPM_RESULT TPM_Process_CMK_ConvertMigration(tpm_state_t *tpm_state,
					    TPM_STORE_BUFFER *response,
					    TPM_TAG tag,
					    uint32_t paramSize,
					    TPM_COMMAND_CODE ordinal,
					    unsigned char *command,
					    TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_KEY_HANDLE	parentHandle;	/* Handle of a loaded key that can decrypt keys. */
    TPM_CMK_AUTH	restrictTicket; /* The digests of public keys belonging to the Migration
					   Authority, the destination parent key and the
					   key-to-be-migrated. */
    TPM_HMAC		sigTicket;	/* A signature ticket, generated by the TPM, signaling a
					   valid signature over restrictTicket */
    TPM_KEY		migratedKey;	/* The public key of the key-to-be-migrated. The private
					   portion MUST be TPM_MIGRATE_ASYMKEY properly XOR'd */
    TPM_SIZED_BUFFER	msaListBuffer;	/* One or more digests of public keys belonging to migration
					   authorities */
    TPM_SIZED_BUFFER	random;		/* Random value used to hide key data. */
    TPM_AUTHHANDLE	authHandle;	/* The authorization session handle used for keyHandle. */
    TPM_NONCE		nonceOdd;	/* Nonce generated by system associated with authHandle */
    TPM_BOOL	continueAuthSession;	/* The continue use flag for the authorization session
					   handle */
    TPM_AUTHDATA	parentAuth;	/* Authorization HMAC: parentKey.usageAuth */

    /* processing parameters */
    unsigned char *		inParamStart;	/* starting point of inParam's */
    unsigned char *		inParamEnd;	/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL			authHandleValid = FALSE;
    TPM_SECRET			*hmacKey;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_KEY			*parentKey;
    TPM_BOOL			parentPCRStatus;
    TPM_SECRET			*parentUsageAuth;
    unsigned char		*d1Decrypt;
    uint32_t			d1DecryptLength = 0;	/* actual valid data */
    BYTE			*o1Oaep;
    unsigned char		*stream;		/* for deserializing structures */
    uint32_t			stream_size;
    TPM_MSA_COMPOSITE		msaList;
    TPM_DIGEST			msaListDigest;
    TPM_DIGEST			migratedPubKeyDigest;
    TPM_STORE_ASYMKEY		d2AsymKey;
    TPM_STORE_BUFFER		d2_sbuffer;
    TPM_DIGEST			parentPubKeyDigest;
    TPM_CMK_SIGTICKET		v1CmkSigticket;
    TPM_CMK_MIGAUTH		m2CmkMigauth;

    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_SIZED_BUFFER	outData;	/* The encrypted private key that can be loaded with
					   TPM_LoadKey */

    printf("TPM_Process_CMK_ConvertMigration: Ordinal Entry\n");
    TPM_CmkAuth_Init(&restrictTicket);		/* freed @1 */
    TPM_Key_Init(&migratedKey);			/* freed @2 */
    TPM_SizedBuffer_Init(&msaListBuffer);	/* freed @3 */
    TPM_SizedBuffer_Init(&random);		/* freed @4 */
    TPM_SizedBuffer_Init(&outData);		/* freed @5 */
    d1Decrypt = NULL;				/* freed @6 */
    TPM_MsaComposite_Init(&msaList);		/* freed @7 */
    TPM_StoreAsymkey_Init(&d2AsymKey);		/* freed @8 */
    TPM_Sbuffer_Init(&d2_sbuffer);		/* freed @9 */
    TPM_CmkSigticket_Init(&v1CmkSigticket);	/* freed @10 */
    o1Oaep = NULL;				/* freed @11 */
    TPM_CmkMigauth_Init(&m2CmkMigauth);		/* freed @12 */
    /*
      get inputs
    */
    /* get parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get restrictTicket */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_ConvertMigration: parentHandle %08x\n", parentHandle);
	returnCode = TPM_CmkAuth_Load(&restrictTicket, &command, &paramSize);
    }
    /* get sigTicket */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Digest_Load(sigTicket, &command, &paramSize);
    }
    /* get migratedKey */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_Load(&migratedKey, &command, &paramSize);
    }
    /* get msaListBuffer */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&msaListBuffer, &command, &paramSize);
    }
    /* get random */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&random, &command, &paramSize);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters  */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					parentAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CMK_ConvertMigration: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Validate the AuthData to use the key in parentHandle */
    /* get the key associated with parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&parentKey, &parentPCRStatus,
						 tpm_state, parentHandle,
						 FALSE,		/* not r/o, using private key */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get parentHandle -> usageAuth */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_GetUsageAuth(&parentUsageAuth, parentKey);
    }	 
    /* get the session data */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      parentKey,
					      parentUsageAuth,			/* OIAP */
					      parentKey->tpm_store_asymkey->pubDataDigest); /*OSAP*/
    }
    /* 1. Validate the authorization to use the key in parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					parentAuth);		/* Authorization digest for input */
    }
    /* 2. If the keyUsage field of the key referenced by parentHandle does not have the value
       TPM_KEY_STORAGE, the TPM must return the error code TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_CMK_ConvertMigration: Error, "
		   "parentHandle -> keyUsage should be TPM_KEY_STORAGE, is %04x\n",
		   parentKey->keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 3. Create d1 by decrypting the migratedKey -> encData area using the key in parentHandle */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_ConvertMigration: Decrypting encData\n");
	TPM_PrintFour("TPM_Process_CMK_ConvertMigration: encData", migratedKey.encData.buffer);
	returnCode = TPM_RSAPrivateDecryptMalloc(&d1Decrypt,		/* decrypted data */
						 &d1DecryptLength,	/* actual size of d1 data */
						 migratedKey.encData.buffer,	/* encrypted data */
						 migratedKey.encData.size,
						 parentKey);
    }
    /* the random input parameter must be the same length as the decrypted data */
    if (returnCode == TPM_SUCCESS) {
	if (d1DecryptLength != random.size) {
	    printf("TPM_Process_CMK_ConvertMigration: Error "
		   "decrypt data length %u random size %u\n",
		   d1DecryptLength, random.size);
	    returnCode = TPM_BAD_PARAMETER;
	}
    }
    /* allocate memory for o1 */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Malloc(&o1Oaep, d1DecryptLength);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_ConvertMigration: d1 length %u\n", d1DecryptLength);
	TPM_PrintFour("TPM_Process_CMK_ConvertMigration: d1 -", d1Decrypt);
	/* 4. Create o1 by XOR d1 and random parameter */
	TPM_XOR(o1Oaep, d1Decrypt, random.buffer, d1DecryptLength);
	/* 5. Create m1 a TPM_MIGRATE_ASYMKEY, seed and pHash by OAEP decoding o1 */
	/* 7. Create k1 by combining seed and the TPM_MIGRATE_ASYMKEY -> partPrivKey */
	/* 8. Create d2 a TPM_STORE_ASYMKEY structure */
	/* a. Set the TPM_STORE_ASYMKEY -> privKey field to k1 */
	/* b. Set d2 -> usageAuth to m1 -> usageAuth */
	/* c. Set d2 -> pubDataDigest to m1 -> pubDataDigest */
	returnCode = TPM_StoreAsymkey_LoadO1(&d2AsymKey, o1Oaep, d1DecryptLength);
    }
    if (returnCode == TPM_SUCCESS) {	
	printf("TPM_Process_CMK_ConvertMigration: Checking pHash\n");
	/* 6. Create migratedPubKey a TPM_PUBKEY structure corresponding to migratedKey */
	/* NOTE this function goes directly to the SHA1 digest */
	returnCode = TPM_Key_GeneratePubkeyDigest(migratedPubKeyDigest, &migratedKey);
    }
    /* 6.a. Verify that pHash == SHA-1( SHA-1[msaList] || SHA-1(migratedPubKey ) */
    /* deserialize to msaListBuffer to msaList */
    if (returnCode == TPM_SUCCESS) {
	stream = msaListBuffer.buffer;
	stream_size = msaListBuffer.size;
	returnCode = TPM_MsaComposite_Load(&msaList, &stream, &stream_size);
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SHA1_GenerateStructure(msaListDigest, &msaList,
						(TPM_STORE_FUNCTION_T)TPM_MsaComposite_Store);
    }
    /* pHash is returned in TPM_STORE_ASYMKEY -> migrationAuth */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SHA1_Check(d2AsymKey.migrationAuth,
				    TPM_DIGEST_SIZE, msaListDigest,
				    TPM_DIGEST_SIZE, migratedPubKeyDigest,
				    0, NULL);
    }
    /* 9. Verify that parentHandle-> keyFlags -> migratable == FALSE and parentHandle-> encData ->
       migrationAuth == tpmProof */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_ConvertMigration: Checking parent key\n");
	if (parentKey->keyFlags & TPM_MIGRATABLE) {
	    printf("TPM_Process_CMK_ConvertMigration: Error, parent migratable\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 10. Verify that m1 -> payload == TPM_PT_CMK_MIGRATE, then set d2-> payload =
       TPM_PT_MIGRATE_EXTERNAL */
    /* NOTE TPM_StoreAsymkey_LoadO1() copied TPM_MIGRATE_ASYMKEY -> payload to TPM_STORE_ASYMKEY ->
       payload */
    if (returnCode == TPM_SUCCESS) {
	if (d2AsymKey.payload != TPM_PT_CMK_MIGRATE) {
	    printf("TPM_Process_CMK_ConvertMigration: Error, invalid payload %02x\n",
		   d2AsymKey.payload);
	    returnCode = TPM_BAD_MIGRATION;
	}
	else {
	    d2AsymKey.payload = TPM_PT_MIGRATE_EXTERNAL;
	}
    }
    /* 11. Verify that for one of the n=1 to n=(msaList -> MSAlist) values of msaList ->
       migAuthDigest[n], sigTicket == HMAC (V1) using tpmProof as the secret where V1 is a
       TPM_CMK_SIGTICKET structure such that: */
    /* a. V1 -> verKeyDigest = msaList -> migAuthDigest[n] */
    /* b. V1 -> signedData = SHA-1[restrictTicket] */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CMK_ConvertMigration: Checking sigTicket\n");
	/* generate SHA1[restrictTicket] */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_SHA1_GenerateStructure(v1CmkSigticket.signedData, &restrictTicket,
						    (TPM_STORE_FUNCTION_T)TPM_CmkAuth_Store);
	}
	if (returnCode == TPM_SUCCESS) {
	    TPM_PrintFour(" TPM_Process_CMK_ConvertMigration: TPM_CMK_SIGTICKET -> sigTicket",
			  v1CmkSigticket.signedData);
	    returnCode = TPM_MsaComposite_CheckSigTicket(sigTicket,
							 tpm_state->tpm_permanent_data.tpmProof,
							 &msaList,
							 &v1CmkSigticket);
	}
    }
    /* 12. Create parentPubKey, a TPM_PUBKEY structure corresponding to parenthandle */
    if (returnCode == TPM_SUCCESS) {
	/* NOTE this function goes directly to the SHA1 digest */
	returnCode = TPM_Key_GeneratePubkeyDigest(parentPubKeyDigest, parentKey);
    }
    /* 13. If [restrictTicket -> destinationKeyDigest] != SHA-1(parentPubKey), return error
       TPM_MA_DESTINATION */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Digest_Compare(restrictTicket.destinationKeyDigest,
					parentPubKeyDigest);
	if (returnCode != TPM_SUCCESS) {
	    printf("TPM_Process_CMK_ConvertMigration: Error checking destinationKeyDigest\n");
	    returnCode = TPM_MA_DESTINATION;
	}	    
    }
    /* 14. Verify that migratedKey is corresponding to d2 */
    /* NOTE check the private key against the public key */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_StorePrivkey_Convert(&d2AsymKey,
					      &(migratedKey.algorithmParms),
					      &(migratedKey.pubKey));
    }
    /* 15. If migratedKey -> keyFlags -> migratable is FALSE, and return error TPM_INVALID_KEYUSAGE
       */
    if (returnCode == TPM_SUCCESS) {
	if (!(migratedKey.keyFlags & TPM_MIGRATABLE)) {
	    printf("TPM_Process_CMK_ConvertMigration: Error, migratedKey migratable is FALSE\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 16. If migratedKey -> keyFlags -> migrateAuthority is FALSE, return error
       TPM_INVALID_KEYUSAGE
       */
    if (returnCode == TPM_SUCCESS) {
	if (!(migratedKey.keyFlags & TPM_MIGRATEAUTHORITY)) {
	    printf("TPM_Process_CMK_ConvertMigration: Error, "
		   "migratedKey migrateauthority is FALSE\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 17. If [restrictTicket -> sourceKeyDigest] != SHA-1(migratedPubKey), return error
       TPM_MA_SOURCE */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Digest_Compare(restrictTicket.sourceKeyDigest, migratedPubKeyDigest);
	if (returnCode != TPM_SUCCESS) {
	    printf("TPM_Process_CMK_ConvertMigration: Error checking sourceKeyDigest\n");
	    returnCode = TPM_MA_SOURCE;
	}
    }
    /* 18. Create M2 a TPM_CMK_MIGAUTH structure */
    /* NOTE Done by TPM_CmkMigauth_Init() */
    /* a. Set M2 -> msaDigest to SHA-1[msaList] */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SHA1_GenerateStructure(m2CmkMigauth.msaDigest, &msaList,
						(TPM_STORE_FUNCTION_T)TPM_MsaComposite_Store);
    }
    if (returnCode == TPM_SUCCESS) {
	/* b. Set M2 -> pubKeyDigest to SHA-1[migratedPubKey] */
	TPM_Digest_Copy(m2CmkMigauth.pubKeyDigest, migratedPubKeyDigest);
	/* 19. Set d2 -> migrationAuth = HMAC(M2) using tpmProof as the secret */
	returnCode = TPM_HMAC_GenerateStructure
		     (d2AsymKey.migrationAuth,	/* HMAC */
		      tpm_state->tpm_permanent_data.tpmProof,	/* HMAC key */
		      &m2CmkMigauth,				/* structure */
		      (TPM_STORE_FUNCTION_T)TPM_CmkMigauth_Store);	/* store function */
   }
    /* 21. Create outData using the key in parentHandle to perform the encryption */
    if (returnCode == TPM_SUCCESS) {
	/* serialize d2Asymkey	to d2_sbuffer */
	returnCode = TPM_StoreAsymkey_Store(&d2_sbuffer, FALSE, &d2AsymKey);
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_RSAPublicEncryptSbuffer_Key(&outData, &d2_sbuffer, parentKey);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CMK_ConvertMigration: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* return the outData */
	    returnCode = TPM_SizedBuffer_Store(response, &outData);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, or continueAuthSession is FALSE, terminate the session */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    TPM_CmkAuth_Delete(&restrictTicket);	/* @1 */
    TPM_Key_Delete(&migratedKey);		/* @2 */
    TPM_SizedBuffer_Delete(&msaListBuffer);	/* @3 */
    TPM_SizedBuffer_Delete(&random);		/* @4 */
    TPM_SizedBuffer_Delete(&outData);		/* @5 */
    free(d1Decrypt);				/* @6 */
    TPM_MsaComposite_Delete(&msaList);		/* @7 */
    TPM_StoreAsymkey_Delete(&d2AsymKey);	/* @8 */
    TPM_Sbuffer_Delete(&d2_sbuffer);		/* @9 */
    TPM_CmkSigticket_Delete(&v1CmkSigticket);	/* @10 */
    free(o1Oaep);				/* @11 */
    TPM_CmkMigauth_Delete(&m2CmkMigauth);	/* @12 */
    return rcf;
}