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
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
|
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# Copyright 2013 Nexenta Systems, Inc. All rights reserved.
#
#
# lib/libsmbfs/Makefile
#
include $(SRC)/lib/Makefile.lib
HDRS= ntlmssp.h smbfs_acl.h smbfs_api.h smb_keychain.h spnego.h
HDRDIR= netsmb
ROOTHDRDIR= $(ROOT)/usr/include/netsmb
ROOTHDRS= $(HDRS:%=$(ROOTHDRDIR)/%)
# ISA targets
# Hammerhead: amd64-only
SUBDIRS = $(MACH64)
# conditional assignments
all : TARGET= all
install : TARGET= install
clean : TARGET= clean
clobber : TARGET= clobber
MSGFILES = `$(GREP) -l gettext smb/*.[ch]`
POFILE = libsmbfs.po
.KEEP_STATE:
all install clean clobber: $(SUBDIRS)
_msg: $(MSGDOMAINPOFILE)
$(POFILE): pofile_MSGFILES
install_h: $(ROOTHDRDIR) $(ROOTHDRS)
check: $(CHECKHDRS)
$(ROOTHDRDIR)/%: %
$(INS.file)
$(ROOTHDRDIR):
$(INS.dir)
$(SUBDIRS): FRC
@cd $@; pwd; $(MAKE) $(TARGET)
FRC:
include $(SRC)/lib/Makefile.targ
include $(SRC)/Makefile.msg.targ
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2009 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
# Copyright 2015 Igor Kozhukhov <ikozhukhov@gmail.com>
#
# Copyright 2018 Nexenta Systems, Inc. All rights reserved.
#
# Copyright (c) 2018, Joyent, Inc.
#
# lib/libsmbfs/Makefile.com
#
LIBRARY= libsmbfs.a
VERS= .1
# leaving out: kiconv.o
OBJ_LIB=\
acl_api.o \
acl_print.o \
charsets.o \
cfopt.o \
connect.o \
crypt.o \
ctx.o \
derparse.o \
file.o \
findvc.o \
getaddr.o \
iod_cl.o \
iod_wk.o \
keychain.o \
krb5ssp.o \
mbuf.o \
nb.o \
nb_name.o \
nb_net.o \
nbns_rq.o \
newvc.o \
nls.o \
ntlm.o \
ntlmssp.o \
print.o \
rcfile.o \
rc_scf.o \
spnego.o \
spnegoparse.o \
ssp.o \
subr.o \
ui-sun.o \
utf_str.o
OBJ_CMN= smbfs_ntacl.o
OBJECTS= $(OBJ_LIB) $(OBJ_CMN)
include $(SRC)/lib/Makefile.lib
# Hammerhead: Include mech_krb5 definitions for direct linking.
# libkrb5.so is a filter library (stub that redirects to mech_krb5.so.1
# at runtime). GNU ld cannot resolve symbols through filter libraries,
# so we link directly against mech_krb5.so instead of using -lkrb5.
include $(SRC)/lib/gss_mechs/mech_krb5/Makefile.mech_krb5
LIBS = $(DYNLIB)
SRCDIR= ../smb
CMNDIR= $(SRC)/common/smbclnt
SRCS= $(OBJ_LIB:%.o=$(SRCDIR)/%.c) \
$(OBJ_CMN:%.o=$(CMNDIR)/%.c)
CSTD= $(CSTD_GNU99)
LDLIBS += -lsocket -lnsl -lc -lmd -lpkcs11 -lsec -lidmap -lscf -luuid
LDLIBS += $(KMECHLIB)
DYNFLAGS += $(KRUNPATH)
# normal warnings...
CFLAGS += $(CCVERBOSE)
CERRWARN += $(CNOWARN_UNINIT)
CERRWARN += -Wno-unused-variable
# not linted
SMATCH=off
CPPFLAGS += -D__EXTENSIONS__ -D_REENTRANT -DMIA \
-I$(SRCDIR) -I.. -I../netsmb \
-I$(SRC)/uts/common \
-I$(SRC)/common/smbclnt
# Debugging - Hammerhead: converted from dmake conditional
ifneq ($(NOT_RELEASE_BUILD),$(POUND_SIGN))
CPPFLAGS += -DDEBUG
endif
all: $(LIBS)
include ../../Makefile.targ
objs/%.o: $(CMNDIR)/%.c
$(COMPILE.c) -o $@ $<
$(POST_PROCESS_O)
pics/%.o: $(CMNDIR)/%.c
$(COMPILE.c) -o $@ $<
$(POST_PROCESS_O)
.KEEP_STATE:
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2008 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
include ../Makefile.com
include ../../Makefile.lib.64
install: all $(ROOTLIBS64) $(ROOTLINKS64)
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: cflib.h,v 1.1.1.1 2001/06/09 00:28:11 zarzycki Exp $
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
#ifndef _CFLIB_H_
#define _CFLIB_H_
struct rcfile;
/*
* A unified options parser
*/
enum opt_argtype {OPTARG_STR, OPTARG_INT, OPTARG_BOOL};
struct opt_args;
typedef int opt_callback_t (struct opt_args *);
#define OPTFL_NONE 0x0000
#define OPTFL_HAVEMIN 0x0001
#define OPTFL_HAVEMAX 0x0002
#define OPTFL_MINMAX NAFL_HAVEMIN | NAFL_HAVEMAX
struct opt_args {
enum opt_argtype type;
int opt; /* command line option */
char *name; /* rc file equiv */
int flag; /* OPTFL_* */
int ival; /* int/bool values, or max len for str value */
char *str; /* string value */
int min; /* min for ival */
int max; /* max for ival */
opt_callback_t *fn; /* call back to validate */
};
typedef struct opt_args opt_args_t;
extern int cf_opterr, cf_optind, cf_optopt, cf_optreset;
extern const char *cf_optarg;
extern struct rcfile *smb_rc;
#ifdef __cplusplus
extern "C" {
#endif
int opt_args_parse(struct rcfile *, struct opt_args *, const char *,
opt_callback_t *);
int opt_args_parseopt(struct opt_args *, int, char *, opt_callback_t *);
int cf_getopt(int, char * const *, const char *);
void cf_opt_lock(void);
void cf_opt_unlock(void);
char *cf_get_client_uuid(void);
int rc_getstringptr(struct rcfile *, const char *, const char *, char **);
int rc_getstring(struct rcfile *, const char *, const char *, size_t, char *);
int rc_getint(struct rcfile *, const char *, const char *, int *);
int rc_getbool(struct rcfile *, const char *, const char *, int *);
int smb_open_rcfile(char *);
void smb_close_rcfile(void);
#ifdef __cplusplus
}
#endif
#endif /* _CFLIB_H_ */
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: nb_lib.h,v 1.4 2004/12/11 05:23:58 lindak Exp $
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _NETSMB_NB_LIB_H_
#define _NETSMB_NB_LIB_H_
/*
* Error codes
*/
#define NBERR_INVALIDFORMAT 0x0001
#define NBERR_SRVFAILURE 0x0002
#define NBERR_NAMENOTFOUND 0x0003
#define NBERR_IMP 0x0004
#define NBERR_REFUSED 0x0005
#define NBERR_ACTIVE 0x0006
#define NBERR_HOSTNOTFOUND 0x0101
#define NBERR_TOOMANYREDIRECTS 0x0102
#define NBERR_INVALIDRESPONSE 0x0103
#define NBERR_NAMETOOLONG 0x0104
#define NBERR_NOBCASTIFS 0x0105
#define NBERR_MAX 0x0106
#define NBERROR(e) ((e) | SMB_NB_ERROR)
#define NBCF_RESOLVED 0x0001
#define NBCF_NS_ENABLE 0x0002 /* any NetBIOS lookup */
#define NBCF_BC_ENABLE 0x0004 /* lookup via broadcast */
/*
* nb environment
*/
struct nb_ctx {
int nb_flags;
int nb_timo;
char *nb_scope; /* NetBIOS scope */
in_addr_t nb_wins1; /* primary WINS */
in_addr_t nb_wins2; /* secondary WINS (unused now) */
struct sockaddr_in nb_lastns; /* see cmd:lookup.c */
};
typedef struct nb_ctx nb_ctx_t;
/*
* resource record
*/
struct nbns_rr {
uchar_t *rr_name; /* compressed NETBIOS name */
uint16_t rr_type;
uint16_t rr_class;
uint32_t rr_ttl;
uint16_t rr_rdlength;
uchar_t *rr_data;
};
typedef struct nbns_rr nfns_rr_t;
/*
* NetBIOS name return
*/
struct nbns_nr {
char ns_name[NB_NAMELEN];
uint16_t ns_flags;
};
typedef struct nbns_nr nbns_nr_t;
#define NBRQF_POINT 0x0000
#define NBRQF_BROADCAST 0x0001
#define NBNS_GROUPFLG 0x8000
struct sockaddr;
#ifdef __cplusplus
extern "C" {
#endif
struct rcfile;
int nb_resolvehost_in(const char *, struct in_addr *);
int nbns_resolvename(const char *, struct nb_ctx *, struct sockaddr **);
int nbns_getnodestatus(struct nb_ctx *ctx, struct in_addr *,
char *system, char *workgroup);
int nb_getlocalname(char *name, size_t maxlen);
const char *nb_strerror(int error);
int nb_ctx_create(struct nb_ctx **);
void nb_ctx_done(struct nb_ctx *);
int nb_ctx_setns(struct nb_ctx *, const char *);
int nb_ctx_setscope(struct nb_ctx *, const char *);
int nb_ctx_resolve(struct nb_ctx *);
int nb_ctx_readrcsection(struct rcfile *, struct nb_ctx *, const char *, int);
#ifdef __cplusplus
}
#endif
#endif /* !_NETSMB_NB_LIB_H_ */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2013 Nexenta Systems, Inc. All rights reserved.
*/
#ifndef _NTLMSSP_H
#define _NTLMSSP_H
/*
* NT LanMan Security Support Package (NTLMSSP)
* Negotiation flags, etc.
*
* Reference: [MS-NLMP] NT LAN Manager (NTLM)
* Authentication Protocol Specification
* http://msdn.microsoft.com/en-us/library/cc236621(PROT.10).aspx
*/
#ifdef __cplusplus
extern "C" {
#endif
/*
* NTLMSSP Message Types
* [MS-NLMP] sec. 2.2.1
*/
#define NTLMSSP_MSGTYPE_NEGOTIATE 1
#define NTLMSSP_MSGTYPE_CHALLENGE 2
#define NTLMSSP_MSGTYPE_AUTHENTICATE 3
/*
* NTLMSSP Negotiate Flags
* [MS-NLMP] sec. 2.2.2.5
*/
#define NTLMSSP_NEGOTIATE_UNICODE 0x00000001
#define NTLMSSP_NEGOTIATE_OEM 0x00000002
#define NTLMSSP_REQUEST_TARGET 0x00000004
/* reserved 0x00000008 */
#define NTLMSSP_NEGOTIATE_SIGN 0x00000010
#define NTLMSSP_NEGOTIATE_SEAL 0x00000020
#define NTLMSSP_NEGOTIATE_DATAGRAM 0x00000040
#define NTLMSSP_NEGOTIATE_LM_KEY 0x00000080
/* reserved (netware) 0x00000100 */
#define NTLMSSP_NEGOTIATE_NTLM 0x00000200
#define NTLMSSP_NEGOTIATE_NT_ONLY 0x00000400
#define NTLMSSP_NEGOTIATE_NULL_SESSION 0x00000800
#define NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED 0x00001000
#define NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED 0x00002000
/* reserved (local caller) 0x00004000 */
#define NTLMSSP_NEGOTIATE_ALWAYS_SIGN 0x00008000
#define NTLMSSP_TARGET_TYPE_DOMAIN 0x00010000
#define NTLMSSP_TARGET_TYPE_SERVER 0x00020000
#define NTLMSSP_TARGET_TYPE_SHARE 0x00040000
#define NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY 0x00080000
#define NTLMSSP_NEGOTIATE_IDENTIFY 0x00100000
/* reserved 0x00200000 */
#define NTLMSSP_REQUEST_NON_NT_SESSION_KEY 0x00400000
#define NTLMSSP_NEGOTIATE_TARGET_INFO 0x00800000
/* reserved 0x01000000 */
#define NTLMSSP_NEGOTIATE_VERSION 0x02000000
/* reserved 0x04000000 */
/* reserved 0x08000000 */
/* reserved 0x10000000 */
#define NTLMSSP_NEGOTIATE_128 0x20000000
#define NTLMSSP_NEGOTIATE_KEY_EXCH 0x40000000
#define NTLMSSP_NEGOTIATE_56 0x80000000
/*
* NTLMSSP AV_PAIR types
* [MS-NLMP] sec. 2.2.2.1
*
* The names are all LE-Unicode.
*/
typedef enum ntlmssp_AvId {
MsvAvEOL = 0, /* End Of List */
MsvAvNbComputerName, /* server's NetBIOS name */
MsvAvNbDomainName, /* server's NetBIOS domain */
MsvAvDnsComputerName, /* server's DNS name */
MsvAvDnsDomainName, /* server's DNS domain */
MsvAvDnsTreeName, /* server's Forest name */
MsvAvFlags, /* 32-bit (LE) flags */
MsvAvTimestamp, /* 64-bit time, [MS-DTYP] sec. 2.3.1 */
MsvAvRestrictions, /* struct, [MS-NLMP] sec. 2.2.2.2 */
MsvAvTargetName, /* SPN of the server */
MsvChannelBindings, /* MD5 hash of GSS challen bindings */
} ntlmssp_AvId_t;
#ifdef __cplusplus
}
#endif
#endif /* _NTLMSSP_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2011 Nexenta Systems, Inc. All rights reserved.
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _SMB_KEYCHAIN_H
#define _SMB_KEYCHAIN_H
/*
* External interface to the libsmbfs/netsmb keychain
* storage mechanism. This interface is consumed by
* the "smbutil" commands: login, logout, ...
* and by the SMBFS PAM module.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define SMB_KEYCHAIN_SUCCESS 0
#define SMB_KEYCHAIN_BADPASSWD 300
#define SMB_KEYCHAIN_BADDOMAIN 301
#define SMB_KEYCHAIN_BADUSER 302
#define SMB_KEYCHAIN_NODRIVER 303
#define SMB_KEYCHAIN_UNKNOWN 304
/* Add a password to the keychain. */
int smbfs_keychain_add(uid_t uid, const char *domain, const char *user,
const char *password);
/* Add an NT-hash (16-bytes) to the keychain. */
int smbfs_keychain_addhash(uid_t uid, const char *domain, const char *user,
const uchar_t *nthash);
/* Delete a password from the keychain. */
int smbfs_keychain_del(uid_t uid, const char *domain, const char *user);
/*
* Check for existence of a keychain entry.
* Returns 0 if it exists, else ENOENT.
*/
int smbfs_keychain_chk(const char *domain, const char *user);
/*
* Delete all keychain entries owned by the caller.
*/
int smbfs_keychain_del_owner(void);
/*
* Delete all keychain entries (regardless of owner).
* Requires super-user privliege.
*/
int smbfs_keychain_del_everyone(void);
/*
* This is not really part of the keychain library,
* but is typically needed in code that wants to
* provide (editable) defaults for domain/user
*
* Get default domain and user names
* Server name is optional.
*/
int
smbfs_default_dom_usr(const char *home, const char *server,
char *dom, int maxdom, char *usr, int maxusr);
#ifdef __cplusplus
}
#endif
#endif /* _SMB_KEYCHAIN_H */
/*
* Copyright (c) 2000-2001 Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: smb_lib.h,v 1.21.82.2 2005/06/02 00:55:39 lindak Exp $
*/
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
#ifndef _NETSMB_SMB_LIB_H_
#define _NETSMB_SMB_LIB_H_
/*
* Internal interface exported to our commands in:
* usr/src/cmd/fs.d/smbclnt/
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/byteorder.h>
#include <netsmb/smbfs_api.h>
#include <netsmb/smb_dev.h>
extern const char smbutil_std_opts[];
#define STDPARAM_OPT smbutil_std_opts
/*
* bits to indicate the source of error
*/
#define SMB_ERRTYPE_MASK 0xf0000
#define SMB_SYS_ERROR 0x00000
#define SMB_RAP_ERROR 0x10000
#define SMB_NB_ERROR 0x20000
/*
* Size of all LM/NTLM hashes (16 bytes).
* The driver needs to know this, so it's
* defined by smb_dev.h
*/
#define NTLM_HASH_SZ SMBIOC_HASH_SZ
#define NTLM_CHAL_SZ 8 /* challenge size */
/*
* This is what goes across the door call to the IOD
* when asking for a new connection.
*/
struct smb_iod_ssn {
struct smbioc_ossn iod_ossn;
int iod_authflags; /* SMB_AT_x */
uchar_t iod_nthash[NTLM_HASH_SZ];
uchar_t iod_lmhash[NTLM_HASH_SZ];
/* Kerberos cred. cache res. name? */
};
typedef struct smb_iod_ssn smb_iod_ssn_t;
/*
* SMB work context. Used to store all values which are necessary
* to establish connection to an SMB server.
*/
struct smb_ctx {
int ct_flags; /* SMBCF_ */
int ct_dev_fd; /* device handle */
int ct_door_fd; /* to smbiod */
int ct_parsedlevel;
int ct_minlevel;
int ct_maxlevel;
char *ct_fullserver; /* orig. server name from cmd line */
char *ct_srvaddr_s; /* hostname or IP address of server */
struct addrinfo *ct_addrinfo; /* IP addresses of the server */
struct nb_ctx *ct_nb; /* NetBIOS info. */
char *ct_locname; /* local (machine) name */
int ct_minauth;
int ct_shtype_req; /* share type wanted */
char *ct_origshare;
char *ct_home;
char *ct_rpath; /* remote file name */
/* See ssp.c */
void *ct_ssp_ctx;
smbioc_ssn_work_t ct_work;
smb_iod_ssn_t ct_iod_ssn;
/* NTLM auth. stuff */
uchar_t ct_clnonce[NTLM_CHAL_SZ];
uchar_t ct_srv_chal[NTLM_CHAL_SZ];
char ct_password[SMBIOC_MAX_NAME];
};
/*
* Short-hand for some of the substruct fields above
*/
#define ct_ssn ct_iod_ssn.iod_ossn
#define ct_vopt ct_iod_ssn.iod_ossn.ssn_vopt
#define ct_minver ct_iod_ssn.iod_ossn.ssn_minver
#define ct_maxver ct_iod_ssn.iod_ossn.ssn_maxver
#define ct_owner ct_iod_ssn.iod_ossn.ssn_owner
#define ct_srvaddr ct_iod_ssn.iod_ossn.ssn_srvaddr
#define ct_domain ct_iod_ssn.iod_ossn.ssn_domain
#define ct_user ct_iod_ssn.iod_ossn.ssn_user
#define ct_srvname ct_iod_ssn.iod_ossn.ssn_srvname
#define ct_authflags ct_iod_ssn.iod_authflags
#define ct_nthash ct_iod_ssn.iod_nthash
#define ct_lmhash ct_iod_ssn.iod_lmhash
#define ct_vcflags ct_work.wk_vcflags
#define ct_ssnkey_len ct_work.wk_u_ssnkey_len
#define ct_ssnkey_buf ct_work.wk_u_ssnkey_buf.lp_ptr
/*
* Bits in smb_ctx_t.ct_flags
*/
#define SMBCF_NOPWD 0x0001 /* don't ask for a password */
#define SMBCF_SRIGHTS 0x0002 /* share access rights supplied */
#define SMBCF_LOCALE 0x0004 /* use current locale */
#define SMBCF_CMD_DOM 0x0010 /* CMD specified domain */
#define SMBCF_CMD_USR 0x0020 /* CMD specified user */
#define SMBCF_CMD_PW 0x0040 /* CMD specified password */
#define SMBCF_RESOLVED 0x8000 /* structure has been verified */
#define SMBCF_KCBAD 0x00080000 /* keychain password failed */
#define SMBCF_KCFOUND 0x00100000 /* password is from keychain */
#define SMBCF_BROWSEOK 0x00200000 /* browser dialogue may be used */
#define SMBCF_AUTHREQ 0x00400000 /* auth. dialog requested */
#define SMBCF_KCSAVE 0x00800000 /* add to keychain requested */
#define SMBCF_KCDOMAIN 0x01000000 /* use domain in KC lookup */
/*
* Context management
*/
int smb_ctx_init(struct smb_ctx *);
void smb_ctx_done(struct smb_ctx *);
int smb_open_driver(void);
int nsmb_ioctl(int, int, void *);
int nsmb_close(int);
int smb_ctx_gethandle(struct smb_ctx *);
int smb_ctx_findvc(struct smb_ctx *);
int smb_ctx_newvc(struct smb_ctx *);
/*
* I/O daemon stuff
*/
#define SMBIOD_RUNDIR "/var/run/smbiod"
#define SMBIOD_SVC_DOOR SMBIOD_RUNDIR "/.svc"
#define SMBIOD_USR_DOOR SMBIOD_RUNDIR "/%d"
#define SMBIOD_START 1
int smb_iod_cl_newvc(smb_ctx_t *ctx);
char *smb_iod_door_path(void);
int smb_iod_open_door(int *);
int smb_iod_connect(struct smb_ctx *);
int smb_iod_work(struct smb_ctx *);
/*
* Other stuff
*/
int smb_open_rcfile(char *);
void smb_close_rcfile(void);
int smb_cf_minauth_from_str(char *);
int smb_cf_version_from_str(char *);
void smb_simplecrypt(char *dst, const char *src);
int smb_simpledecrypt(char *dst, const char *src);
int nls_setrecode(const char *, const char *);
int nls_setlocale(const char *);
char *nls_str_toext(char *, const char *);
char *nls_str_toloc(char *, const char *);
void *nls_mem_toext(void *, const void *, int);
void *nls_mem_toloc(void *, const void *, int);
char *nls_str_upper(char *, const char *);
char *nls_str_lower(char *, const char *);
char *smb_getprogname();
#define __progname smb_getprogname()
#endif /* _NETSMB_SMB_LIB_H_ */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2010 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _NETSMB_SMBFS_ACL_H
#define _NETSMB_SMBFS_ACL_H
/*
* Get/set ACL via contracted interface in libsmbfs.
* The ACL is in the form used by libsec (type=ACE_T)
* but we need to carry the uid/gid info here too.
*/
#include <sys/acl.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Get a ZFS-style acl from an FD opened in smbfs.
* Intentionally similar to: facl_get(3SEC)
*
* Allocates an acl_t via libsec. Free with: acl_free(3SEC)
* Get owner/group IDs too if ID pointers != NULL
*/
int smbfs_acl_get(int fd, acl_t **, uid_t *, gid_t *);
/*
* Set a ZFS-style acl onto an FD opened in smbfs.
* Intentionally similar to: facl_set(3SEC)
*
* The acl_t must be of type ACE_T (from libsec).
* Set owner/group IDs too if ID values != -1
*/
int smbfs_acl_set(int fd, acl_t *, uid_t, gid_t);
/*
* Slightly lower-level functions, allowing access to
* the raw Windows Security Descriptor (SD)
*
* The struct i_ntsid is opaque in this I/F.
* Real decl. in: common/smbclnt/smbfs_ntacl.h
*/
struct i_ntsd;
/*
* Get an "internal form" SD from the FD (opened in smbfs).
* Allocates a hierarchy in isdp. Caller must free it via
* smbfs_acl_free_isd()
*/
int smbfs_acl_getsd(int fd, uint32_t, struct i_ntsd **);
/*
* Set an "internal form" SD onto the FD (opened in smbfs).
*/
int smbfs_acl_setsd(int fd, uint32_t, struct i_ntsd *);
/*
* Selector bits (2nd arg above) copied from smb.h so we
* don't need that whole thing exposed to our consumers.
* Any mismatch would be detected in smb/acl_api.c
*/
#define OWNER_SECURITY_INFORMATION 0x00000001
#define GROUP_SECURITY_INFORMATION 0x00000002
#define DACL_SECURITY_INFORMATION 0x00000004
#define SACL_SECURITY_INFORMATION 0x00000008
struct __FILE;
void smbfs_acl_print_sd(struct __FILE *, struct i_ntsd *);
/*
* These are duplicated from common/smbclnt/smbfs_ntacl.h
* rather than exporting that header for this library.
* Any mismatch would be detected in smb/acl_api.c
*/
int smbfs_acl_sd2zfs(struct i_ntsd *, acl_t *, uid_t *, gid_t *);
int smbfs_acl_zfs2sd(acl_t *, uid_t, gid_t, uint32_t, struct i_ntsd **);
void smbfs_acl_free_sd(struct i_ntsd *);
#ifdef __cplusplus
}
#endif
#endif /* _NETSMB_SMBFS_ACL_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
#ifndef _NETSMB_SMBFS_API_H
#define _NETSMB_SMBFS_API_H
/*
* Define the API exported to our commands and to
* libraries doing DCE-RPC over SMB named pipes.
*/
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Some errno values we need to expose in this API.
* NB: These two defines are duplicated from the
* driver smb_dev.h to avoid exposing that here.
*
* EBADRPC is used for message decoding errors.
* EAUTH is used for CIFS authentication errors.
*/
#ifndef EBADRPC
#define EBADRPC 113
#endif
#ifndef EAUTH
#define EAUTH 114
#endif
/*
* Share type values for smb_ctx_new, _init
* Based on NetUseAdd() USE_INFO_[12] _asg_type values
* They also happen to match: STYPE_DISKTREE, etc.
* Note: these values appear on the wire.
*/
typedef enum {
USE_DISKDEV = 0, /* also STYPE_DISKTREE */
USE_SPOOLDEV, /* also STYPE_PRINTQ */
USE_CHARDEV, /* also STYPE_DEVICE */
USE_IPC, /* also STYPE_IPC */
USE_WILDCARD /* also STYPE_UNKNOWN */
} smb_use_shtype_t;
/*
* Parse "level" spec. for smb_ctx_parseunc()
* i.e. whether we require a share name, etc.
*/
typedef enum {
SMBL_NONE = 0, /* have nothing */
SMBL_SERVER, /* have server */
SMBL_VC = 1, /* alias for _SERVER */
SMBL_SHARE, /* have server share */
SMBL_PATH /* have server share path */
} smb_parse_level_t;
/*
* Authentication type flags
* See: smb_ctx_setauthflags()
*/
#define SMB_AT_ANON 1 /* anonymous (NULL session) */
#define SMB_AT_LM1 2 /* LM1 (with NTLM) */
#define SMB_AT_NTLM1 4 /* NTLM (v1) */
#define SMB_AT_NTLM2 8 /* NTLMv2 */
#define SMB_AT_KRB5 0x10 /* Kerberos5 (AD) */
struct smb_ctx; /* anonymous here; real one in smb_lib.h */
typedef struct smb_ctx smb_ctx_t;
extern int smb_debug, smb_verbose;
int smb_lib_init(void);
void smb_error(const char *, int, ...);
/*
* Context management
*/
int smb_ctx_alloc(struct smb_ctx **);
void smb_ctx_free(struct smb_ctx *);
int smb_ctx_kill(struct smb_ctx *);
int smb_ctx_scan_argv(struct smb_ctx *, int, char **, int, int, int);
int smb_ctx_parseunc(struct smb_ctx *, const char *, int, int, int,
const char **);
int smb_ctx_readrc(struct smb_ctx *);
int smb_ctx_opt(struct smb_ctx *, int, const char *);
int smb_get_authentication(struct smb_ctx *);
int smb_ctx_flags2(struct smb_ctx *);
int smb_ctx_resolve(struct smb_ctx *);
int smb_ctx_get_ssn(struct smb_ctx *);
int smb_ctx_get_tree(struct smb_ctx *);
int smb_ctx_setauthflags(struct smb_ctx *, int);
int smb_ctx_setcharset(struct smb_ctx *, const char *);
int smb_ctx_setfullserver(struct smb_ctx *, const char *);
int smb_ctx_setsigning(struct smb_ctx *, int ena, int req);
int smb_ctx_setminver(struct smb_ctx *, int ver);
int smb_ctx_setmaxver(struct smb_ctx *, int ver);
int smb_ctx_setnbflags(struct smb_ctx *, int ena, int bcast);
int smb_ctx_setscope(struct smb_ctx *, const char *);
int smb_ctx_setwins(struct smb_ctx *, const char *, const char *);
int smb_ctx_setsrvaddr(struct smb_ctx *, const char *);
int smb_ctx_setserver(struct smb_ctx *, const char *);
int smb_ctx_setshare(struct smb_ctx *, const char *, int);
int smb_ctx_setdomain(struct smb_ctx *, const char *, int);
int smb_ctx_setuser(struct smb_ctx *, const char *, int);
int smb_ctx_setpassword(struct smb_ctx *, const char *, int);
int smb_ctx_setpwhash(struct smb_ctx *, const uchar_t *, const uchar_t *);
typedef void (*smb_ctx_close_hook_t)(struct smb_ctx *);
void smb_ctx_set_close_hook(smb_ctx_close_hook_t);
int smb_fh_close(int);
int smb_fh_open(struct smb_ctx *ctx, const char *, int);
int smb_fh_read(int, off64_t, size_t, char *);
int smb_fh_write(int, off64_t, size_t, const char *);
int smb_fh_xactnp(int, int, const char *,
int *, char *, int *);
int smb_fh_getssnkey(int, uchar_t *, size_t);
int smb_open_printer(struct smb_ctx *, const char *, int, int);
void smbfs_set_default_domain(const char *);
void smbfs_set_default_user(const char *);
char *smb_strerror(int);
#ifdef __cplusplus
}
#endif
#endif /* _NETSMB_SMBFS_API_H */
/*
* Copyright (C) 2002 Microsoft Corporation
* All rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS"
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
* OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTIBILITY
* AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*
* Date - 10/08/2002
* Author - Sanj Surati
*/
/*
* Copyright 2012 Nexenta Systems, Inc. All rights reserved.
* Copyright 2022 RackTop Systems, Inc.
*/
/*
* spnego.h
*
* SPNEGO Token Handler Header File
*
* Contains the definitions required to interpret and create
* SPNEGO tokens so that Kerberos GSS tokens can be
* Unpackaged/packaged.
*/
#ifndef _SPNEGO_H
#define _SPNEGO_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* Type Definitions
*/
/*
* Users of SPNEGO Token Handler API will request
* these as well as free them,
*/
typedef void* SPNEGO_TOKEN_HANDLE;
/*
* Defines the element types that are found
* in each of the tokens.
*/
typedef enum spnego_element_type
{
spnego_element_min, /* Lower bound */
/* Init token elements */
spnego_init_mechtypes,
spnego_init_reqFlags,
spnego_init_mechToken,
spnego_init_mechListMIC,
/* Targ token elements */
spnego_targ_negResult,
spnego_targ_supportedMech,
spnego_targ_responseToken,
spnego_targ_mechListMIC,
spnego_element_max /* Upper bound */
} SPNEGO_ELEMENT_TYPE;
/*
* Token Element Availability. Elements in both
* token types are optional. Since there are only
* 4 elements in each Token, we will allocate space
* to hold the information, but we need a way to
* indicate whether or not an element is available
*/
#define SPNEGO_TOKEN_ELEMENT_UNAVAILABLE 0
#define SPNEGO_TOKEN_ELEMENT_AVAILABLE 1
/*
* Token type values. SPNEGO has 2 token types:
* NegTokenInit and NegTokenTarg
*/
#define SPNEGO_TOKEN_INIT 0
#define SPNEGO_TOKEN_TARG 1
/*
* GSS Mechanism OID enumeration. We only really handle
* 3 different OIDs. These are stored in an array structure
* defined in the parsing code.
*/
typedef enum spnego_mech_oid
{
/* Init token elements */
spnego_mech_oid_Kerberos_V5_Legacy, /* Really V5, but OID off by 1 */
spnego_mech_oid_Kerberos_V5,
spnego_mech_oid_Spnego,
spnego_mech_oid_NTLMSSP,
spnego_mech_oid_NotUsed = -1
} SPNEGO_MECH_OID;
/*
* Defines the negResult values.
*/
typedef enum spnego_negResult
{
spnego_negresult_success,
spnego_negresult_incomplete,
spnego_negresult_rejected,
spnego_negresult_request_mic,
spnego_negresult_NotUsed = -1
} SPNEGO_NEGRESULT;
/*
* Context Flags in NegTokenInit
*/
/*
* ContextFlags values MUST be zero or a combination
* of the below
*/
#define SPNEGO_NEGINIT_CONTEXT_DELEG_FLAG 0x80
#define SPNEGO_NEGINIT_CONTEXT_MUTUAL_FLAG 0x40
#define SPNEGO_NEGINIT_CONTEXT_REPLAY_FLAG 0x20
#define SPNEGO_NEGINIT_CONTEXT_SEQUENCE_FLAG 0x10
#define SPNEGO_NEGINIT_CONTEXT_ANON_FLAG 0x8
#define SPNEGO_NEGINIT_CONTEXT_CONF_FLAG 0x4
#define SPNEGO_NEGINIT_CONTEXT_INTEG_FLAG 0x2
/*
* Mask to retrieve valid values.
*/
#define SPNEGO_NEGINIT_CONTEXT_MASK 0xFE
/*
* SPNEGO API return codes.
*/
/* API function was successful */
#define SPNEGO_E_SUCCESS 0
/* The supplied Token was invalid */
#define SPNEGO_E_INVALID_TOKEN -1
/* An invalid length was encountered */
#define SPNEGO_E_INVALID_LENGTH -2
/* The Token Parse failed */
#define SPNEGO_E_PARSE_FAILED -3
/* The requested value was not found */
#define SPNEGO_E_NOT_FOUND -4
/* The requested element is not available */
#define SPNEGO_E_ELEMENT_UNAVAILABLE -5
/* Out of Memory */
#define SPNEGO_E_OUT_OF_MEMORY -6
/* Not Implemented */
#define SPNEGO_E_NOT_IMPLEMENTED -7
/* Invalid Parameter */
#define SPNEGO_E_INVALID_PARAMETER -8
/* Token Handler encountered an unexpected OID */
#define SPNEGO_E_UNEXPECTED_OID -9
/* The requested token was not found */
#define SPNEGO_E_TOKEN_NOT_FOUND -10
/* An unexpected type was encountered in the encoding */
#define SPNEGO_E_UNEXPECTED_TYPE -11
/* The buffer was too small */
#define SPNEGO_E_BUFFER_TOO_SMALL -12
/* A Token Element was invalid (e.g. improper length or value) */
#define SPNEGO_E_INVALID_ELEMENT -13
/* Miscelaneous API Functions */
/* Frees opaque data */
void spnegoFreeData(SPNEGO_TOKEN_HANDLE hSpnegoToken);
/* Initializes SPNEGO_TOKEN structure from DER encoded binary data */
int spnegoInitFromBinary(unsigned char *pbTokenData, unsigned long ulLength,
SPNEGO_TOKEN_HANDLE* phSpnegoToken);
/* Initializes SPNEGO_TOKEN structure for a NegTokenInit type */
int spnegoCreateNegTokenHint(SPNEGO_MECH_OID *pMechTypeList, int MechTypeCnt,
unsigned char *pbPrincipal, SPNEGO_TOKEN_HANDLE* phSpnegoToken);
/* Initializes SPNEGO_TOKEN structure for a NegTokenInit type */
int spnegoCreateNegTokenInit(SPNEGO_MECH_OID MechType,
unsigned char ucContextFlags, unsigned char *pbMechToken,
unsigned long ulMechTokenLen, unsigned char *pbMechTokenMIC,
unsigned long ulMechTokenMIC, SPNEGO_TOKEN_HANDLE *phSpnegoToken);
/* Initializes SPNEGO_TOKEN structure for a NegTokenTarg type */
int spnegoCreateNegTokenTarg(SPNEGO_MECH_OID MechType,
SPNEGO_NEGRESULT spnegoNegResult, unsigned char *pbMechToken,
unsigned long ulMechTokenLen, unsigned char *pbMechListMIC,
unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken);
/* Copies binary representation of SPNEGO Data into user supplied buffer */
int spnegoTokenGetBinary(SPNEGO_TOKEN_HANDLE hSpnegoToken,
unsigned char *pbTokenData, unsigned long *pulDataLen);
/* Returns SPNEGO Token Type */
int spnegoGetTokenType(SPNEGO_TOKEN_HANDLE hSpnegoToken, int *piTokenType);
/* Reading an Init Token */
/* Returns the Initial Mech Type in the MechList element in the NegInitToken. */
int spnegoIsMechTypeAvailable(SPNEGO_TOKEN_HANDLE hSpnegoToken,
SPNEGO_MECH_OID MechOID, int *piMechTypeIndex);
/* Returns the value from the context flags element in the NegInitToken */
int spnegoGetContextFlags(SPNEGO_TOKEN_HANDLE hSpnegoToken,
unsigned char *pucContextFlags);
/* Reading a Response Token */
/*
* Returns the value from the negResult element
* (Status code of GSS call - 0,1,2)
*/
int spnegoGetNegotiationResult(SPNEGO_TOKEN_HANDLE hSpnegoToken,
SPNEGO_NEGRESULT* pnegResult);
/* Returns the Supported Mech Type from the NegTokenTarg. */
int spnegoGetSupportedMechType(SPNEGO_TOKEN_HANDLE hSpnegoToken,
SPNEGO_MECH_OID* pMechOID);
/* Reading either Token Type */
/*
* Returns the actual Mechanism data from the token
* (this is what is passed into GSS-API functions
*/
int spnegoGetMechToken(SPNEGO_TOKEN_HANDLE hSpnegoToken,
unsigned char *pbTokenData, unsigned long *pulDataLen);
/* Returns the Message Integrity BLOB in the token */
int spnegoGetMechListMIC(SPNEGO_TOKEN_HANDLE hSpnegoToken,
unsigned char *pbMICData, unsigned long *pulDataLen);
#ifdef __cplusplus
}
#endif
#endif /* _SPNEGO_H */
/*
* Copyright (c) 2001 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
* Reserved. This file contains Original Code and/or Modifications of
* Original Code as defined in and that are subject to the Apple Public
* Source License Version 1.0 (the 'License'). You may not use this file
* except in compliance with the License. Please obtain a copy of the
* License at http://www.apple.com/publicsource and read it before using
* this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License."
*
* @APPLE_LICENSE_HEADER_END@
*/
PORTIONS OF LIBSMBFS IN SMB CLIENT
Copyright (c) 2000, 2001 Boris Popov
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by Boris Popov.
4. Neither the name of the author nor the names of any co-contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
PORTIONS OF LIBSMBFS IN SMB CLIENT
/*
* Copyright (c) 1982, 1986, 1988 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*/
PORTIONS OF LIBSMBFS IN SMB CLIENT
/*
// Copyright (C) 2002 Microsoft Corporation
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS"
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
// OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTIBILITY
// AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*/
PORTIONS OF LIBSMBFS IN SMB CLIENT
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2010 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2017 Nexenta Systems, Inc. All rights reserved.
*/
/*
* ACL API for smbfs
*/
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/cred.h>
#include <sys/cmn_err.h>
#include <sys/kmem.h>
#include <sys/sunddi.h>
#include <sys/acl.h>
#include <sys/vnode.h>
#include <sys/vfs.h>
#include <sys/byteorder.h>
#include <errno.h>
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <umem.h>
#include <idmap.h>
#include <sys/fs/smbfs_ioctl.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include <netsmb/smbfs_acl.h>
#include "smbfs_ntacl.h"
#include "private.h"
/* Sanity check SD sizes */
#define MAX_RAW_SD_SIZE 32768
/* XXX: acl_common.h */
acl_t *acl_alloc(enum acl_type);
void acl_free(acl_t *);
/*
* Get/set a Windows security descriptor (SD)
* using the (private) smbfs ioctl mechanism.
* Note: Get allocates mbp->mb_top
*/
/* ARGSUSED */
int
smbfs_acl_iocget(int fd, uint32_t selector, mbdata_t *mbp)
{
ioc_sdbuf_t iocb;
struct mbuf *m;
int error;
error = mb_init_sz(mbp, MAX_RAW_SD_SIZE);
if (error)
return (error);
m = mbp->mb_top;
bzero(&iocb, sizeof (iocb));
iocb.addr = mtod(m, uintptr_t);
iocb.alloc = m->m_maxlen;
iocb.used = 0;
iocb.selector = selector;
/*
* This does the OTW Get.
*/
if (nsmb_ioctl(fd, SMBFSIO_GETSD, &iocb) < 0) {
error = errno;
goto errout;
}
m->m_len = iocb.used;
return (0);
errout:
mb_done(mbp);
return (error);
}
/* ARGSUSED */
int
smbfs_acl_iocset(int fd, uint32_t selector, mbdata_t *mbp)
{
ioc_sdbuf_t iocb;
struct mbuf *m;
int error;
/* Make the data contiguous. */
error = m_lineup(mbp->mb_top, &m);
if (error)
return (error);
if (mbp->mb_top != m)
mb_initm(mbp, m);
bzero(&iocb, sizeof (iocb));
iocb.addr = mtod(m, uintptr_t);
iocb.alloc = m->m_maxlen;
iocb.used = m->m_len;
iocb.selector = selector;
/*
* This does the OTW Set.
*/
if (nsmb_ioctl(fd, SMBFSIO_SETSD, &iocb) < 0)
error = errno;
return (error);
}
/*
* Get an NT SD from the open file via ioctl.
*/
int
smbfs_acl_getsd(int fd, uint32_t selector, i_ntsd_t **sdp)
{
mbdata_t *mbp, mb_store;
int error;
mbp = &mb_store;
bzero(mbp, sizeof (*mbp));
/*
* Get the raw Windows SD via ioctl.
* Returns allocated mbchain in mbp.
*/
error = smbfs_acl_iocget(fd, selector, mbp);
if (error == 0) {
/*
* Import the raw SD into "internal" form.
* (like "absolute" form per. NT docs)
* Returns allocated data in sdp
*/
error = md_get_ntsd(mbp, sdp);
}
mb_done(mbp);
return (error);
}
/*
* Set an NT SD onto the open file via ioctl.
*/
int
smbfs_acl_setsd(int fd, uint32_t selector, i_ntsd_t *sd)
{
mbdata_t *mbp, mb_store;
int error;
mbp = &mb_store;
error = mb_init_sz(mbp, MAX_RAW_SD_SIZE);
if (error)
return (error);
/*
* Export the "internal" SD into an mb chain.
* (a.k.a "self-relative" form per. NT docs)
* Returns allocated mbchain in mbp.
*/
error = mb_put_ntsd(mbp, sd);
if (error == 0) {
/*
* Set the raw Windows SD via ioctl.
*/
error = smbfs_acl_iocset(fd, selector, mbp);
}
mb_done(mbp);
return (error);
}
/*
* Convenience function to Get security using a
* ZFS-style ACL (libsec acl, type=ACE_T)
* Intentionally similar to: facl_get(3SEC)
*/
int
smbfs_acl_get(int fd, acl_t **aclp, uid_t *uidp, gid_t *gidp)
{
i_ntsd_t *sd = NULL;
acl_t *acl = NULL;
uint32_t selector;
int error;
/*
* Which parts of the SD are being requested?
* XXX: Should we request the SACL too? If so,
* might that cause this access to be denied?
* Or maybe: if we get access denied, try the
* open/fetch again without the SACL bit.
*/
selector = 0;
if (aclp)
selector |= DACL_SECURITY_INFORMATION;
if (uidp)
selector |= OWNER_SECURITY_INFORMATION;
if (gidp)
selector |= GROUP_SECURITY_INFORMATION;
if (selector == 0)
return (0);
/*
* Get the Windows SD via ioctl, in
* "internal" (absolute) form.
*/
error = smbfs_acl_getsd(fd, selector, &sd);
if (error)
return (error);
/* Note: sd now holds allocated data. */
/*
* Convert the internal SD to a ZFS ACL.
* Get uid/gid too if pointers != NULL.
*/
if (aclp) {
acl = acl_alloc(ACE_T);
if (acl == NULL) {
error = ENOMEM;
goto out;
}
}
error = smbfs_acl_sd2zfs(sd, acl, uidp, gidp);
if (error)
goto out;
/* Success! */
if (aclp) {
*aclp = acl;
acl = NULL;
}
out:
if (acl)
acl_free(acl);
smbfs_acl_free_sd(sd);
return (error);
}
/*
* Convenience function to Set security using a
* ZFS-style ACL (libsec acl, type=ACE_T)
* Intentionally similar to: facl_set(3SEC)
*/
int
smbfs_acl_set(int fd, acl_t *acl, uid_t uid, gid_t gid)
{
struct stat st;
i_ntsd_t *sd = NULL;
uint32_t selector;
int error;
if (acl && acl->acl_type != ACE_T)
return (EINVAL);
/*
* Which parts of the SD are being modified?
* XXX: Ditto comments above re. SACL.
*/
selector = 0;
if (acl)
selector |= DACL_SECURITY_INFORMATION;
if (uid != (uid_t)-1)
selector |= OWNER_SECURITY_INFORMATION;
if (gid != (gid_t)-1)
selector |= GROUP_SECURITY_INFORMATION;
if (selector == 0)
return (0);
if (uid == (uid_t)-1 || gid == (gid_t)-1) {
/*
* If not setting owner or group, we need the
* current owner and group for translating
* references via owner@ or group@ ACEs.
*/
if (fstat(fd, &st) != 0)
return (errno);
if (uid == (uid_t)-1)
uid = st.st_uid;
if (gid == (gid_t)-1)
gid = st.st_gid;
}
/*
* Convert the ZFS ACL to an internal SD.
* Returns allocated data in sd
*/
error = smbfs_acl_zfs2sd(acl, uid, gid, selector, &sd);
if (error == 0)
error = smbfs_acl_setsd(fd, selector, sd);
smbfs_acl_free_sd(sd);
return (error);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2010 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* Print an NT Security Descriptor (SD) and its sub-components.
*/
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/cred.h>
#include <sys/cmn_err.h>
#include <sys/kmem.h>
#include <sys/sunddi.h>
#include <sys/acl.h>
#include <sys/vnode.h>
#include <sys/vfs.h>
#include <sys/byteorder.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <umem.h>
#include <idmap.h>
#include <sys/fs/smbfs_ioctl.h>
#include <netsmb/smb_lib.h>
#include <netsmb/smbfs_acl.h>
#include "smbfs_ntacl.h"
static void
fprint_sid(FILE *fp, i_ntsid_t *sid)
{
static char sidbuf[256];
if (sid == NULL) {
fprintf(fp, "(null)\n");
return;
}
if (smbfs_sid2str(sid, sidbuf, sizeof (sidbuf), NULL) < 0)
fprintf(fp, "(error)\n");
else
fprintf(fp, "%s\n", sidbuf);
}
static void
fprint_ntace(FILE *fp, i_ntace_t *ace)
{
if (ace == NULL) {
fprintf(fp, " (null)\n");
return;
}
/* ACEs are always printed in a list, so indent by 2. */
fprintf(fp, " ace_type=%d ace_flags=0x%x ace_rights=0x%x\n",
ace->ace_hdr.ace_type, ace->ace_hdr.ace_flags,
ace->ace_v2.ace_rights);
/* Show the SID as a "continuation" line. */
fprintf(fp, " ace_sid: ");
fprint_sid(fp, ace->ace_v2.ace_sid);
}
static void
fprint_ntacl(FILE *fp, i_ntacl_t *acl)
{
int i;
if (acl == NULL) {
fprintf(fp, "(null)\n");
return;
}
fprintf(fp, "acl_rev=%d acl_acecount=%d\n",
acl->acl_revision, acl->acl_acecount);
for (i = 0; i < acl->acl_acecount; i++)
fprint_ntace(fp, acl->acl_acevec[i]);
}
void
smbfs_acl_print_sd(FILE *fp, i_ntsd_t *sd)
{
fprintf(fp, "sd_rev=%d, flags=0x%x\n",
sd->sd_revision, sd->sd_flags);
fprintf(fp, "owner: ");
fprint_sid(fp, sd->sd_owner);
fprintf(fp, "group: ");
fprint_sid(fp, sd->sd_group);
fprintf(fp, "sacl: ");
fprint_ntacl(fp, sd->sd_sacl);
fprintf(fp, "dacl: ");
fprint_ntacl(fp, sd->sd_dacl);
}
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: cfopt.c,v 1.1.1.1 2001/06/09 00:28:12 zarzycki Exp $
*/
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <synch.h>
#include <libintl.h>
#include <cflib.h>
#include <netsmb/smb_lib.h>
#include <assert.h>
/* lock for the variables below */
mutex_t cf_opt_mutex = DEFAULTMUTEX;
int cf_opterr = 1, /* if error message should be printed */
cf_optind = 1, /* index into parent argv vector */
cf_optopt, /* character checked for validity */
cf_optreset; /* reset getopt */
const char *cf_optarg; /* argument associated with option */
#define BADCH (int)'?'
#define BADARG (int)':'
#define EMSG ""
void
cf_opt_lock(void)
{
mutex_lock(&cf_opt_mutex);
}
void
cf_opt_unlock(void)
{
mutex_unlock(&cf_opt_mutex);
}
int
cf_getopt(nargc, nargv, ostr)
int nargc;
char * const *nargv;
const char *ostr;
{
static const char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
int tmpind;
assert(MUTEX_HELD(&cf_opt_mutex));
if (cf_optreset || !*place) { /* update scanning pointer */
cf_optreset = 0;
tmpind = cf_optind;
for (;;) {
if (tmpind >= nargc) {
place = EMSG;
return (-1);
}
if (*(place = nargv[tmpind]) != '-') {
tmpind++;
continue; /* lookup next option */
}
if (place[1] && *++place == '-') { /* found "--" */
cf_optind = ++tmpind;
place = EMSG;
return (-1);
}
cf_optind = tmpind;
break;
}
} /* option letter okay? */
if ((cf_optopt = (int)*place++) == (int)':' ||
!(oli = strchr(ostr, cf_optopt))) {
/*
* if the user didn't specify '-' as an option,
* assume it means -1.
*/
if (cf_optopt == (int)'-')
return (-1);
if (!*place)
++cf_optind;
if (cf_opterr && *ostr != ':')
(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
"%s: illegal option -- %c\n"),
__progname, cf_optopt);
return (BADCH);
}
if (*++oli != ':') { /* don't need argument */
cf_optarg = NULL;
if (!*place)
++cf_optind;
} else { /* need an argument */
if (*place) /* no white space */
cf_optarg = place;
else if (nargc <= ++cf_optind) { /* no arg */
place = EMSG;
if (*ostr == ':')
return (BADARG);
if (cf_opterr)
(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
"%s: option requires an argument -- %c\n"),
__progname, cf_optopt);
return (BADCH);
} else /* white space */
cf_optarg = nargv[cf_optind];
place = EMSG;
++cf_optind;
}
return (cf_optopt); /* dump back option letter */
}
/*
* Copyright (c) 2001 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
* Reserved. This file contains Original Code and/or Modifications of
* Original Code as defined in and that are subject to the Apple Public
* Source License Version 1.0 (the 'License'). You may not use this file
* except in compliance with the License. Please obtain a copy of the
* License at http://www.apple.com/publicsource and read it before using
* this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License."
*
* @APPLE_LICENSE_HEADER_END@
*/
/* CSTYLED */
/*
* @(#)charsets.c *
* (c) 2004 Apple Computer, Inc. All Rights Reserved
*
*
* charsets.c -- Routines converting between UTF-8, 16-bit
* little-endian Unicode, and various Windows
* code pages.
*
* MODIFICATION HISTORY:
* 28-Nov-2004 Guy Harris New today
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <iconv.h>
#include <langinfo.h>
#include <strings.h>
#include <libintl.h>
#include <sys/isa_defs.h>
#include <netsmb/smb_lib.h>
#include <netsmb/mchain.h>
#include "charsets.h"
/*
* On Solaris, we will need to do some rewriting to use our iconv
* routines for the conversions. For now, we're effectively
* stubbing out code, leaving the details of what happens on
* Darwin in case it's useful as a guide later.
*/
static unsigned
xtoi(char u)
{
if (isdigit(u))
return (u - '0');
else if (islower(u))
return (10 + u - 'a');
else if (isupper(u))
return (10 + u - 'A');
return (16);
}
/*
* Removes the "%" escape sequences from a URL component.
* See IETF RFC 2396.
*/
char *
unpercent(char *component)
{
char c, *s;
unsigned hi, lo;
if (component == NULL)
return (component);
for (s = component; (c = *s) != 0; s++) {
if (c != '%')
continue;
if ((hi = xtoi(s[1])) > 15 || (lo = xtoi(s[2])) > 15)
continue; /* ignore invalid escapes */
s[0] = hi*16 + lo;
/*
* This was strcpy(s + 1, s + 3);
* But nowadays leftward overlapping copies are
* officially undefined in C. Ours seems to
* work or not depending upon alignment.
*/
memmove(s+1, s+3, strlen(s+3) + 1);
}
return (component);
}
/* BEGIN CSTYLED */
#ifdef NOTPORTED
static CFStringEncoding
get_windows_encoding_equivalent( void )
{
CFStringEncoding encoding;
uint32_t index,region;
/* important! use root ID so you can read the config file! */
seteuid(eff_uid);
__CFStringGetInstallationEncodingAndRegion(&index,®ion);
seteuid(real_uid);
switch ( index )
{
case kCFStringEncodingMacRoman:
if (region) /* anything nonzero is not US */
encoding = kCFStringEncodingDOSLatin1;
else /* US region */
encoding = kCFStringEncodingDOSLatinUS;
break;
case kCFStringEncodingMacJapanese:
encoding = kCFStringEncodingDOSJapanese;
break;
case kCFStringEncodingMacChineseTrad:
encoding = kCFStringEncodingDOSChineseTrad;
break;
case kCFStringEncodingMacKorean:
encoding = kCFStringEncodingDOSKorean;
break;
case kCFStringEncodingMacArabic:
encoding = kCFStringEncodingDOSArabic;
break;
case kCFStringEncodingMacHebrew:
encoding = kCFStringEncodingDOSHebrew;
break;
case kCFStringEncodingMacGreek:
encoding = kCFStringEncodingDOSGreek;
break;
case kCFStringEncodingMacCyrillic:
encoding = kCFStringEncodingDOSCyrillic;
break;
case kCFStringEncodingMacThai:
encoding = kCFStringEncodingDOSThai;
break;
case kCFStringEncodingMacChineseSimp:
encoding = kCFStringEncodingDOSChineseSimplif;
break;
case kCFStringEncodingMacCentralEurRoman:
encoding = kCFStringEncodingDOSLatin2;
break;
case kCFStringEncodingMacTurkish:
encoding = kCFStringEncodingDOSTurkish;
break;
case kCFStringEncodingMacCroatian:
encoding = kCFStringEncodingDOSLatin2;
break;
case kCFStringEncodingMacIcelandic:
encoding = kCFStringEncodingDOSIcelandic;
break;
case kCFStringEncodingMacRomanian:
encoding = kCFStringEncodingDOSLatin2;
break;
case kCFStringEncodingMacFarsi:
encoding = kCFStringEncodingDOSArabic;
break;
case kCFStringEncodingMacUkrainian:
encoding = kCFStringEncodingDOSCyrillic;
break;
default:
encoding = kCFStringEncodingDOSLatin1;
break;
}
return encoding;
}
#endif /* NOTPORTED */
/*
* XXX - NLS, or CF? We should probably use the same routine for all
* conversions.
*/
char *
convert_wincs_to_utf8(const char *windows_string)
{
#ifdef NOTPORTED
CFStringRef s;
CFIndex maxlen;
char *result;
s = CFStringCreateWithCString(NULL, windows_string,
get_windows_encoding_equivalent());
if (s == NULL) {
smb_error("CFStringCreateWithCString for Windows code page failed on \"%s\" ", -1,
windows_string);
/* kCFStringEncodingMacRoman should always succeed */
s = CFStringCreateWithCString(NULL, windows_string,
kCFStringEncodingMacRoman);
if (s == NULL) {
smb_error("CFStringCreateWithCString for Windows code page failed on \"%s\" with kCFStringEncodingMacRoman - skipping",
-1, windows_string);
return NULL;
}
}
maxlen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(s),
kCFStringEncodingUTF8) + 1;
result = malloc(maxlen);
if (result == NULL) {
smb_error("Couldn't allocate buffer for UTF-8 string for \"%s\" - skipping", -1,
windows_string);
CFRelease(s);
return NULL;
}
if (!CFStringGetCString(s, result, maxlen, kCFStringEncodingUTF8)) {
smb_error("CFStringGetCString for UTF-8 failed on \"%s\" - skipping",
-1, windows_string);
CFRelease(s);
return NULL;
}
CFRelease(s);
return result;
#else /* NOTPORTED */
return (strdup((char*)windows_string));
#endif /* NOTPORTED */
}
/*
* XXX - NLS, or CF? We should probably use the same routine for all
* conversions.
*/
char *
convert_utf8_to_wincs(const char *utf8_string)
{
#ifdef NOTPORTED
CFStringRef s;
CFIndex maxlen;
char *result;
s = CFStringCreateWithCString(NULL, utf8_string,
kCFStringEncodingUTF8);
if (s == NULL) {
smb_error("CFStringCreateWithCString for UTF-8 failed on \"%s\"", -1,
utf8_string);
return NULL;
}
maxlen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(s),
get_windows_encoding_equivalent()) + 1;
result = malloc(maxlen);
if (result == NULL) {
smb_error("Couldn't allocate buffer for Windows code page string for \"%s\" - skipping", -1,
utf8_string);
CFRelease(s);
return NULL;
}
if (!CFStringGetCString(s, result, maxlen,
get_windows_encoding_equivalent())) {
smb_error("CFStringGetCString for Windows code page failed on \"%s\" - skipping",
-1, utf8_string);
CFRelease(s);
return NULL;
}
CFRelease(s);
return result;
#else /* NOTPORTED */
return (strdup((char*)utf8_string));
#endif /* NOTPORTED */
}
/* END CSTYLED */
/*
* We replaced these routines for Solaris:
* convert_leunicode_to_utf8
* convert_unicode_to_utf8
* convert_utf8_to_leunicode
* with new code in: utf_str.c
*/
/*
* Copyright (c) 2001 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
* Reserved. This file contains Original Code and/or Modifications of
* Original Code as defined in and that are subject to the Apple Public
* Source License Version 1.0 (the 'License'). You may not use this file
* except in compliance with the License. Please obtain a copy of the
* License at http://www.apple.com/publicsource and read it before using
* this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License."
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* @(#)charsets.h
* (c) 2004 Apple Computer, Inc. All Rights Reserved
*
*
* charsets.h -- Routines converting between UTF-8, 16-bit
* little-endian Unicode, 16-bit host-byte-order
* Unicode, and various Windows code pages.
*
* MODIFICATION HISTORY:
* 28-Nov-2004 Guy Harris New today
*/
#ifndef __CHARSETS_H__
#define __CHARSETS_H__
extern char *convert_wincs_to_utf8(const char *windows_string);
extern char *convert_utf8_to_wincs(const char *utf8_string);
extern char *convert_leunicode_to_utf8(unsigned short *windows_string);
extern char *convert_unicode_to_utf8(unsigned short *windows_string);
extern unsigned short *convert_utf8_to_leunicode(const char *utf8_string);
extern size_t unicode_strlen(const uint16_t *unicode_string);
extern char *utf8_str_tolower(const char *s);
extern char *utf8_str_toupper(const char *s);
extern char *unpercent(char *component);
#endif /* __CHARSETS_H__ */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Functions to setup connections (TCP and/or NetBIOS)
* This has the fall-back logic for IP6, IP4, NBT
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <libintl.h>
#include <xti.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/byteorder.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <uuid/uuid.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include <netsmb/mchain.h>
#include <netsmb/netbios.h>
#include <netsmb/nb_lib.h>
#include <netsmb/smb_dev.h>
#include <cflib.h>
#include "charsets.h"
#include "private.h"
#include "smb_crypt.h"
static int
smb__ssnsetup(struct smb_ctx *ctx,
struct mbdata *mbc1, struct mbdata *mbc2);
int smb_ssnsetup_spnego(struct smb_ctx *, struct mbdata *);
const char *
smb_iod_state_name(enum smbiod_state st)
{
const char *n = "(?)";
switch (st) {
case SMBIOD_ST_UNINIT:
n = "UNINIT!";
break;
case SMBIOD_ST_IDLE:
n = "IDLE";
break;
case SMBIOD_ST_RECONNECT:
n = "RECONNECT";
break;
case SMBIOD_ST_RCFAILED:
n = "RCFAILED";
break;
case SMBIOD_ST_CONNECTED:
n = "CONNECTED";
break;
case SMBIOD_ST_NEGOTIATED:
n = "NEGOTIATED";
break;
case SMBIOD_ST_AUTHCONT:
n = "AUTHCONT";
break;
case SMBIOD_ST_AUTHFAIL:
n = "AUTHFAIL";
break;
case SMBIOD_ST_AUTHOK:
n = "AUTHOK";
break;
case SMBIOD_ST_VCACTIVE:
n = "VCACTIVE";
break;
case SMBIOD_ST_DEAD:
n = "DEAD";
break;
}
return (n);
}
/*
* Make a new connection, or reconnect.
*
* This is called first from the door service thread in smbiod
* (so that can report success or failure to the door client)
* and thereafter it's called when we need to reconnect after a
* network outage (or whatever might cause connection loss).
*/
int
smb_iod_connect(smb_ctx_t *ctx)
{
smbioc_ossn_t *ossn = &ctx->ct_ssn;
smbioc_ssn_work_t *work = &ctx->ct_work;
char *uuid_str;
int err;
struct mbdata blob;
char *nego_buf = NULL;
uint32_t nego_len;
memset(&blob, 0, sizeof (blob));
if (ctx->ct_srvname[0] == '\0') {
DPRINT("sername not set!");
return (EINVAL);
}
DPRINT("server: %s", ctx->ct_srvname);
if (smb_debug)
dump_ctx("smb_iod_connect", ctx);
/*
* Get local machine name.
* Full name - not a NetBIOS name.
*/
if (ctx->ct_locname == NULL) {
err = smb_getlocalname(&ctx->ct_locname);
if (err) {
smb_error(dgettext(TEXT_DOMAIN,
"can't get local name"), err);
return (err);
}
}
/*
* Get local machine uuid.
*/
uuid_str = cf_get_client_uuid();
if (uuid_str == NULL) {
err = EINVAL;
smb_error(dgettext(TEXT_DOMAIN,
"can't get local UUID"), err);
return (err);
}
(void) uuid_parse(uuid_str, ctx->ct_work.wk_cl_guid);
free(uuid_str);
uuid_str = NULL;
/*
* We're called with each IP address
* already copied into ct_srvaddr.
*/
ctx->ct_flags |= SMBCF_RESOLVED;
/*
* Ask the drvier to connect.
*/
DPRINT("Try ioctl connect...");
if (nsmb_ioctl(ctx->ct_dev_fd, SMBIOC_IOD_CONNECT, work) < 0) {
err = errno;
smb_error(dgettext(TEXT_DOMAIN,
"%s: connect failed"),
err, ossn->ssn_srvname);
return (err);
}
DPRINT("Connect OK, new state=%s",
smb_iod_state_name(work->wk_out_state));
/*
* Setup a buffer to recv the nego. hint.
*/
nego_len = 4096;
err = mb_init_sz(&blob, nego_len);
if (err)
goto out;
nego_buf = blob.mb_top->m_data;
work->wk_u_auth_rbuf.lp_ptr = nego_buf;
work->wk_u_auth_rlen = nego_len;
/*
* Ask the driver for SMB negotiate
*/
DPRINT("Try ioctl negotiate...");
if (nsmb_ioctl(ctx->ct_dev_fd, SMBIOC_IOD_NEGOTIATE, work) < 0) {
err = errno;
smb_error(dgettext(TEXT_DOMAIN,
"%s: negotiate failed"),
err, ossn->ssn_srvname);
goto out;
}
DPRINT("Negotiate OK, new state=%s",
smb_iod_state_name(work->wk_out_state));
nego_len = work->wk_u_auth_rlen;
blob.mb_top->m_len = nego_len;
if (smb_debug) {
DPRINT("Sec. blob: %d", nego_len);
smb_hexdump(nego_buf, nego_len);
}
/*
* Do SMB Session Setup (authenticate)
* Always "extended security" now (SPNEGO)
*/
DPRINT("Do session setup...");
err = smb_ssnsetup_spnego(ctx, &blob);
if (err != 0) {
DPRINT("Session setup err=%d", err);
goto out;
}
/*
* Success! We return zero now, and our caller (normally
* the smbiod program) will then call smb_iod_work in a
* new thread to service this VC as long as necessary.
*/
DPRINT("Session setup OK");
out:
mb_done(&blob);
return (err);
}
/*
* smb_ssnsetup_spnego
*
* This does an SMB session setup sequence using SPNEGO.
* The state changes seen during this sequence are there
* just to help track what's going on.
*/
int
smb_ssnsetup_spnego(struct smb_ctx *ctx, struct mbdata *hint_mb)
{
struct mbdata send_mb, recv_mb;
smbioc_ssn_work_t *work = &ctx->ct_work;
int err;
bzero(&send_mb, sizeof (send_mb));
bzero(&recv_mb, sizeof (recv_mb));
err = ssp_ctx_create_client(ctx, hint_mb);
if (err)
goto out;
/* NULL input indicates first call. */
err = ssp_ctx_next_token(ctx, NULL, &send_mb);
if (err) {
DPRINT("smb__ssnsetup, ssp next, err=%d", err);
goto out;
}
for (;;) {
err = smb__ssnsetup(ctx, &send_mb, &recv_mb);
DPRINT("smb__ssnsetup rc=%d, new state=%s", err,
smb_iod_state_name(work->wk_out_state));
if (err == 0) {
/*
* Session setup complete w/ success.
* Should have state AUTHOK
*/
if (work->wk_out_state != SMBIOD_ST_AUTHOK) {
DPRINT("Wrong state (expected AUTHOK)");
}
break;
}
if (err != EINPROGRESS) {
/*
* Session setup complete w/ failure.
* Should have state AUTHFAIL
*/
if (work->wk_out_state != SMBIOD_ST_AUTHFAIL) {
DPRINT("Wrong state (expected AUTHFAIL)");
}
goto out;
}
/*
* err == EINPROGRESS
* Session setup continuing.
* Should have state AUTHCONT
*/
if (work->wk_out_state != SMBIOD_ST_AUTHCONT) {
DPRINT("Wrong state (expected AUTHCONT)");
}
/* middle calls get both in, out */
err = ssp_ctx_next_token(ctx, &recv_mb, &send_mb);
if (err) {
DPRINT("smb__ssnsetup, ssp next, err=%d", err);
goto out;
}
}
/*
* Only get here via break in the err==0 case above,
* so we're finalizing a successful session setup.
*
* NULL output token here indicates the final call.
*/
(void) ssp_ctx_next_token(ctx, &recv_mb, NULL);
/*
* The session key is in ctx->ct_ssnkey_buf
* (a.k.a. ct_work.wk_u_ssn_key_buf)
*/
out:
/* Done with ctx->ct_ssp_ctx */
ssp_ctx_destroy(ctx);
return (err);
}
int smb_max_authtok_sz = 0x10000;
/*
* Session Setup function, calling the nsmb driver.
*
* Args
* send_mb: [in] outgoing blob data to send
* recv_mb: [out] received blob data buffer
*/
static int
smb__ssnsetup(struct smb_ctx *ctx,
struct mbdata *send_mb, struct mbdata *recv_mb)
{
smbioc_ossn_t *ossn = &ctx->ct_ssn;
smbioc_ssn_work_t *work = &ctx->ct_work;
mbuf_t *m;
int err;
/* Setup receive buffer for the auth data. */
err = mb_init_sz(recv_mb, smb_max_authtok_sz);
if (err != 0)
return (err);
m = recv_mb->mb_top;
work->wk_u_auth_rbuf.lp_ptr = m->m_data;
work->wk_u_auth_rlen = m->m_maxlen;
/* ... and the auth data to send. */
m = send_mb->mb_top;
work->wk_u_auth_wbuf.lp_ptr = m->m_data;
work->wk_u_auth_wlen = m->m_len;
DPRINT("Session setup ioctl...");
if (nsmb_ioctl(ctx->ct_dev_fd, SMBIOC_IOD_SSNSETUP, work) < 0) {
err = errno;
if (err != 0 && err != EINPROGRESS) {
smb_error(dgettext(TEXT_DOMAIN,
"%s: session setup "),
err, ossn->ssn_srvname);
}
}
DPRINT("Session setup ret %d", err);
/* Free the auth data we sent. */
mb_done(send_mb);
/* Setup length of received auth data */
m = recv_mb->mb_top;
m->m_len = work->wk_u_auth_rlen;
return (err);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
* Copyright 2013 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Crypto support, using libpkcs11
*
* Some code copied from the server: libsmb smb_crypt.c
* with minor changes, i.e. errno.h return values.
* XXX: Later, make the server use these.
*/
#include <sys/types.h>
#include <sys/md4.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <security/cryptoki.h>
#include <security/pkcs11.h>
#include <cryptoutil.h>
#include "smb_crypt.h"
static void
smb_initlmkey(uchar_t *keyout, const uchar_t *keyin);
/*
* Like libsmb smb_auth_DES,
* but use uchar_t, return errno.
*/
int
smb_encrypt_DES(uchar_t *Result, int ResultLen,
const uchar_t *Key, int KeyLen,
const uchar_t *Data, int DataLen)
{
CK_RV rv;
CK_MECHANISM mechanism;
CK_OBJECT_HANDLE hKey;
CK_SESSION_HANDLE hSession;
CK_ULONG ciphertext_len;
uchar_t des_key[8];
int error = 0;
int K, D;
int k, d;
/*
* Calculate proper number of iterations.
* Known call cases include:
* ResultLen=16, KeyLen=14, DataLen=8
* ResultLen=24, KeyLen=21, DataLen=8
* ResultLen=16, KeyLen=14, DataLen=16
*/
K = KeyLen / 7;
D = DataLen / 8;
if ((KeyLen % 7) || (DataLen % 8))
return (EINVAL);
if (K == 0 || D == 0)
return (EINVAL);
if (ResultLen < (K * 8))
return (EINVAL);
/*
* Use SUNW convenience function to initialize the cryptoki
* library, and open a session with a slot that supports
* the mechanism we plan on using.
*/
mechanism.mechanism = CKM_DES_ECB;
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
rv = SUNW_C_GetMechSession(mechanism.mechanism, &hSession);
if (rv != CKR_OK) {
return (ENOTSUP);
}
for (d = k = 0; k < K; k++, d++) {
/* Cycle the input again, as necessary. */
if (d == D)
d = 0;
smb_initlmkey(des_key, &Key[k * 7]);
rv = SUNW_C_KeyToObject(hSession, mechanism.mechanism,
des_key, 8, &hKey);
if (rv != CKR_OK) {
error = EIO;
goto exit_session;
}
/* Initialize the encryption operation in the session */
rv = C_EncryptInit(hSession, &mechanism, hKey);
if (rv != CKR_OK) {
error = EIO;
goto exit_encrypt;
}
ciphertext_len = 8;
/* Read in the data and encrypt this portion */
rv = C_EncryptUpdate(hSession,
(CK_BYTE_PTR)Data + (d * 8), 8,
(CK_BYTE_PTR)Result + (k * 8),
&ciphertext_len);
if (rv != CKR_OK) {
error = EIO;
goto exit_encrypt;
}
(void) C_DestroyObject(hSession, hKey);
}
goto exit_session;
exit_encrypt:
(void) C_DestroyObject(hSession, hKey);
exit_session:
(void) C_CloseSession(hSession);
return (error);
}
/*
* See "Netlogon Credential Computation" section of MS-NRPC document.
* Same as in libsmb, but output arg first.
*/
static void
smb_initlmkey(uchar_t *keyout, const uchar_t *keyin)
{
int i;
keyout[0] = keyin[0] >> 0x01;
keyout[1] = ((keyin[0] & 0x01) << 6) | (keyin[1] >> 2);
keyout[2] = ((keyin[1] & 0x03) << 5) | (keyin[2] >> 3);
keyout[3] = ((keyin[2] & 0x07) << 4) | (keyin[3] >> 4);
keyout[4] = ((keyin[3] & 0x0f) << 3) | (keyin[4] >> 5);
keyout[5] = ((keyin[4] & 0x1f) << 2) | (keyin[5] >> 6);
keyout[6] = ((keyin[5] & 0x3f) << 1) | (keyin[6] >> 7);
keyout[7] = keyin[6] & 0x7f;
for (i = 0; i < 8; i++)
keyout[i] = (keyout[i] << 1) & 0xfe;
}
/*
* CKM_RC4
*/
int
smb_encrypt_RC4(uchar_t *Result, int ResultLen,
const uchar_t *Key, int KeyLen,
const uchar_t *Data, int DataLen)
{
CK_RV rv;
CK_MECHANISM mechanism;
CK_OBJECT_HANDLE hKey;
CK_SESSION_HANDLE hSession;
CK_ULONG ciphertext_len;
int error = EIO;
/*
* Use SUNW convenience function to initialize the cryptoki
* library, and open a session with a slot that supports
* the mechanism we plan on using.
*/
mechanism.mechanism = CKM_RC4;
mechanism.pParameter = NULL;
mechanism.ulParameterLen = 0;
rv = SUNW_C_GetMechSession(mechanism.mechanism, &hSession);
if (rv != CKR_OK) {
return (ENOTSUP);
}
rv = SUNW_C_KeyToObject(hSession, mechanism.mechanism,
Key, KeyLen, &hKey);
if (rv != CKR_OK)
goto exit_session;
/* Initialize the encryption operation in the session */
rv = C_EncryptInit(hSession, &mechanism, hKey);
if (rv != CKR_OK)
goto exit_encrypt;
ciphertext_len = ResultLen;
rv = C_EncryptUpdate(hSession,
(CK_BYTE_PTR)Data, DataLen,
(CK_BYTE_PTR)Result, &ciphertext_len);
if (rv == CKR_OK)
error = 0;
exit_encrypt:
(void) C_DestroyObject(hSession, hKey);
exit_session:
(void) C_CloseSession(hSession);
return (error);
}
/*
* Get some random bytes from /dev/urandom
*
* There may be a preferred way to call this via libpkcs11
* XXX: (see: C_GenerateRandom, etc. -- later...)
* Just read from /dev/urandom for now.
*/
int
smb_get_urandom(void *data, size_t dlen)
{
int fd, rlen;
fd = open("/dev/urandom", O_RDONLY);
if (fd < 0)
return (errno);
rlen = read(fd, data, dlen);
close(fd);
if (rlen < 0)
return (errno);
if (rlen < dlen)
return (EIO);
return (0);
}
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: ctx.c,v 1.32.70.2 2005/06/02 00:55:40 lindak Exp $
*/
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
* Copyright 2021-2025 RackTop Systems, Inc.
*/
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/byteorder.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <unistd.h>
#include <libintl.h>
#include <assert.h>
#include <nss_dbdefs.h>
#include <cflib.h>
#include <netsmb/smb_lib.h>
#include <netsmb/netbios.h>
#include <netsmb/nb_lib.h>
#include <netsmb/smb_dev.h>
#include "charsets.h"
#include "private.h"
#include "ntlm.h"
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
#define SMB_AT_DEFAULT (SMB_AT_KRB5 | SMB_AT_NTLM2)
#define SMB_AT_MINAUTH (SMB_AT_KRB5 | SMB_AT_NTLM2 | SMB_AT_NTLM1)
struct nv {
char *name;
int value;
};
/* These two may be set by commands. */
int smb_debug, smb_verbose;
/*
* Was: STDPARAM_OPT - see smb_ctx_scan_argv, smb_ctx_opt
*/
const char smbutil_std_opts[] = "ABCD:E:I:L:M:NO:P:U:R:S:T:W:";
/*
* Defaults for new contexts (connections to servers).
* These are set by smbfs_set_default_...
*/
static char default_domain[SMBIOC_MAX_NAME];
static char default_user[SMBIOC_MAX_NAME];
/*
* Give the RPC library a callback hook that will be
* called whenever we destroy or reinit an smb_ctx_t.
* The name rpc_cleanup_smbctx() is legacy, and was
* originally a direct call into the RPC code.
*/
static smb_ctx_close_hook_t close_hook;
static void
rpc_cleanup_smbctx(struct smb_ctx *ctx)
{
if (close_hook)
(*close_hook)(ctx);
}
void
smb_ctx_set_close_hook(smb_ctx_close_hook_t hook)
{
close_hook = hook;
}
void
dump_ctx_flags(int flags)
{
printf(" Flags: ");
if (flags == 0)
printf("0");
if (flags & SMBCF_NOPWD)
printf("NOPWD ");
if (flags & SMBCF_SRIGHTS)
printf("SRIGHTS ");
if (flags & SMBCF_LOCALE)
printf("LOCALE ");
if (flags & SMBCF_CMD_DOM)
printf("CMD_DOM ");
if (flags & SMBCF_CMD_USR)
printf("CMD_USR ");
if (flags & SMBCF_CMD_PW)
printf("CMD_PW ");
if (flags & SMBCF_RESOLVED)
printf("RESOLVED ");
if (flags & SMBCF_KCBAD)
printf("KCBAD ");
if (flags & SMBCF_KCFOUND)
printf("KCFOUND ");
if (flags & SMBCF_BROWSEOK)
printf("BROWSEOK ");
if (flags & SMBCF_AUTHREQ)
printf("AUTHREQ ");
if (flags & SMBCF_KCSAVE)
printf("KCSAVE ");
if (flags & SMBCF_KCDOMAIN)
printf("KCDOMAIN ");
printf("\n");
}
void
dump_iod_ssn(smb_iod_ssn_t *is)
{
static const char zeros[NTLM_HASH_SZ] = {0};
struct smbioc_ossn *ssn = &is->iod_ossn;
printf(" ct_srvname=\"%s\", ", ssn->ssn_srvname);
dump_sockaddr(&ssn->ssn_srvaddr.sa);
printf(" dom=\"%s\", user=\"%s\"\n",
ssn->ssn_domain, ssn->ssn_user);
printf(" ct_vopt=0x%x, ct_owner=%d\n",
ssn->ssn_vopt, ssn->ssn_owner);
printf(" ct_minver=0x%x, ct_maxver=0x%x\n",
ssn->ssn_minver, ssn->ssn_maxver);
printf(" ct_authflags=0x%x\n", is->iod_authflags);
printf(" ct_nthash:");
if (bcmp(zeros, &is->iod_nthash, NTLM_HASH_SZ))
smb_hexdump(&is->iod_nthash, NTLM_HASH_SZ);
else
printf(" {0}\n");
printf(" ct_lmhash:");
if (bcmp(zeros, &is->iod_lmhash, NTLM_HASH_SZ))
smb_hexdump(&is->iod_lmhash, NTLM_HASH_SZ);
else
printf(" {0}\n");
}
void
dump_ctx(char *where, struct smb_ctx *ctx)
{
printf("context %s:\n", where);
dump_ctx_flags(ctx->ct_flags);
if (ctx->ct_locname)
printf(" localname=\"%s\"", ctx->ct_locname);
else
printf(" localname=NULL");
if (ctx->ct_fullserver)
printf(" fullserver=\"%s\"", ctx->ct_fullserver);
else
printf(" fullserver=NULL");
if (ctx->ct_srvaddr_s)
printf(" srvaddr_s=\"%s\"\n", ctx->ct_srvaddr_s);
else
printf(" srvaddr_s=NULL\n");
if (ctx->ct_addrinfo)
dump_addrinfo(ctx->ct_addrinfo);
else
printf(" ct_addrinfo = NULL\n");
dump_iod_ssn(&ctx->ct_iod_ssn);
printf(" share_name=\"%s\", share_type=%d\n",
ctx->ct_origshare ? ctx->ct_origshare : "",
ctx->ct_shtype_req);
printf(" ct_home=\"%s\"\n", ctx->ct_home);
printf(" ct_rpath=\"%s\"\n", ctx->ct_rpath);
}
int
smb_ctx_alloc(struct smb_ctx **ctx_pp)
{
smb_ctx_t *ctx;
int err;
ctx = malloc(sizeof (*ctx));
if (ctx == NULL)
return (ENOMEM);
err = smb_ctx_init(ctx);
if (err != 0) {
free(ctx);
return (err);
}
*ctx_pp = ctx;
return (0);
}
/*
* Initialize an smb_ctx struct (defaults)
*/
int
smb_ctx_init(struct smb_ctx *ctx)
{
int error;
bzero(ctx, sizeof (*ctx));
error = nb_ctx_create(&ctx->ct_nb);
if (error)
return (error);
ctx->ct_dev_fd = -1;
ctx->ct_door_fd = -1;
ctx->ct_parsedlevel = SMBL_NONE;
ctx->ct_minlevel = SMBL_NONE;
ctx->ct_maxlevel = SMBL_PATH;
/* Fill in defaults */
ctx->ct_vopt = SMBVOPT_SIGNING_ENABLED;
ctx->ct_owner = SMBM_ANY_OWNER;
ctx->ct_authflags = SMB_AT_DEFAULT;
ctx->ct_minauth = SMB_AT_MINAUTH;
ctx->ct_maxver = SMB2_DIALECT_MAX;
/*
* Default domain, user, ...
*/
strlcpy(ctx->ct_domain, default_domain,
sizeof (ctx->ct_domain));
strlcpy(ctx->ct_user, default_user,
sizeof (ctx->ct_user));
return (0);
}
/*
* "Scan" the command line args to find the server name,
* user name, and share name, as needed. We need these
* before reading the RC files and/or sharectl values.
*
* The sequence for getting all the members filled in
* has some tricky aspects. Here's how it works:
*
* The search order for options is as follows:
* command line options
* values parsed from UNC path (cmd)
* values from RC file (per-user)
* values from SMF (system-wide)
* built-in defaults
*
* Normally, one would simply get all the values starting with
* the bottom of the above list and working to the top, and
* overwriting values as you go. But we need an exception.
*
* In this function, we parse the UNC path and command line options,
* because we need (at least) the server name when we're getting the
* SMF and RC file values. However, values we get from the command
* should not be overwritten by SMF or RC file parsing, so we mark
* values from the command as "from CMD" and the RC file parser
* leaves in place any values so marked. See: SMBCF_CMD_*
*
* The semantics of these flags are: "This value came from the
* current command instance, not from sources that may apply to
* multiple commands." (Different from the old "FROMUSR" flag.)
*
* Note that smb_ctx_opt() is called later to handle the
* remaining options, which should be ignored here.
* The (magic) leading ":" in cf_getopt() makes it
* ignore options not in the options string.
*/
int
smb_ctx_scan_argv(struct smb_ctx *ctx, int argc, char **argv,
int minlevel, int maxlevel, int sharetype)
{
int ind, opt, error = 0;
int aflg = 0, uflg = 0;
const char *arg;
/*
* Parse options, if any. Values from here too
* are marked as "from CMD".
*/
if (argv == NULL)
return (0);
ctx->ct_minlevel = minlevel;
ctx->ct_maxlevel = maxlevel;
ctx->ct_shtype_req = sharetype;
cf_opt_lock();
/* Careful: no return/goto before cf_opt_unlock! */
while (error == 0) {
/*
* Leading ':' tells this to skip unknown opts.
* Just get -A and -U here so we know the user
* for config file parsing.
*/
opt = cf_getopt(argc, argv, ":AU:");
if (opt == -1)
break;
arg = cf_optarg;
/* NB: handle most in smb_ctx_opt */
switch (opt) {
case 'A':
aflg = 1;
error = smb_ctx_setuser(ctx, "", TRUE);
ctx->ct_flags |= SMBCF_NOPWD;
break;
case 'U':
uflg = 1;
error = smb_ctx_setuser(ctx, arg, TRUE);
break;
default:
DPRINT("skip opt=%c", opt);
break;
}
}
ind = cf_optind;
arg = argv[ind];
cf_optind = cf_optreset = 1;
cf_opt_unlock();
if (error)
return (error);
if (aflg && uflg) {
printf(gettext("-A and -U flags are exclusive.\n"));
return (EINVAL);
}
/*
* Parse the UNC path. Values from here are
* marked as "from CMD".
*/
for (; ind < argc; ind++) {
arg = argv[ind];
if (strncmp(arg, "//", 2) != 0)
continue;
error = smb_ctx_parseunc(ctx, arg,
minlevel, maxlevel, sharetype, &arg);
if (error)
return (error);
break;
}
return (error);
}
void
smb_ctx_free(smb_ctx_t *ctx)
{
smb_ctx_done(ctx);
free(ctx);
}
void
smb_ctx_done(struct smb_ctx *ctx)
{
rpc_cleanup_smbctx(ctx);
if (ctx->ct_dev_fd != -1) {
nsmb_close(ctx->ct_dev_fd);
ctx->ct_dev_fd = -1;
}
if (ctx->ct_door_fd != -1) {
close(ctx->ct_door_fd);
ctx->ct_door_fd = -1;
}
if (ctx->ct_srvaddr_s) {
free(ctx->ct_srvaddr_s);
ctx->ct_srvaddr_s = NULL;
}
if (ctx->ct_nb) {
nb_ctx_done(ctx->ct_nb);
ctx->ct_nb = NULL;
}
if (ctx->ct_locname) {
free(ctx->ct_locname);
ctx->ct_locname = NULL;
}
if (ctx->ct_origshare) {
free(ctx->ct_origshare);
ctx->ct_origshare = NULL;
}
if (ctx->ct_fullserver) {
free(ctx->ct_fullserver);
ctx->ct_fullserver = NULL;
}
if (ctx->ct_addrinfo) {
freeaddrinfo(ctx->ct_addrinfo);
ctx->ct_addrinfo = NULL;
}
if (ctx->ct_home) {
free(ctx->ct_home);
ctx->ct_home = NULL;
}
if (ctx->ct_rpath) {
free(ctx->ct_rpath);
ctx->ct_rpath = NULL;
}
if (ctx->ct_ssnkey_buf) {
free(ctx->ct_ssnkey_buf);
ctx->ct_ssnkey_buf = NULL;
}
}
/*
* Parse the UNC path. Here we expect something like
* "//[[domain;]user[:password]@]host[/share[/path]]"
* See http://ietf.org/internet-drafts/draft-crhertel-smb-url-07.txt
* Values found here are marked as "from CMD".
*/
int
smb_ctx_parseunc(struct smb_ctx *ctx, const char *unc,
int minlevel, int maxlevel, int sharetype,
const char **next)
{
char tmp[1024];
char *host, *share, *path;
char *dom, *usr, *pw, *p;
int error;
/*
* This may be called outside of _scan_argv,
* so make sure these get initialized.
*/
ctx->ct_minlevel = minlevel;
ctx->ct_maxlevel = maxlevel;
ctx->ct_shtype_req = sharetype;
ctx->ct_parsedlevel = SMBL_NONE;
dom = usr = pw = host = NULL;
/* Work on a temporary copy, fix back slashes. */
strlcpy(tmp, unc, sizeof (tmp));
for (p = tmp; *p; p++)
if (*p == '\\')
*p = '/';
if (tmp[0] != '/' || tmp[1] != '/') {
smb_error(dgettext(TEXT_DOMAIN,
"UNC should start with '//'"), 0);
error = EINVAL;
goto out;
}
p = tmp + 2; /* user@host... */
/* Find the share part, if any. */
share = strchr(p, '/');
if (share)
*share = '\0';
(void) unpercent(p); /* host component */
/*
* Parse the "host" stuff right to left:
* 1: trailing "@hostname" (or whole field)
* 2: trailing ":password"
* 3: trailing "domain;user" (or just user)
*/
host = strrchr(p, '@');
if (host == NULL) {
host = p; /* no user@ prefix */
} else {
*host++ = '\0';
/* may have [[domain;]user[:passwd]] */
pw = strchr(p, ':');
if (pw)
*pw++ = '\0';
usr = strchr(p, ';');
if (usr) {
*usr++ = '\0';
dom = p;
} else
usr = p;
}
if (*host == '\0') {
smb_error(dgettext(TEXT_DOMAIN, "empty server name"), 0);
error = EINVAL;
goto out;
}
error = smb_ctx_setfullserver(ctx, host);
if (error)
goto out;
ctx->ct_parsedlevel = SMBL_VC;
if (dom != NULL) {
error = smb_ctx_setdomain(ctx, dom, TRUE);
if (error)
goto out;
}
if (usr != NULL) {
if (*usr == '\0') {
smb_error(dgettext(TEXT_DOMAIN,
"empty user name"), 0);
error = EINVAL;
goto out;
}
if (ctx->ct_maxlevel < SMBL_VC) {
smb_error(dgettext(TEXT_DOMAIN,
"no user name required"), 0);
error = EINVAL;
goto out;
}
error = smb_ctx_setuser(ctx, usr, TRUE);
if (error)
goto out;
}
if (pw != NULL) {
error = smb_ctx_setpassword(ctx, pw, TRUE);
if (error)
goto out;
}
if (share != NULL) {
/* restore the slash */
*share = '/';
p = share + 1;
/* Find the path part, if any. */
path = strchr(p, '/');
if (path)
*path = '\0';
(void) unpercent(p); /* share component */
if (*p == '\0') {
smb_error(dgettext(TEXT_DOMAIN,
"empty share name"), 0);
error = EINVAL;
goto out;
}
if (ctx->ct_maxlevel < SMBL_SHARE) {
smb_error(dgettext(TEXT_DOMAIN,
"no share name required"), 0);
error = EINVAL;
goto out;
}
/*
* Special case UNC names like:
* //host/PIPE/endpoint
* to have share: IPC$
*/
if (strcasecmp(p, "PIPE") == 0) {
sharetype = USE_IPC;
p = "IPC$";
}
error = smb_ctx_setshare(ctx, p, sharetype);
if (error)
goto out;
ctx->ct_parsedlevel = SMBL_SHARE;
if (path) {
/* restore the slash */
*path = '/';
p = path + 1;
(void) unpercent(p); /* remainder */
free(ctx->ct_rpath);
ctx->ct_rpath = strdup(path);
}
} else if (ctx->ct_minlevel >= SMBL_SHARE) {
smb_error(dgettext(TEXT_DOMAIN, "empty share name"), 0);
error = EINVAL;
goto out;
}
if (next)
*next = NULL;
out:
if (error == 0 && smb_debug > 0)
dump_ctx("after smb_ctx_parseunc", ctx);
return (error);
}
#ifdef KICONV_SUPPORT
int
smb_ctx_setcharset(struct smb_ctx *ctx, const char *arg)
{
char *cp, *servercs, *localcs;
int cslen = sizeof (ctx->ct_ssn.ioc_localcs);
int scslen, lcslen, error;
cp = strchr(arg, ':');
lcslen = cp ? (cp - arg) : 0;
if (lcslen == 0 || lcslen >= cslen) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid local charset specification (%s)"), 0, arg);
return (EINVAL);
}
scslen = (size_t)strlen(++cp);
if (scslen == 0 || scslen >= cslen) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid server charset specification (%s)"), 0, arg);
return (EINVAL);
}
localcs = memcpy(ctx->ct_ssn.ioc_localcs, arg, lcslen);
localcs[lcslen] = 0;
servercs = strcpy(ctx->ct_ssn.ioc_servercs, cp);
error = nls_setrecode(localcs, servercs);
if (error == 0)
return (0);
smb_error(dgettext(TEXT_DOMAIN,
"can't initialize iconv support (%s:%s)"),
error, localcs, servercs);
localcs[0] = 0;
servercs[0] = 0;
return (error);
}
#endif /* KICONV_SUPPORT */
int
smb_ctx_setauthflags(struct smb_ctx *ctx, int flags)
{
ctx->ct_authflags = flags;
return (0);
}
int
smb_ctx_setfullserver(struct smb_ctx *ctx, const char *name)
{
char *p = strdup(name);
if (p == NULL)
return (ENOMEM);
if (ctx->ct_fullserver)
free(ctx->ct_fullserver);
ctx->ct_fullserver = p;
return (0);
}
int
smb_ctx_setserver(struct smb_ctx *ctx, const char *name)
{
strlcpy(ctx->ct_srvname, name,
sizeof (ctx->ct_srvname));
return (0);
}
int
smb_ctx_setuser(struct smb_ctx *ctx, const char *name, int from_cmd)
{
if (strlen(name) >= sizeof (ctx->ct_user)) {
smb_error(dgettext(TEXT_DOMAIN,
"user name '%s' too long"), 0, name);
return (ENAMETOOLONG);
}
/*
* Don't overwrite a value from the command line
* with one from anywhere else.
*/
if (!from_cmd && (ctx->ct_flags & SMBCF_CMD_USR))
return (0);
strlcpy(ctx->ct_user, name,
sizeof (ctx->ct_user));
/* Mark this as "from the command line". */
if (from_cmd)
ctx->ct_flags |= SMBCF_CMD_USR;
return (0);
}
/*
* Don't overwrite a domain name from the
* command line with one from anywhere else.
* See smb_ctx_init() for notes about this.
*/
int
smb_ctx_setdomain(struct smb_ctx *ctx, const char *name, int from_cmd)
{
if (strlen(name) >= sizeof (ctx->ct_domain)) {
smb_error(dgettext(TEXT_DOMAIN,
"workgroup name '%s' too long"), 0, name);
return (ENAMETOOLONG);
}
/*
* Don't overwrite a value from the command line
* with one from anywhere else.
*/
if (!from_cmd && (ctx->ct_flags & SMBCF_CMD_DOM))
return (0);
strlcpy(ctx->ct_domain, name,
sizeof (ctx->ct_domain));
/* Mark this as "from the command line". */
if (from_cmd)
ctx->ct_flags |= SMBCF_CMD_DOM;
return (0);
}
int
smb_ctx_setpassword(struct smb_ctx *ctx, const char *passwd, int from_cmd)
{
int err;
if (passwd == NULL)
return (EINVAL);
if (strlen(passwd) >= sizeof (ctx->ct_password)) {
smb_error(dgettext(TEXT_DOMAIN, "password too long"), 0);
return (ENAMETOOLONG);
}
/*
* If called again after comand line parsing,
* don't overwrite a value from the command line
* with one from any stored config.
*/
if (!from_cmd && (ctx->ct_flags & SMBCF_CMD_PW))
return (0);
memset(ctx->ct_password, 0, sizeof (ctx->ct_password));
if (strncmp(passwd, "$$1", 3) == 0)
(void) smb_simpledecrypt(ctx->ct_password, passwd);
else
strlcpy(ctx->ct_password, passwd,
sizeof (ctx->ct_password));
/*
* Compute LM hash, NT hash.
*/
if (ctx->ct_password[0]) {
err = ntlm_compute_nt_hash(ctx->ct_nthash, ctx->ct_password);
if (err != 0)
return (err);
err = ntlm_compute_lm_hash(ctx->ct_lmhash, ctx->ct_password);
if (err != 0)
return (err);
}
/* Mark this as "from the command line". */
if (from_cmd)
ctx->ct_flags |= SMBCF_CMD_PW;
return (0);
}
/*
* Use this to set NTLM auth. info (hashes)
* when we don't have the password.
*/
int
smb_ctx_setpwhash(smb_ctx_t *ctx,
const uchar_t *nthash, const uchar_t *lmhash)
{
/* Need ct_password to be non-null. */
if (ctx->ct_password[0] == '\0')
strlcpy(ctx->ct_password, "$HASH",
sizeof (ctx->ct_password));
/*
* Compute LM hash, NT hash.
*/
memcpy(ctx->ct_nthash, nthash, NTLM_HASH_SZ);
/* The LM hash is optional */
if (lmhash) {
memcpy(ctx->ct_nthash, nthash, NTLM_HASH_SZ);
}
return (0);
}
int
smb_ctx_setshare(struct smb_ctx *ctx, const char *share, int stype)
{
if (strlen(share) >= SMBIOC_MAX_NAME) {
smb_error(dgettext(TEXT_DOMAIN,
"share name '%s' too long"), 0, share);
return (ENAMETOOLONG);
}
if (ctx->ct_origshare)
free(ctx->ct_origshare);
if ((ctx->ct_origshare = strdup(share)) == NULL)
return (ENOMEM);
ctx->ct_shtype_req = stype;
return (0);
}
int
smb_ctx_setsrvaddr(struct smb_ctx *ctx, const char *addr)
{
if (addr == NULL || addr[0] == 0)
return (EINVAL);
if (ctx->ct_srvaddr_s)
free(ctx->ct_srvaddr_s);
if ((ctx->ct_srvaddr_s = strdup(addr)) == NULL)
return (ENOMEM);
return (0);
}
/*
* API for library caller to set signing enabled, required
* Note: if not enable, ignore require
*/
int
smb_ctx_setsigning(struct smb_ctx *ctx, int enable, int require)
{
ctx->ct_vopt &= ~SMBVOPT_SIGNING_MASK;
if (enable) {
ctx->ct_vopt |= SMBVOPT_SIGNING_ENABLED;
if (require)
ctx->ct_vopt |= SMBVOPT_SIGNING_REQUIRED;
}
return (0);
}
/*
* Handle .nsmbrc "minver" option.
* Must be <= maxver
*/
int
smb_ctx_setminver(struct smb_ctx *ctx, int ver)
{
if (ver < 0 || ver > ctx->ct_maxver)
return (EINVAL);
ctx->ct_minver = (uint16_t)ver;
return (0);
}
/*
* Handle .nsmbrc "maxver" option.
* Must be >= minver
*
* Any "too high" value is just clamped, so the caller
* doesn't need to know what's the highest we support.
*/
int
smb_ctx_setmaxver(struct smb_ctx *ctx, int ver)
{
if (ver < 1 || ver < ctx->ct_minver)
return (EINVAL);
if (ver > SMB2_DIALECT_MAX)
ver = SMB2_DIALECT_MAX;
ctx->ct_maxver = (uint16_t)ver;
return (0);
}
static int
smb_parse_owner(char *pair, uid_t *uid, gid_t *gid)
{
struct group gr;
struct passwd pw;
char buf[NSS_BUFLEN_PASSWD];
char *cp;
cp = strchr(pair, ':');
if (cp) {
*cp++ = '\0';
if (*cp && gid) {
if (getgrnam_r(cp, &gr, buf, sizeof (buf)) != NULL) {
*gid = gr.gr_gid;
} else
smb_error(dgettext(TEXT_DOMAIN,
"Invalid group name %s, ignored"), 0, cp);
}
}
if (*pair) {
if (getpwnam_r(pair, &pw, buf, sizeof (buf)) != NULL) {
*uid = pw.pw_uid;
} else
smb_error(dgettext(TEXT_DOMAIN,
"Invalid user name %s, ignored"), 0, pair);
}
return (0);
}
/*
* Suport a securty options arg, i.e. -S lm,ntlm
* for testing various type of authenticators.
*/
static struct nv
sectype_table[] = {
{ "anon", SMB_AT_ANON },
{ "lm", SMB_AT_LM1 },
{ "ntlm", SMB_AT_NTLM1 },
{ "ntlm2", SMB_AT_NTLM2 },
{ "krb5", SMB_AT_KRB5 },
{ NULL, 0 },
};
int
smb_parse_secopts(struct smb_ctx *ctx, const char *arg)
{
const char *sep = ":;,";
const char *p = arg;
struct nv *nv;
int nlen, tlen;
int authflags = 0;
for (;;) {
/* skip separators */
tlen = strspn(p, sep);
p += tlen;
nlen = strcspn(p, sep);
if (nlen == 0)
break;
/* This is rarely called, so not optimized. */
for (nv = sectype_table; nv->name; nv++) {
tlen = strlen(nv->name);
if (tlen == nlen && 0 == strncmp(p, nv->name, tlen))
break;
}
if (nv->name == NULL) {
smb_error(dgettext(TEXT_DOMAIN,
"%s: invalid security options"), 0, p);
return (EINVAL);
}
authflags |= nv->value;
p += nlen;
}
if (authflags)
ctx->ct_authflags = authflags;
return (0);
}
/*
* Commands use this with getopt. See:
* STDPARAM_OPT, STDPARAM_ARGS
* Called after smb_ctx_readrc().
*/
int
smb_ctx_opt(struct smb_ctx *ctx, int opt, const char *arg)
{
int error = 0;
char *p, *cp;
char tmp[1024];
switch (opt) {
case 'A':
case 'U':
/* Handled in smb_ctx_init() */
break;
case 'I':
error = smb_ctx_setsrvaddr(ctx, arg);
break;
case 'M':
/* share connect rights - ignored */
ctx->ct_flags |= SMBCF_SRIGHTS;
break;
case 'N':
ctx->ct_flags |= SMBCF_NOPWD;
break;
case 'O':
p = strdup(arg);
cp = strchr(p, '/');
if (cp)
*cp = '\0';
error = smb_parse_owner(cp, &ctx->ct_owner, NULL);
free(p);
break;
case 'P':
/* ctx->ct_vopt |= SMBCOPT_PERMANENT; */
break;
case 'R':
/* retry count - ignored */
break;
case 'S':
/* Security options (undocumented, just for tests) */
error = smb_parse_secopts(ctx, arg);
break;
case 'T':
/* timeout - ignored */
break;
case 'D': /* domain */
case 'W': /* workgroup (legacy alias) */
error = smb_ctx_setdomain(ctx, tmp, TRUE);
break;
}
return (error);
}
/*
* Original code injected iconv tables into the kernel.
* Not sure if we'll need this or not... REVISIT
*/
#ifdef KICONV_SUPPORT
static int
smb_addiconvtbl(const char *to, const char *from, const uchar_t *tbl)
{
int error = 0;
error = kiconv_add_xlat_table(to, from, tbl);
if (error && error != EEXIST) {
smb_error(dgettext(TEXT_DOMAIN,
"can not setup kernel iconv table (%s:%s)"),
error, from, to);
return (error);
}
return (error);
}
#endif /* KICONV_SUPPORT */
/*
* Verify context info. before connect operation(s),
* lookup specified server and try to fill all forgotten fields.
* Legacy name used by commands.
*/
int
smb_ctx_resolve(struct smb_ctx *ctx)
{
struct smbioc_ossn *ssn = &ctx->ct_ssn;
int error = 0;
#ifdef KICONV_SUPPORT
uchar_t cstbl[256];
uint_t i;
#endif
if (smb_debug)
dump_ctx("before smb_ctx_resolve", ctx);
ctx->ct_flags &= ~SMBCF_RESOLVED;
if (ctx->ct_fullserver == NULL) {
smb_error(dgettext(TEXT_DOMAIN,
"no server name specified"), 0);
return (EINVAL);
}
if (ctx->ct_minlevel >= SMBL_SHARE &&
ctx->ct_origshare == NULL) {
smb_error(dgettext(TEXT_DOMAIN,
"no share name specified for %s@%s"),
0, ssn->ssn_user, ctx->ct_fullserver);
return (EINVAL);
}
error = nb_ctx_resolve(ctx->ct_nb);
if (error)
return (error);
#ifdef KICONV_SUPPORT
if (ssn->ioc_localcs[0] == 0)
strcpy(ssn->ioc_localcs, "default"); /* XXX: locale name ? */
error = smb_addiconvtbl("tolower", ssn->ioc_localcs, nls_lower);
if (error)
return (error);
error = smb_addiconvtbl("toupper", ssn->ioc_localcs, nls_upper);
if (error)
return (error);
if (ssn->ioc_servercs[0] != 0) {
for (i = 0; i < sizeof (cstbl); i++)
cstbl[i] = i;
nls_mem_toext(cstbl, cstbl, sizeof (cstbl));
error = smb_addiconvtbl(ssn->ioc_servercs, ssn->ioc_localcs,
cstbl);
if (error)
return (error);
for (i = 0; i < sizeof (cstbl); i++)
cstbl[i] = i;
nls_mem_toloc(cstbl, cstbl, sizeof (cstbl));
error = smb_addiconvtbl(ssn->ioc_localcs, ssn->ioc_servercs,
cstbl);
if (error)
return (error);
}
#endif /* KICONV_SUPPORT */
/*
* Lookup the IP address and fill in ct_addrinfo.
*
* Note: smb_ctx_getaddr() returns a EAI_xxx
* error value like getaddrinfo(3), but this
* function needs to return an errno value.
*/
error = smb_ctx_getaddr(ctx);
if (error) {
const char *ais = gai_strerror(error);
smb_error(dgettext(TEXT_DOMAIN,
"can't resolve name\"%s\", %s"),
0, ctx->ct_fullserver, ais);
return (ENODATA);
}
assert(ctx->ct_addrinfo != NULL);
/*
* Empty user name means an explicit request for
* NULL session setup, which is a special case.
* (No SMB signing, per [MS-SMB] 3.3.5.3)
*/
if (ctx->ct_user[0] == '\0') {
/* Null user should have null domain too. */
ctx->ct_domain[0] = '\0';
ctx->ct_authflags = SMB_AT_ANON;
ctx->ct_vopt |= SMBVOPT_ANONYMOUS;
ctx->ct_vopt &= ~SMBVOPT_SIGNING_REQUIRED;
}
/*
* If we have a user name but no password,
* check for a keychain entry.
* XXX: Only for auth NTLM?
*/
if (ctx->ct_user[0] != '\0') {
/*
* Have a user name.
* If we don't have a p/w yet,
* try the keychain.
*/
if (ctx->ct_password[0] == '\0' &&
smb_get_keychain(ctx) == 0) {
strlcpy(ctx->ct_password, "$HASH",
sizeof (ctx->ct_password));
}
/*
* Mask out disallowed auth types.
*/
ctx->ct_authflags &= ctx->ct_minauth;
}
if (ctx->ct_authflags == 0) {
smb_error(dgettext(TEXT_DOMAIN,
"no valid auth. types"), 0);
return (ENOTSUP);
}
ctx->ct_flags |= SMBCF_RESOLVED;
if (smb_debug)
dump_ctx("after smb_ctx_resolve", ctx);
return (0);
}
/*
* Note: The next three have NODIRECT binding so the
* "fksmbcl" development tool can provide its own.
*/
int
smb_open_driver()
{
int fd;
fd = open("/dev/"NSMB_NAME, O_RDWR);
if (fd < 0) {
return (-1);
}
/* This handle controls per-process resources. */
(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
return (fd);
}
int
nsmb_close(int fd)
{
return (close(fd));
}
int
nsmb_ioctl(int fd, int cmd, void *arg)
{
return (ioctl(fd, cmd, arg));
}
int
smb_ctx_gethandle(struct smb_ctx *ctx)
{
int fd, err;
uint32_t version;
if (ctx->ct_dev_fd != -1) {
rpc_cleanup_smbctx(ctx);
nsmb_close(ctx->ct_dev_fd);
ctx->ct_dev_fd = -1;
}
fd = smb_open_driver();
if (fd < 0) {
err = errno;
smb_error(dgettext(TEXT_DOMAIN,
"failed to open driver"), err);
return (err);
}
/*
* Check the driver version (paranoia)
*/
if (nsmb_ioctl(fd, SMBIOC_GETVERS, &version) < 0)
version = 0;
if (version != NSMB_VERSION) {
smb_error(dgettext(TEXT_DOMAIN,
"incorrect driver version"), 0);
nsmb_close(fd);
return (ENODEV);
}
ctx->ct_dev_fd = fd;
return (0);
}
/*
* Find or create a connection + logon session
*/
int
smb_ctx_get_ssn(struct smb_ctx *ctx)
{
int err = 0;
if ((ctx->ct_flags & SMBCF_RESOLVED) == 0)
return (EINVAL);
/*
* Check whether the driver already has a VC
* we can use. If so, we're done!
*/
err = smb_ctx_findvc(ctx);
if (err == 0) {
DPRINT("found an existing VC");
} else {
/*
* If we're authenticating (real user, not NULL session)
* and we don't yet have a password, return EAUTH and
* the caller will prompt for it and call again.
*/
if (ctx->ct_user[0] != '\0' &&
ctx->ct_password[0] == '\0')
return (EAUTH);
/*
* This calls the IOD to create a new session.
*/
DPRINT("setup a new VC");
err = smb_ctx_newvc(ctx);
if (err != 0)
return (err);
/*
* Call findvc again. The new VC sould be
* found in the driver this time.
*/
err = smb_ctx_findvc(ctx);
}
return (err);
}
/*
* Find or create a tree connection
*/
int
smb_ctx_get_tree(struct smb_ctx *ctx)
{
smbioc_tcon_t *tcon = NULL;
int cmd, err = 0;
if (ctx->ct_dev_fd < 0 ||
ctx->ct_origshare == NULL) {
return (EINVAL);
}
cmd = SMBIOC_TREE_CONNECT;
tcon = malloc(sizeof (*tcon));
if (tcon == NULL)
return (ENOMEM);
bzero(tcon, sizeof (*tcon));
tcon->tc_flags = SMBLK_CREATE;
tcon->tc_opt = 0;
/* The share name */
strlcpy(tcon->tc_sh.sh_name, ctx->ct_origshare,
sizeof (tcon->tc_sh.sh_name));
/* The share "use" type. */
tcon->tc_sh.sh_use = ctx->ct_shtype_req;
/*
* Todo: share passwords for share-level security.
*
* The driver does the actual TCON call.
*/
if (nsmb_ioctl(ctx->ct_dev_fd, cmd, tcon) == -1) {
err = errno;
goto out;
}
/*
* Check the returned share type
*/
DPRINT("ret. sh_type: \"%d\"", tcon->tc_sh.sh_type);
if (ctx->ct_shtype_req != USE_WILDCARD &&
ctx->ct_shtype_req != tcon->tc_sh.sh_type) {
smb_error(dgettext(TEXT_DOMAIN,
"%s: incompatible share type"),
0, ctx->ct_origshare);
}
out:
if (tcon != NULL)
free(tcon);
return (err);
}
/*
* Return the hflags2 word for an smb_ctx.
*/
int
smb_ctx_flags2(struct smb_ctx *ctx)
{
uint16_t flags2;
if (nsmb_ioctl(ctx->ct_dev_fd, SMBIOC_FLAGS2, &flags2) == -1) {
smb_error(dgettext(TEXT_DOMAIN,
"can't get flags2 for a session"), errno);
return (-1);
}
return (flags2);
}
/*
* Get the transport level session key.
* Must already have an active SMB session.
*/
int
smb_fh_getssnkey(int dev_fd, uchar_t *key, size_t len)
{
if (len < SMBIOC_HASH_SZ)
return (EINVAL);
if (nsmb_ioctl(dev_fd, SMBIOC_GETSSNKEY, key) == -1)
return (errno);
return (0);
}
/*
* RC file parsing stuff
*/
static struct nv
minauth_table[] = {
/* Allowed auth. types */
{ "kerberos", SMB_AT_KRB5 },
{ "ntlmv2", SMB_AT_KRB5|SMB_AT_NTLM2 },
{ "ntlm", SMB_AT_KRB5|SMB_AT_NTLM2|SMB_AT_NTLM1 },
{ "lm", SMB_AT_KRB5|SMB_AT_NTLM2|SMB_AT_NTLM1|SMB_AT_LM1 },
{ "none", SMB_AT_KRB5|SMB_AT_NTLM2|SMB_AT_NTLM1|SMB_AT_LM1|
SMB_AT_ANON },
{ NULL }
};
int
smb_cf_minauth_from_str(char *str)
{
struct nv *nvp;
for (nvp = minauth_table; nvp->name; nvp++)
if (strcmp(nvp->name, str) == 0)
return (nvp->value);
return (-1);
}
/*
* SMB 2.1 is the oldest SMB2 dialect implemented (we skipped SMB 2.002)
* so if we see a_protocol value of just "2" assume they meant 2.1
*/
static struct nv
smbver_table[] = {
{ "3.11", SMB2_DIALECT_0311 },
{ "3.02", SMB2_DIALECT_0302 },
{ "3.0", SMB2_DIALECT_0300 },
{ "2.1", SMB2_DIALECT_0210 },
{ "2", SMB2_DIALECT_0210 },
{ "1", 1 },
{ NULL, 0 }
};
int
smb_cf_version_from_str(char *str)
{
struct nv *nvp;
for (nvp = smbver_table; nvp->name; nvp++)
if (strcmp(nvp->name, str) == 0)
return (nvp->value);
return (-1);
}
/*
* level values:
* 0 - default
* 1 - server
* 2 - server:user
* 3 - server:user:share
*/
static int
smb_ctx_readrcsection(struct smb_ctx *ctx, const char *sname, int level)
{
char *p;
int ival;
int error;
int minver, maxver;
#ifdef KICONV_SUPPORT
if (level > 0) {
rc_getstringptr(smb_rc, sname, "charsets", &p);
if (p) {
error = smb_ctx_setcharset(ctx, p);
if (error)
smb_error(dgettext(TEXT_DOMAIN,
"charset specification in the section '%s' ignored"),
error, sname);
}
}
#endif
if (level <= 1) {
/* Section is: [default] or [server] */
/*
* Handle min_protocol, max_protocol
* (SMB protocol versions)
*/
minver = -1;
rc_getstringptr(smb_rc, sname, "min_protocol", &p);
if (p != NULL) {
minver = smb_cf_version_from_str(p);
if (minver == -1) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid min_protocol value \"%s\" specified in the section %s"),
0, p, sname);
}
}
maxver = -1;
rc_getstringptr(smb_rc, sname, "max_protocol", &p);
if (p != NULL) {
maxver = smb_cf_version_from_str(p);
if (maxver == -1) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid max_protocol value \"%s\" specified in the section %s"),
0, p, sname);
}
}
/*
* If setting both min/max protocol,
* validate against each other
*/
if (minver != -1 && maxver != -1) {
if (minver > maxver) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid min/max protocol combination in the section %s"),
0, sname);
} else {
ctx->ct_minver = minver;
ctx->ct_maxver = maxver;
}
}
/*
* Setting just min or max, validate against
* current settings
*/
if (minver != -1) {
if (minver > ctx->ct_maxver) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid min/max protocol combination in the section %s"),
0, sname);
} else {
ctx->ct_minver = minver;
}
}
if (maxver != -1) {
if (maxver < ctx->ct_minver) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid min/max protocol combination in the section %s"),
0, sname);
} else {
ctx->ct_maxver = maxver;
}
}
rc_getstringptr(smb_rc, sname, "minauth", &p);
if (p) {
/*
* "minauth" was set in this section; override
* the current minimum authentication setting.
*/
ival = smb_cf_minauth_from_str(p);
if (ival != -1) {
ctx->ct_minauth = ival;
} else {
/*
* Unknown minimum authentication level.
*/
smb_error(dgettext(TEXT_DOMAIN,
"invalid minimum authentication level \"%s\" specified in the section %s"),
0, p, sname);
return (EINVAL);
}
}
rc_getstringptr(smb_rc, sname, "signing", &p);
if (p) {
/*
* "signing" was set in this section; override
* the current signing settings. Note:
* setsigning flags are: enable, require
*/
if (strcmp(p, "disabled") == 0) {
(void) smb_ctx_setsigning(ctx, FALSE, FALSE);
} else if (strcmp(p, "enabled") == 0) {
(void) smb_ctx_setsigning(ctx, TRUE, FALSE);
} else if (strcmp(p, "required") == 0) {
(void) smb_ctx_setsigning(ctx, TRUE, TRUE);
} else {
/*
* Unknown "signing" value.
*/
smb_error(dgettext(TEXT_DOMAIN,
"invalid signing policy \"%s\" specified in the section %s"),
0, p, sname);
return (EINVAL);
}
}
/*
* Domain name. Allow both keywords:
* "workgroup", "domain"
*
* Note: these are NOT marked "from CMD".
* See long comment at smb_ctx_init()
*/
rc_getstringptr(smb_rc, sname, "workgroup", &p);
if (p) {
error = smb_ctx_setdomain(ctx, p, 0);
if (error)
smb_error(dgettext(TEXT_DOMAIN,
"workgroup specification in the "
"section '%s' ignored"), error, sname);
}
rc_getstringptr(smb_rc, sname, "domain", &p);
if (p) {
error = smb_ctx_setdomain(ctx, p, 0);
if (error)
smb_error(dgettext(TEXT_DOMAIN,
"domain specification in the "
"section '%s' ignored"), error, sname);
}
rc_getstringptr(smb_rc, sname, "user", &p);
if (p) {
error = smb_ctx_setuser(ctx, p, 0);
if (error)
smb_error(dgettext(TEXT_DOMAIN,
"user specification in the "
"section '%s' ignored"), error, sname);
}
}
if (level == 1) {
/* Section is: [server] */
rc_getstringptr(smb_rc, sname, "addr", &p);
if (p) {
error = smb_ctx_setsrvaddr(ctx, p);
if (error) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid address specified in section %s"),
0, sname);
return (error);
}
}
}
rc_getstringptr(smb_rc, sname, "password", &p);
if (p) {
error = smb_ctx_setpassword(ctx, p, 0);
if (error)
smb_error(dgettext(TEXT_DOMAIN,
"password specification in the section '%s' ignored"),
error, sname);
}
return (0);
}
/*
* read rc file as follows:
* 0: read [default] section
* 1: override with [server] section
* 2: override with [server:user] section
* 3: override with [server:user:share] section
* Since absence of rcfile is not fatal, silently ignore this fact.
* smb_rc file should be closed by caller.
*/
int
smb_ctx_readrc(struct smb_ctx *ctx)
{
char pwbuf[NSS_BUFLEN_PASSWD];
struct passwd pw;
char *sname = NULL;
int sname_max;
int err = 0;
/*
* If the user name is not specified some other way,
* use the current user name. Also save the homedir.
* NB: ct_home=NULL is allowed, and we don't want to
* bail out with an error for a missing ct_home.
*/
if (getpwuid_r(getuid(), &pw, pwbuf, sizeof (pwbuf)) != NULL) {
if (ctx->ct_user[0] == 0)
(void) smb_ctx_setuser(ctx, pw.pw_name, B_FALSE);
if (ctx->ct_home == NULL)
ctx->ct_home = strdup(pw.pw_dir);
}
if ((err = smb_open_rcfile(ctx->ct_home)) != 0) {
DPRINT("smb_open_rcfile, err=%d", err);
/* ignore any error here */
return (0);
}
sname_max = 3 * SMBIOC_MAX_NAME + 4;
sname = malloc(sname_max);
if (sname == NULL) {
err = ENOMEM;
goto done;
}
/*
* default parameters (level=0)
*/
smb_ctx_readrcsection(ctx, "default", 0);
nb_ctx_readrcsection(smb_rc, ctx->ct_nb, "default", 0);
/*
* If we don't have a server name, we can't read any of the
* [server...] sections.
*/
if (ctx->ct_fullserver == NULL)
goto done;
/*
* SERVER parameters.
*/
smb_ctx_readrcsection(ctx, ctx->ct_fullserver, 1);
/*
* If we don't have a user name, we can't read any of the
* [server:user...] sections.
*/
if (ctx->ct_user[0] == 0)
goto done;
/*
* SERVER:USER parameters
*/
snprintf(sname, sname_max, "%s:%s",
ctx->ct_fullserver,
ctx->ct_user);
smb_ctx_readrcsection(ctx, sname, 2);
/*
* If we don't have a share name, we can't read any of the
* [server:user:share] sections.
*/
if (ctx->ct_origshare == NULL)
goto done;
/*
* SERVER:USER:SHARE parameters
*/
snprintf(sname, sname_max, "%s:%s:%s",
ctx->ct_fullserver,
ctx->ct_user,
ctx->ct_origshare);
smb_ctx_readrcsection(ctx, sname, 3);
done:
if (sname)
free(sname);
smb_close_rcfile();
if (smb_debug)
dump_ctx("after smb_ctx_readrc", ctx);
if (err)
DPRINT("err=%d\n", err);
return (err);
}
void
smbfs_set_default_domain(const char *domain)
{
strlcpy(default_domain, domain, sizeof (default_domain));
}
void
smbfs_set_default_user(const char *user)
{
strlcpy(default_user, user, sizeof (default_user));
}
// Copyright 2012 Nexenta Systems, Inc. All rights reserved.
// Copyright (C) 2002 Microsoft Corporation
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS"
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
// OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTIBILITY
// AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Date - 10/08/2002
// Author - Sanj Surati
/////////////////////////////////////////////////////////////
//
// DERPARSE.C
//
// SPNEGO Token Handler Source File
//
// Contains implementation of ASN.1 DER read/write functions
// as defined in DERPARSE.H.
//
/////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <sys/byteorder.h>
#include "spnego.h"
#include "derparse.h"
//
// The GSS Mechanism OID enumeration values (SPNEGO_MECH_OID) control which offset in
// the array below, that a mechanism can be found.
//
MECH_OID g_stcMechOIDList [] =
{
{(unsigned char *)"\x06\x09\x2a\x86\x48\x82\xf7\x12\x01\x02\x02",
11, 9, spnego_mech_oid_Kerberos_V5_Legacy}, // 1.2.840.48018.1.2.2
{(unsigned char *)"\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02",
11, 9, spnego_mech_oid_Kerberos_V5}, // 1.2.840.113554.1.2.2
{(unsigned char *)"\x06\x06\x2b\x06\x01\x05\x05\x02",
8, 6, spnego_mech_oid_Spnego}, // 1.3.6.1.5.5.2
{(unsigned char *)"\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a",
12, 10, spnego_mech_oid_NTLMSSP}, // 1.3.6.1.4.1.311.2.2.10
{(unsigned char *)"", 0, 0, spnego_mech_oid_NotUsed // Placeholder
}
};
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerGetLength
//
// Parameters:
// [in] pbLengthData - DER Length Data
// [in] nBoundaryLength - Length that value must not exceed.
// [out] pnLength - Filled out with length value
// [out] pnNumLengthBytes - Filled out with number of bytes
// consumed by DER length.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Interprets the data at pbLengthData as a DER length. The length must
// fit within the bounds of nBoundary length. We do not currently
// process lengths that take more than 4 bytes.
//
////////////////////////////////////////////////////////////////////////////
int ASNDerGetLength( unsigned char* pbLengthData, long nBoundaryLength, long* pnLength,
long* pnNumLengthBytes )
{
int nReturn = SPNEGO_E_INVALID_LENGTH;
int nNumLengthBytes = 0;
// First check if the extended length bit is set
if ( *pbLengthData & LEN_XTND )
{
// Lower 7 bits contain the number of trailing bytes that describe the length
nNumLengthBytes = *pbLengthData & LEN_MASK;
// Check that the number of bytes we are about to read is within our boundary
// constraints
if ( nNumLengthBytes <= nBoundaryLength - 1 )
{
// For now, our handler won't deal with lengths greater than 4 bytes
if ( nNumLengthBytes >= 1 && nNumLengthBytes <= 4 )
{
// 0 out the initial length
*pnLength = 0L;
// Bump by 1 byte
pbLengthData++;
#ifdef _LITTLE_ENDIAN
// There may be a cleaner way to do this, but for now, this seems to be
// an easy way to do the transformation
switch ( nNumLengthBytes )
{
case 1:
{
*( ( (unsigned char*) pnLength ) ) = *pbLengthData;
break;
}
case 2:
{
*( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 1);
*( ( (unsigned char*) pnLength ) + 1 ) = *(pbLengthData);
break;
}
case 3:
{
*( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 2);
*( ( (unsigned char*) pnLength ) + 2 ) = *(pbLengthData + 1);
*( ( (unsigned char*) pnLength ) + 3 ) = *(pbLengthData);
break;
}
case 4:
{
*( ( (unsigned char*) pnLength ) ) = *(pbLengthData + 3);
*( ( (unsigned char*) pnLength ) + 1 ) = *(pbLengthData + 2);
*( ( (unsigned char*) pnLength ) + 2 ) = *(pbLengthData + 1);
*( ( (unsigned char*) pnLength ) + 3 ) = *(pbLengthData);
break;
}
} // SWITCH ( nNumLengthBytes )
#else
// We are Big-Endian, so the length can be copied in from the source
// as is. Ensure that we adjust for the number of bytes we actually
// copy.
memcpy( ( (unsigned char *) pnLength ) + ( 4 - nNumLengthBytes ),
pbLengthData, nNumLengthBytes );
#endif
// Account for the initial length byte
*pnNumLengthBytes = nNumLengthBytes + 1;
nReturn = SPNEGO_E_SUCCESS;
} // IF Valid Length
} // IF num bytes to read is within the boundary length
} // IF xtended length
else
{
// Extended bit is not set, so the length is in the value and the one
// byte describes the length
*pnLength = *pbLengthData & LEN_MASK;
*pnNumLengthBytes = 1;
nReturn = SPNEGO_E_SUCCESS;
}
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerCheckToken
//
// Parameters:
// [in] pbTokenData - Token Data
// [in] nToken - Token identifier to check for
// [in] nLengthWithToken - Expected token length (with data)
// [in] nBoundaryLength - Length that value must not exceed.
// [out] pnLength - Filled out with data length
// [out] pnTokenLength - Filled out with number of bytes
// consumed by token identifier and length.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Checks the data pointed to by pbTokenData for the specified token
// identifier and the length that immediately follows. If
// nLengthWithToken is > 0, the calculated length must match. The
// length must also not exceed the specified boundary length .
//
////////////////////////////////////////////////////////////////////////////
int ASNDerCheckToken( unsigned char* pbTokenData, unsigned char nToken,
long nLengthWithToken, long nBoundaryLength,
long* pnLength, long* pnTokenLength )
{
int nReturn = SPNEGO_E_INVALID_LENGTH;
long nNumLengthBytes = 0L;
// Make sure that we've at least got 2 bytes of room to work with
if ( nBoundaryLength >= 2 )
{
// The first byte of the token data MUST match the specified token
if ( *pbTokenData == nToken )
{
// Next byte indicates the length
pbTokenData++;
// Get the length described by the token
if ( ( nReturn = ASNDerGetLength( pbTokenData, nBoundaryLength, pnLength,
&nNumLengthBytes ) ) == SPNEGO_E_SUCCESS )
{
// Verify that the length is LESS THAN the boundary length
// (this should prevent us walking out of our buffer)
if ( ( nBoundaryLength - ( nNumLengthBytes + 1 ) < *pnLength ) )
{
nReturn = SPNEGO_E_INVALID_LENGTH;
}
// If we were passed a length to check, do so now
if ( nLengthWithToken > 0L )
{
// Check that the expected length matches
if ( ( nLengthWithToken - ( nNumLengthBytes + 1 ) ) != *pnLength )
{
nReturn = SPNEGO_E_INVALID_LENGTH;
}
} // IF need to validate length
if ( SPNEGO_E_SUCCESS == nReturn )
{
*pnTokenLength = nNumLengthBytes + 1;
}
} // IF ASNDerGetLength
} // IF token matches
else
{
nReturn = SPNEGO_E_TOKEN_NOT_FOUND;
}
} // IF Boundary Length is at least 2 bytes
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerCheckOID
//
// Parameters:
// [in] pbTokenData - Token Data
// [in] nMechOID - OID we are looking for
// [in] nBoundaryLength - Length that value must not exceed.
// [out] pnTokenLength - Filled out with number of bytes
// consumed by token and data.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Checks the data pointed to by pbTokenData for the specified OID.
//
////////////////////////////////////////////////////////////////////////////
int ASNDerCheckOID( unsigned char* pbTokenData, SPNEGO_MECH_OID nMechOID, long nBoundaryLength,
long* pnTokenLength )
{
int nReturn = 0L;
long nLength = 0L;
// Verify that we have an OID token
if ( ( nReturn = ASNDerCheckToken( pbTokenData, OID, 0L, nBoundaryLength,
&nLength, pnTokenLength ) ) == SPNEGO_E_SUCCESS )
{
// Add the data length to the Token Length
*pnTokenLength += nLength;
// Token Lengths plus the actual length must match the length in our OID list element.
// If it doesn't, we're done
if ( *pnTokenLength == g_stcMechOIDList[nMechOID].iLen )
{
// Memcompare the token and the expected field
if ( memcmp( pbTokenData, g_stcMechOIDList[nMechOID].ucOid, *pnTokenLength ) != 0 )
{
nReturn = SPNEGO_E_UNEXPECTED_OID;
}
}
else
{
nReturn = SPNEGO_E_UNEXPECTED_OID;
}
} // IF OID Token CHecks
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerCalcNumLengthBytes
//
// Parameters:
// [in] nLength - Length to calculate length bytes for.
//
// Returns:
// int Number of bytes necessary to represent length
//
// Comments :
// Helper function to calculate the number of length bytes necessary to
// represent a length value. For our purposes, a 32-bit value should be
// enough to describea length.
//
////////////////////////////////////////////////////////////////////////////
int ASNDerCalcNumLengthBytes( long nLength )
{
if ( nLength <= 0x7F )
{
// A single byte will be sufficient for describing this length.
// The byte will simply contain the length
return 1;
}
else if ( nLength <= 0xFF )
{
// Two bytes are necessary, one to say how many following bytes
// describe the length, and one to give the length
return 2;
}
else if ( nLength <= 0xFFFF )
{
// Three bytes are necessary, one to say how many following bytes
// describe the length, and two to give the length
return 3;
}
else if ( nLength <= 0xFFFFFF )
{
// Four bytes are necessary, one to say how many following bytes
// describe the length, and three to give the length
return 4;
}
else
{
// Five bytes are necessary, one to say how many following bytes
// describe the length, and four to give the length
return 5;
}
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerCalcTokenLength
//
// Parameters:
// [in] nLength - Length to calculate length bytes for.
// [in] nDataLength - Actual Data length value.
//
// Returns:
// long Number of bytes necessary to represent a token, length and data
//
// Comments :
// Helper function to calculate a token and value size, based on a
// supplied length value, and any binary data that will need to be
// written out.
//
////////////////////////////////////////////////////////////////////////////
long ASNDerCalcTokenLength( long nLength, long nDataLength )
{
// Add a byte to the length size to account for a single byte to
// hold the token type.
long nTotalLength = ASNDerCalcNumLengthBytes( nLength ) + 1;
return nTotalLength + nDataLength;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerCalcElementLength
//
// Parameters:
// [in] nDataLength - Length of data.
// [out] pnInternalLength - Filled out with length of element
// without sequence info.
//
// Returns:
// long Number of bytes necessary to represent an element
//
// Comments :
// Helper function to calculate an element length. An element consists
// of a sequence token, a type token and then the data.
//
////////////////////////////////////////////////////////////////////////////
long ASNDerCalcElementLength( long nDataLength, long* pnInternalLength )
{
// First the type token and the actual data
long nTotalLength = ASNDerCalcTokenLength( nDataLength, nDataLength );
// Internal length is the length without the element sequence token
if ( NULL != pnInternalLength )
{
*pnInternalLength = nTotalLength;
}
// Next add in the element's sequence token (remember that its
// length is the total length of the type token and data)
nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L );
return nTotalLength;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerCalcMechListLength
//
// Parameters:
// [in] mechoid - Mech OID to put in list.
// [out] pnInternalLength - Filled out with length of element
// without the primary sequence token.
//
// Returns:
// long Number of bytes necessary to represent a mechList
//
// Comments :
// Helper function to calculate a MechList length. A mechlist consists
// of a NegTokenInit sequence token, a sequence token for the MechList
// and finally a list of OIDs.
//
////////////////////////////////////////////////////////////////////////////
long ASNDerCalcMechListLength( SPNEGO_MECH_OID *mechOidLst, int mechOidCnt,
long* pnInternalLength )
{
// First the OID
SPNEGO_MECH_OID oid_idx;
long nTotalLength;
int i;
nTotalLength = 0;
for (i = 0; i < mechOidCnt; i++) {
oid_idx = mechOidLst[i];
nTotalLength += g_stcMechOIDList[oid_idx].iLen;
}
// Next add in a sequence token
nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L );
// Internal length is the length without the element sequence token
if ( NULL != pnInternalLength )
{
*pnInternalLength = nTotalLength;
}
// Finally add in the element's sequence token
nTotalLength += ASNDerCalcTokenLength( nTotalLength, 0L );
return nTotalLength;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerWriteLength
//
// Parameters:
// [out] pbData - Buffer to write into.
// [in] nLength - Length to write out.
//
// Returns:
// int Number of bytes written out
//
// Comments :
// Helper function to write out a length value following DER rules .
//
////////////////////////////////////////////////////////////////////////////
int ASNDerWriteLength( unsigned char* pbData, long nLength )
{
int nNumBytesRequired = ASNDerCalcNumLengthBytes( nLength );
int nNumLengthBytes = nNumBytesRequired - 1;
if ( nNumBytesRequired > 1 )
{
// Write out the number of bytes following which will be used
*pbData = (unsigned char ) ( LEN_XTND | nNumLengthBytes );
// Point to where we'll actually write the length
pbData++;
#ifdef _LITTLE_ENDIAN
// There may be a cleaner way to do this, but for now, this seems to be
// an easy way to do the transformation
switch ( nNumLengthBytes )
{
case 1:
{
// Cast the length to a single byte, since we know that it
// is 0x7F or less (or we wouldn't only need a single byte).
*pbData = (unsigned char) nLength;
break;
}
case 2:
{
*pbData = *( ( (unsigned char*) &nLength ) + 1 );
*( pbData + 1) = *( ( (unsigned char*) &nLength ) );
break;
}
case 3:
{
*pbData = *( ( (unsigned char*) &nLength ) + 3 );
*( pbData + 1) = *( ( (unsigned char*) &nLength ) + 2 );
*( pbData + 2) = *( ( (unsigned char*) &nLength ) );
break;
}
case 4:
{
*pbData = *( ( (unsigned char*) &nLength ) + 3 );
*( pbData + 1) = *( ( (unsigned char*) &nLength ) + 2 );
*( pbData + 2) = *( ( (unsigned char*) &nLength ) + 1 );
*( pbData + 3) = *( ( (unsigned char*) &nLength ) );
break;
}
} // SWITCH ( nNumLengthBytes )
#else
// We are Big-Endian, so the length can be copied in from the source
// as is. Ensure that we adjust for the number of bytes we actually
// copy.
memcpy( pbData,
( (unsigned char *) &nLength ) + ( 4 - nNumLengthBytes ), nNumLengthBytes );
#endif
} // IF > 1 byte for length
else
{
// Cast the length to a single byte, since we know that it
// is 0x7F or less (or we wouldn't only need a single byte).
*pbData = (unsigned char) nLength;
}
return nNumBytesRequired;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerWriteToken
//
// Parameters:
// [out] pbData - Buffer to write into.
// [in] ucType - Token Type
// [in] pbTokenValue - Actual Value
// [in] nLength - Length of Data.
//
// Returns:
// int Number of bytes written out
//
// Comments :
// Helper function to write out a token and any associated data. If
// pbTokenValue is non-NULL, then it is written out in addition to the
// token identifier and the length bytes.
//
////////////////////////////////////////////////////////////////////////////
int ASNDerWriteToken( unsigned char* pbData, unsigned char ucType,
unsigned char* pbTokenValue, long nLength )
{
int nTotalBytesWrittenOut = 0L;
int nNumLengthBytesWritten = 0L;
// Write out the type
*pbData = ucType;
// Wrote 1 byte, and move data pointer
nTotalBytesWrittenOut++;
pbData++;
// Now write out the length and adjust the number of bytes written out
nNumLengthBytesWritten = ASNDerWriteLength( pbData, nLength );
nTotalBytesWrittenOut += nNumLengthBytesWritten;
pbData += nNumLengthBytesWritten;
// Write out the token value if we got one. The assumption is that the
// nLength value indicates how many bytes are in pbTokenValue.
if ( NULL != pbTokenValue )
{
memcpy( pbData, pbTokenValue, nLength );
nTotalBytesWrittenOut += nLength;
}
return nTotalBytesWrittenOut;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerWriteOID
//
// Parameters:
// [out] pbData - Buffer to write into.
// [in] eMechOID - OID to write out.
//
// Returns:
// int Number of bytes written out
//
// Comments :
// Helper function to write out an OID. For these we have the raw bytes
// listed in a global structure. The caller simply indicates which OID
// should be written and we will splat out the data.
//
////////////////////////////////////////////////////////////////////////////
int ASNDerWriteOID( unsigned char* pbData, SPNEGO_MECH_OID eMechOID )
{
if (pbData != NULL) {
memcpy( pbData, g_stcMechOIDList[eMechOID].ucOid,
g_stcMechOIDList[eMechOID].iLen );
}
return g_stcMechOIDList[eMechOID].iLen;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerWriteMechList
//
// Parameters:
// [out] pbData - Buffer to write into.
// [in] eMechOID - OID to put in MechList.
//
// Returns:
// int Number of bytes written out
//
// Comments :
// Helper function to write out a MechList. A MechList consists of the
// Init Token Sequence, a sequence token and then the list of OIDs. In
// our case the OID is from a global array of known OIDs.
//
////////////////////////////////////////////////////////////////////////////
long ASNDerWriteMechList( unsigned char* pbData, SPNEGO_MECH_OID *mechOidLst, int mechOidCnt )
{
// First get the length
long nInternalLength = 0L;
long nMechListLength;
long nTempLength = 0L;
int i;
nMechListLength = ASNDerCalcMechListLength(mechOidLst, mechOidCnt, &nInternalLength);
nTempLength = ASNDerWriteToken( pbData, SPNEGO_NEGINIT_ELEMENT_MECHTYPES,
NULL, nInternalLength );
// Adjust the data pointer
pbData += nTempLength;
nInternalLength -= nTempLength;
// Now write the Sequence token and the OID (the OID is a BLOB in the global
// structure.
nTempLength = ASNDerWriteToken( pbData, SPNEGO_CONSTRUCTED_SEQUENCE,
NULL, nInternalLength);
pbData += nTempLength;
for (i = 0; i < mechOidCnt; i++) {
nTempLength = ASNDerWriteOID( pbData, mechOidLst[i] );
pbData += nTempLength;
}
return nMechListLength;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ASNDerWriteElement
//
// Parameters:
// [out] pbData - Buffer to write into.
// [in] ucElementSequence - Sequence Token
// [in] ucType - Token Type
// [in] pbTokenValue - Actual Value
// [in] nLength - Length of Data.
//
// Returns:
// int Number of bytes written out
//
// Comments :
// Helper function to write out a SPNEGO Token element. An element
// consists of a sequence token, a type token and the associated data.
//
////////////////////////////////////////////////////////////////////////////
int ASNDerWriteElement( unsigned char* pbData, unsigned char ucElementSequence,
unsigned char ucType, unsigned char* pbTokenValue, long nLength )
{
// First get the length
long nInternalLength = 0L;
long nElementLength = ASNDerCalcElementLength( nLength, &nInternalLength );
long nTempLength = 0L;
// Write out the sequence byte and the length of the type and data
nTempLength = ASNDerWriteToken( pbData, ucElementSequence, NULL, nInternalLength );
// Adjust the data pointer
pbData += nTempLength;
// Now write the type and the data.
nTempLength = ASNDerWriteToken( pbData, ucType, pbTokenValue, nLength );
return nElementLength;
}
// Copyright 2012 Nexenta Systems, Inc. All rights reserved.
// Copyright (C) 2002 Microsoft Corporation
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS"
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
// OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTIBILITY
// AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Date - 10/08/2002
// Author - Sanj Surati
/////////////////////////////////////////////////////////////
//
// DERPARSE.H
//
// SPNEGO Token Handler Header File
//
// Contains the definitions required to properly parse the
// SPNEGO DER encoding.
//
/////////////////////////////////////////////////////////////
#ifndef __DERPARSE_H__
#define __DERPARSE_H__
// C++ Specific
#if defined(__cplusplus)
extern "C"
{
#endif
/* Identifier Types */
#define IDENTIFIER_MASK 0xC0 // Bits 7 and 8
#define IDENTIFIER_UNIVERSAL 0x00 // 00 = universal
#define IDENTIFIER_APPLICATION 0x40 // 01 = application
#define IDENTIFIER_CONTEXT_SPECIFIC 0x80 // 10 = context specific
#define IDENTIFIER_PRIVATE 0xC0 // 11 = Private
/* Encoding type */
#define FORM_MASK 0x20 /* Bit 6 */
#define PRIMITIVE 0x00 /* 0 = primitive */
#define CONSTRUCTED 0x20 /* 1 = constructed */
/* Universal tags */
#define TAG_MASK 0x1F /* Bits 5 - 1 */
#define BOOLEAN 0x01 /* 1: TRUE or FALSE */
#define INTEGER 0x02 /* 2: Arbitrary precision integer */
#define BITSTRING 0x03 /* 2: Sequence of bits */
#define OCTETSTRING 0x04 /* 4: Sequence of bytes */
#define NULLTAG 0x05 /* 5: NULL */
#define OID 0x06 /* 6: Object Identifier (numeric sequence) */
#define OBJDESCRIPTOR 0x07 /* 7: Object Descriptor (human readable) */
#define EXTERNAL 0x08 /* 8: External / Instance Of */
#define REAL 0x09 /* 9: Real (Mantissa * Base^Exponent) */
#define ENUMERATED 0x0A /* 10: Enumerated */
#define EMBEDDED_PDV 0x0B /* 11: Embedded Presentation Data Value */
#define SEQUENCE 0x10 /* 16: Constructed Sequence / Sequence Of */
#define SET 0x11 /* 17: Constructed Set / Set Of */
#define NUMERICSTR 0x12 /* 18: Numeric String (digits only) */
#define PRINTABLESTR 0x13 /* 19: Printable String */
#define T61STR 0x14 /* 20: T61 String (Teletex) */
#define VIDEOTEXSTR 0x15 /* 21: Videotex String */
#define IA5STR 0x16 /* 22: IA5 String */
#define UTCTIME 0x17 /* 23: UTC Time */
#define GENERALIZEDTIME 0x18 /* 24: Generalized Time */
#define GRAPHICSTR 0x19 /* 25: Graphic String */
#define VISIBLESTR 0x1A /* 26: Visible String (ISO 646) */
#define GENERALSTR 0x1B /* 27: General String */
#define UNIVERSALSTR 0x1C /* 28: Universal String */
#define BMPSTR 0x1E /* 30: Basic Multilingual Plane String */
/* Length encoding */
#define LEN_XTND 0x80 /* Indefinite or long form */
#define LEN_MASK 0x7f /* Bits 7 - 1 */
#define SEQ_ELM(n) (IDENTIFIER_CONTEXT_SPECIFIC | CONSTRUCTED | ((n)&TAG_MASK))
//
// SPNEGO Token Parsing Constants
//
// Fixed Length of NegTokenInit ReqFlags field
#define SPNEGO_NEGINIT_MAXLEN_REQFLAGS 2
// Difference in bits for ReqFlags token
#define SPNEGO_NEGINIT_REQFLAGS_BITDIFF 1
// Fixed Length of NegTokenTarg NegResult field
#define SPNEGO_NEGTARG_MAXLEN_NEGRESULT 1
// Application Specific Construct - Always at the start of a NegTokenInit
#define SPNEGO_NEGINIT_APP_CONSTRUCT ( IDENTIFIER_APPLICATION | CONSTRUCTED ) // 0x60
// Constructed Sequence token - after the actual token identifier token
#define SPNEGO_CONSTRUCTED_SEQUENCE ( SEQUENCE | CONSTRUCTED )
// MechList Type Identifier
#define SPNEGO_MECHLIST_TYPE ( SEQUENCE | CONSTRUCTED | OID )
//
// NegTokenInit - Token Identifier and Elements
//
// NegTokenInit - 0xa0
#define SPNEGO_NEGINIT_TOKEN_IDENTIFIER ( IDENTIFIER_CONTEXT_SPECIFIC | CONSTRUCTED | \
SPNEGO_TOKEN_INIT )
// Structure elements for NegTokenInit
#define SPNEGO_NEGINIT_MECHTYPES 0x0 // MechTypes is element 0
#define SPNEGO_NEGINIT_REQFLAGS 0x1 // ReqFlags is element 1
#define SPNEGO_NEGINIT_MECHTOKEN 0x2 // MechToken is element 2
#define SPNEGO_NEGINIT_MECHLISTMIC 0x3 // MechListMIC is element 3
// MechTypes element is 0xa0
#define SPNEGO_NEGINIT_ELEMENT_MECHTYPES SEQ_ELM(SPNEGO_NEGINIT_MECHTYPES)
// ReqFlags element is 0xa1
#define SPNEGO_NEGINIT_ELEMENT_REQFLAGS SEQ_ELM(SPNEGO_NEGINIT_REQFLAGS)
// MechToken element is 0xa2
#define SPNEGO_NEGINIT_ELEMENT_MECHTOKEN SEQ_ELM(SPNEGO_NEGINIT_MECHTOKEN)
// MechListMIC element is 0xa3
#define SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC SEQ_ELM(SPNEGO_NEGINIT_MECHLISTMIC)
//
// NegTokenTarg - Token Identifier and Elements
//
// NegTokenTarg - 0xa1
#define SPNEGO_NEGTARG_TOKEN_IDENTIFIER ( IDENTIFIER_CONTEXT_SPECIFIC | CONSTRUCTED | \
SPNEGO_TOKEN_TARG )
// Structure elements for NegTokenTarg
#define SPNEGO_NEGTARG_NEGRESULT 0x0 // NegResult is element 0
#define SPNEGO_NEGTARG_SUPPORTEDMECH 0x1 // SupportedMech is element 1
#define SPNEGO_NEGTARG_RESPONSETOKEN 0x2 // ResponseToken is element 2
#define SPNEGO_NEGTARG_MECHLISTMIC 0x3 // MechListMIC is element 3
// NegResult element is 0xa0
#define SPNEGO_NEGTARG_ELEMENT_NEGRESULT SEQ_ELM(SPNEGO_NEGTARG_NEGRESULT)
// SupportedMech element is 0xa1
#define SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH SEQ_ELM(SPNEGO_NEGTARG_SUPPORTEDMECH)
// ResponseToken element is 0xa2
#define SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN SEQ_ELM(SPNEGO_NEGTARG_RESPONSETOKEN)
// MechListMIC element is 0xa3
#define SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC SEQ_ELM(SPNEGO_NEGTARG_MECHLISTMIC)
//
// Defines a GSS Mechanism OID. We keep a single static array
// of these which we'll use for validation/searches/parsing.
//
typedef struct _mechOID
{
unsigned char* ucOid; // Byte representation of OID
int iLen; // Length of the OID, length and identifier
int iActualDataLen; // Length of the actual OID
SPNEGO_MECH_OID eMechanismOID; // Which OID is this?
} MECH_OID;
//
// ASN Der functions
//
int ASNDerGetLength( unsigned char* pbLengthData, long nBoundaryLength, long* pnLength,
long* pnNumLengthBytes );
int ASNDerCheckToken( unsigned char* pbTokenData, unsigned char nToken,
long nCheckLength, long nBoundaryLength, long* pnLength,
long* pnTokenLength );
int ASNDerCheckOID( unsigned char* pbTokenData, SPNEGO_MECH_OID nMechOID, long nBoundaryLength,
long* pnTokenLength );
int ASNDerCalcNumLengthBytes( long nLength );
long ASNDerCalcTokenLength( long nLength, long nDataLength );
long ASNDerCalcElementLength( long nDataLength, long* pnInternalLength );
long ASNDerCalcMechListLength( SPNEGO_MECH_OID *mechOidLst, int mechOidCnt,
long* pnInternalLength );
int ASNDerWriteLength( unsigned char* pbData, long nLength );
int ASNDerWriteToken( unsigned char* pbData, unsigned char ucType,
unsigned char* pbTokenValue, long nLength );
int ASNDerWriteOID( unsigned char* pbData, SPNEGO_MECH_OID eMechOID );
long ASNDerWriteMechList( unsigned char* pbData, SPNEGO_MECH_OID *mechOidLst, int mechOidCnt );
int ASNDerWriteElement( unsigned char* pbData, unsigned char ucElementSequence,
unsigned char ucType, unsigned char* pbTokenValue, long nLength );
// C++ Specific
#if defined(__cplusplus)
}
#endif
#endif
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: file.c,v 1.4 2004/12/13 00:25:21 lindak Exp $
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/mount.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <unistd.h>
#include <libintl.h>
#include <sys/types.h>
#include <sys/file.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include "private.h"
/*
* It's not actually necessary to call the CLOSEFH ioctl, but doing it
* makes debugging a little easier. If we were to skip the ioctl,
* nsmb_close would cleanup the handle, here or in process exit.
*/
int
smb_fh_close(int fd)
{
(void) nsmb_ioctl(fd, SMBIOC_CLOSEFH, NULL);
return (nsmb_close(fd));
}
int
smb_fh_ntcreate(
struct smb_ctx *ctx, char *path,
int req_acc, int efattr, int share_acc,
int open_disp, int create_opts)
{
smbioc_ntcreate_t ioc;
int err, nmlen;
int new_fd = -1;
int32_t from_fd;
nmlen = strlen(path);
if (nmlen >= SMBIOC_MAX_NAME) {
err = EINVAL;
goto errout;
}
/*
* Will represent this SMB-level open as a new
* open device handle. Get one, then duplicate
* the driver session and tree bindings.
*/
new_fd = smb_open_driver();
if (new_fd < 0) {
err = errno;
goto errout;
}
from_fd = ctx->ct_dev_fd;
if (nsmb_ioctl(new_fd, SMBIOC_DUP_DEV, &from_fd) == -1) {
err = errno;
goto errout;
}
/*
* Do the SMB-level open with the new dev handle.
*/
bzero(&ioc, sizeof (ioc));
strlcpy(ioc.ioc_name, path, SMBIOC_MAX_NAME);
ioc.ioc_req_acc = req_acc;
ioc.ioc_efattr = efattr;
ioc.ioc_share_acc = share_acc;
ioc.ioc_open_disp = open_disp;
ioc.ioc_creat_opts = create_opts;
if (nsmb_ioctl(new_fd, SMBIOC_NTCREATE, &ioc) == -1) {
err = errno;
goto errout;
}
return (new_fd);
errout:
if (new_fd != -1)
nsmb_close(new_fd);
errno = err;
return (-1);
}
/*
* Conveinence wrapper for smb_fh_ntcreate
* Converts Unix-style open call to NTCreate.
*/
int
smb_fh_open(struct smb_ctx *ctx, const char *path, int oflag)
{
int mode, open_disp, req_acc, share_acc;
char *p, *ntpath = NULL;
int fd = -1;
/*
* Convert Unix path to NT (backslashes)
*/
ntpath = strdup(path);
if (ntpath == NULL)
return (-1); /* errno was set */
for (p = ntpath; *p; p++)
if (*p == '/')
*p = '\\';
/*
* Map O_RDONLY, O_WRONLY, O_RDWR
* to FREAD, FWRITE
*/
mode = (oflag & 3) + 1;
/*
* Compute requested access, share access.
*/
req_acc = (
STD_RIGHT_READ_CONTROL_ACCESS |
STD_RIGHT_SYNCHRONIZE_ACCESS);
share_acc = NTCREATEX_SHARE_ACCESS_NONE;
if (mode & FREAD) {
req_acc |= (
SA_RIGHT_FILE_READ_DATA |
SA_RIGHT_FILE_READ_EA |
SA_RIGHT_FILE_READ_ATTRIBUTES);
share_acc |= NTCREATEX_SHARE_ACCESS_READ;
}
if (mode & FWRITE) {
req_acc |= (
SA_RIGHT_FILE_WRITE_DATA |
SA_RIGHT_FILE_APPEND_DATA |
SA_RIGHT_FILE_WRITE_EA |
SA_RIGHT_FILE_WRITE_ATTRIBUTES);
share_acc |= NTCREATEX_SHARE_ACCESS_WRITE;
}
/*
* Compute open disposition
*/
if (oflag & FCREAT) {
/* Creat if necessary. */
if (oflag & FEXCL) {
/* exclusive */
open_disp = NTCREATEX_DISP_CREATE;
} else if (oflag & FTRUNC)
open_disp = NTCREATEX_DISP_OVERWRITE_IF;
else
open_disp = NTCREATEX_DISP_OPEN_IF;
} else {
/* Not creating. */
if (oflag & FTRUNC)
open_disp = NTCREATEX_DISP_OVERWRITE;
else
open_disp = NTCREATEX_DISP_OPEN;
}
fd = smb_fh_ntcreate(ctx, ntpath,
req_acc, SMB_EFA_NORMAL, share_acc, open_disp,
NTCREATEX_OPTIONS_NON_DIRECTORY_FILE);
free(ntpath);
return (fd);
}
int
smb_fh_read(int fd, off64_t offset, size_t count,
char *dst)
{
struct smbioc_rw rwrq;
bzero(&rwrq, sizeof (rwrq));
rwrq.ioc_base = dst;
rwrq.ioc_cnt = count;
rwrq.ioc_offset = offset;
if (nsmb_ioctl(fd, SMBIOC_READ, &rwrq) == -1) {
return (-1);
}
return (rwrq.ioc_cnt);
}
int
smb_fh_write(int fd, off64_t offset, size_t count,
const char *src)
{
struct smbioc_rw rwrq;
bzero(&rwrq, sizeof (rwrq));
rwrq.ioc_base = (char *)src;
rwrq.ioc_cnt = count;
rwrq.ioc_offset = offset;
if (nsmb_ioctl(fd, SMBIOC_WRITE, &rwrq) == -1) {
return (-1);
}
return (rwrq.ioc_cnt);
}
/*
* Do a TRANSACT_NAMED_PIPE, which is basically just a
* pipe write and pipe read, all in one round trip.
*
* tdlen, tdata describe the data to send.
* rdlen, rdata on input describe the receive buffer,
* and on output *rdlen is the received length.
*/
int
smb_fh_xactnp(int fd,
int tdlen, const char *tdata, /* transmit */
int *rdlen, char *rdata, /* receive */
int *more)
{
smbioc_xnp_t ioc;
/* this gets copyin & copyout */
bzero(&ioc, sizeof (ioc));
ioc.ioc_tdlen = tdlen;
ioc.ioc_rdlen = *rdlen;
ioc.ioc_more = 0;
ioc.ioc_tdata = (char *)tdata;
ioc.ioc_rdata = rdata;
if (nsmb_ioctl(fd, SMBIOC_XACTNP, &ioc) == -1) {
*rdlen = 0;
return (-1);
}
*rdlen = ioc.ioc_rdlen;
*more = ioc.ioc_more;
return (0);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Find existing an VC given a list of addresses.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <libintl.h>
#include <xti.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/byteorder.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include <netsmb/netbios.h>
#include <netsmb/nb_lib.h>
#include <netsmb/smb_dev.h>
#include "charsets.h"
#include "private.h"
/*
* Ask the driver if it has a VC with this IP address.
*/
static int
findvc(struct smb_ctx *ctx, struct addrinfo *ai)
{
smbioc_ossn_t *ssn = &ctx->ct_ssn;
/*
* Copy the passed address into ssn_srvaddr,
* but first sanity-check lengths. Also,
* zero it first to avoid trailing junk.
*/
if (ai->ai_addrlen > sizeof (ssn->ssn_srvaddr))
return (EINVAL);
bzero(&ssn->ssn_srvaddr, sizeof (ssn->ssn_srvaddr));
bcopy(ai->ai_addr, &ssn->ssn_srvaddr, ai->ai_addrlen);
if (nsmb_ioctl(ctx->ct_dev_fd, SMBIOC_SSN_FIND, ssn) == -1)
return (errno);
return (0);
}
/*
* Find (and reuse) an existing VC.
* See also: newvc.c
*/
int
smb_ctx_findvc(struct smb_ctx *ctx)
{
struct addrinfo *ai;
int err;
/* Should already have the address list. */
if ((ctx->ct_flags & SMBCF_RESOLVED) == 0)
return (EINVAL);
if (ctx->ct_dev_fd < 0) {
if ((err = smb_ctx_gethandle(ctx)))
return (err);
}
for (ai = ctx->ct_addrinfo; ai; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET:
case AF_INET6:
case AF_NETBIOS:
err = findvc(ctx, ai);
break;
default:
DPRINT("skipped family %d", ai->ai_family);
err = EPROTONOSUPPORT;
break;
}
if (err == 0) {
/* re-use an existing VC */
return (0);
}
}
return (ENOENT);
}
/*
* Forcibly disconnect the current session, even if
* there are others using it! This is used by the
* SMB server netlogon when it wants to setup a new
* logon session and does not want any re-use.
*/
int
smb_ctx_kill(struct smb_ctx *ctx)
{
if (nsmb_ioctl(ctx->ct_dev_fd, SMBIOC_SSN_KILL, NULL) == -1)
return (errno);
return (0);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Functions to get list of addresses (TCP and/or NetBIOS)
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <netdb.h>
#include <libintl.h>
#include <xti.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/byteorder.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include <netsmb/netbios.h>
#include <netsmb/nb_lib.h>
#include <netsmb/smb_dev.h>
#include "charsets.h"
#include "private.h"
static char smb_port[16] = "445";
void
dump_addrinfo(struct addrinfo *ai)
{
int i;
if (ai == NULL) {
printf("ai==NULL\n");
return;
}
for (i = 0; ai; i++, ai = ai->ai_next) {
printf("ai[%d]: af=%d, len=%d", i,
ai->ai_family, ai->ai_addrlen);
dump_sockaddr(ai->ai_addr);
if (ai->ai_canonname) {
printf("ai[%d]: cname=\"%s\"\n",
i, ai->ai_canonname);
}
}
}
void
dump_sockaddr(struct sockaddr *sa)
{
char paddrbuf[INET6_ADDRSTRLEN];
struct sockaddr_in *sin;
struct sockaddr_in6 *sin6;
int af = sa->sa_family;
const char *ip;
printf(" saf=%d,", af);
switch (af) {
case AF_NETBIOS: /* see nbns_rq.c */
case AF_INET:
sin = (void *)sa;
ip = inet_ntop(AF_INET, &sin->sin_addr,
paddrbuf, sizeof (paddrbuf));
break;
case AF_INET6:
sin6 = (void *)sa;
ip = inet_ntop(AF_INET6, &sin6->sin6_addr,
paddrbuf, sizeof (paddrbuf));
break;
default:
ip = "?";
break;
}
printf(" IP=%s\n", ip);
}
/*
* SMB client name resolution - normal, and/or NetBIOS.
* Returns an EAI_xxx error number like getaddrinfo(3)
*/
int
smb_ctx_getaddr(struct smb_ctx *ctx)
{
struct nb_ctx *nbc = ctx->ct_nb;
struct addrinfo hints, *res;
char *srvaddr_str;
int gaierr;
if (ctx->ct_fullserver == NULL || ctx->ct_fullserver[0] == '\0')
return (EAI_NONAME);
if (ctx->ct_addrinfo != NULL) {
freeaddrinfo(ctx->ct_addrinfo);
ctx->ct_addrinfo = NULL;
}
/*
* If the user specified an address, use it,
* and don't do NetBIOS lookup.
*/
if (ctx->ct_srvaddr_s) {
srvaddr_str = ctx->ct_srvaddr_s;
nbc->nb_flags &= ~NBCF_NS_ENABLE;
} else
srvaddr_str = ctx->ct_fullserver;
/*
* Default the server name we'll use in the
* protocol (i.e. NTLM, tree connect).
*/
strlcpy(ctx->ct_srvname, ctx->ct_fullserver,
sizeof (ctx->ct_srvname));
/*
* Try to lookup the host address using the
* normal name-to-IP address mechanisms.
* If that fails, we MAY try NetBIOS.
*/
memset(&hints, 0, sizeof (hints));
hints.ai_flags = AI_CANONNAME;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
gaierr = getaddrinfo(srvaddr_str, smb_port, &hints, &res);
if (gaierr == 0) {
ctx->ct_addrinfo = res;
return (0);
}
/*
* If we really want to support NetBIOS, we should add
* an AF_NETBIOS entry to the address list here.
* For now, let's just skip NetBIOS.
* (Can we just kill NetBIOS? Please? :)
*/
#if 0 /* XXX Just kill NetBIOS? */
/*
* If regular IP name lookup failed, try NetBIOS,
* but only if given a valid NetBIOS name and if
* NetBIOS name lookup is enabled.
*/
if (nbc->nb_flags & NBCF_NS_ENABLE) {
int gaierr2 = nbns_getaddrinfo(ctx->ct_fullserver, nbc, &res);
if (gaierr2 == 0) {
if (res->ai_canonname)
strlcpy(ctx->ct_srvname,
res->ai_canonname,
sizeof (ctx->ct_srvname));
ctx->ct_addrinfo = res;
return (0);
}
}
#endif
/*
* Return the original error from getaddrinfo
*/
if (smb_verbose) {
smb_error(dgettext(TEXT_DOMAIN,
"getaddrinfo: %s: %s"), 0,
ctx->ct_fullserver,
gai_strerror(gaierr));
}
return (gaierr);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Client-side interface to the IO Daemon (IOD)
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <libintl.h>
#include <door.h>
#include <sys/byteorder.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netsmb/smb_lib.h>
#include <netsmb/netbios.h>
#include <netsmb/nb_lib.h>
#include <netsmb/smb_dev.h>
#include <assert.h>
#include "charsets.h"
#include "private.h"
/*
* This is constant for the life of a process,
* and initialized at startup, so no locks.
*/
static char door_path[64];
static int iod_start_timeout = 10; /* seconds */
char *
smb_iod_door_path(void)
{
uid_t uid;
int x;
if (door_path[0] == '\0') {
uid = getuid();
x = snprintf(door_path, sizeof (door_path),
SMBIOD_USR_DOOR, uid);
assert(x <= sizeof (door_path));
}
return (door_path);
}
/*
* Open the door (client side) and
* find out if the service is there.
*/
int
smb_iod_open_door(int *fdp)
{
door_arg_t da;
char *path;
int fd, rc;
int err = 0;
path = smb_iod_door_path();
fd = open(path, O_RDONLY, 0);
if (fd < 0)
return (errno);
/*
* Make sure the IOD is running.
* Pass NULL args.
*/
memset(&da, 0, sizeof (da));
da.rbuf = (void *) &err;
da.rsize = sizeof (err);
rc = door_call(fd, &da);
if (rc < 0) {
err = errno;
close(fd);
return (err);
}
if (err != 0) {
close(fd);
return (err);
}
/* This handle controls per-process resources. */
(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
*fdp = fd;
return (0);
}
/*
* Request the creation of our per-user smbiod
* via door call to the "main" IOD service.
*/
static int
start_iod(void)
{
const char *svc_door = SMBIOD_SVC_DOOR;
door_arg_t da;
int32_t cmd, err;
int fd, rc;
fd = open(svc_door, O_RDONLY, 0);
if (fd < 0) {
err = errno;
DPRINT("%s: open failed, err %d", svc_door, err);
return (err);
}
cmd = SMBIOD_START;
memset(&da, 0, sizeof (da));
da.data_ptr = (void *) &cmd;
da.data_size = sizeof (cmd);
da.rbuf = (void *) &err;
da.rsize = sizeof (err);
rc = door_call(fd, &da);
close(fd);
if (rc < 0) {
err = errno;
DPRINT("door_call, err %d", err);
return (err);
}
return (err);
}
/*
* Get a door handle to the IOD, starting it if necessary.
* On success, sets ctx->ct_door_fd
*/
int
smb_iod_start(smb_ctx_t *ctx)
{
int err, tmo;
int fd = -1;
tmo = iod_start_timeout;
while ((err = smb_iod_open_door(&fd)) != 0) {
if (--tmo <= 0)
goto errout;
/*
* We have no per-user IOD yet. Request one.
* Do this request every time through the loop
* because the master IOD will only start our
* per-user IOD if we don't have one, and our
* first requst could have happened while we
* had an IOD that was doing shutdown.
* (Prevents a shutdown/startup race).
*/
err = start_iod();
if (err != 0)
goto errout;
/*
* Wait for it to get ready.
*/
(void) sleep(1);
}
/* Save the door fd. */
if (ctx->ct_door_fd != -1)
close(ctx->ct_door_fd);
ctx->ct_door_fd = fd;
return (0);
errout:
smb_error(dgettext(TEXT_DOMAIN,
"Could not contact service: %s"),
0, "svc:/network/smb/client");
return (ENOTACTIVE);
}
/*
* Ask the IOD to connect using the info in ctx.
* Called by newvc.
*/
int
smb_iod_cl_newvc(smb_ctx_t *ctx)
{
door_arg_t da;
int err = 0;
/* Should already have the IOD door. */
if (ctx->ct_door_fd < 0)
return (EINVAL);
da.data_ptr = (void *) &ctx->ct_iod_ssn;
da.data_size = sizeof (ctx->ct_iod_ssn);
da.desc_ptr = NULL;
da.desc_num = 0;
da.rbuf = (void *) &err;
da.rsize = sizeof (err);
if (door_call(ctx->ct_door_fd, &da) < 0) {
err = errno;
DPRINT("door_call, err=%d", err);
}
return (err);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Functions called by the IO deamon (IOD).
* Here in the library to simplify testing.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <libintl.h>
#include <sys/byteorder.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include <netsmb/netbios.h>
#include <netsmb/nb_lib.h>
#include <netsmb/smb_dev.h>
#include "charsets.h"
#include "private.h"
/*
* The user agent (smbiod) calls smb_iod_connect for the first
* connection to some server, and if that succeeds, will start a
* thread running this function, passing the smb_ctx_t
*
* This thread now enters the driver and stays there, reading
* network responses as long as the connection is alive.
*/
int
smb_iod_work(smb_ctx_t *ctx)
{
smbioc_ssn_work_t *work = &ctx->ct_work;
int err = 0;
DPRINT("server: %s", ctx->ct_srvname);
/*
* This is the reader / reconnect loop.
*
* We could start with state "idle", but
* we know someone wants a connection to
* this server, so start in "vcactive".
*
* XXX: Add some syslog calls in here?
*/
for (;;) {
DPRINT("state: %s",
smb_iod_state_name(work->wk_out_state));
switch (work->wk_out_state) {
case SMBIOD_ST_IDLE:
/*
* Wait for driver requests to arrive
* for this VC, then return here.
* Next state is normally RECONNECT.
*/
DPRINT("Call _ioc_idle...");
if (nsmb_ioctl(ctx->ct_dev_fd,
SMBIOC_IOD_IDLE, work) == -1) {
err = errno;
DPRINT("ioc_idle: err %d", err);
goto out;
}
DPRINT("Ret. from _ioc_idle");
continue;
case SMBIOD_ST_RECONNECT:
DPRINT("Call _iod_connect...");
err = smb_iod_connect(ctx);
if (err == 0)
continue;
DPRINT("iod_connect: err %d", err);
/*
* If the error was EAUTH, retry is
* not likely to succeed either, so
* just exit this thread. The user
* will need to run smbutil to get
* a new thread with new auth info.
*/
if (err == EAUTH) {
DPRINT("iod_connect: EAUTH (give up)");
goto out;
}
/*
* Reconnect failed. Notify any requests
* that we're not connected, and delay.
* Next state will be IDLE or RECONNECT.
*/
DPRINT("Call _iod_rcfail...");
if (nsmb_ioctl(ctx->ct_dev_fd,
SMBIOC_IOD_RCFAIL, work) == -1) {
err = errno;
DPRINT("iod_rcfail: err %d", err);
goto out;
}
continue;
case SMBIOD_ST_AUTHOK:
/*
* This is where we enter the driver and
* stay there. While the connection is up
* the VC will have SMBIOD_ST_VCACTIVE
*/
DPRINT("Call _iod_work...");
if (nsmb_ioctl(ctx->ct_dev_fd,
SMBIOC_IOD_WORK, work) == -1) {
err = errno;
DPRINT("iod_work: err %d", err);
goto out;
}
DPRINT("Ret. from _ioc_work");
continue;
case SMBIOD_ST_DEAD:
DPRINT("got state=DEAD");
err = 0;
goto out;
default:
DPRINT("Unexpected state: %d (%s)",
work->wk_out_state,
smb_iod_state_name(work->wk_out_state));
err = EFAULT;
goto out;
}
}
out:
if (ctx->ct_dev_fd != -1) {
nsmb_close(ctx->ct_dev_fd);
ctx->ct_dev_fd = -1;
}
return (err);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2017 Nexenta Systems, Inc. All rights reserved.
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* External interface to the libsmbfs/netsmb keychain
* storage mechanism. This interface is consumed by
* the "smbutil" commands: login, logout, ...
* and by the SMBFS PAM module.
*/
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libintl.h>
#include <cflib.h>
#include <netsmb/smb_dev.h>
#include <netsmb/smb_lib.h>
#include <netsmb/smb_keychain.h>
#include "charsets.h"
#include "private.h"
#include "ntlm.h"
/* common func. for add/del/chk */
static int
smbfs_keychain_cmn(
int cmd,
uid_t uid,
const char *dom,
const char *usr,
uchar_t *lmhash,
uchar_t *nthash)
{
smbioc_pk_t pk;
int err, fd, sz;
memset(&pk, 0, sizeof (pk));
pk.pk_uid = uid;
err = 0;
fd = -1;
switch (cmd) {
case SMBIOC_PK_ADD:
/*
* Add password hashes to the keychain.
*/
if (lmhash == NULL || nthash == NULL) {
err = SMB_KEYCHAIN_BADPASSWD;
goto out;
}
memcpy(pk.pk_lmhash, lmhash, SMBIOC_HASH_SZ);
memcpy(pk.pk_nthash, nthash, SMBIOC_HASH_SZ);
/* FALLTHROUGH */
case SMBIOC_PK_CHK:
case SMBIOC_PK_DEL:
/*
* Copy domain and user.
*/
if (dom == NULL) {
err = SMB_KEYCHAIN_BADDOMAIN;
goto out;
}
sz = sizeof (pk.pk_dom);
if (strlcpy(pk.pk_dom, dom, sz) >= sz) {
err = SMB_KEYCHAIN_BADDOMAIN;
goto out;
}
if (usr == NULL) {
err = SMB_KEYCHAIN_BADUSER;
goto out;
}
sz = sizeof (pk.pk_usr);
if (strlcpy(pk.pk_usr, usr, sz) >= sz) {
err = SMB_KEYCHAIN_BADUSER;
goto out;
}
break;
case SMBIOC_PK_DEL_OWNER: /* all owned by the caller */
case SMBIOC_PK_DEL_EVERYONE: /* all owned by everyone */
/*
* These two do not copyin any args, but we'll
* pass pk here anyway just so we can use the
* common code path below.
*/
break;
default:
err = SMB_KEYCHAIN_UNKNOWN;
goto out;
}
fd = smb_open_driver();
if (fd < 0) {
err = SMB_KEYCHAIN_NODRIVER;
goto out;
}
err = 0;
if (nsmb_ioctl(fd, cmd, &pk) < 0) {
err = errno;
goto out;
}
if (cmd == SMBIOC_PK_CHK) {
if (lmhash != NULL)
memcpy(lmhash, pk.pk_lmhash, SMBIOC_HASH_SZ);
if (nthash != NULL)
memcpy(nthash, pk.pk_nthash, SMBIOC_HASH_SZ);
}
out:
if (fd != -1)
nsmb_close(fd);
return (err);
}
/*
* Add a password to the keychain.
*
* Note: pass is a cleartext password.
* We use it here to compute the LM hash and NT hash,
* and then store ONLY the hashes.
*/
int
smbfs_keychain_add(uid_t uid, const char *dom, const char *usr,
const char *pass)
{
uchar_t lmhash[SMBIOC_HASH_SZ];
uchar_t nthash[SMBIOC_HASH_SZ];
int err, cmd = SMBIOC_PK_ADD;
if (pass == NULL)
return (SMB_KEYCHAIN_BADPASSWD);
if ((err = ntlm_compute_lm_hash(lmhash, pass)) != 0)
return (err);
if ((err = ntlm_compute_nt_hash(nthash, pass)) != 0)
return (err);
err = smbfs_keychain_cmn(cmd, uid, dom, usr, lmhash, nthash);
return (err);
}
/* Variant of the above that takes an NT hash. */
int
smbfs_keychain_addhash(uid_t uid, const char *dom, const char *usr,
const uchar_t *nthash)
{
static const uchar_t lmhash[SMBIOC_HASH_SZ] = { 0 };
int err, cmd = SMBIOC_PK_ADD;
err = smbfs_keychain_cmn(cmd, uid, dom, usr,
(uchar_t *)lmhash, (uchar_t *)nthash);
return (err);
}
/* Delete a password from the keychain. */
int
smbfs_keychain_del(uid_t uid, const char *dom, const char *usr)
{
return (smbfs_keychain_cmn(SMBIOC_PK_DEL, uid, dom, usr, NULL, NULL));
}
/*
* Check for existence of a keychain entry.
* Returns 0 if it exists, else ENOENT.
*/
int
smbfs_keychain_chk(const char *dom, const char *usr)
{
uid_t uid = (uid_t)-1;
return (smbfs_keychain_cmn(SMBIOC_PK_CHK, uid, dom, usr, NULL, NULL));
}
/*
* Get the stored hashes
*/
int
smbfs_keychain_get(const char *dom, const char *usr,
uchar_t *lmhash, uchar_t *nthash)
{
uid_t uid = (uid_t)-1;
int err, cmd = SMBIOC_PK_CHK;
err = smbfs_keychain_cmn(cmd, uid, dom, usr, lmhash, nthash);
return (err);
}
/*
* Delete all keychain entries owned by the caller.
*/
int
smbfs_keychain_del_owner()
{
int cmd = SMBIOC_PK_DEL_OWNER;
uid_t uid = getuid();
return (smbfs_keychain_cmn(cmd, uid, NULL, NULL, NULL, NULL));
}
/*
* Delete all keychain entries (regardless of onwer).
* Requires super-user privliege.
*/
int
smbfs_keychain_del_everyone()
{
int cmd = SMBIOC_PK_DEL_EVERYONE;
uid_t uid = getuid();
return (smbfs_keychain_cmn(cmd, uid, NULL, NULL, NULL, NULL));
}
/*
* Private function to get keychain p/w hashes.
*/
int
smb_get_keychain(struct smb_ctx *ctx)
{
int err;
if (ctx->ct_fullserver == NULL) {
DPRINT("ct_fullserver == NULL");
return (EINVAL);
}
/*
* 1st: try lookup using system name
*/
err = smbfs_keychain_get(ctx->ct_fullserver, ctx->ct_user,
ctx->ct_lmhash, ctx->ct_nthash);
if (!err) {
ctx->ct_flags |= SMBCF_KCFOUND;
DPRINT("found keychain entry for"
" server/user: %s/%s\n",
ctx->ct_fullserver, ctx->ct_user);
return (0);
}
/*
* 2nd: try lookup using domain name
*/
err = smbfs_keychain_get(ctx->ct_domain, ctx->ct_user,
ctx->ct_lmhash, ctx->ct_nthash);
if (!err) {
ctx->ct_flags |= (SMBCF_KCFOUND | SMBCF_KCDOMAIN);
DPRINT("found keychain entry for"
" domain/user: %s/%s\n",
ctx->ct_domain, ctx->ct_user);
return (0);
}
return (err);
}
/*
* This is not really part of the keychain library,
* but is typically needed in code that wants to
* provide (editable) defaults for domain/user
*
* Get default domain and user names
* Server name is optional.
*/
int
smbfs_default_dom_usr(const char *home, const char *server,
char *dom, int maxdom, char *usr, int maxusr)
{
struct smb_ctx *ctx;
int err;
err = smb_ctx_alloc(&ctx);
if (err)
return (err);
if (server) {
err = smb_ctx_setfullserver(ctx, server);
if (err != 0)
goto out;
}
if (home && *home) {
if (ctx->ct_home)
free(ctx->ct_home);
ctx->ct_home = strdup(home);
}
err = smb_ctx_readrc(ctx);
if (err)
goto out;
if (dom)
strlcpy(dom, ctx->ct_domain, maxdom);
if (usr)
strlcpy(usr, ctx->ct_user, maxusr);
out:
smb_ctx_free(ctx);
return (err);
}
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Kerberos V Security Support Provider
*
* Based on code previously in ctx.c (from Boris Popov?)
* but then mostly rewritten at Sun.
*/
#include <errno.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <netdb.h>
#include <libintl.h>
#include <xti.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/byteorder.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include <netsmb/mchain.h>
#include "private.h"
#include "charsets.h"
#include "spnego.h"
#include "derparse.h"
#include "ssp.h"
#include <kerberosv5/krb5.h>
#include <kerberosv5/com_err.h>
#include <gssapi/gssapi.h>
#include <gssapi/mechs/krb5/include/auth_con.h>
/* RFC 4121 checksum type ID. */
#define CKSUM_TYPE_RFC4121 0x8003
/* RFC 1964 token ID codes */
#define KRB_AP_REQ 1
#define KRB_AP_REP 2
#define KRB_ERROR 3
extern MECH_OID g_stcMechOIDList [];
typedef struct krb5ssp_state {
/* Filled in by krb5ssp_init_client */
krb5_context ss_krb5ctx; /* krb5 context (ptr) */
krb5_ccache ss_krb5cc; /* credentials cache (ptr) */
krb5_principal ss_krb5clp; /* client principal (ptr) */
/* Filled in by krb5ssp_get_tkt */
krb5_auth_context ss_auth; /* auth ctx. w/ server (ptr) */
} krb5ssp_state_t;
/*
* adds a GSSAPI wrapper
*/
int
krb5ssp_tkt2gtok(uchar_t *tkt, ulong_t tktlen,
uchar_t **gtokp, ulong_t *gtoklenp)
{
ulong_t len;
ulong_t bloblen = tktlen;
uchar_t krbapreq[2] = { KRB_AP_REQ, 0 };
uchar_t *blob = NULL; /* result */
uchar_t *b;
bloblen += sizeof (krbapreq);
bloblen += g_stcMechOIDList[spnego_mech_oid_Kerberos_V5].iLen;
len = bloblen;
bloblen = ASNDerCalcTokenLength(bloblen, bloblen);
if ((blob = malloc(bloblen)) == NULL) {
DPRINT("malloc");
return (ENOMEM);
}
b = blob;
b += ASNDerWriteToken(b, SPNEGO_NEGINIT_APP_CONSTRUCT, NULL, len);
b += ASNDerWriteOID(b, spnego_mech_oid_Kerberos_V5);
memcpy(b, krbapreq, sizeof (krbapreq));
b += sizeof (krbapreq);
assert(b + tktlen == blob + bloblen);
memcpy(b, tkt, tktlen);
*gtoklenp = bloblen;
*gtokp = blob;
return (0);
}
/*
* See "Windows 2000 Kerberos Interoperability" paper by
* Christopher Nebergall. RC4 HMAC is the W2K default but
* Samba support lagged (not due to Samba itself, but due to OS'
* Kerberos implementations.)
*
* Only session enc type should matter, not ticket enc type,
* per Sam Hartman on krbdev.
*
* Preauthentication failure topics in krb-protocol may help here...
* try "John Brezak" and/or "Clifford Neuman" too.
*/
static krb5_enctype kenctypes[] = {
ENCTYPE_ARCFOUR_HMAC, /* defined in krb5.h */
ENCTYPE_DES_CBC_MD5,
ENCTYPE_DES_CBC_CRC,
ENCTYPE_NULL
};
static const int rq_opts =
AP_OPTS_USE_SUBKEY | AP_OPTS_MUTUAL_REQUIRED;
/*
* Obtain a kerberos ticket for the host we're connecting to.
* (This does the KRB_TGS exchange.)
*/
static int
krb5ssp_get_tkt(krb5ssp_state_t *ss, char *server,
uchar_t **tktp, ulong_t *tktlenp)
{
krb5_context kctx = ss->ss_krb5ctx;
krb5_ccache kcc = ss->ss_krb5cc;
krb5_data indata = {0};
krb5_data outdata = {0};
krb5_error_code kerr = 0;
const char *fn = NULL;
uchar_t *tkt;
/* Should have these from krb5ssp_init_client. */
if (kctx == NULL || kcc == NULL) {
fn = "null kctx or kcc";
kerr = EINVAL;
goto out;
}
kerr = krb5_set_default_tgs_enctypes(kctx, kenctypes);
if (kerr != 0) {
fn = "krb5_set_default_tgs_enctypes";
goto out;
}
/* Get ss_auth now so we can set req_chsumtype. */
kerr = krb5_auth_con_init(kctx, &ss->ss_auth);
if (kerr != 0) {
fn = "krb5_auth_con_init";
goto out;
}
/* Missing krb5_auth_con_set_req_cksumtype(), so inline. */
ss->ss_auth->req_cksumtype = CKSUM_TYPE_RFC4121;
/*
* Build an RFC 4121 "checksum" with NULL channel bindings,
* like make_gss_checksum(). Numbers here from the RFC.
*/
indata.length = 24;
if ((indata.data = calloc(1, indata.length)) == NULL) {
kerr = ENOMEM;
fn = "malloc checksum";
goto out;
}
indata.data[0] = 16; /* length of "Bnd" field. */
indata.data[20] = GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG;
/* Done building the "checksum". */
kerr = krb5_mk_req(kctx, &ss->ss_auth, rq_opts, "cifs", server,
&indata, kcc, &outdata);
if (kerr != 0) {
fn = "krb5_mk_req";
goto out;
}
if ((tkt = malloc(outdata.length)) == NULL) {
kerr = ENOMEM;
fn = "malloc signing key";
goto out;
}
memcpy(tkt, outdata.data, outdata.length);
*tktp = tkt;
*tktlenp = outdata.length;
kerr = 0;
out:
if (kerr) {
if (fn == NULL)
fn = "?";
DPRINT("%s err 0x%x: %s", fn, kerr, error_message(kerr));
if (kerr <= 0 || kerr > ESTALE)
kerr = EAUTH;
}
if (outdata.data)
krb5_free_data_contents(kctx, &outdata);
if (indata.data)
free(indata.data);
/* Free kctx in krb5ssp_destroy */
return (kerr);
}
/*
* Build an RFC 1964 KRB_AP_REQ message
* The caller puts on the SPNEGO wrapper.
*/
int
krb5ssp_put_request(struct ssp_ctx *sp, struct mbdata *out_mb)
{
int err;
struct smb_ctx *ctx = sp->smb_ctx;
krb5ssp_state_t *ss = sp->sp_private;
uchar_t *tkt = NULL;
ulong_t tktlen;
uchar_t *gtok = NULL; /* gssapi token */
ulong_t gtoklen; /* gssapi token length */
char *prin = ctx->ct_srvname;
if ((err = krb5ssp_get_tkt(ss, prin, &tkt, &tktlen)) != 0)
goto out;
if ((err = krb5ssp_tkt2gtok(tkt, tktlen, >ok, >oklen)) != 0)
goto out;
if ((err = mb_init_sz(out_mb, gtoklen)) != 0)
goto out;
if ((err = mb_put_mem(out_mb, gtok, gtoklen, MB_MSYSTEM)) != 0)
goto out;
out:
if (gtok)
free(gtok);
if (tkt)
free(tkt);
return (err);
}
/*
* Unwrap a GSS-API encapsulated RFC 1964 reply message,
* i.e. type KRB_AP_REP or KRB_ERROR.
*/
int
krb5ssp_get_reply(struct ssp_ctx *sp, struct mbdata *in_mb)
{
krb5ssp_state_t *ss = sp->sp_private;
mbuf_t *m = in_mb->mb_top;
int err = EBADRPC;
int dlen, rc;
long actual_len, token_len;
uchar_t *data;
krb5_data ap = {0};
krb5_ap_rep_enc_part *reply = NULL;
/* cheating: this mbuf is contiguous */
assert(m->m_data == in_mb->mb_pos);
data = (uchar_t *)m->m_data;
dlen = m->m_len;
/*
* Peel off the GSS-API wrapper. Looks like:
* AppToken: 60 81 83
* OID(KRB5): 06 09 2a 86 48 86 f7 12 01 02 02
* KRB_AP_REP: 02 00
*/
rc = ASNDerCheckToken(data, SPNEGO_NEGINIT_APP_CONSTRUCT,
0, dlen, &token_len, &actual_len);
if (rc != SPNEGO_E_SUCCESS) {
DPRINT("no AppToken? rc=0x%x", rc);
goto out;
}
if (dlen < actual_len)
goto out;
data += actual_len;
dlen -= actual_len;
/* OID (KRB5) */
rc = ASNDerCheckOID(data, spnego_mech_oid_Kerberos_V5,
dlen, &actual_len);
if (rc != SPNEGO_E_SUCCESS) {
DPRINT("no OID? rc=0x%x", rc);
goto out;
}
if (dlen < actual_len)
goto out;
data += actual_len;
dlen -= actual_len;
/* KRB_AP_REP or KRB_ERROR */
if (data[0] != KRB_AP_REP) {
DPRINT("KRB5 type: %d", data[1]);
goto out;
}
if (dlen < 2)
goto out;
data += 2;
dlen -= 2;
/*
* Now what's left should be a krb5 reply
* NB: ap is NOT allocated, so don't free it.
*/
ap.length = dlen;
ap.data = (char *)data;
rc = krb5_rd_rep(ss->ss_krb5ctx, ss->ss_auth, &ap, &reply);
if (rc != 0) {
DPRINT("krb5_rd_rep: err 0x%x (%s)",
rc, error_message(rc));
err = EAUTH;
goto out;
}
/*
* Have the decoded reply. Save anything?
*
* NB: If this returns an error, we will get
* no more calls into this back-end module.
*/
err = 0;
out:
if (reply != NULL)
krb5_free_ap_rep_enc_part(ss->ss_krb5ctx, reply);
if (err)
DPRINT("ret %d", err);
return (err);
}
/*
* krb5ssp_final
*
* Called after successful authentication.
* Setup the MAC key for signing.
*/
int
krb5ssp_final(struct ssp_ctx *sp)
{
struct smb_ctx *ctx = sp->smb_ctx;
krb5ssp_state_t *ss = sp->sp_private;
krb5_keyblock *ssn_key = NULL;
int err;
/*
* Save the session key, used for SMB signing
* and possibly other consumers (RPC).
*/
err = krb5_auth_con_getlocalsubkey(
ss->ss_krb5ctx, ss->ss_auth, &ssn_key);
if (err != 0) {
DPRINT("_getlocalsubkey, err=0x%x (%s)",
err, error_message(err));
if (err <= 0 || err > ESTALE)
err = EAUTH;
goto out;
}
/* Sanity check the length */
if (ssn_key->length > 1024) {
DPRINT("session key too long");
err = EAUTH;
goto out;
}
/*
* Update/save the session key.
*/
if (ctx->ct_ssnkey_buf != NULL) {
free(ctx->ct_ssnkey_buf);
ctx->ct_ssnkey_buf = NULL;
}
ctx->ct_ssnkey_buf = malloc(ssn_key->length);
if (ctx->ct_ssnkey_buf == NULL) {
err = ENOMEM;
goto out;
}
ctx->ct_ssnkey_len = ssn_key->length;
memcpy(ctx->ct_ssnkey_buf, ssn_key->contents, ctx->ct_ssnkey_len);
err = 0;
out:
if (ssn_key != NULL)
krb5_free_keyblock(ss->ss_krb5ctx, ssn_key);
return (err);
}
/*
* krb5ssp_next_token
*
* See ssp.c: ssp_ctx_next_token
*/
int
krb5ssp_next_token(struct ssp_ctx *sp, struct mbdata *in_mb,
struct mbdata *out_mb)
{
int err;
/*
* Note: in_mb == NULL on the first call.
*/
if (in_mb) {
err = krb5ssp_get_reply(sp, in_mb);
if (err)
goto out;
}
if (out_mb) {
err = krb5ssp_put_request(sp, out_mb);
} else
err = krb5ssp_final(sp);
out:
if (err)
DPRINT("ret: %d", err);
return (err);
}
/*
* krb5ssp_ctx_destroy
*
* Destroy mechanism-specific data.
*/
void
krb5ssp_destroy(struct ssp_ctx *sp)
{
krb5ssp_state_t *ss;
krb5_context kctx;
ss = sp->sp_private;
if (ss == NULL)
return;
sp->sp_private = NULL;
if ((kctx = ss->ss_krb5ctx) != NULL) {
/* from krb5ssp_get_tkt */
if (ss->ss_auth)
(void) krb5_auth_con_free(kctx, ss->ss_auth);
/* from krb5ssp_init_client */
if (ss->ss_krb5clp)
krb5_free_principal(kctx, ss->ss_krb5clp);
if (ss->ss_krb5cc)
(void) krb5_cc_close(kctx, ss->ss_krb5cc);
krb5_free_context(kctx);
}
free(ss);
}
/*
* krb5ssp_init_clnt
*
* Initialize a new Kerberos SSP client context.
*
* The user must already have a TGT in their credential cache,
* as shown by the "klist" command.
*/
int
krb5ssp_init_client(struct ssp_ctx *sp)
{
krb5ssp_state_t *ss;
krb5_error_code kerr;
krb5_context kctx = NULL;
krb5_ccache kcc = NULL;
krb5_principal kprin = NULL;
if ((sp->smb_ctx->ct_authflags & SMB_AT_KRB5) == 0) {
DPRINT("KRB5 not in authflags");
return (ENOTSUP);
}
ss = calloc(1, sizeof (*ss));
if (ss == NULL)
return (ENOMEM);
sp->sp_nexttok = krb5ssp_next_token;
sp->sp_destroy = krb5ssp_destroy;
sp->sp_private = ss;
kerr = krb5_init_context(&kctx);
if (kerr) {
DPRINT("krb5_init_context, kerr 0x%x", kerr);
goto errout;
}
ss->ss_krb5ctx = kctx;
/* non-default would instead use krb5_cc_resolve */
kerr = krb5_cc_default(kctx, &kcc);
if (kerr) {
DPRINT("krb5_cc_default, kerr 0x%x", kerr);
goto errout;
}
ss->ss_krb5cc = kcc;
/*
* Get the client principal (ticket),
* or discover that we don't have one.
*/
kerr = krb5_cc_get_principal(kctx, kcc, &kprin);
if (kerr) {
DPRINT("krb5_cc_get_principal, kerr 0x%x", kerr);
goto errout;
}
ss->ss_krb5clp = kprin;
/* Success! */
DPRINT("Ticket cache: %s:%s",
krb5_cc_get_type(kctx, kcc),
krb5_cc_get_name(kctx, kcc));
return (0);
errout:
krb5ssp_destroy(sp);
return (ENOTSUP);
}
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2018 Nexenta Systems, Inc. All rights reserved.
#
#
# MAPFILE HEADER START
#
# WARNING: STOP NOW. DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
# usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#
#
# Note that several things in here are NODIRECT so that the
# "fksmbcl" development tool can provide its own versions.
#
$mapfile_version 2
SYMBOL_VERSION SUNWprivate {
global:
convert_leunicode_to_utf8;
convert_unicode_to_utf8;
convert_utf8_to_leunicode;
convert_utf8_to_unicode;
convert_utf8_to_wincs;
convert_wincs_to_utf8;
nb_ctx_create;
nb_ctx_done;
nb_ctx_readrcsection;
nb_ctx_resolve;
nb_ctx_setns;
nb_resolvehost_in;
nb_strerror;
nbns_getnodestatus;
nbns_resolvename;
nls_str_toloc;
nls_str_upper;
nsmb_close { FLAGS = NODIRECT; };
nsmb_ioctl { FLAGS = NODIRECT; };
smb_cf_minauth_from_str;
smb_cf_version_from_str;
smb_close_rcfile;
smb_ctx_alloc;
smb_ctx_done;
smb_ctx_findvc;
smb_ctx_flags2;
smb_ctx_free;
smb_ctx_get_ssn;
smb_ctx_get_tree;
smb_ctx_gethandle;
smb_ctx_init;
smb_ctx_kill;
smb_ctx_newvc { FLAGS = NODIRECT; };
smb_ctx_opt;
smb_ctx_parseunc;
smb_ctx_readrc;
smb_ctx_resolve;
smb_ctx_scan_argv;
smb_ctx_set_close_hook;
smb_ctx_setauthflags;
smb_ctx_setdomain;
smb_ctx_setfullserver;
smb_ctx_setminver;
smb_ctx_setmaxver;
smb_ctx_setnbflags;
smb_ctx_setpassword;
smb_ctx_setpwhash;
smb_ctx_setscope;
smb_ctx_setserver;
smb_ctx_setshare;
smb_ctx_setsigning;
smb_ctx_setsrvaddr;
smb_ctx_setuser;
smb_ctx_setwins;
smb_debug {
ASSERT = {
TYPE = OBJECT;
SIZE = 4;
};
FLAGS = NODIRECT;
};
smb_error;
#
# Functions to support named pipes
smb_fh_close;
smb_fh_getssnkey;
smb_fh_open;
smb_fh_read;
smb_fh_write;
smb_fh_xactnp;
#
smb_get_authentication;
smb_getprogname;
smb_iod_connect;
smb_iod_door_path;
smb_iod_open_door { FLAGS = NODIRECT; };
smb_iod_start { FLAGS = NODIRECT; };
smb_iod_work;
smb_lib_init;
smb_open_driver { FLAGS = NODIRECT; };
smb_open_printer;
smb_open_rcfile;
smb_simplecrypt;
smb_simpledecrypt;
smb_strerror;
smb_verbose {
ASSERT = {
TYPE = OBJECT;
SIZE = 4;
};
FLAGS = NODIRECT;
};
#
# Functions to support Access Control Lists (ACLs)
smbfs_acl_free_sd;
smbfs_acl_get;
smbfs_acl_getsd;
smbfs_acl_print_sd;
smbfs_acl_sd2zfs;
smbfs_acl_set;
smbfs_acl_setsd;
smbfs_acl_zfs2sd;
#
smbfs_default_dom_usr;
smbfs_keychain_add;
smbfs_keychain_addhash;
smbfs_keychain_chk;
smbfs_keychain_del;
smbfs_keychain_del_everyone;
smbfs_keychain_del_owner;
smbfs_set_default_domain;
smbfs_set_default_user;
smbutil_std_opts {
ASSERT = {
TYPE = OBJECT;
SIZE = 29;
};
};
spnegoCreateNegTokenHint;
spnegoCreateNegTokenInit;
spnegoCreateNegTokenTarg;
spnegoFreeData;
spnegoGetContextFlags;
spnegoGetMechListMIC;
spnegoGetMechToken;
spnegoGetNegotiationResult;
spnegoGetSupportedMechType;
spnegoGetTokenType;
spnegoInitFromBinary;
spnegoIsMechTypeAvailable;
spnegoTokenGetBinary;
local:
*;
};
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: mbuf.c,v 1.3 2004/12/13 00:25:22 lindak Exp $
*/
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
*/
#include <sys/types.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <libintl.h>
#include <assert.h>
#include <netsmb/smb_lib.h>
#include <netsmb/mchain.h>
#include "private.h"
#include "charsets.h"
/*
* Note: Leaving a little space (8 bytes) between the
* mbuf header and the start of the data so we can
* prepend a NetBIOS header in that space.
*/
#define M_ALIGNFACTOR (sizeof (long))
#define M_ALIGN(len) (((len) + M_ALIGNFACTOR - 1) & ~(M_ALIGNFACTOR - 1))
#define M_BASESIZE (sizeof (struct mbuf) + 8)
#define M_MINSIZE (1024 - M_BASESIZE)
#define M_TOP(m) ((char *)(m) + M_BASESIZE)
#define M_TRAILINGSPACE(m) ((m)->m_maxlen - (m)->m_len)
int
m_get(int len, struct mbuf **mpp)
{
struct mbuf *m;
assert(len < 0x100000); /* sanity */
len = M_ALIGN(len);
if (len < M_MINSIZE)
len = M_MINSIZE;
m = malloc(M_BASESIZE + len);
if (m == NULL)
return (ENOMEM);
bzero(m, M_BASESIZE + len);
m->m_maxlen = len;
m->m_data = M_TOP(m);
*mpp = m;
return (0);
}
static void
m_free(struct mbuf *m)
{
free(m);
}
void
m_freem(struct mbuf *m0)
{
struct mbuf *m;
while (m0) {
m = m0->m_next;
m_free(m0);
m0 = m;
}
}
size_t
m_totlen(struct mbuf *m0)
{
struct mbuf *m = m0;
int len = 0;
while (m) {
len += m->m_len;
m = m->m_next;
}
return (len);
}
int
m_lineup(struct mbuf *m0, struct mbuf **mpp)
{
struct mbuf *nm, *m;
char *dp;
size_t len, totlen;
int error;
if (m0->m_next == NULL) {
*mpp = m0;
return (0);
}
totlen = m_totlen(m0);
if ((error = m_get(totlen, &nm)) != 0)
return (error);
dp = mtod(nm, char *);
while (m0) {
len = m0->m_len;
bcopy(m0->m_data, dp, len);
dp += len;
m = m0->m_next;
m_free(m0);
m0 = m;
}
nm->m_len = totlen;
*mpp = nm;
return (0);
}
int
mb_init(struct mbdata *mbp)
{
return (mb_init_sz(mbp, M_MINSIZE));
}
int
mb_init_sz(struct mbdata *mbp, int size)
{
struct mbuf *m;
int error;
if ((error = m_get(size, &m)) != 0)
return (error);
mb_initm(mbp, m);
return (0);
}
void
mb_initm(struct mbdata *mbp, struct mbuf *m)
{
bzero(mbp, sizeof (*mbp));
mbp->mb_top = mbp->mb_cur = m;
mbp->mb_pos = mtod(m, char *);
}
void
mb_done(struct mbdata *mbp)
{
if (mbp->mb_top) {
m_freem(mbp->mb_top);
mbp->mb_top = NULL;
}
}
int
m_getm(struct mbuf *top, int len, struct mbuf **mpp)
{
struct mbuf *m, *mp;
int error, ts;
for (mp = top; ; mp = mp->m_next) {
ts = M_TRAILINGSPACE(mp);
if (len <= ts)
goto out;
len -= ts;
if (mp->m_next == NULL)
break;
}
if (len > 0) {
if ((error = m_get(len, &m)) != 0)
return (error);
mp->m_next = m;
}
out:
*mpp = top;
return (0);
}
/*
* Routines to put data in a buffer
*/
void *
mb_reserve(mbchain_t *mbp, int size)
{
char *p;
if (mb_fit(mbp, size, &p) != 0)
return (NULL);
return (p);
}
/*
* Check if object of size 'size' fit to the current position and
* allocate new mbuf if not. Advance pointers and increase length of mbuf(s).
* Return pointer to the object placeholder or NULL if any error occured.
*/
int
mb_fit(mbchain_t *mbp, int size, char **pp)
{
struct mbuf *m, *mn;
int error;
m = mbp->mb_cur;
if (M_TRAILINGSPACE(m) < (int)size) {
if ((error = m_get(size, &mn)) != 0)
return (error);
mbp->mb_pos = mtod(mn, char *);
mbp->mb_cur = m->m_next = mn;
m = mn;
}
m->m_len += size;
*pp = mbp->mb_pos;
mbp->mb_pos += size;
mbp->mb_count += size;
return (0);
}
int
mb_put_uint8(mbchain_t *mbp, uint8_t x)
{
uint8_t y = x;
return (mb_put_mem(mbp, &y, sizeof (y), MB_MINLINE));
}
int
mb_put_uint16be(mbchain_t *mbp, uint16_t x)
{
uint16_t y = htobes(x);
return (mb_put_mem(mbp, &y, sizeof (y), MB_MINLINE));
}
int
mb_put_uint16le(mbchain_t *mbp, uint16_t x)
{
uint16_t y = htoles(x);
return (mb_put_mem(mbp, &y, sizeof (y), MB_MINLINE));
}
int
mb_put_uint32be(mbchain_t *mbp, uint32_t x)
{
uint32_t y = htobel(x);
return (mb_put_mem(mbp, &y, sizeof (y), MB_MINLINE));
}
int
mb_put_uint32le(mbchain_t *mbp, uint32_t x)
{
uint32_t y = htolel(x);
return (mb_put_mem(mbp, &y, sizeof (y), MB_MINLINE));
}
int
mb_put_uint64be(mbchain_t *mbp, uint64_t x)
{
uint64_t y = htobeq(x);
return (mb_put_mem(mbp, &y, sizeof (y), MB_MINLINE));
}
int
mb_put_uint64le(mbchain_t *mbp, uint64_t x)
{
uint64_t y = htoleq(x);
return (mb_put_mem(mbp, &y, sizeof (y), MB_MINLINE));
}
/* ARGSUSED */
int
mb_put_mem(mbchain_t *mbp, const void *vmem, int size, int type)
{
struct mbuf *m;
const char *src;
char *dst;
size_t cplen;
int error;
if (size == 0)
return (0);
src = vmem;
m = mbp->mb_cur;
if ((error = m_getm(m, size, &m)) != 0)
return (error);
while (size > 0) {
cplen = M_TRAILINGSPACE(m);
if (cplen == 0) {
m = m->m_next;
continue;
}
if (cplen > size)
cplen = size;
dst = mtod(m, char *) + m->m_len;
if (src) {
bcopy(src, dst, cplen);
src += cplen;
} else
bzero(dst, cplen);
size -= cplen;
m->m_len += cplen;
mbp->mb_count += cplen;
}
mbp->mb_pos = mtod(m, char *) + m->m_len;
mbp->mb_cur = m;
return (0);
}
/*
* Append another mbuf to the mbuf chain.
* If what we're appending is smaller than
* the current trailing space, just copy.
* This always consumes the passed mbuf.
*/
int
mb_put_mbuf(mbchain_t *mbp, struct mbuf *m)
{
struct mbuf *cm = mbp->mb_cur;
int ts = M_TRAILINGSPACE(cm);
if (m->m_next == NULL && m->m_len <= ts) {
/* just copy */
mb_put_mem(mbp, m->m_data, m->m_len, MB_MSYSTEM);
m_freem(m);
return (0);
}
cm->m_next = m;
while (m) {
mbp->mb_count += m->m_len;
if (m->m_next == NULL)
break;
m = m->m_next;
}
mbp->mb_pos = mtod(m, char *) + m->m_len;
mbp->mb_cur = m;
return (0);
}
/*
* Convenience function to put an OEM or Unicode string,
* null terminated, and aligned if necessary.
*/
int
mb_put_string(mbchain_t *mbp, const char *s, int uc)
{
int err;
if (uc) {
/* Put Unicode. align(2) first. */
if (mbp->mb_count & 1)
mb_put_uint8(mbp, 0);
err = mb_put_ustring(mbp, s);
} else {
/* Put ASCII (really OEM) */
err = mb_put_astring(mbp, s);
}
return (err);
}
/*
* Put an ASCII string (really OEM), given a UTF-8 string.
*/
int
mb_put_astring(mbchain_t *mbp, const char *s)
{
char *abuf;
int err, len;
abuf = convert_utf8_to_wincs(s);
if (abuf == NULL)
return (ENOMEM);
len = strlen(abuf) + 1;
err = mb_put_mem(mbp, abuf, len, MB_MSYSTEM);
free(abuf);
return (err);
}
/*
* Put UCS-2LE, given a UTF-8 string.
*/
int
mb_put_ustring(mbchain_t *mbp, const char *s)
{
uint16_t *ubuf;
int err, len;
ubuf = convert_utf8_to_leunicode(s);
if (ubuf == NULL)
return (ENOMEM);
len = 2 * (unicode_strlen(ubuf) + 1);
err = mb_put_mem(mbp, ubuf, len, MB_MSYSTEM);
free(ubuf);
return (err);
}
/*
* Routines for fetching data from an mbuf chain
*/
#define mb_left(m, p) (mtod(m, char *) + (m)->m_len - (p))
int
md_get_uint8(mdchain_t *mbp, uint8_t *x)
{
return (md_get_mem(mbp, x, 1, MB_MINLINE));
}
int
md_get_uint16le(mdchain_t *mbp, uint16_t *x)
{
uint16_t v;
int err;
if ((err = md_get_mem(mbp, &v, sizeof (v), MB_MINLINE)) != 0)
return (err);
if (x != NULL)
*x = letohs(v);
return (0);
}
int
md_get_uint16be(mdchain_t *mbp, uint16_t *x) {
uint16_t v;
int err;
if ((err = md_get_mem(mbp, &v, sizeof (v), MB_MINLINE)) != 0)
return (err);
if (x != NULL)
*x = betohs(v);
return (0);
}
int
md_get_uint32be(mdchain_t *mbp, uint32_t *x)
{
uint32_t v;
int err;
if ((err = md_get_mem(mbp, &v, sizeof (v), MB_MINLINE)) != 0)
return (err);
if (x != NULL)
*x = betohl(v);
return (0);
}
int
md_get_uint32le(mdchain_t *mbp, uint32_t *x)
{
uint32_t v;
int err;
if ((err = md_get_mem(mbp, &v, sizeof (v), MB_MINLINE)) != 0)
return (err);
if (x != NULL)
*x = letohl(v);
return (0);
}
int
md_get_uint64be(mdchain_t *mbp, uint64_t *x)
{
uint64_t v;
int err;
if ((err = md_get_mem(mbp, &v, sizeof (v), MB_MINLINE)) != 0)
return (err);
if (x != NULL)
*x = betohq(v);
return (0);
}
int
md_get_uint64le(mdchain_t *mbp, uint64_t *x)
{
uint64_t v;
int err;
if ((err = md_get_mem(mbp, &v, sizeof (v), MB_MINLINE)) != 0)
return (err);
if (x != NULL)
*x = letohq(v);
return (0);
}
/* ARGSUSED */
int
md_get_mem(mdchain_t *mbp, void *vmem, int size, int type)
{
struct mbuf *m = mbp->mb_cur;
char *dst = vmem;
uint_t count;
while (size > 0) {
if (m == NULL) {
/* DPRINT("incomplete copy"); */
return (EBADRPC);
}
count = mb_left(m, mbp->mb_pos);
if (count == 0) {
mbp->mb_cur = m = m->m_next;
if (m)
mbp->mb_pos = mtod(m, char *);
continue;
}
if (count > size)
count = size;
size -= count;
if (dst) {
if (count == 1) {
*dst++ = *mbp->mb_pos;
} else {
bcopy(mbp->mb_pos, dst, count);
dst += count;
}
}
mbp->mb_pos += count;
}
return (0);
}
/*
* Get the next SIZE bytes as a separate mblk.
* Nothing fancy here - just copy.
*/
int
md_get_mbuf(mdchain_t *mbp, int size, mbuf_t **ret)
{
mbuf_t *m;
int err;
err = m_get(size, &m);
if (err)
return (err);
err = md_get_mem(mbp, m->m_data, size, MB_MSYSTEM);
if (err) {
m_freem(m);
return (err);
}
m->m_len = size;
*ret = m;
return (0);
}
/*
* Get a string from the mbuf chain,
* either Unicode or OEM chars.
*/
int
md_get_string(mdchain_t *mbp, char **str_pp, int uc)
{
int err;
if (uc)
err = md_get_ustring(mbp, str_pp);
else
err = md_get_astring(mbp, str_pp);
return (err);
}
/*
* Get an ASCII (really OEM) string from the mbuf chain
* and convert it to UTF-8
*
* Similar to md_get_ustring below.
*/
int
md_get_astring(mdchain_t *real_mbp, char **str_pp)
{
mdchain_t tmp_mb, *mbp;
char *tstr, *ostr;
int err, i, slen;
uint8_t ch;
/*
* First, figure out the string length.
* Use a copy of the real_mbp so we don't
* actually consume it here, then search for
* the null (or end of data).
*/
bcopy(real_mbp, &tmp_mb, sizeof (tmp_mb));
mbp = &tmp_mb;
slen = 0;
for (;;) {
err = md_get_uint8(mbp, &ch);
if (err)
break;
if (ch == 0)
break;
slen++;
}
/*
* Now read the (OEM) string for real.
* No need to re-check errors.
*/
tstr = malloc(slen + 1);
if (tstr == NULL)
return (ENOMEM);
mbp = real_mbp;
for (i = 0; i < slen; i++) {
md_get_uint8(mbp, &ch);
tstr[i] = ch;
}
tstr[i] = 0;
md_get_uint8(mbp, NULL);
/*
* Convert OEM to UTF-8
*/
ostr = convert_wincs_to_utf8(tstr);
free(tstr);
if (ostr == NULL)
return (ENOMEM);
*str_pp = ostr;
return (0);
}
/*
* Get a UCS-2LE string from the mbuf chain, and
* convert it to UTF-8.
*
* Similar to md_get_astring above.
*/
int
md_get_ustring(mdchain_t *real_mbp, char **str_pp)
{
mdchain_t tmp_mb, *mbp;
uint16_t *tstr;
char *ostr;
int err, i, slen;
uint16_t ch;
/*
* First, align(2) on the real_mbp
*/
if (((uintptr_t)real_mbp->mb_pos) & 1)
md_get_uint8(real_mbp, NULL);
/*
* Next, figure out the string length.
* Use a copy of the real_mbp so we don't
* actually consume it here, then search for
* the null (or end of data).
*/
bcopy(real_mbp, &tmp_mb, sizeof (tmp_mb));
mbp = &tmp_mb;
slen = 0;
for (;;) {
err = md_get_uint16le(mbp, &ch);
if (err)
break;
if (ch == 0)
break;
slen++;
}
/*
* Now read the (UCS-2) string for real.
* No need to re-check errors. Note:
* This puts the UCS-2 in NATIVE order!
*/
tstr = calloc(slen + 1, 2);
if (tstr == NULL)
return (ENOMEM);
mbp = real_mbp;
for (i = 0; i < slen; i++) {
md_get_uint16le(mbp, &ch);
tstr[i] = ch;
}
tstr[i] = 0;
md_get_uint16le(mbp, NULL);
/*
* Convert UCS-2 (native!) to UTF-8
*/
ostr = convert_unicode_to_utf8(tstr);
free(tstr);
if (ostr == NULL)
return (ENOMEM);
*str_pp = ostr;
return (0);
}
/*
* Copyright (c) 2000, 2001 Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: nb.c,v 1.1.1.2 2001/07/06 22:38:42 conrad Exp $
*/
/*
* Copyright 2010 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <sys/param.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <libintl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cflib.h>
#include <netsmb/netbios.h>
#include <netsmb/smb_lib.h>
#include <netsmb/nb_lib.h>
void nb_ctx_setnbflags(struct nb_ctx *, int ns_ena, int bc_ena);
int nb_ctx_setwins(struct nb_ctx *, const char *, const char *);
/*
* API for seting NetBIOS name lookup flags:
* NetBIOS name lookup enable,
* NetBIOS broadcast enable.
*/
int
smb_ctx_setnbflags(struct smb_ctx *ctx, int ns_ena, int bc_ena)
{
struct nb_ctx *nb = ctx->ct_nb;
if (nb == NULL)
return (EINVAL);
nb_ctx_setnbflags(nb, ns_ena, bc_ena);
return (0);
}
/*
* API for library consumer to set wins1, wins2
*/
int
smb_ctx_setwins(struct smb_ctx *ctx, const char *wins1, const char *wins2)
{
struct nb_ctx *nb = ctx->ct_nb;
if (nb == NULL)
return (EINVAL);
return (nb_ctx_setwins(nb, wins1, wins2));
}
/*
* API for library consumer to set NB scope.
*/
int
smb_ctx_setscope(struct smb_ctx *ctx, const char *scope)
{
struct nb_ctx *nb = ctx->ct_nb;
if (nb == NULL)
return (EINVAL);
return (nb_ctx_setscope(nb, scope));
}
int
nb_ctx_create(struct nb_ctx **ctxpp)
{
struct nb_ctx *ctx;
ctx = malloc(sizeof (struct nb_ctx));
if (ctx == NULL)
return (ENOMEM);
bzero(ctx, sizeof (struct nb_ctx));
*ctxpp = ctx;
return (0);
}
void
nb_ctx_done(struct nb_ctx *ctx)
{
if (ctx == NULL)
return;
if (ctx->nb_scope)
free(ctx->nb_scope);
if (ctx)
free(ctx);
}
void
nb_ctx_setnbflags(struct nb_ctx *nb, int ns_ena, int bc_ena)
{
nb->nb_flags &= ~(NBCF_NS_ENABLE | NBCF_BC_ENABLE);
if (ns_ena) {
nb->nb_flags |= NBCF_NS_ENABLE;
if (bc_ena)
nb->nb_flags |= NBCF_BC_ENABLE;
}
}
int
nb_ctx_setwins(struct nb_ctx *ctx, const char *wins1, const char *wins2)
{
struct in_addr ina;
int error;
if (wins1 == NULL) {
ctx->nb_wins1 = 0;
ctx->nb_wins2 = 0;
return (0);
}
error = nb_resolvehost_in(wins1, &ina);
if (error) {
smb_error(dgettext(TEXT_DOMAIN, "can't resolve %s"),
error, wins1);
return (error);
}
ctx->nb_wins1 = ina.s_addr;
if (wins2 == NULL)
ctx->nb_wins2 = 0;
else {
error = nb_resolvehost_in(wins2, &ina);
if (error) {
smb_error(dgettext(TEXT_DOMAIN, "can't resolve %s"),
error, wins2);
return (error);
}
ctx->nb_wins2 = ina.s_addr;
}
return (0);
}
/*
* This is called by "smbutil lookup" to handle the
* "-w wins_server" option. Let the semantics of
* this option be: Use specified WINS server only.
* If specified server is the broadcast address,
* set broadcast mode (and no WINS servers).
*/
int
nb_ctx_setns(struct nb_ctx *ctx, const char *addr)
{
int error;
error = nb_ctx_setwins(ctx, addr, NULL);
if (error)
return (error);
/* Deal with explicit request for broadcast. */
if (ctx->nb_wins1 == INADDR_BROADCAST) {
ctx->nb_wins1 = 0;
ctx->nb_flags |= NBCF_BC_ENABLE;
}
return (0);
}
int
nb_ctx_setscope(struct nb_ctx *ctx, const char *scope)
{
size_t slen = strlen(scope);
if (slen >= 128) {
smb_error(dgettext(TEXT_DOMAIN,
"scope '%s' is too long"), 0, scope);
return (ENAMETOOLONG);
}
if (ctx->nb_scope)
free(ctx->nb_scope);
ctx->nb_scope = malloc(slen + 1);
if (ctx->nb_scope == NULL)
return (ENOMEM);
nls_str_upper(ctx->nb_scope, scope);
return (0);
}
/*
* Now get the WINS server IP addresses directly
* when reading the RC files, so no longer need to
* lookup any names here.
*/
int
nb_ctx_resolve(struct nb_ctx *ctx)
{
ctx->nb_flags |= NBCF_RESOLVED;
return (0);
}
/*
* used level values:
* 0 - default
* 1 - server
*
* All of these are normally system-wide settings;
* the checks are in rc_parse() in rcfile.c.
*/
int
nb_ctx_readrcsection(struct rcfile *rcfile, struct nb_ctx *ctx,
const char *sname, int level)
{
char *wins1, *wins2;
int error;
int nbns_enable;
int nbns_broadcast;
if (level > 1)
return (EINVAL);
/* External callers pass NULL to get the default. */
if (rcfile == NULL)
rcfile = smb_rc;
#ifdef NOT_DEFINED
rc_getint(rcfile, sname, "nbtimeout", &ctx->nb_timo);
rc_getstringptr(rcfile, sname, "nbscope", &p);
if (p)
nb_ctx_setscope(ctx, p);
#endif
/*
* Get "wins1", "wins2" config strings.
* Also support legacy "nbns".
*/
rc_getstringptr(rcfile, sname, "wins1", &wins1);
if (wins1 == NULL)
rc_getstringptr(rcfile, sname, "nbns", &wins1);
rc_getstringptr(rcfile, sname, "wins2", &wins2);
if (wins1 != NULL) {
error = nb_ctx_setwins(ctx, wins1, wins2);
if (error) {
smb_error(dgettext(TEXT_DOMAIN,
"invalid address specified in the section %s"),
0, sname);
return (error);
}
}
/*
* Want to use nb_ctx_setnbflags here, but
* have to get both boolean values first,
* either from settings or defaults.
*/
nbns_enable = nbns_broadcast = 1; /* defaults */
rc_getbool(rcfile, sname, "nbns_enable", &nbns_enable);
rc_getbool(rcfile, sname, "nbns_broadcast", &nbns_broadcast);
nb_ctx_setnbflags(ctx, nbns_enable, nbns_broadcast);
return (0);
}
#ifdef I18N /* never defined, permits xgettext(1) to pick out strings */
static const char *nb_err_rcode[] = {
gettext("bad request/response format"),
gettext("NBNS server failure"),
gettext("no such name"),
gettext("unsupported request"),
gettext("request rejected"),
gettext("name already registered)"
};
static const char *nb_err[] = {
gettext("host not found"),
gettext("too many redirects"),
gettext("invalid response"),
gettext("NETBIOS name too long"),
gettext("no interface to broadcast on and no NBNS server specified")
};
#else
static const char *nb_err_rcode[] = {
"bad request/response format",
"NBNS server failure",
"no such name",
"unsupported request",
"request rejected",
"name already registered"
};
static const char *nb_err[] = {
"host not found",
"too many redirects",
"invalid response",
"NETBIOS name too long",
"no interface to broadcast on and no NBNS server specified"
};
#endif
const char *
nb_strerror(int error)
{
if (error == 0)
return (NULL);
if (error <= NBERR_ACTIVE)
return (nb_err_rcode[error - 1]);
else if (error >= NBERR_HOSTNOTFOUND && error < NBERR_MAX)
return (nb_err[error - NBERR_HOSTNOTFOUND]);
else
return (NULL);
}
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: nb_name.c,v 1.11 2004/12/11 05:23:59 lindak Exp $
*/
#include <sys/param.h>
#include <sys/socket.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <libintl.h>
#include <assert.h>
#include <netsmb/netbios.h>
#include <netsmb/smb_lib.h>
#include <netsmb/nb_lib.h>
#include <netsmb/mchain.h>
#include "private.h"
int
nb_snballoc(struct sockaddr_nb **dst)
{
struct sockaddr_nb *snb;
int slen;
slen = sizeof (struct sockaddr_nb);
snb = malloc(slen);
if (snb == NULL)
return (ENOMEM);
bzero(snb, slen);
snb->snb_family = AF_NETBIOS;
*dst = snb;
return (0);
}
void
nb_snbfree(struct sockaddr *snb)
{
free(snb);
}
/*
* Create a full NETBIOS address
* Passed names should already be upper case.
* Stores the names truncated or blank padded.
* NetBIOS name encoding happens later.
*/
int
nb_sockaddr(struct sockaddr *peer, struct nb_name *np,
struct sockaddr_nb **dst)
{
struct sockaddr_nb *snb;
struct sockaddr_in *sin;
int error;
if (peer && (peer->sa_family != AF_INET))
return (EPROTONOSUPPORT);
error = nb_snballoc(&snb);
if (error)
return (error);
if (strcmp(np->nn_name, "*") == 0) {
/* Star is special: No blanks, type, etc. */
snb->snb_name[0] = '*';
} else {
/* Normal name: pad with blanks, add type. */
snprintf(snb->snb_name, NB_NAMELEN,
"%-15.15s", np->nn_name);
snb->snb_name[15] = (char)np->nn_type;
}
if (peer) {
/*LINTED*/
sin = (struct sockaddr_in *)peer;
snb->snb_ipaddr = sin->sin_addr.s_addr;
}
*dst = snb;
return (0);
}
int
nb_name_len(struct nb_name *np)
{
char *name;
int len, sclen;
len = 1 + NB_ENCNAMELEN;
if (np->nn_scope == NULL)
return (len + 1);
sclen = 0;
for (name = np->nn_scope; *name; name++) {
if (*name == '.') {
sclen = 0;
} else {
if (sclen < NB_MAXLABLEN) {
sclen++;
len++;
}
}
}
return (len + 1);
}
int
nb_encname_len(const uchar_t *str)
{
const uchar_t *cp = str;
int len, blen;
if ((cp[0] & 0xc0) == 0xc0)
return (-1); /* first two bytes are offset to name */
len = 1;
for (;;) {
blen = *cp;
if (blen++ == 0)
break;
len += blen;
cp += blen;
}
return (len);
}
int
nb_name_encode(struct mbdata *mbp, struct nb_name *nn)
{
char *plen;
uchar_t ch;
char *p, namebuf[NB_NAMELEN+1];
int i, lblen;
bcopy(nn->nn_name, namebuf, NB_NAMELEN);
namebuf[NB_NAMELEN-1] = (char)nn->nn_type;
namebuf[NB_NAMELEN] = '\0'; /* for debug */
/*
* Do the NetBIOS "first-level encoding" here.
* (RFC1002 explains this weirdness...)
*
* Here is what we marshall:
* uint8_t NAME_LENGTH (always 32)
* uint8_t ENCODED_NAME[32]
* uint8_t SCOPE_LENGTH
* Scope follows here, then another null.
*/
/* NAME_LENGTH */
mb_put_uint8(mbp, (2 * NB_NAMELEN));
/* ENCODED_NAME */
for (i = 0; i < NB_NAMELEN; i++) {
ch = namebuf[i];
mb_put_uint8(mbp, 'A' + ((ch >> 4) & 0xF));
mb_put_uint8(mbp, 'A' + ((ch) & 0xF));
}
/*
* NetBIOS "scope" sting encoding,
* a.k.a second-level encoding.
* See RFC1002 for the details.
*
* Note: plen points to the length byte at the
* start of each string. This keeps a pointer
* to the location and fills it in after the
* length of the string is determined.
*
* One string of length zero terminates.
* With no scope string, the zero-length
* string is the only thing there.
*/
if (nn->nn_scope == NULL) {
mb_put_uint8(mbp, 0);
return (0);
}
(void) mb_fit(mbp, 1, &plen);
*plen = 0; /* will update below */
lblen = 0;
for (p = nn->nn_scope; ; p++) {
if (*p == '\0') {
*plen = lblen;
if (lblen)
mb_put_uint8(mbp, 0);
break;
}
if (*p == '.') {
*plen = lblen;
(void) mb_fit(mbp, 1, &plen);
*plen = 0;
lblen = 0;
} else {
if (lblen < NB_MAXLABLEN) {
mb_put_uint8(mbp, *p);
lblen++;
}
}
}
return (0);
}
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: nb_net.c,v 1.8 2004/03/19 01:49:47 lindak Exp $
*/
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <nss_dbdefs.h>
#include <err.h>
#include <netsmb/netbios.h>
#include <netsmb/smb_lib.h>
#include <netsmb/nb_lib.h>
#include "private.h"
/*
* General networking stuff, in spite of the names
* that imply they're specific to NetBIOS.
*/
int
nb_resolvehost_in(const char *name, struct in_addr *ia)
{
char he_buf[NSS_BUFLEN_HOSTS];
struct hostent he, *h;
int err;
h = gethostbyname_r(name, &he, he_buf, sizeof (he_buf), &err);
if (h == NULL) {
#ifdef DEBUG
warnx("can't get server address `%s': ", name);
#endif
return (ENETDOWN);
}
if (h->h_addrtype != AF_INET) {
#ifdef DEBUG
warnx("address for `%s' is not in the AF_INET family", name);
#endif
return (EAFNOSUPPORT);
}
if (h->h_length != 4) {
#ifdef DEBUG
warnx("address for `%s' has invalid length", name);
#endif
return (EAFNOSUPPORT);
}
memcpy(ia, h->h_addr, sizeof (*ia));
return (0);
}
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: nbns_rq.c,v 1.9 2005/02/24 02:04:38 lindak Exp $
*/
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
*/
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <ctype.h>
#include <netdb.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <libintl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <tsol/label.h>
#define NB_NEEDRESOLVER
#include <netsmb/netbios.h>
#include <netsmb/smb_lib.h>
#include <netsmb/nb_lib.h>
#include <netsmb/mchain.h>
#include "charsets.h"
#include "private.h"
/*
* nbns request
*/
struct nbns_rq {
int nr_opcode;
int nr_nmflags;
int nr_rcode;
int nr_qdcount;
int nr_ancount;
int nr_nscount;
int nr_arcount;
struct nb_name *nr_qdname;
uint16_t nr_qdtype;
uint16_t nr_qdclass;
struct in_addr nr_dest; /* receiver of query */
struct sockaddr_in nr_sender; /* sender of response */
int nr_rpnmflags;
int nr_rprcode;
uint16_t nr_rpancount;
uint16_t nr_rpnscount;
uint16_t nr_rparcount;
uint16_t nr_trnid;
struct nb_ctx *nr_nbd;
struct mbdata nr_rq;
struct mbdata nr_rp;
struct nb_ifdesc *nr_if;
int nr_flags;
int nr_fd;
int nr_maxretry;
};
typedef struct nbns_rq nbns_rq_t;
static int nbns_rq_create(int opcode, struct nb_ctx *ctx,
struct nbns_rq **rqpp);
static void nbns_rq_done(struct nbns_rq *rqp);
static int nbns_rq_getrr(struct nbns_rq *rqp, struct nbns_rr *rrp);
static int nbns_rq_prepare(struct nbns_rq *rqp);
static int nbns_rq(struct nbns_rq *rqp);
/*
* Call NetBIOS name lookup and return a result in the
* same form as getaddrinfo(3) returns. Return code is
* zero or one of the EAI_xxx codes like getaddrinfo.
*/
int
nbns_getaddrinfo(const char *name, struct nb_ctx *nbc, struct addrinfo **res)
{
struct addrinfo *nai = NULL;
struct sockaddr *sap = NULL;
char *ucname = NULL;
int err;
/*
* Try NetBIOS name lookup.
*/
if (strlen(name) >= NB_NAMELEN) {
err = EAI_OVERFLOW;
goto out;
}
ucname = utf8_str_toupper(name);
if (ucname == NULL)
goto nomem;
/* Note: this returns an NBERROR value. */
err = nbns_resolvename(ucname, nbc, &sap);
if (err) {
if (smb_verbose)
smb_error(dgettext(TEXT_DOMAIN,
"nbns_resolvename: %s"),
err, name);
err = EAI_NODATA;
goto out;
}
/* Note: sap allocated */
/*
* Build the addrinfo struct to return.
*/
nai = malloc(sizeof (*nai));
if (nai == NULL)
goto nomem;
bzero(nai, sizeof (*nai));
nai->ai_flags = AI_CANONNAME;
nai->ai_family = sap->sa_family;
nai->ai_socktype = SOCK_STREAM;
nai->ai_canonname = ucname;
ucname = NULL;
/*
* The type of this is really sockaddr_in,
* but is returned in the generic form.
* See nbns_resolvename.
*/
nai->ai_addrlen = sizeof (struct sockaddr_in);
nai->ai_addr = sap;
*res = nai;
return (0);
nomem:
err = EAI_MEMORY;
out:
if (nai != NULL)
free(nai);
if (sap)
free(sap);
if (ucname)
free(ucname);
*res = NULL;
return (err);
}
int
nbns_resolvename(const char *name, struct nb_ctx *ctx, struct sockaddr **adpp)
{
struct nbns_rq *rqp;
struct nb_name nn;
struct nbns_rr rr;
struct sockaddr_in *dest;
int error, rdrcount, len;
if (strlen(name) >= NB_NAMELEN)
return (NBERROR(NBERR_NAMETOOLONG));
error = nbns_rq_create(NBNS_OPCODE_QUERY, ctx, &rqp);
if (error)
return (error);
/*
* Pad the name with blanks, but
* leave the "type" byte NULL.
* nb_name_encode adds the type.
*/
bzero(&nn, sizeof (nn));
snprintf(nn.nn_name, NB_NAMELEN, "%-15.15s", name);
nn.nn_type = NBT_SERVER;
nn.nn_scope = ctx->nb_scope;
rqp->nr_nmflags = NBNS_NMFLAG_RD;
rqp->nr_qdname = &nn;
rqp->nr_qdtype = NBNS_QUESTION_TYPE_NB;
rqp->nr_qdclass = NBNS_QUESTION_CLASS_IN;
rqp->nr_qdcount = 1;
rqp->nr_maxretry = 5;
error = nbns_rq_prepare(rqp);
if (error) {
nbns_rq_done(rqp);
return (error);
}
rdrcount = NBNS_MAXREDIRECTS;
for (;;) {
error = nbns_rq(rqp);
if (error)
break;
if ((rqp->nr_rpnmflags & NBNS_NMFLAG_AA) == 0) {
/*
* Not an authoritative answer. Query again
* using the NS address in the 2nd record.
*/
if (rdrcount-- == 0) {
error = NBERROR(NBERR_TOOMANYREDIRECTS);
break;
}
error = nbns_rq_getrr(rqp, &rr);
if (error)
break;
error = nbns_rq_getrr(rqp, &rr);
if (error)
break;
bcopy(rr.rr_data, &rqp->nr_dest, 4);
continue;
}
if (rqp->nr_rpancount == 0) {
error = NBERROR(NBERR_HOSTNOTFOUND);
break;
}
error = nbns_rq_getrr(rqp, &rr);
if (error)
break;
len = sizeof (struct sockaddr_in);
dest = malloc(len);
if (dest == NULL)
return (ENOMEM);
bzero(dest, len);
/*
* Solaris sockaddr_in doesn't a sin_len field.
* dest->sin_len = len;
*/
dest->sin_family = AF_NETBIOS; /* nb_lib.h */
bcopy(rr.rr_data + 2, &dest->sin_addr.s_addr, 4);
*adpp = (struct sockaddr *)dest;
ctx->nb_lastns = rqp->nr_sender;
break;
}
nbns_rq_done(rqp);
return (error);
}
/*
* NB: system, workgroup are both NB_NAMELEN
*/
int
nbns_getnodestatus(struct nb_ctx *ctx,
struct in_addr *targethost, char *system, char *workgroup)
{
struct nbns_rq *rqp;
struct nbns_rr rr;
struct nb_name nn;
struct nbns_nr *nrp;
char nrtype;
char *cp, *retname = NULL;
unsigned char nrcount;
int error, i, foundserver = 0, foundgroup = 0;
error = nbns_rq_create(NBNS_OPCODE_QUERY, ctx, &rqp);
if (error)
return (error);
bzero(&nn, sizeof (nn));
strcpy((char *)nn.nn_name, "*");
nn.nn_scope = ctx->nb_scope;
nn.nn_type = NBT_WKSTA;
rqp->nr_nmflags = 0;
rqp->nr_qdname = &nn;
rqp->nr_qdtype = NBNS_QUESTION_TYPE_NBSTAT;
rqp->nr_qdclass = NBNS_QUESTION_CLASS_IN;
rqp->nr_qdcount = 1;
rqp->nr_maxretry = 2;
rqp->nr_dest = *targethost;
error = nbns_rq_prepare(rqp);
if (error) {
nbns_rq_done(rqp);
return (error);
}
/*
* Darwin had a loop here, allowing redirect, etc.
* but we only handle point-to-point for node status.
*/
error = nbns_rq(rqp);
if (error)
goto out;
if (rqp->nr_rpancount == 0) {
error = NBERROR(NBERR_HOSTNOTFOUND);
goto out;
}
error = nbns_rq_getrr(rqp, &rr);
if (error)
goto out;
/* Compiler didn't like cast on lvalue++ */
nrcount = *((unsigned char *)rr.rr_data);
rr.rr_data++;
/* LINTED */
for (i = 1, nrp = (struct nbns_nr *)rr.rr_data;
i <= nrcount; ++i, ++nrp) {
nrtype = nrp->ns_name[NB_NAMELEN-1];
/* Terminate the string: */
nrp->ns_name[NB_NAMELEN-1] = (char)0;
/* Strip off trailing spaces */
for (cp = &nrp->ns_name[NB_NAMELEN-2];
cp >= nrp->ns_name; --cp) {
if (*cp != (char)0x20)
break;
*cp = (char)0;
}
nrp->ns_flags = ntohs(nrp->ns_flags);
DPRINT(" %s[%02x] Flags 0x%x",
nrp->ns_name, nrtype, nrp->ns_flags);
if (nrp->ns_flags & NBNS_GROUPFLG) {
if (!foundgroup ||
(foundgroup != NBT_WKSTA+1 &&
nrtype == NBT_WKSTA)) {
strlcpy(workgroup, nrp->ns_name,
NB_NAMELEN);
foundgroup = nrtype+1;
}
} else {
/*
* Track at least ONE name, in case
* no server name is found
*/
retname = nrp->ns_name;
}
/*
* Keep the first NBT_SERVER name.
*/
if (nrtype == NBT_SERVER && foundserver == 0) {
strlcpy(system, nrp->ns_name,
NB_NAMELEN);
foundserver = 1;
}
}
if (foundserver == 0 && retname != NULL)
strlcpy(system, retname, NB_NAMELEN);
ctx->nb_lastns = rqp->nr_sender;
out:
nbns_rq_done(rqp);
return (error);
}
int
nbns_rq_create(int opcode, struct nb_ctx *ctx, struct nbns_rq **rqpp)
{
struct nbns_rq *rqp;
static uint16_t trnid;
int error;
if (trnid == 0)
trnid = getpid();
rqp = malloc(sizeof (*rqp));
if (rqp == NULL)
return (ENOMEM);
bzero(rqp, sizeof (*rqp));
error = mb_init_sz(&rqp->nr_rq, NBDG_MAXSIZE);
if (error) {
free(rqp);
return (error);
}
rqp->nr_opcode = opcode;
rqp->nr_nbd = ctx;
rqp->nr_trnid = trnid++;
*rqpp = rqp;
return (0);
}
void
nbns_rq_done(struct nbns_rq *rqp)
{
if (rqp == NULL)
return;
if (rqp->nr_fd >= 0)
close(rqp->nr_fd);
mb_done(&rqp->nr_rq);
mb_done(&rqp->nr_rp);
if (rqp->nr_if)
free(rqp->nr_if);
free(rqp);
}
/*
* Extract resource record from the packet. Assume that there is only
* one mbuf.
*/
int
nbns_rq_getrr(struct nbns_rq *rqp, struct nbns_rr *rrp)
{
struct mbdata *mbp = &rqp->nr_rp;
uchar_t *cp;
int error, len;
bzero(rrp, sizeof (*rrp));
cp = (uchar_t *)mbp->mb_pos;
len = nb_encname_len(cp);
if (len < 1)
return (NBERROR(NBERR_INVALIDRESPONSE));
rrp->rr_name = cp;
error = md_get_mem(mbp, NULL, len, MB_MSYSTEM);
if (error)
return (error);
md_get_uint16be(mbp, &rrp->rr_type);
md_get_uint16be(mbp, &rrp->rr_class);
md_get_uint32be(mbp, &rrp->rr_ttl);
md_get_uint16be(mbp, &rrp->rr_rdlength);
rrp->rr_data = (uchar_t *)mbp->mb_pos;
error = md_get_mem(mbp, NULL, rrp->rr_rdlength, MB_MSYSTEM);
return (error);
}
int
nbns_rq_prepare(struct nbns_rq *rqp)
{
struct nb_ctx *ctx = rqp->nr_nbd;
struct mbdata *mbp = &rqp->nr_rq;
uint16_t ofr; /* opcode, flags, rcode */
int error;
error = mb_init_sz(&rqp->nr_rp, NBDG_MAXSIZE);
if (error)
return (error);
/*
* When looked into the ethereal trace, 'nmblookup' command sets this
* flag. We will also set.
*/
mb_put_uint16be(mbp, rqp->nr_trnid);
ofr = ((rqp->nr_opcode & 0x1F) << 11) |
((rqp->nr_nmflags & 0x7F) << 4); /* rcode=0 */
mb_put_uint16be(mbp, ofr);
mb_put_uint16be(mbp, rqp->nr_qdcount);
mb_put_uint16be(mbp, rqp->nr_ancount);
mb_put_uint16be(mbp, rqp->nr_nscount);
error = mb_put_uint16be(mbp, rqp->nr_arcount);
if (rqp->nr_qdcount) {
if (rqp->nr_qdcount > 1)
return (EINVAL);
(void) nb_name_encode(mbp, rqp->nr_qdname);
mb_put_uint16be(mbp, rqp->nr_qdtype);
error = mb_put_uint16be(mbp, rqp->nr_qdclass);
}
if (error)
return (error);
error = m_lineup(mbp->mb_top, &mbp->mb_top);
if (error)
return (error);
if (ctx->nb_timo == 0)
ctx->nb_timo = 1; /* by default 1 second */
return (0);
}
static int
nbns_rq_recv(struct nbns_rq *rqp)
{
struct mbdata *mbp = &rqp->nr_rp;
void *rpdata = mtod(mbp->mb_top, void *);
fd_set rd, wr, ex;
struct timeval tv;
struct sockaddr_in sender;
int s = rqp->nr_fd;
int n, len;
FD_ZERO(&rd);
FD_ZERO(&wr);
FD_ZERO(&ex);
FD_SET(s, &rd);
tv.tv_sec = rqp->nr_nbd->nb_timo;
tv.tv_usec = 0;
n = select(s + 1, &rd, &wr, &ex, &tv);
if (n == -1)
return (-1);
if (n == 0)
return (ETIMEDOUT);
if (FD_ISSET(s, &rd) == 0)
return (ETIMEDOUT);
len = sizeof (sender);
n = recvfrom(s, rpdata, mbp->mb_top->m_maxlen, 0,
(struct sockaddr *)&sender, &len);
if (n < 0)
return (errno);
mbp->mb_top->m_len = mbp->mb_count = n;
rqp->nr_sender = sender;
return (0);
}
static int
nbns_rq_opensocket(struct nbns_rq *rqp)
{
struct sockaddr_in locaddr;
int opt = 1, s;
struct nb_ctx *ctx = rqp->nr_nbd;
s = rqp->nr_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0)
return (errno);
if (ctx->nb_flags & NBCF_BC_ENABLE) {
if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &opt,
sizeof (opt)) < 0)
return (errno);
}
if (is_system_labeled())
(void) setsockopt(s, SOL_SOCKET, SO_MAC_EXEMPT, &opt,
sizeof (opt));
bzero(&locaddr, sizeof (locaddr));
locaddr.sin_family = AF_INET;
/* locaddr.sin_len = sizeof (locaddr); */
if (bind(s, (struct sockaddr *)&locaddr, sizeof (locaddr)) < 0)
return (errno);
return (0);
}
static int
nbns_rq_send(struct nbns_rq *rqp, in_addr_t ina)
{
struct sockaddr_in dest;
struct mbdata *mbp = &rqp->nr_rq;
int s = rqp->nr_fd;
uint16_t ofr, ofr_save; /* opcode, nmflags, rcode */
uint16_t *datap;
uint8_t nmflags;
int rc;
bzero(&dest, sizeof (dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(IPPORT_NETBIOS_NS);
dest.sin_addr.s_addr = ina;
if (ina == INADDR_BROADCAST) {
/* Turn on the broadcast bit. */
nmflags = rqp->nr_nmflags | NBNS_NMFLAG_BCAST;
/*LINTED*/
datap = mtod(mbp->mb_top, uint16_t *);
ofr = ((rqp->nr_opcode & 0x1F) << 11) |
((nmflags & 0x7F) << 4); /* rcode=0 */
ofr_save = datap[1];
datap[1] = htons(ofr);
}
rc = sendto(s, mtod(mbp->mb_top, char *), mbp->mb_count, 0,
(struct sockaddr *)&dest, sizeof (dest));
if (ina == INADDR_BROADCAST) {
/* Turn the broadcast bit back off. */
datap[1] = ofr_save;
}
if (rc < 0)
return (errno);
return (0);
}
int
nbns_rq(struct nbns_rq *rqp)
{
struct nb_ctx *ctx = rqp->nr_nbd;
struct mbdata *mbp = &rqp->nr_rq;
uint16_t ofr, rpid;
int error, tries, maxretry;
error = nbns_rq_opensocket(rqp);
if (error)
return (error);
maxretry = rqp->nr_maxretry;
for (tries = 0; tries < maxretry; tries++) {
/*
* Minor hack: If nr_dest is set, send there only.
* Used by _getnodestatus, _resolvname redirects.
*/
if (rqp->nr_dest.s_addr) {
error = nbns_rq_send(rqp, rqp->nr_dest.s_addr);
if (error) {
smb_error(dgettext(TEXT_DOMAIN,
"nbns error %d sending to %s"),
0, error, inet_ntoa(rqp->nr_dest));
}
goto do_recv;
}
if (ctx->nb_wins1) {
error = nbns_rq_send(rqp, ctx->nb_wins1);
if (error) {
smb_error(dgettext(TEXT_DOMAIN,
"nbns error %d sending to wins1"),
0, error);
}
}
if (ctx->nb_wins2 && (tries > 0)) {
error = nbns_rq_send(rqp, ctx->nb_wins2);
if (error) {
smb_error(dgettext(TEXT_DOMAIN,
"nbns error %d sending to wins2"),
0, error);
}
}
/*
* If broadcast is enabled, start broadcasting
* only after wins servers fail to respond, or
* immediately if no WINS servers configured.
*/
if ((ctx->nb_flags & NBCF_BC_ENABLE) &&
((tries > 1) || (ctx->nb_wins1 == 0))) {
error = nbns_rq_send(rqp, INADDR_BROADCAST);
if (error) {
smb_error(dgettext(TEXT_DOMAIN,
"nbns error %d sending broadcast"),
0, error);
}
}
/*
* Wait for responses from ANY of the above.
*/
do_recv:
error = nbns_rq_recv(rqp);
if (error == ETIMEDOUT)
continue;
if (error) {
smb_error(dgettext(TEXT_DOMAIN,
"nbns recv error %d"),
0, error);
return (error);
}
mbp = &rqp->nr_rp;
if (mbp->mb_count < 12)
return (NBERROR(NBERR_INVALIDRESPONSE));
md_get_uint16be(mbp, &rpid);
if (rpid != rqp->nr_trnid)
return (NBERROR(NBERR_INVALIDRESPONSE));
break;
}
if (tries == maxretry)
return (NBERROR(NBERR_HOSTNOTFOUND));
md_get_uint16be(mbp, &ofr);
rqp->nr_rpnmflags = (ofr >> 4) & 0x7F;
rqp->nr_rprcode = ofr & 0xf;
if (rqp->nr_rprcode)
return (NBERROR(rqp->nr_rprcode));
md_get_uint16be(mbp, &rpid); /* QDCOUNT */
md_get_uint16be(mbp, &rqp->nr_rpancount);
md_get_uint16be(mbp, &rqp->nr_rpnscount);
md_get_uint16be(mbp, &rqp->nr_rparcount);
return (0);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* Create a new VC given a list of addresses.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <libintl.h>
#include <xti.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/byteorder.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include <netsmb/netbios.h>
#include <netsmb/nb_lib.h>
#include <netsmb/smb_dev.h>
#include "charsets.h"
#include "private.h"
/*
* Ask the IOD to create a VC with this IP address.
*/
static int
newvc(struct smb_ctx *ctx, struct addrinfo *ai)
{
smbioc_ossn_t *ssn = &ctx->ct_ssn;
/*
* Copy the passed address into ssn_srvaddr,
* but first sanity-check lengths. Also,
* zero it first to avoid trailing junk.
*/
if (ai->ai_addrlen > sizeof (ssn->ssn_srvaddr))
return (EINVAL);
bzero(&ssn->ssn_srvaddr, sizeof (ssn->ssn_srvaddr));
bcopy(ai->ai_addr, &ssn->ssn_srvaddr, ai->ai_addrlen);
return (smb_iod_cl_newvc(ctx));
}
/*
* Setup a new VC via the IOD.
* Similar to findvc.c
*/
int
smb_ctx_newvc(struct smb_ctx *ctx)
{
struct addrinfo *ai;
int err;
/* Should already have the address list. */
if ((ctx->ct_flags & SMBCF_RESOLVED) == 0)
return (EINVAL);
/*
* Get a door handle to the smbiod if we
* don't have one already. This also
* starts the smbiod if necessary.
*/
if (ctx->ct_door_fd < 0) {
err = smb_iod_start(ctx);
if (err != 0)
return (err);
}
err = EPROTONOSUPPORT; /* in case no AF match */
for (ai = ctx->ct_addrinfo; ai; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET:
case AF_INET6:
case AF_NETBIOS:
err = newvc(ctx, ai);
if (err == 0)
goto OK;
break;
default:
DPRINT("skipped family %d", ai->ai_family);
break;
}
}
/*
* In the error case, the caller may try again
* with new auth. info, so keep the door open.
* Error return will close in smb_ctx_done.
*/
return (err);
OK:
/* Done with the door handle. */
close(ctx->ct_door_fd);
ctx->ct_door_fd = -1;
return (0);
}
/*
* Copyright (c) 2000-2001, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: nls.c,v 1.10 2004/12/13 00:25:22 lindak Exp $
*/
#include <sys/types.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <locale.h>
#include <errno.h>
#include <netsmb/smb_lib.h>
/*
* prototype iconv* functions
*/
typedef void *iconv_t;
static size_t(*my_iconv)(iconv_t, const char **, size_t *, char **, size_t *);
uchar_t nls_lower[256];
uchar_t nls_upper[256];
static iconv_t nls_toext, nls_toloc;
static int iconv_loaded;
int
nls_setlocale(const char *name)
{
int i;
if (setlocale(LC_CTYPE, name) == NULL) {
fprintf(stdout, dgettext(TEXT_DOMAIN,
"can't set locale '%s'\n"), name);
}
for (i = 0; i < 256; i++) {
nls_lower[i] = tolower(i);
nls_upper[i] = toupper(i);
}
return (0);
}
/*ARGSUSED*/
int
nls_setrecode(const char *local, const char *external)
{
return (ENOENT);
}
char *
nls_str_toloc(char *dst, const char *src)
{
char *p = dst;
size_t inlen, outlen;
if (!iconv_loaded)
return (strcpy(dst, src));
if (nls_toloc == (iconv_t)0)
return (strcpy(dst, src));
inlen = outlen = strlen(src);
my_iconv(nls_toloc, NULL, NULL, &p, &outlen);
my_iconv(nls_toloc, &src, &inlen, &p, &outlen);
*p = 0;
return (dst);
}
char *
nls_str_toext(char *dst, const char *src)
{
char *p = dst;
size_t inlen, outlen;
if (!iconv_loaded)
return (strcpy(dst, src));
if (nls_toext == (iconv_t)0)
return (strcpy(dst, src));
inlen = outlen = strlen(src);
my_iconv(nls_toext, NULL, NULL, &p, &outlen);
my_iconv(nls_toext, &src, &inlen, &p, &outlen);
*p = 0;
return (dst);
}
void *
nls_mem_toloc(void *dst, const void *src, int size)
{
char *p = dst;
const char *s = src;
size_t inlen, outlen;
if (!iconv_loaded)
return (memcpy(dst, src, size));
if (size == 0)
return (NULL);
if (nls_toloc == (iconv_t)0)
return (memcpy(dst, src, size));
inlen = outlen = size;
my_iconv(nls_toloc, NULL, NULL, &p, &outlen);
my_iconv(nls_toloc, &s, &inlen, &p, &outlen);
return (dst);
}
void *
nls_mem_toext(void *dst, const void *src, int size)
{
char *p = dst;
const char *s = src;
size_t inlen, outlen;
if (size == 0)
return (NULL);
if (!iconv_loaded || nls_toext == (iconv_t)0)
return (memcpy(dst, src, size));
inlen = outlen = size;
my_iconv(nls_toext, NULL, NULL, &p, &outlen);
my_iconv(nls_toext, &s, &inlen, &p, &outlen);
return (dst);
}
char *
nls_str_upper(char *dst, const char *src)
{
char *p = dst;
while (*src)
*dst++ = toupper(*src++);
*dst = 0;
return (p);
}
char *
nls_str_lower(char *dst, const char *src)
{
char *p = dst;
while (*src)
*dst++ = tolower(*src++);
*dst = 0;
return (p);
}
/*
* Copyright (c) 2000-2001, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: smb_crypt.c,v 1.13 2005/01/26 23:50:50 lindak Exp $
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* NTLM support functions
*
* Some code from the driver: smb_smb.c, smb_crypt.c
*/
#include <sys/errno.h>
#include <sys/types.h>
#include <sys/md4.h>
#include <sys/md5.h>
#include <ctype.h>
#include <stdlib.h>
#include <strings.h>
#include <netsmb/smb_lib.h>
#include "private.h"
#include "charsets.h"
#include "smb_crypt.h"
#include "ntlm.h"
/*
* ntlm_compute_lm_hash
*
* Given a password, compute the LM hash.
* a.k.a. ResponseKeyLM in [MS-NLMP]
*
* Output:
* hash: 16-byte "LanMan" (LM) hash (normally ctx->ct_lmhash)
* Inputs:
* ucpw: User's password, upper-case UTF-8 string.
*
* Source: Implementing CIFS (Chris Hertel)
*
* P14 = UCPW padded to 14-bytes, or truncated (as needed)
* result = Encrypt(Key=P14, Data=MagicString)
*/
int
ntlm_compute_lm_hash(uchar_t *hash, const char *pass)
{
static const uchar_t M8[8] __nonstring = "KGS!@#$%";
uchar_t P14[14 + 1];
int err;
char *ucpw;
/* First, convert the p/w to upper case. */
ucpw = utf8_str_toupper(pass);
if (ucpw == NULL)
return (ENOMEM);
/* Pad or truncate the upper-case P/W as needed. */
bzero(P14, sizeof (P14));
(void) strncpy((char *)P14, ucpw, 14);
/* Compute the hash. */
err = smb_encrypt_DES(hash, NTLM_HASH_SZ,
P14, 14, M8, 8);
free(ucpw);
return (err);
}
/*
* ntlm_compute_nt_hash
*
* Given a password, compute the NT hash.
* a.k.a. the ResponseKeyNT in [MS-NLMP]
*
* Output:
* hash: 16-byte "NT" hash (normally ctx->ct_nthash)
* Inputs:
* upw: User's password, mixed-case UCS-2LE.
* pwlen: Size (in bytes) of upw
*/
int
ntlm_compute_nt_hash(uchar_t *hash, const char *pass)
{
MD4_CTX ctx;
uint16_t *unipw = NULL;
int pwsz;
/* First, convert the password to unicode. */
unipw = convert_utf8_to_leunicode(pass);
if (unipw == NULL)
return (ENOMEM);
pwsz = unicode_strlen(unipw) << 1;
/* Compute the hash. */
MD4Init(&ctx);
MD4Update(&ctx, unipw, pwsz);
MD4Final(hash, &ctx);
free(unipw);
return (0);
}
/*
* ntlm_v1_response
* a.k.a. DESL() in [MS-NLMP]
*
* Create an LM response from the given LM hash and challenge,
* or an NTLM repsonse from a given NTLM hash and challenge.
* Both response types are 24 bytes (NTLM_V1_RESP_SZ)
*/
static int
ntlm_v1_response(uchar_t *resp,
const uchar_t *hash,
const uchar_t *chal, int clen)
{
uchar_t S21[21];
int err;
/*
* 14-byte LM Hash should be padded with 5 nul bytes to create
* a 21-byte string to be used in producing LM response
*/
bzero(&S21, sizeof (S21));
bcopy(hash, S21, NTLM_HASH_SZ);
/* padded LM Hash -> LM Response */
err = smb_encrypt_DES(resp, NTLM_V1_RESP_SZ,
S21, 21, chal, clen);
return (err);
}
/*
* Calculate an NTLMv1 session key (16 bytes).
*/
static void
ntlm_v1_session_key(uchar_t *ssn_key, const uchar_t *nt_hash)
{
MD4_CTX md4;
MD4Init(&md4);
MD4Update(&md4, nt_hash, NTLM_HASH_SZ);
MD4Final(ssn_key, &md4);
}
/*
* Compute both the LM(v1) response and the NTLM(v1) response,
* and put them in the mbdata chains passed. This allocates
* mbuf chains in the output args, which the caller frees.
*/
int
ntlm_put_v1_responses(struct smb_ctx *ctx,
struct mbdata *lm_mbp, struct mbdata *nt_mbp,
uchar_t *ssn_key)
{
uchar_t *lmresp, *ntresp;
int err;
/* Get mbuf chain for the LM response. */
if ((err = mb_init_sz(lm_mbp, NTLM_V1_RESP_SZ)) != 0)
return (err);
/* Get mbuf chain for the NT response. */
if ((err = mb_init_sz(nt_mbp, NTLM_V1_RESP_SZ)) != 0)
return (err);
/*
* Compute the NTLM response, derived from
* the challenge and the NT hash (a.k.a ResponseKeyNT)
*/
err = mb_fit(nt_mbp, NTLM_V1_RESP_SZ, (char **)&ntresp);
if (err)
return (err);
bzero(ntresp, NTLM_V1_RESP_SZ);
err = ntlm_v1_response(ntresp, ctx->ct_nthash,
ctx->ct_srv_chal, NTLM_CHAL_SZ);
/*
* Compute the LM response, derived from
* the challenge and the ASCII password.
* Per. [MS-NLMP 3.3.1] if NoLmResponse,
* send the NT response for both NT+LM.
*/
err = mb_fit(lm_mbp, NTLM_V1_RESP_SZ, (char **)&lmresp);
if (err)
return (err);
memcpy(lmresp, ntresp, NTLM_V1_RESP_SZ);
if (ctx->ct_authflags & SMB_AT_LM1) {
/* They asked to send the LM hash too. */
err = ntlm_v1_response(lmresp, ctx->ct_lmhash,
ctx->ct_srv_chal, NTLM_CHAL_SZ);
if (err)
return (err);
}
/*
* Compute the session key
*/
ntlm_v1_session_key(ssn_key, ctx->ct_nthash);
return (err);
}
/*
* Compute both the LM(v1x) response and the NTLM(v1x) response,
* and put them in the mbdata chains passed. "v1x" here refers to
* NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY used with NTLMSSP,
* also known by its shorter alias NTLMSSP_NEGOTIATE_NTLM2.
* [MS-NLMP 3.3.1]
*
* This allocates mbuf chains in the output args (caller frees).
*/
int
ntlm_put_v1x_responses(struct smb_ctx *ctx,
struct mbdata *lm_mbp, struct mbdata *nt_mbp,
uchar_t *ssn_key)
{
MD5_CTX context;
uchar_t challenges[2 * NTLM_CHAL_SZ];
uchar_t digest[NTLM_HASH_SZ];
uchar_t *lmresp, *ntresp;
int err;
/* Get mbuf chain for the LM response. */
if ((err = mb_init_sz(lm_mbp, NTLM_V1_RESP_SZ)) != 0)
return (err);
/* Get mbuf chain for the NT response. */
if ((err = mb_init_sz(nt_mbp, NTLM_V1_RESP_SZ)) != 0)
return (err);
/*
* challenges = ConcatenationOf(ServerChallenge, ClientChallenge)
*/
memcpy(challenges, ctx->ct_srv_chal, NTLM_CHAL_SZ);
memcpy(challenges + NTLM_CHAL_SZ, ctx->ct_clnonce, NTLM_CHAL_SZ);
/*
* digest = MD5(challenges)
*/
MD5Init(&context);
MD5Update(&context, challenges, sizeof (challenges));
MD5Final(digest, &context);
/*
* Compute the NTLM response, derived from the
* NT hash (a.k.a ResponseKeyNT) and the first
* 8 bytes of the MD5 digest of the challenges.
*/
err = mb_fit(nt_mbp, NTLM_V1_RESP_SZ, (char **)&ntresp);
if (err)
return (err);
bzero(ntresp, NTLM_V1_RESP_SZ);
err = ntlm_v1_response(ntresp, ctx->ct_nthash,
digest, NTLM_CHAL_SZ);
/*
* With "Extended Session Security", the LM response
* is simply the client challenge (nonce) padded out.
*/
err = mb_fit(lm_mbp, NTLM_V1_RESP_SZ, (char **)&lmresp);
if (err)
return (err);
bzero(lmresp, NTLM_V1_RESP_SZ);
memcpy(lmresp, ctx->ct_clnonce, NTLM_CHAL_SZ);
/*
* Compute the session key
*/
ntlm_v1_session_key(ssn_key, ctx->ct_nthash);
return (err);
}
/*
* A variation on HMAC-MD5 known as HMACT64 is used by Windows systems.
* The HMACT64() function is the same as the HMAC-MD5() except that
* it truncates the input key to 64 bytes rather than hashing it down
* to 16 bytes using the MD5() function.
*
* Output: digest (16-bytes)
*/
static void
HMACT64(uchar_t *digest,
const uchar_t *key, size_t key_len,
const uchar_t *data, size_t data_len)
{
MD5_CTX context;
uchar_t k_ipad[64]; /* inner padding - key XORd with ipad */
uchar_t k_opad[64]; /* outer padding - key XORd with opad */
int i;
/* if key is longer than 64 bytes use only the first 64 bytes */
if (key_len > 64)
key_len = 64;
/*
* The HMAC-MD5 (and HMACT64) transform looks like:
*
* MD5(K XOR opad, MD5(K XOR ipad, data))
*
* where K is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* and data is the data being protected.
*/
/* start out by storing key in pads */
bzero(k_ipad, sizeof (k_ipad));
bzero(k_opad, sizeof (k_opad));
bcopy(key, k_ipad, key_len);
bcopy(key, k_opad, key_len);
/* XOR key with ipad and opad values */
for (i = 0; i < 64; i++) {
k_ipad[i] ^= 0x36;
k_opad[i] ^= 0x5c;
}
/*
* perform inner MD5
*/
MD5Init(&context); /* init context for 1st pass */
MD5Update(&context, k_ipad, 64); /* start with inner pad */
MD5Update(&context, data, data_len); /* then data of datagram */
MD5Final(digest, &context); /* finish up 1st pass */
/*
* perform outer MD5
*/
MD5Init(&context); /* init context for 2nd pass */
MD5Update(&context, k_opad, 64); /* start with outer pad */
MD5Update(&context, digest, 16); /* then results of 1st hash */
MD5Final(digest, &context); /* finish up 2nd pass */
}
/*
* Compute an NTLMv2 hash given the NTLMv1 hash, the user name,
* and the destination (machine or domain name).
*
* Output:
* v2hash: 16-byte NTLMv2 hash.
* Inputs:
* v1hash: 16-byte NTLMv1 hash.
* user: User name, UPPER-case UTF-8 string.
* destination: Domain or server, MIXED-case UTF-8 string.
*/
static int
ntlm_v2_hash(uchar_t *v2hash, const uchar_t *v1hash,
const char *user, const char *destination)
{
int ulen, dlen;
size_t ucs2len;
uint16_t *ucs2data = NULL;
char *utf8data = NULL;
int err = ENOMEM;
/*
* v2hash = HMACT64(v1hash, 16, concat(upcase(user), dest))
* where "dest" is the domain or server name ("target name")
* Note: user name is converted to upper-case by the caller.
*/
/* utf8data = concat(user, dest) */
ulen = strlen(user);
dlen = strlen(destination);
utf8data = malloc(ulen + dlen + 1);
if (utf8data == NULL)
goto out;
bcopy(user, utf8data, ulen);
bcopy(destination, utf8data + ulen, dlen + 1);
/* Convert to UCS-2LE */
ucs2data = convert_utf8_to_leunicode(utf8data);
if (ucs2data == NULL)
goto out;
ucs2len = 2 * unicode_strlen(ucs2data);
HMACT64(v2hash, v1hash, NTLM_HASH_SZ,
(uchar_t *)ucs2data, ucs2len);
err = 0;
out:
if (ucs2data)
free(ucs2data);
if (utf8data)
free(utf8data);
return (err);
}
/*
* Compute a partial LMv2 or NTLMv2 response (first 16-bytes).
* The full response is composed by the caller by
* appending the client_data to the returned hash.
*
* Output:
* rhash: _partial_ LMv2/NTLMv2 response (first 16-bytes)
* Inputs:
* v2hash: 16-byte NTLMv2 hash.
* C8: Challenge from server (8 bytes)
* client_data: client nonce (for LMv2) or the
* "blob" from ntlm_build_target_info (NTLMv2)
*/
static int
ntlm_v2_resp_hash(uchar_t *rhash,
const uchar_t *v2hash, const uchar_t *C8,
const uchar_t *client_data, size_t cdlen)
{
size_t dlen;
uchar_t *data = NULL;
/* data = concat(C8, client_data) */
dlen = 8 + cdlen;
data = malloc(dlen);
if (data == NULL)
return (ENOMEM);
bcopy(C8, data, 8);
bcopy(client_data, data + 8, cdlen);
HMACT64(rhash, v2hash, NTLM_HASH_SZ, data, dlen);
free(data);
return (0);
}
/*
* Calculate an NTLMv2 session key (16 bytes).
*/
static void
ntlm_v2_session_key(uchar_t *ssn_key,
const uchar_t *v2hash,
const uchar_t *ntresp)
{
/* session key uses only 1st 16 bytes of ntresp */
HMACT64(ssn_key, v2hash, NTLM_HASH_SZ, ntresp, NTLM_HASH_SZ);
}
/*
* Compute both the LMv2 response and the NTLMv2 response,
* and put them in the mbdata chains passed. This allocates
* mbuf chains in the output args, which the caller frees.
* Also computes the session key.
*/
int
ntlm_put_v2_responses(struct smb_ctx *ctx, struct mbdata *ti_mbp,
struct mbdata *lm_mbp, struct mbdata *nt_mbp,
uchar_t *ssn_key)
{
uchar_t *lmresp, *ntresp;
int err;
char *ucuser = NULL; /* upper-case user name */
uchar_t v2hash[NTLM_HASH_SZ];
struct mbuf *tim = ti_mbp->mb_top;
/*
* Convert the user name to upper-case, as
* that's what's used when computing LMv2
* and NTLMv2 responses. Note that the
* domain name is NOT upper-cased!
*/
if (ctx->ct_user[0] == '\0')
return (EINVAL);
ucuser = utf8_str_toupper(ctx->ct_user);
if (ucuser == NULL)
return (ENOMEM);
if ((err = mb_init(lm_mbp)) != 0)
goto out;
if ((err = mb_init(nt_mbp)) != 0)
goto out;
/*
* Compute the NTLMv2 hash
*/
err = ntlm_v2_hash(v2hash, ctx->ct_nthash,
ucuser, ctx->ct_domain);
if (err)
goto out;
/*
* Compute the LMv2 response, derived from
* the v2hash, the server challenge, and
* the client nonce (random bits).
*
* We compose it from two parts:
* 1: 16-byte response hash
* 2: Client nonce
*/
lmresp = mb_reserve(lm_mbp, NTLM_HASH_SZ);
err = ntlm_v2_resp_hash(lmresp,
v2hash, ctx->ct_srv_chal,
ctx->ct_clnonce, NTLM_CHAL_SZ);
if (err)
goto out;
mb_put_mem(lm_mbp, ctx->ct_clnonce, NTLM_CHAL_SZ, MB_MSYSTEM);
/*
* Compute the NTLMv2 response, derived
* from the server challenge and the
* "target info." blob passed in.
*
* Again composed from two parts:
* 1: 16-byte response hash
* 2: "target info." blob
*/
ntresp = mb_reserve(nt_mbp, NTLM_HASH_SZ);
err = ntlm_v2_resp_hash(ntresp,
v2hash, ctx->ct_srv_chal,
(uchar_t *)tim->m_data, tim->m_len);
if (err)
goto out;
mb_put_mem(nt_mbp, tim->m_data, tim->m_len, MB_MSYSTEM);
/*
* Compute the session key
*/
ntlm_v2_session_key(ssn_key, v2hash, ntresp);
out:
if (err) {
mb_done(lm_mbp);
mb_done(nt_mbp);
}
free(ucuser);
return (err);
}
/*
* Helper for ntlm_build_target_info below.
* Put a name in the NTLMv2 "target info." blob.
*/
static void
smb_put_blob_name(struct mbdata *mbp, char *name, int type)
{
uint16_t *ucs = NULL;
int nlen;
if (name)
ucs = convert_utf8_to_leunicode(name);
if (ucs)
nlen = unicode_strlen(ucs);
else
nlen = 0;
nlen <<= 1; /* length in bytes, without null. */
mb_put_uint16le(mbp, type);
mb_put_uint16le(mbp, nlen);
mb_put_mem(mbp, (char *)ucs, nlen, MB_MSYSTEM);
if (ucs)
free(ucs);
}
/*
* Build an NTLMv2 "target info." blob. When called from NTLMSSP,
* the list of names comes from the Type 2 message. Otherwise,
* we create the name list here.
*/
int
ntlm_build_target_info(struct smb_ctx *ctx, struct mbuf *names,
struct mbdata *mbp)
{
struct timeval now;
uint64_t nt_time;
char *ucdom = NULL; /* user's domain */
int err;
/* Get mbuf chain for the "target info". */
if ((err = mb_init(mbp)) != 0)
return (err);
/*
* Get the "NT time" for the target info header.
*/
(void) gettimeofday(&now, 0);
smb_time_local2NT(&now, 0, &nt_time);
/*
* Build the "target info." block.
*
* Based on information at:
* http://davenport.sourceforge.net/ntlm.html#theNtlmv2Response
*
* First the fixed-size part.
*/
mb_put_uint32le(mbp, 0x101); /* Blob signature */
mb_put_uint32le(mbp, 0); /* reserved */
mb_put_uint64le(mbp, nt_time); /* NT time stamp */
mb_put_mem(mbp, ctx->ct_clnonce, NTLM_CHAL_SZ, MB_MSYSTEM);
mb_put_uint32le(mbp, 0); /* unknown */
/*
* Now put the list of names, either from the
* NTLMSSP Type 2 message or composed here.
*/
if (names) {
err = mb_put_mem(mbp, names->m_data, names->m_len, MB_MSYSTEM);
} else {
/* Get upper-case names. */
ucdom = utf8_str_toupper(ctx->ct_domain);
if (ucdom == NULL) {
err = ENOMEM;
goto out;
}
smb_put_blob_name(mbp, ucdom, NAMETYPE_DOMAIN_NB);
smb_put_blob_name(mbp, NULL, NAMETYPE_EOL);
/* OK, that's the whole "target info." blob! */
}
err = 0;
out:
free(ucdom);
return (err);
}
/*
* Helper for ntlmssp_put_type3 - Build the "key exchange key"
* used when we have both NTLM(v1) and NTLMSSP_NEGOTIATE_NTLM2.
* HMAC_MD5(SessionBaseKey, concat(ServerChallenge, LmResponse[0..7]))
*/
void
ntlm2_kxkey(struct smb_ctx *ctx, struct mbdata *lm_mbp,
uchar_t *ssn_key, uchar_t *kxkey)
{
uchar_t data[NTLM_HASH_SZ];
uchar_t *p = mtod(lm_mbp->mb_top, uchar_t *);
/* concat(ServerChallenge, LmResponse[0..7]) */
memcpy(data, ctx->ct_srv_chal, NTLM_CHAL_SZ);
memcpy(data + NTLM_CHAL_SZ, p, NTLM_CHAL_SZ);
/* HMAC_MD5(SessionBaseKey, concat(...)) */
HMACT64(kxkey, ssn_key, NTLM_HASH_SZ,
data, NTLM_HASH_SZ);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
#ifndef _NTLM_H
#define _NTLM_H
/*
* NTLM support functions
* See ntlm.c
*/
/*
* Size of all LM/NTLM hashes, challenge
* NTLM_HASH_SZ: 16 bytes (see smb_lib.h)
* NTLM_CHAL_SZ: 8 bytes (see smb_lib.h)
*/
#define NTLM_V1_RESP_SZ 24 /* response size */
#define NAMETYPE_EOL 0x0000 /* end of list of names */
#define NAMETYPE_MACHINE_NB 0x0001 /* NetBIOS machine name */
#define NAMETYPE_DOMAIN_NB 0x0002 /* NetBIOS domain name */
#define NAMETYPE_MACHINE_DNS 0x0003 /* DNS machine name */
#define NAMETYPE_DOMAIN_DNS 0x0004 /* DNS (AD) domain name */
int
ntlm_compute_lm_hash(uchar_t *hash, const char *pw);
int
ntlm_compute_nt_hash(uchar_t *hash, const char *pw);
int
ntlm_build_target_info(struct smb_ctx *, struct mbuf *, struct mbdata *);
int
ntlm_put_v1_responses(struct smb_ctx *ctx,
struct mbdata *lm_mbp, struct mbdata *nt_mbp,
uchar_t *ssnkey);
int
ntlm_put_v1x_responses(struct smb_ctx *ctx,
struct mbdata *lm_mbp, struct mbdata *nt_mbp,
uchar_t *ssnkey);
int
ntlm_put_v2_responses(struct smb_ctx *ctx, struct mbdata *ti_mbp,
struct mbdata *lm_mbp, struct mbdata *nt_mbp,
uchar_t *ssnkey);
void
ntlm2_kxkey(struct smb_ctx *ctx, struct mbdata *lm_mbp,
uchar_t *ssn_key, uchar_t *kxkey);
#endif /* _NTLM_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* NT Lan Manager Security Support Provider (NTLMSSP)
*
* Based on information from the "Davenport NTLM" page:
* http://davenport.sourceforge.net/ntlm.html
*/
#include <errno.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <netdb.h>
#include <libintl.h>
#include <xti.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/byteorder.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include <netsmb/mchain.h>
#include "private.h"
#include "charsets.h"
#include "smb_crypt.h"
#include "spnego.h"
#include "derparse.h"
#include "ssp.h"
#include "ntlm.h"
#include "ntlmssp.h"
/* A shorter alias for a crazy long name from [MS-NLMP] */
#define NTLMSSP_NEGOTIATE_ESS \
NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
typedef struct ntlmssp_state {
uint32_t ss_flags;
char *ss_target_name; /* Primary domain or server name */
struct mbuf *ss_target_info;
uchar_t ss_ssnkey[NTLM_HASH_SZ];
uchar_t ss_kxkey[NTLM_HASH_SZ];
} ntlmssp_state_t;
/*
* So called "security buffer".
* A lot like an RPC string.
*/
struct sec_buf {
uint16_t sb_length;
uint16_t sb_maxlen;
uint32_t sb_offset;
};
#define ID_SZ 8
static const char ntlmssp_id[ID_SZ] = "NTLMSSP";
static int
ntlm_rand_ssn_key(ntlmssp_state_t *ssp_st, struct mbdata *ek_mbp);
/*
* Get a "security buffer" (header part)
*/
static int
md_get_sb_hdr(struct mbdata *mbp, struct sec_buf *sb)
{
int err;
(void) md_get_uint16le(mbp, &sb->sb_length);
(void) md_get_uint16le(mbp, &sb->sb_maxlen);
err = md_get_uint32le(mbp, &sb->sb_offset);
return (err);
}
/*
* Get a "security buffer" (data part), where
* the data is delivered as an mbuf.
*/
static int
md_get_sb_data(struct mbdata *mbp, struct sec_buf *sb, struct mbuf **mp)
{
struct mbdata tmp_mb;
int err;
/*
* Setup tmp_mb to point to the start of the header.
* This is a dup ref - do NOT free it.
*/
mb_initm(&tmp_mb, mbp->mb_top);
/* Skip data up to the offset. */
err = md_get_mem(&tmp_mb, NULL, sb->sb_offset, MB_MSYSTEM);
if (err)
return (err);
/* Get the data (as an mbuf). */
err = md_get_mbuf(&tmp_mb, sb->sb_maxlen, mp);
return (err);
}
/*
* Put a "security buffer" (header part)
*/
static int
mb_put_sb_hdr(struct mbdata *mbp, struct sec_buf *sb)
{
int err;
(void) mb_put_uint16le(mbp, sb->sb_length);
(void) mb_put_uint16le(mbp, sb->sb_maxlen);
err = mb_put_uint32le(mbp, sb->sb_offset);
return (err);
}
/*
* Put a "security buffer" (data part), where
* the data is an mbuf. Note: consumes m.
*/
static int
mb_put_sb_data(struct mbdata *mbp, struct sec_buf *sb, struct mbuf *m)
{
int cnt0;
int err = 0;
sb->sb_offset = cnt0 = mbp->mb_count;
if (m != NULL)
err = mb_put_mbuf(mbp, m);
sb->sb_maxlen = sb->sb_length = mbp->mb_count - cnt0;
return (err);
}
/*
* Put a "security buffer" (data part), where
* the data is a string (OEM or unicode).
*
* The string is NOT null terminated.
*/
static int
mb_put_sb_string(struct mbdata *mbp, struct sec_buf *sb,
const char *str, int unicode)
{
int err, trim;
struct mbdata tmp_mb;
bzero(&tmp_mb, sizeof (tmp_mb));
if (str != NULL && *str != '\0') {
/*
* Put the string into a temp. mbuf,
* then chop off the null terminator
* before appending to caller's mbp.
*/
err = mb_init(&tmp_mb);
if (err)
return (err);
err = mb_put_string(&tmp_mb, str, unicode);
if (err)
return (err);
trim = (unicode) ? 2 : 1;
if (tmp_mb.mb_cur->m_len < trim)
trim = 0;
tmp_mb.mb_cur->m_len -= trim;
}
err = mb_put_sb_data(mbp, sb, tmp_mb.mb_top);
/*
* Note: tmp_mb.mb_top (if any) is consumed,
* so do NOT free it (no mb_done)
*/
return (err);
}
/*
* Build a Type 1 message
*
* This message has a header section containing offsets to
* data later in the message. We use the common trick of
* building it in two parts and then concatenatening.
*/
int
ntlmssp_put_type1(struct ssp_ctx *sp, struct mbdata *out_mb)
{
struct type1hdr {
char h_id[ID_SZ];
uint32_t h_type;
uint32_t h_flags;
struct sec_buf h_cldom;
struct sec_buf h_wksta;
} hdr;
struct mbdata mb2; /* 2nd part */
int err;
struct smb_ctx *ctx = sp->smb_ctx;
ntlmssp_state_t *ssp_st = sp->sp_private;
if ((err = mb_init(&mb2)) != 0)
return (err);
mb2.mb_count = sizeof (hdr);
/*
* The initial negotiation flags represent the union of all
* options we support. The server selects from these.
* See: [MS-NLMP 2.2.2.5 NEGOTIATE]
*/
ssp_st->ss_flags =
NTLMSSP_NEGOTIATE_UNICODE |
NTLMSSP_NEGOTIATE_OEM |
NTLMSSP_REQUEST_TARGET |
NTLMSSP_NEGOTIATE_SIGN |
NTLMSSP_NEGOTIATE_SEAL |
/* NTLMSSP_NEGOTIATE_LM_KEY (never) */
NTLMSSP_NEGOTIATE_NTLM |
NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
NTLMSSP_NEGOTIATE_ESS |
NTLMSSP_NEGOTIATE_128 |
NTLMSSP_NEGOTIATE_KEY_EXCH |
NTLMSSP_NEGOTIATE_56;
if ((ctx->ct_vopt & SMBVOPT_SIGNING_ENABLED) == 0)
ssp_st->ss_flags &= ~NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
bcopy(ntlmssp_id, &hdr.h_id, ID_SZ);
hdr.h_type = NTLMSSP_MSGTYPE_NEGOTIATE;
hdr.h_flags = ssp_st->ss_flags;
/*
* We could put the client domain, client name strings
* here, (always in OEM format, upper-case), and set
* NTLMSSP_NEGOTIATE_OEM_..._SUPPLIED, but Windows
* leaves these NULL so let's do the same.
*/
(void) mb_put_sb_string(&mb2, &hdr.h_cldom, NULL, 0);
(void) mb_put_sb_string(&mb2, &hdr.h_wksta, NULL, 0);
/*
* Marshal the header (in LE order)
* then concatenate the 2nd part.
*/
(void) mb_put_mem(out_mb, &hdr.h_id, ID_SZ, MB_MSYSTEM);
(void) mb_put_uint32le(out_mb, hdr.h_type);
(void) mb_put_uint32le(out_mb, hdr.h_flags);
(void) mb_put_sb_hdr(out_mb, &hdr.h_cldom);
(void) mb_put_sb_hdr(out_mb, &hdr.h_wksta);
err = mb_put_mbuf(out_mb, mb2.mb_top);
return (err);
}
/*
* Parse a Type 2 message
*/
int
ntlmssp_get_type2(struct ssp_ctx *sp, struct mbdata *in_mb)
{
struct type2hdr {
char h_id[ID_SZ];
uint32_t h_type;
struct sec_buf h_target_name;
uint32_t h_flags;
uint8_t h_challenge[8];
uint32_t h_context[2]; /* optional */
struct sec_buf h_target_info; /* optional */
} hdr;
struct mbdata top_mb, tmp_mb;
struct mbuf *m;
int err, uc;
int min_hdr_sz = offsetof(struct type2hdr, h_context);
struct smb_ctx *ctx = sp->smb_ctx;
ntlmssp_state_t *ssp_st = sp->sp_private;
char *buf = NULL;
if (m_totlen(in_mb->mb_top) < min_hdr_sz) {
err = EBADRPC;
goto out;
}
/*
* Save the mbdata pointers before we consume anything.
* Careful to NOT free this (would be dup. free)
* We use this below to find data based on offsets
* from the start of the header.
*/
top_mb = *in_mb;
/* Parse the fixed size header stuff. */
bzero(&hdr, sizeof (hdr));
(void) md_get_mem(in_mb, &hdr.h_id, ID_SZ, MB_MSYSTEM);
(void) md_get_uint32le(in_mb, &hdr.h_type);
if (hdr.h_type != NTLMSSP_MSGTYPE_CHALLENGE) {
err = EPROTO;
goto out;
}
(void) md_get_sb_hdr(in_mb, &hdr.h_target_name);
(void) md_get_uint32le(in_mb, &hdr.h_flags);
(void) md_get_mem(in_mb, &hdr.h_challenge, NTLM_CHAL_SZ, MB_MSYSTEM);
/*
* Save flags, server challenge for later.
*/
ssp_st->ss_flags = hdr.h_flags;
bcopy(&hdr.h_challenge, ctx->ct_srv_chal, NTLM_CHAL_SZ);
/*
* Turn off flags that might have been given but
* that we don't want to send with authenticate.
*/
uc = hdr.h_flags & NTLMSSP_NEGOTIATE_UNICODE;
ssp_st->ss_flags &= ~NTLMSSP_NEGOTIATE_VERSION;
/*
* Now find out if the optional parts are there.
*/
if ((m_totlen(top_mb.mb_top) > sizeof (hdr)) &&
(hdr.h_target_name.sb_offset >= sizeof (hdr))) {
(void) md_get_uint32le(in_mb, &hdr.h_context[0]);
(void) md_get_uint32le(in_mb, &hdr.h_context[1]);
(void) md_get_sb_hdr(in_mb, &hdr.h_target_info);
}
/*
* Get the target name string. (Server name or
* Primary domain name.) First get a copy of the
* data from the offset/length indicated in the
* security buffer header; then parse the string.
*/
err = md_get_sb_data(&top_mb, &hdr.h_target_name, &m);
if (err)
goto out;
mb_initm(&tmp_mb, m);
err = md_get_string(&tmp_mb, &ssp_st->ss_target_name, uc);
mb_done(&tmp_mb);
/*
* Get the target info blob, if present.
*/
if (hdr.h_target_info.sb_offset >= sizeof (hdr)) {
err = md_get_sb_data(&top_mb, &hdr.h_target_info,
&ssp_st->ss_target_info);
}
out:
if (buf != NULL)
free(buf);
return (err);
}
/*
* Build a Type 3 message
*
* This message has a header section containing offsets to
* data later in the message. We use the common trick of
* building it in two parts and then concatenatening.
*/
int
ntlmssp_put_type3(struct ssp_ctx *sp, struct mbdata *out_mb)
{
struct type3hdr {
char h_id[ID_SZ];
uint32_t h_type;
struct sec_buf h_lm_resp;
struct sec_buf h_nt_resp;
struct sec_buf h_domain;
struct sec_buf h_user;
struct sec_buf h_wksta;
struct sec_buf h_ssn_key;
uint32_t h_flags;
/* Version struct (ommitted) */
uchar_t h_mic[NTLM_HASH_SZ];
} hdr;
struct mbdata lm_mbc; /* LM response */
struct mbdata nt_mbc; /* NT response */
struct mbdata ti_mbc; /* target info */
struct mbdata ek_mbc; /* encrypted session key */
struct mbdata mb2; /* payload */
int err, uc;
struct smb_ctx *ctx = sp->smb_ctx;
ntlmssp_state_t *ssp_st = sp->sp_private;
uchar_t *pmic;
bzero(&hdr, sizeof (hdr));
bzero(&lm_mbc, sizeof (lm_mbc));
bzero(&nt_mbc, sizeof (nt_mbc));
bzero(&ti_mbc, sizeof (ti_mbc));
bzero(&ek_mbc, sizeof (ek_mbc));
bzero(&mb2, sizeof (mb2));
/*
* Fill in the NTLMSSP header, etc.
*/
if ((err = mb_init(&mb2)) != 0)
goto out;
mb2.mb_count = sizeof (hdr);
uc = ssp_st->ss_flags & NTLMSSP_NEGOTIATE_UNICODE;
bcopy(ntlmssp_id, &hdr.h_id, ID_SZ);
hdr.h_type = NTLMSSP_MSGTYPE_AUTHENTICATE;
hdr.h_flags = ssp_st->ss_flags;
/*
* Put the NTLMv2/LMv2 or NTLM/LM (v1) responses,
* and compute the session key, etc.
*/
if (ctx->ct_authflags & SMB_AT_ANON) {
/*
* We're setting up a NULL session, meaning
* the lm_mbc, nt_mbc parts remain empty.
* Let's add the "anon" flag (hint), and
* as we have no OWF hashes, we can't use
* "extended session security" (_ESS).
* The SessionBaseKey is all zeros, so
* the KeyExchangeKey is too. Otherwise
* this is like NTLMv2/LMv2
*/
ssp_st->ss_flags |= NTLMSSP_NEGOTIATE_NULL_SESSION;
ssp_st->ss_flags &= ~NTLMSSP_NEGOTIATE_ESS;
hdr.h_flags = ssp_st->ss_flags;
err = 0;
/* KeyExchangeKey = SessionBaseKey = (zeros) */
memset(ssp_st->ss_ssnkey, 0, NTLM_HASH_SZ);
memset(ssp_st->ss_kxkey, 0, NTLM_HASH_SZ);
} else if (ctx->ct_authflags & SMB_AT_NTLM2) {
/*
* Doing NTLMv2/LMv2
*/
err = ntlm_build_target_info(ctx,
ssp_st->ss_target_info, &ti_mbc);
if (err)
goto out;
err = ntlm_put_v2_responses(ctx, &ti_mbc,
&lm_mbc, &nt_mbc, ssp_st->ss_ssnkey);
if (err)
goto out;
/* KeyExchangeKey = SessionBaseKey (v2) */
memcpy(ssp_st->ss_kxkey, ssp_st->ss_ssnkey, NTLM_HASH_SZ);
} else if (ssp_st->ss_flags & NTLMSSP_NEGOTIATE_ESS) {
/*
* Doing NTLM ("v1x") which is NTLM with
* "Extended Session Security"
*/
err = ntlm_put_v1x_responses(ctx,
&lm_mbc, &nt_mbc, ssp_st->ss_ssnkey);
if (err)
goto out;
/*
* "v1x computes the KeyExchangeKey from both the
* server and client nonce and (v1) SessionBaseKey.
*/
ntlm2_kxkey(ctx, &lm_mbc, ssp_st->ss_ssnkey,
ssp_st->ss_kxkey);
} else {
/*
* Doing plain old NTLM (and LM if enabled)
*/
err = ntlm_put_v1_responses(ctx,
&lm_mbc, &nt_mbc, ssp_st->ss_ssnkey);
if (err)
goto out;
/* KeyExchangeKey = SessionBaseKey (v1) */
memcpy(ssp_st->ss_kxkey, ssp_st->ss_ssnkey, NTLM_HASH_SZ);
}
/*
* Compute the "ExportedSessionKey" and (possibly) the
* "EncryptedRandomSesionKey". [MS-NLMP 3.1.5.1.2]
*/
if (ssp_st->ss_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) {
err = ntlm_rand_ssn_key(ssp_st, &ek_mbc);
if (err)
goto out;
} else {
/* ExportedSessionKey is the KeyExchangeKey */
memcpy(ssp_st->ss_ssnkey, ssp_st->ss_kxkey, NTLM_HASH_SZ);
/* EncryptedRandomSessionKey remains NULL */
}
err = mb_put_sb_data(&mb2, &hdr.h_lm_resp, lm_mbc.mb_top);
lm_mbc.mb_top = NULL; /* consumed */
if (err)
goto out;
err = mb_put_sb_data(&mb2, &hdr.h_nt_resp, nt_mbc.mb_top);
nt_mbc.mb_top = NULL; /* consumed */
if (err)
goto out;
/*
* Put the "target" (domain), user, workstation
*/
err = mb_put_sb_string(&mb2, &hdr.h_domain, ctx->ct_domain, uc);
if (err)
goto out;
err = mb_put_sb_string(&mb2, &hdr.h_user, ctx->ct_user, uc);
if (err)
goto out;
err = mb_put_sb_string(&mb2, &hdr.h_wksta, ctx->ct_locname, uc);
if (err)
goto out;
/*
* Put the "Encrypted Random Session Key", if any.
* (ek_mbc.mb_top may be NULL)
*/
err = mb_put_sb_data(&mb2, &hdr.h_ssn_key, ek_mbc.mb_top);
ek_mbc.mb_top = NULL; /* consumed (if any) */
if (err)
goto out;
/*
* Marshal the header (in LE order)
* then concatenate the 2nd part.
*/
(void) mb_put_mem(out_mb, &hdr.h_id, ID_SZ, MB_MSYSTEM);
(void) mb_put_uint32le(out_mb, hdr.h_type);
(void) mb_put_sb_hdr(out_mb, &hdr.h_lm_resp);
(void) mb_put_sb_hdr(out_mb, &hdr.h_nt_resp);
(void) mb_put_sb_hdr(out_mb, &hdr.h_domain);
(void) mb_put_sb_hdr(out_mb, &hdr.h_user);
(void) mb_put_sb_hdr(out_mb, &hdr.h_wksta);
(void) mb_put_sb_hdr(out_mb, &hdr.h_ssn_key);
(void) mb_put_uint32le(out_mb, hdr.h_flags);
/* Put zeros for the MIC - filled in later */
pmic = mb_reserve(out_mb, NTLM_HASH_SZ);
/* Put the payload. */
err = mb_put_mbuf(out_mb, mb2.mb_top);
mb2.mb_top = NULL; /* consumed */
/*
* Compute the MIC and stuff that in...
* The MIC is apparently optional.
*/
(void) pmic;
out:
mb_done(&mb2);
mb_done(&lm_mbc);
mb_done(&nt_mbc);
mb_done(&ti_mbc);
mb_done(&ek_mbc);
return (err);
}
/*
* Helper for ntlmssp_put_type3 when doing key exchange.
*
* "ExportedSessionKey" is what we give to the "application"
* layer, which in here means the MAC key for SMB signing.
* With "key exchange", we replace the ExportedSessionKey
* with random data and send that (encrypted) to the peer.
*/
static int
ntlm_rand_ssn_key(
ntlmssp_state_t *ssp_st,
struct mbdata *ek_mbp)
{
uchar_t *encr_ssn_key;
int err;
if ((err = mb_init(ek_mbp)) != 0)
return (err);
encr_ssn_key = mb_reserve(ek_mbp, NTLM_HASH_SZ);
/* Set "ExportedSessionKey to NONCE(16) */
(void) smb_get_urandom(ssp_st->ss_ssnkey, NTLM_HASH_SZ);
/* Set "EncryptedRandomSessionKey" to RC4(...) */
err = smb_encrypt_RC4(encr_ssn_key, NTLM_HASH_SZ,
ssp_st->ss_kxkey, NTLM_HASH_SZ,
ssp_st->ss_ssnkey, NTLM_HASH_SZ);
return (err);
}
/*
* ntlmssp_final
*
* Called after successful authentication.
* Save the session key.
*/
int
ntlmssp_final(struct ssp_ctx *sp)
{
struct smb_ctx *ctx = sp->smb_ctx;
ntlmssp_state_t *ssp_st = sp->sp_private;
int err = 0;
/*
* Update/save the session key.
*/
if (ctx->ct_ssnkey_buf != NULL) {
free(ctx->ct_ssnkey_buf);
ctx->ct_ssnkey_buf = NULL;
}
ctx->ct_ssnkey_buf = malloc(NTLM_HASH_SZ);
if (ctx->ct_ssnkey_buf == NULL) {
err = ENOMEM;
goto out;
}
ctx->ct_ssnkey_len = NTLM_HASH_SZ;
memcpy(ctx->ct_ssnkey_buf, ssp_st->ss_ssnkey, NTLM_HASH_SZ);
out:
return (err);
}
/*
* ntlmssp_next_token
*
* See ssp.c: ssp_ctx_next_token
*/
int
ntlmssp_next_token(struct ssp_ctx *sp, struct mbdata *in_mb,
struct mbdata *out_mb)
{
int err;
if (out_mb == NULL) {
/* final call on successful auth. */
err = ntlmssp_final(sp);
goto out;
}
/* Will build an ouptut token. */
err = mb_init(out_mb);
if (err)
goto out;
/*
* When called with in_mb == NULL, it means
* this is the first call for this session,
* so put a Type 1 (initialize) token.
*/
if (in_mb == NULL) {
err = ntlmssp_put_type1(sp, out_mb);
goto out;
}
/*
* This is not the first call, so
* parse the response token we received.
* It should be a Type 2 (challenge).
* Then put a Type 3 (authenticate)
*/
err = ntlmssp_get_type2(sp, in_mb);
if (err)
goto out;
err = ntlmssp_put_type3(sp, out_mb);
out:
if (err)
DPRINT("ret: %d", err);
return (err);
}
/*
* ntlmssp_ctx_destroy
*
* Destroy mechanism-specific data.
*/
void
ntlmssp_destroy(struct ssp_ctx *sp)
{
ntlmssp_state_t *ssp_st;
ssp_st = sp->sp_private;
if (ssp_st != NULL) {
sp->sp_private = NULL;
free(ssp_st->ss_target_name);
m_freem(ssp_st->ss_target_info);
free(ssp_st);
}
}
/*
* ntlmssp_init_clnt
*
* Initialize a new NTLMSSP client context.
*/
int
ntlmssp_init_client(struct ssp_ctx *sp)
{
ntlmssp_state_t *ssp_st;
smb_ctx_t *ctx = sp->smb_ctx;
if ((ctx->ct_authflags &
(SMB_AT_NTLM2 | SMB_AT_NTLM1 | SMB_AT_ANON)) == 0) {
DPRINT("No NTLM authflags");
return (EINVAL);
}
/* Get the client nonce. */
(void) smb_get_urandom(ctx->ct_clnonce, NTLM_CHAL_SZ);
ssp_st = calloc(1, sizeof (*ssp_st));
if (ssp_st == NULL)
return (ENOMEM);
sp->sp_nexttok = ntlmssp_next_token;
sp->sp_destroy = ntlmssp_destroy;
sp->sp_private = ssp_st;
return (0);
}
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: print.c,v 1.1.1.3 2001/07/06 22:38:43 conrad Exp $
*/
/*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/mount.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <unistd.h>
#include <libintl.h>
#include <netsmb/smb.h>
#include <netsmb/smb_lib.h>
#include "private.h"
/*
* Replacing invalid characters in print job titles:
*
* The spec. is unclear about what characters are allowed in a
* print job title (used with NtCreate) so out of caution this
* makes sure the title contains none of the characters that
* are known to be illegal in a file name component.
*/
static const char invalid_chars[] = SMB_FILENAME_INVALID_CHARS;
int
smb_open_printer(struct smb_ctx *ctx, const char *title,
int setuplen, int mode)
{
smbioc_printjob_t ioc;
char *p;
int err, tlen;
int new_fd = -1;
int32_t from_fd;
tlen = strlen(title);
if (tlen >= SMBIOC_MAX_NAME)
return (EINVAL);
/*
* Will represent this SMB-level open as a new
* open device handle. Get one, then duplicate
* the driver session and tree bindings.
*/
new_fd = smb_open_driver();
if (new_fd < 0)
return (errno);
from_fd = ctx->ct_dev_fd;
if (nsmb_ioctl(new_fd, SMBIOC_DUP_DEV, &from_fd) == -1) {
err = errno;
goto errout;
}
/*
* Do the SMB-level open with the new dev handle.
*/
bzero(&ioc, sizeof (ioc));
ioc.ioc_setuplen = setuplen;
ioc.ioc_prmode = mode;
strlcpy(ioc.ioc_title, title, SMBIOC_MAX_NAME);
/*
* The title is used in NtCreate so sanitize by
* replacing any illegal chars with spaces.
*/
for (p = ioc.ioc_title; *p != '\0'; p++)
if (strchr(invalid_chars, *p) != NULL)
*p = ' ';
if (nsmb_ioctl(new_fd, SMBIOC_PRINTJOB, &ioc) == -1) {
err = errno;
goto errout;
}
return (new_fd);
errout:
nsmb_close(new_fd);
errno = err;
return (-1);
}
/*
* Copyright (c) 2000-2001 Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
#ifndef _PRIVATE_H
#define _PRIVATE_H
/*
* Private declarations for this library.
* Moved from smb_lib.h
*/
#include <inttypes.h>
#include <sys/byteorder.h>
#include <sys/ccompile.h>
#include <netsmb/mchain.h>
#include <netsmb/netbios.h>
extern void dprint(const char *, const char *, ...)
__PRINTFLIKE(2);
#if defined(DEBUG) || defined(__lint)
#define DPRINT(...) dprint(__func__, __VA_ARGS__)
#else
#define DPRINT(...) ((void)0)
#endif
/*
* This library extends the mchain.h function set a little.
*/
int m_getm(struct mbuf *, int, struct mbuf **);
int m_lineup(struct mbuf *, struct mbuf **);
size_t m_totlen(struct mbuf *);
int mb_init_sz(struct mbdata *, int);
int mb_fit(struct mbdata *mbp, int size, char **pp);
int mb_put_string(struct mbdata *mbp, const char *s, int);
int mb_put_astring(struct mbdata *mbp, const char *s);
int mb_put_ustring(struct mbdata *mbp, const char *s);
int md_get_string(struct mbdata *, char **, int);
int md_get_astring(struct mbdata *, char **);
int md_get_ustring(struct mbdata *, char **);
/*
* Network stuff (NetBIOS and otherwise)
*/
struct nb_name;
struct sockaddr_nb;
extern int smb_recv_timeout; /* seconds */
void dump_ctx(char *, struct smb_ctx *);
void dump_addrinfo(struct addrinfo *);
void dump_sockaddr(struct sockaddr *);
int nb_ssn_request(struct smb_ctx *, char *);
int nb_name_len(struct nb_name *);
int nb_name_encode(struct mbdata *, struct nb_name *);
int nb_encname_len(const uchar_t *);
int nb_snballoc(struct sockaddr_nb **);
void nb_snbfree(struct sockaddr *);
int nb_sockaddr(struct sockaddr *, struct nb_name *, struct sockaddr_nb **);
int nbns_getaddrinfo(const char *name, struct nb_ctx *nbc,
struct addrinfo **res);
int nbns_resolvename(const char *, struct nb_ctx *, struct sockaddr **);
int get_xti_err(int);
/*
* Private SMB stuff
*/
struct smb_bitname {
uint_t bn_bit;
char *bn_name;
};
typedef struct smb_bitname smb_bitname_t;
char *smb_printb(char *, int, const struct smb_bitname *);
int smb_ctx_getaddr(struct smb_ctx *ctx);
int smb_ctx_gethandle(struct smb_ctx *ctx);
int smb_iod_start(struct smb_ctx *);
const char *smb_iod_state_name(enum smbiod_state st);
void smb_time_local2server(struct timeval *, int, long *);
void smb_time_server2local(ulong_t, int, struct timeval *);
void smb_time_NT2local(uint64_t, int, struct timeval *);
void smb_time_local2NT(struct timeval *, int, uint64_t *);
int smb_getlocalname(char **);
int smb_get_authentication(struct smb_ctx *);
int smb_get_keychain(struct smb_ctx *ctx);
void smb_hexdump(const void *buf, int len);
/* See ssp.c */
int ssp_ctx_create_client(struct smb_ctx *, struct mbdata *);
int ssp_ctx_next_token(struct smb_ctx *, struct mbdata *, struct mbdata *);
void ssp_ctx_destroy(struct smb_ctx *);
#ifdef KICONV_SUPPORT
/* See nls.c (get rid of this?) */
extern uchar_t nls_lower[256], nls_upper[256];
#endif /* KICONV_SUPPORT */
#endif /* _PRIVATE_H */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)queue.h 8.5 (Berkeley) 8/20/94
*/
/*
* This file [used to define] five types of data structures:
* singly-linked lists, ...
* [ all other types of lists removed ]
*
* Using excerpts of FreeBSD 4.5 sys/queue.h here,
* but only temporarily, until rcfile.c is replaced
* by SMF integration code.
*
* Yes we also have queue.h in uts/common/fs/smbclnt
* but don't want to make that part of the exported
* interface to the user-level code.
*/
/*
* Singly-linked List declarations.
*/
#define SLIST_HEAD(name, type) \
struct name { \
struct type *slh_first; /* first element */ \
}
#define SLIST_ENTRY(type) \
struct { \
struct type *sle_next; /* next element */ \
}
/*
* Singly-linked List functions.
*/
#define SLIST_EMPTY(head) ((head)->slh_first == NULL)
#define SLIST_FIRST(head) ((head)->slh_first)
#define SLIST_FOREACH(var, head, field) \
for ((var) = SLIST_FIRST((head)); \
(var); \
(var) = SLIST_NEXT((var), field))
#define SLIST_INIT(head) do { \
SLIST_FIRST((head)) = NULL; \
} while (0)
#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \
SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \
SLIST_NEXT((slistelm), field) = (elm); \
} while (0)
#define SLIST_INSERT_HEAD(head, elm, field) do { \
SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \
SLIST_FIRST((head)) = (elm); \
} while (0)
#define SLIST_NEXT(elm, field) ((elm)->field.sle_next)
#define SLIST_REMOVE(head, elm, type, field) do { \
if (SLIST_FIRST((head)) == (elm)) { \
SLIST_REMOVE_HEAD((head), field); \
} \
else { \
struct type *curelm = SLIST_FIRST((head)); \
while (SLIST_NEXT(curelm, field) != (elm)) \
curelm = SLIST_NEXT(curelm, field); \
SLIST_NEXT(curelm, field) = \
SLIST_NEXT(SLIST_NEXT(curelm, field), field); \
} \
} while (0)
#define SLIST_REMOVE_HEAD(head, field) do { \
SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \
} while (0)
/*
* This file and its contents are supplied under the terms of the
* Common Development and Distribution License ("CDDL"), version 1.0.
* You may only use this file in accordance with the terms of version
* 1.0 of the CDDL.
*
* A full copy of the text of the CDDL should have accompanied this
* source. A copy of the CDDL is also available via the Internet at
* http://www.illumos.org/license/CDDL.
*/
/*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Support functions for getting things libsmbfs needs
* from the SMF configuration (using libscf).
*/
#include <sys/types.h>
#include <sys/queue.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <libscf.h>
#include <cflib.h>
#include "rcfile_priv.h"
#define IDMAP_SERVICE_FMRI "svc:/system/idmap"
#define IDMAP_PG_NAME "config"
#define MACHINE_UUID "machine_uuid"
#define SMBC_DEFAULT_INSTANCE_FMRI "svc:/network/smb/client:default"
scf_handle_t *_scf_handle_create_and_bind(scf_version_t ver);
/*
* Get the "machine_uuid" from idmap, as a string (allocated)
*/
char *
cf_get_client_uuid(void)
{
char val_buf[64];
char *ret = NULL;
scf_handle_t *h = NULL;
scf_service_t *svc = NULL;
scf_propertygroup_t *pg = NULL;
scf_property_t *prop = NULL;
scf_value_t *val = NULL;
if ((h = _scf_handle_create_and_bind(SCF_VERSION)) == NULL)
goto out;
if ((svc = scf_service_create(h)) == NULL ||
(pg = scf_pg_create(h)) == NULL ||
(prop = scf_property_create(h)) == NULL ||
(val = scf_value_create(h)) == NULL)
goto out;
if (scf_handle_decode_fmri(h, IDMAP_SERVICE_FMRI,
NULL, svc, NULL, NULL, NULL, 0) == -1)
goto out;
if (scf_service_get_pg(svc, IDMAP_PG_NAME, pg) != 0)
goto out;
if (scf_pg_get_property(pg, MACHINE_UUID, prop) != 0)
goto out;
if (scf_property_get_value(prop, val) != 0)
goto out;
if (scf_value_get_as_string(val, val_buf, sizeof (val_buf)) < 0)
goto out;
ret = strdup(val_buf);
out:
scf_value_destroy(val);
scf_property_destroy(prop);
scf_pg_destroy(pg);
scf_service_destroy(svc);
if (h != NULL)
scf_handle_destroy(h);
return (ret);
}
/*
* Get the output of "sharectl get smbfs" into a file, without an
* actual fork/exec of sharectl.
*
* Each section of the smbfs settings are represented as an SMF
* property group with an "S-" prefix and a UUID, and the section
* name itself a property which can have a more flexible name than
* a property group name can have.
*/
int
rc_scf_get_sharectl(FILE *fp)
{
char sect_name[256];
char prop_name[256];
char val_buf[1024];
scf_handle_t *h = NULL;
scf_service_t *svc = NULL;
scf_instance_t *inst = NULL;
scf_propertygroup_t *pg = NULL;
scf_property_t *prop = NULL;
scf_value_t *val = NULL;
scf_iter_t *pgiter = NULL;
scf_iter_t *propiter = NULL;
scf_iter_t *valiter = NULL;
int ret = -1;
if ((h = _scf_handle_create_and_bind(SCF_VERSION)) == NULL)
goto out;
if ((svc = scf_service_create(h)) == NULL ||
(inst = scf_instance_create(h)) == NULL ||
(pgiter = scf_iter_create(h)) == NULL ||
(propiter = scf_iter_create(h)) == NULL ||
(valiter = scf_iter_create(h)) == NULL ||
(pg = scf_pg_create(h)) == NULL ||
(prop = scf_property_create(h)) == NULL ||
(val = scf_value_create(h)) == NULL)
goto out;
if (scf_handle_decode_fmri(h, SMBC_DEFAULT_INSTANCE_FMRI,
NULL, svc, inst, NULL, NULL, 0) == -1)
goto out;
if (scf_iter_instance_pgs_composed(pgiter, inst, NULL) == -1)
goto out;
while ((ret = scf_iter_next_pg(pgiter, pg)) == 1) {
/*
* Using prop_name array for pg name temporarily.
* Skip any property groups names other than "S-*".
*/
if (scf_pg_get_name(pg, prop_name, sizeof (prop_name)) < 0)
continue;
if (strncmp(prop_name, "S-", 2) != 0)
continue;
/*
* Get the "section" name, which is a property of
* this property group.
*/
if (scf_pg_get_property(pg, "section", prop) != 0)
continue;
if (scf_property_get_value(prop, val) != 0)
continue;
if (scf_value_get_as_string(val, sect_name,
sizeof (sect_name)) < 0)
continue;
/*
* Have an S-* property group with a "section" name.
* Print the section start.
*/
fprintf(fp, "[%s]\n", sect_name);
/*
* Now print the remaining properties in this PG,
* but skip the special "section" (name) prop.
*/
if (scf_iter_pg_properties(propiter, pg) == -1)
goto out;
while ((ret = scf_iter_next_property(propiter, prop)) == 1) {
if (scf_property_get_name(prop, prop_name,
sizeof (prop_name)) < 0)
continue;
/* Skip the "section" prop. now */
if (strcmp(prop_name, "section") == 0)
continue;
if (scf_property_get_value(prop, val) != 0)
continue;
if (scf_value_get_as_string(val, val_buf,
sizeof (val_buf)) < 0)
continue;
fprintf(fp, "%s=%s\n", prop_name, val_buf);
}
}
ret = 0;
out:
fflush(fp);
scf_value_destroy(val);
scf_property_destroy(prop);
scf_pg_destroy(pg);
scf_iter_destroy(valiter);
scf_iter_destroy(propiter);
scf_iter_destroy(pgiter);
scf_instance_destroy(inst);
scf_service_destroy(svc);
if (h != NULL)
scf_handle_destroy(h);
return (ret);
}
/*
* Simple test wrapper. Compile with:
* cc -o rc_scf_test -I.. -DTEST_MAIN rc_scf.c -lscf
*/
#ifdef TEST_MAIN
int
main(int argc, char **arv)
{
char *s;
int rc;
rc = rc_scf_get_sharectl(stdout);
printf("# rc=%d\n", rc);
return (0);
}
#endif /* TEST_MAIN */
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: rcfile.c,v 1.1.1.2 2001/07/06 22:38:43 conrad Exp $
*/
/*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
* Copyright 2026 RackTop Systems, Inc.
*/
#include <fcntl.h>
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <synch.h>
#include <unistd.h>
#include <pwd.h>
#include <libintl.h>
#include <cflib.h>
#include "rcfile_priv.h"
#include <assert.h>
#if 0 /* before SMF */
#define SMB_CFG_FILE "/etc/nsmb.conf"
#define OLD_SMB_CFG_FILE "/usr/local/etc/nsmb.conf"
#endif
extern int smb_debug;
static struct rcfile *rc_cachelookup(const char *filename);
static struct rcsection *rc_findsect(struct rcfile *rcp, const char *sectname);
static struct rcsection *rc_addsect(struct rcfile *rcp, const char *sectname);
static int rc_freesect(struct rcfile *rcp, struct rcsection *rsp);
static struct rckey *rc_sect_findkey(struct rcsection *rsp, const char *key);
static struct rckey *rc_sect_addkey(struct rcsection *rsp, const char *name,
const char *value);
static void rc_key_free(struct rckey *p);
static void rc_parse(struct rcfile *rcp);
/* lock for the variables below */
mutex_t rcfile_mutex = DEFAULTMUTEX;
SLIST_HEAD(rcfile_head, rcfile);
static struct rcfile_head pf_head = {NULL};
struct rcfile *smb_rc;
int home_nsmbrc;
int insecure_nsmbrc;
/*
* open rcfile and load its content, if already open - return previous handle
*/
static int
rc_open(const char *filename, const char *mode, struct rcfile **rcfile)
{
struct stat statbuf;
struct rcfile *rcp;
FILE *f;
assert(MUTEX_HELD(&rcfile_mutex));
rcp = rc_cachelookup(filename);
if (rcp) {
*rcfile = rcp;
return (0);
}
f = fopen(filename, mode);
if (f == NULL)
return (errno);
insecure_nsmbrc = 0;
if (fstat(fileno(f), &statbuf) >= 0 &&
(statbuf.st_mode & 077) != 0)
insecure_nsmbrc = 1;
rcp = malloc(sizeof (struct rcfile));
if (rcp == NULL) {
fclose(f);
return (ENOMEM);
}
bzero(rcp, sizeof (struct rcfile));
rcp->rf_name = strdup(filename);
rcp->rf_f = f;
SLIST_INSERT_HEAD(&pf_head, rcp, rf_next);
rc_parse(rcp);
*rcfile = rcp;
return (0);
}
static int
rc_merge(const char *filename, struct rcfile **rcfile)
{
struct stat statbuf;
struct rcfile *rcp = *rcfile;
FILE *f, *t;
assert(MUTEX_HELD(&rcfile_mutex));
insecure_nsmbrc = 0;
if (rcp == NULL) {
return (rc_open(filename, "r", rcfile));
}
f = fopen(filename, "r");
if (f == NULL)
return (errno);
insecure_nsmbrc = 0;
if (fstat(fileno(f), &statbuf) >= 0 &&
(statbuf.st_mode & 077) != 0)
insecure_nsmbrc = 1;
t = rcp->rf_f;
rcp->rf_f = f;
rc_parse(rcp);
rcp->rf_f = t;
fclose(f);
return (0);
}
/*
* Like rc_open, but creates a temporary file and
* reads the sharectl settings into it.
* The file is deleted when we close it.
*/
static int
rc_open_sharectl(struct rcfile **rcfile)
{
static char template[24] = "/tmp/smbfsXXXXXX";
struct rcfile *rcp = NULL;
FILE *fp = NULL;
int err;
int fd = -1;
assert(MUTEX_HELD(&rcfile_mutex));
fd = mkstemp(template);
if (fd < 0) {
err = errno;
goto errout;
}
fp = fdopen(fd, "w+");
if (fp == NULL) {
err = errno;
close(fd);
goto errout;
}
fd = -1; /* The fp owns this fd now. */
/*
* Get smbfs sharectl settings into the file.
*/
if ((err = rc_scf_get_sharectl(fp)) != 0)
goto errout;
rcp = malloc(sizeof (struct rcfile));
if (rcp == NULL) {
err = ENOMEM;
goto errout;
}
bzero(rcp, sizeof (struct rcfile));
rcp->rf_name = strdup(template);
if (rcp->rf_name == NULL) {
err = ENOMEM;
goto errout;
}
rcp->rf_f = fp;
rcp->rf_flags = RCFILE_DELETE_ON_CLOSE;
SLIST_INSERT_HEAD(&pf_head, rcp, rf_next);
insecure_nsmbrc = 0;
rc_parse(rcp);
*rcfile = rcp;
/* fclose(f) in rc_close */
return (0);
errout:
if (rcp != NULL)
free(rcp);
if (fp != NULL) {
fclose(fp);
fd = -1;
}
if (fd != -1)
close(fd);
return (err);
}
static int
rc_close(struct rcfile *rcp)
{
struct rcsection *p, *n;
mutex_lock(&rcfile_mutex);
fclose(rcp->rf_f);
if (rcp->rf_flags & RCFILE_DELETE_ON_CLOSE)
(void) unlink(rcp->rf_name);
for (p = SLIST_FIRST(&rcp->rf_sect); p; ) {
n = p;
p = SLIST_NEXT(p, rs_next);
rc_freesect(rcp, n);
}
free(rcp->rf_name);
SLIST_REMOVE(&pf_head, rcp, rcfile, rf_next);
free(rcp);
mutex_unlock(&rcfile_mutex);
return (0);
}
static struct rcfile *
rc_cachelookup(const char *filename)
{
struct rcfile *p;
assert(MUTEX_HELD(&rcfile_mutex));
SLIST_FOREACH(p, &pf_head, rf_next)
if (strcmp(filename, p->rf_name) == 0)
return (p);
return (0);
}
static struct rcsection *
rc_findsect(struct rcfile *rcp, const char *sectname)
{
struct rcsection *p;
assert(MUTEX_HELD(&rcfile_mutex));
SLIST_FOREACH(p, &rcp->rf_sect, rs_next)
if (strcasecmp(p->rs_name, sectname) == 0)
return (p);
return (NULL);
}
static struct rcsection *
rc_addsect(struct rcfile *rcp, const char *sectname)
{
struct rcsection *p;
assert(MUTEX_HELD(&rcfile_mutex));
p = rc_findsect(rcp, sectname);
if (p)
return (p);
p = malloc(sizeof (*p));
if (!p)
return (NULL);
p->rs_name = strdup(sectname);
SLIST_INIT(&p->rs_keys);
SLIST_INSERT_HEAD(&rcp->rf_sect, p, rs_next);
return (p);
}
static int
rc_freesect(struct rcfile *rcp, struct rcsection *rsp)
{
struct rckey *p, *n;
assert(MUTEX_HELD(&rcfile_mutex));
SLIST_REMOVE(&rcp->rf_sect, rsp, rcsection, rs_next);
for (p = SLIST_FIRST(&rsp->rs_keys); p; ) {
n = p;
p = SLIST_NEXT(p, rk_next);
rc_key_free(n);
}
free(rsp->rs_name);
free(rsp);
return (0);
}
static struct rckey *
rc_sect_findkey(struct rcsection *rsp, const char *keyname)
{
struct rckey *p;
assert(MUTEX_HELD(&rcfile_mutex));
SLIST_FOREACH(p, &rsp->rs_keys, rk_next)
if (strcmp(p->rk_name, keyname) == 0)
return (p);
return (NULL);
}
static struct rckey *
rc_sect_addkey(struct rcsection *rsp, const char *name, const char *value)
{
struct rckey *p;
assert(MUTEX_HELD(&rcfile_mutex));
p = rc_sect_findkey(rsp, name);
if (!p) {
p = malloc(sizeof (*p));
if (!p)
return (NULL);
SLIST_INSERT_HEAD(&rsp->rs_keys, p, rk_next);
p->rk_name = strdup(name);
p->rk_value = value ? strdup(value) : strdup("");
}
return (p);
}
#if 0
void
rc_sect_delkey(struct rcsection *rsp, struct rckey *p)
{
SLIST_REMOVE(&rsp->rs_keys, p, rckey, rk_next);
rc_key_free(p);
}
#endif
static void
rc_key_free(struct rckey *p)
{
free(p->rk_value);
free(p->rk_name);
free(p);
}
static char *minauth_values[] = {
"none",
"lm",
"ntlm",
"ntlmv2",
"kerberos",
NULL
};
static int
eval_minauth(char *auth)
{
int i;
for (i = 0; minauth_values[i]; i++)
if (strcmp(auth, minauth_values[i]) == 0)
return (i);
return (-1);
}
/*
* Ensure that "minauth" is set to the highest level
*/
/*ARGSUSED*/
static void
set_value(struct rcfile *rcp, struct rcsection *rsp, struct rckey *rkp,
char *ptr)
{
int now, new;
#ifdef DEBUG
char *from = "SMF";
if (home_nsmbrc != 0)
from = "user file";
#endif
if (strcmp(rkp->rk_name, "minauth") == 0) {
now = eval_minauth(rkp->rk_value);
new = eval_minauth(ptr);
if (new <= now) {
#ifdef DEBUG
if (smb_debug)
fprintf(stderr,
"set_value: rejecting %s=%s"
" in %s from %s\n",
rkp->rk_name, ptr,
rsp->rs_name, from);
#endif
return;
}
}
#ifdef DEBUG
if (smb_debug)
fprintf(stderr,
"set_value: applying %s=%s in %s from %s\n",
rkp->rk_name, ptr, rsp->rs_name, from);
#endif
rkp->rk_value = strdup(ptr);
}
/* states in rc_parse */
enum { stNewLine, stHeader, stSkipToEOL, stGetKey, stGetValue};
static void
rc_parse(struct rcfile *rcp)
{
FILE *f = rcp->rf_f;
int state = stNewLine, c;
struct rcsection *rsp = NULL;
struct rckey *rkp = NULL;
char buf[2048];
char *next = buf, *last = &buf[sizeof (buf)-1];
assert(MUTEX_HELD(&rcfile_mutex));
while ((c = getc(f)) != EOF) {
if (c == '\r')
continue;
if (state == stNewLine) {
next = buf;
if (isspace(c))
continue; /* skip leading junk */
if (c == '[') {
state = stHeader;
rsp = NULL;
continue;
}
if (c == '#' || c == ';') {
state = stSkipToEOL;
} else { /* something meaningfull */
state = stGetKey;
}
}
/* ignore long lines */
if (state == stSkipToEOL || next == last) {
if (c == '\n') {
state = stNewLine;
next = buf;
}
continue;
}
if (state == stHeader) {
if (c == ']') {
*next = 0;
next = buf;
rsp = rc_addsect(rcp, buf);
state = stSkipToEOL;
} else
*next++ = c;
continue;
}
if (state == stGetKey) {
/* side effect: 'key name=' */
if (c == ' ' || c == '\t')
continue; /* become 'keyname=' */
if (c == '\n') { /* silently ignore ... */
state = stNewLine;
continue;
}
if (c != '=') {
*next++ = c;
continue;
}
*next = 0;
if (rsp == NULL) {
fprintf(stderr, dgettext(TEXT_DOMAIN,
"Key '%s' defined before section\n"), buf);
state = stSkipToEOL;
continue;
}
if (home_nsmbrc != 0 && (
strcmp(buf, "nbns") == 0 ||
strcmp(buf, "nbns_enable") == 0 ||
strcmp(buf, "nbns_broadcast") == 0)) {
fprintf(stderr, dgettext(TEXT_DOMAIN,
"option %s may not be set "
"in user .nsmbrc file\n"), buf);
next = buf;
state = stNewLine;
continue;
}
if (insecure_nsmbrc != 0 &&
strcmp(buf, "password") == 0) {
fprintf(stderr, dgettext(TEXT_DOMAIN,
"Warning: .nsmbrc file not secure, "
"ignoring passwords\n"));
next = buf;
state = stNewLine;
continue;
}
rkp = rc_sect_addkey(rsp, buf, NULL);
next = buf;
state = stGetValue;
continue;
}
/* only stGetValue left */
if (state != stGetValue) {
fprintf(stderr, dgettext(TEXT_DOMAIN,
"Well, I can't parse file '%s'\n"), rcp->rf_name);
state = stSkipToEOL;
}
if (c != '\n') {
*next++ = c;
continue;
}
*next = 0;
set_value(rcp, rsp, rkp, buf);
state = stNewLine;
rkp = NULL;
} /* while */
if (c == EOF && state == stGetValue) {
*next = 0;
set_value(rcp, rsp, rkp, buf);
}
}
int
rc_getstringptr(struct rcfile *rcp, const char *section, const char *key,
char **dest)
{
struct rcsection *rsp;
struct rckey *rkp;
int err;
mutex_lock(&rcfile_mutex);
*dest = NULL;
rsp = rc_findsect(rcp, section);
if (!rsp) {
err = ENOENT;
goto out;
}
rkp = rc_sect_findkey(rsp, key);
if (!rkp) {
err = ENOENT;
goto out;
}
*dest = rkp->rk_value;
err = 0;
out:
mutex_unlock(&rcfile_mutex);
return (err);
}
int
rc_getstring(struct rcfile *rcp, const char *section, const char *key,
size_t maxlen, char *dest)
{
char *value;
int error;
error = rc_getstringptr(rcp, section, key, &value);
if (error)
return (error);
if (strlen(value) >= maxlen) {
fprintf(stderr, dgettext(TEXT_DOMAIN,
"line too long for key '%s' in section '%s', max = %d\n"),
key, section, maxlen);
return (EINVAL);
}
strcpy(dest, value);
return (0);
}
int
rc_getint(struct rcfile *rcp, const char *section, const char *key, int *value)
{
struct rcsection *rsp;
struct rckey *rkp;
int err;
mutex_lock(&rcfile_mutex);
rsp = rc_findsect(rcp, section);
if (!rsp) {
err = ENOENT;
goto out;
}
rkp = rc_sect_findkey(rsp, key);
if (!rkp) {
err = ENOENT;
goto out;
}
errno = 0;
*value = strtol(rkp->rk_value, NULL, 0);
if ((err = errno) != 0) {
fprintf(stderr, dgettext(TEXT_DOMAIN,
"invalid int value '%s' for key '%s' in section '%s'\n"),
rkp->rk_value, key, section);
}
out:
mutex_unlock(&rcfile_mutex);
return (err);
}
/*
* 1,yes,true
* 0,no,false
*/
int
rc_getbool(struct rcfile *rcp, const char *section, const char *key, int *value)
{
struct rcsection *rsp;
struct rckey *rkp;
char *p;
int err;
mutex_lock(&rcfile_mutex);
rsp = rc_findsect(rcp, section);
if (!rsp) {
err = ENOENT;
goto out;
}
rkp = rc_sect_findkey(rsp, key);
if (!rkp) {
err = ENOENT;
goto out;
}
p = rkp->rk_value;
while (*p && isspace(*p)) p++;
if (*p == '0' ||
strcasecmp(p, "no") == 0 ||
strcasecmp(p, "false") == 0) {
*value = 0;
err = 0;
goto out;
}
if (*p == '1' ||
strcasecmp(p, "yes") == 0 ||
strcasecmp(p, "true") == 0) {
*value = 1;
err = 0;
goto out;
}
fprintf(stderr, dgettext(TEXT_DOMAIN,
"invalid boolean value '%s' for key '%s' in section '%s' \n"),
p, key, section);
err = EINVAL;
out:
mutex_unlock(&rcfile_mutex);
return (err);
}
#ifdef DEBUG
void
dump_props(char *where)
{
struct rcsection *rsp = NULL;
struct rckey *rkp = NULL;
fprintf(stderr, "Settings %s\n", where);
if (smb_rc == NULL) {
fprintf(stderr, "(empty)\n");
fflush(stderr);
return;
}
SLIST_FOREACH(rsp, &smb_rc->rf_sect, rs_next) {
fprintf(stderr, "section=%s\n", rsp->rs_name);
fflush(stderr);
SLIST_FOREACH(rkp, &rsp->rs_keys, rk_next) {
fprintf(stderr, " key=%s, value=%s\n",
rkp->rk_name, rkp->rk_value);
fflush(stderr);
}
}
}
#endif
/*
* first parse "sharectl get smbfs, then $HOME/.nsmbrc
* This is called by library consumers (commands)
*/
int
smb_open_rcfile(char *home)
{
char *fn;
int len, error = 0;
mutex_lock(&rcfile_mutex);
smb_rc = NULL;
#if 0 /* before SMF */
fn = SMB_CFG_FILE;
error = rc_open(fn, &smb_rc);
#else
fn = "(sharectl get smbfs)";
error = rc_open_sharectl(&smb_rc);
#endif
if (error != 0 && error != ENOENT) {
/* Error from fopen. strerror is OK. */
fprintf(stderr, dgettext(TEXT_DOMAIN,
"Can't open %s: %s\n"), fn, strerror(errno));
}
#ifdef DEBUG
if (smb_debug)
dump_props(fn);
#endif
if (home) {
len = strlen(home) + 20;
fn = malloc(len);
snprintf(fn, len, "%s/.nsmbrc", home);
home_nsmbrc = 1;
error = rc_merge(fn, &smb_rc);
if (error != 0 && error != ENOENT) {
fprintf(stderr, dgettext(TEXT_DOMAIN,
"Can't open %s: %s\n"), fn, strerror(errno));
}
home_nsmbrc = 0;
#ifdef DEBUG
if (smb_debug)
dump_props(fn);
#endif
free(fn);
}
/* Mostly ignore error returns above. */
if (smb_rc == NULL)
error = ENOENT;
else
error = 0;
mutex_unlock(&rcfile_mutex);
return (error);
}
/*
* This is called by library consumers (commands)
*/
void
smb_close_rcfile(void)
{
struct rcfile *rcp;
if ((rcp = smb_rc) != NULL) {
smb_rc = NULL;
rc_close(rcp);
}
}
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
/*
* Copyright 2018 Nexenta Systems, Inc. All rights reserved.
*/
#ifndef _RCFILE_PRIV_H
#define _RCFILE_PRIV_H
/*
* Private RC file support.
*/
#include <sys/queue.h>
#ifdef __cplusplus
extern "C" {
#endif
struct rckey {
SLIST_ENTRY(rckey) rk_next;
char *rk_name;
char *rk_value;
};
struct rcsection {
SLIST_ENTRY(rcsection) rs_next;
SLIST_HEAD(rckey_head, rckey) rs_keys;
char *rs_name;
};
struct rcfile {
SLIST_ENTRY(rcfile) rf_next;
SLIST_HEAD(rcsec_head, rcsection) rf_sect;
char *rf_name;
FILE *rf_f;
int rf_flags; /* RCFILE_... */
};
#define RCFILE_HOME_NSMBRC 1
#define RCFILE_IS_INSECURE 2
#define RCFILE_DELETE_ON_CLOSE 4
int rc_scf_get_sharectl(FILE *);
#ifdef __cplusplus
}
#endif
#endif /* _RCFILE_PRIV_H */
/*
* Copyright (c) 2000-2001 Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
* Copyright 2013 Nexenta Systems, Inc. All rights reserved.
*/
#ifndef _SMB_CRYPT_H
#define _SMB_CRYPT_H
/*
* Various crypto stuff.
* from the driver: smb_crypt.c
*/
#ifdef __cplusplus
extern "C" {
#endif
int
smb_encrypt_DES(uchar_t *Result, int ResultLen,
const uchar_t *Key, int KeyLen,
const uchar_t *Data, int DataLen);
int
smb_encrypt_RC4(uchar_t *Result, int ResultLen,
const uchar_t *Key, int KeyLen,
const uchar_t *Data, int DataLen);
int
smb_get_urandom(void *data, size_t dlen);
#ifdef __cplusplus
}
#endif
#endif /* _SMB_CRYPT_H */
// Copyright 2012 Nexenta Systems, Inc. All rights reserved.
// Copyright (C) 2002 Microsoft Corporation
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS"
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
// OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTIBILITY
// AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Date - 10/08/2002
// Author - Sanj Surati
/////////////////////////////////////////////////////////////
//
// SPNEGO.C
//
// SPNEGO Token Handler Source File
//
// Contains implementation of SPNEGO Token Handling API
// as defined in SPNEGO.H.
//
/////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include "spnego.h"
#include "derparse.h"
#include "spnegoparse.h"
//
// Defined in DERPARSE.C
//
extern MECH_OID g_stcMechOIDList [];
/**********************************************************************/
/** **/
/** **/
/** **/
/** **/
/** SPNEGO Token Handler API implementation **/
/** **/
/** **/
/** **/
/** **/
/**********************************************************************/
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoInitFromBinary
//
// Parameters:
// [in] pbTokenData - Binary Token Data
// [in] ulLength - Length of binary Token Data
// [out] phSpnegoToken - SPNEGO_TOKEN_HANDLE pointer
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Initializes a SPNEGO_TOKEN_HANDLE from the supplied
// binary data. Data is copied locally. Returned data structure
// must be freed by calling spnegoFreeData().
//
////////////////////////////////////////////////////////////////////////////
int spnegoInitFromBinary( unsigned char* pbTokenData, unsigned long ulLength, SPNEGO_TOKEN_HANDLE* phSpnegoToken )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken;
// Pass off to a handler function that allows tighter control over how the token structure
// is handled. In this case, we want the token data copied and we want the associated buffer
// freed.
nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYDATA,
SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA, pbTokenData,
ulLength, ppSpnegoToken );
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoCreateNegTokenHint
//
// Parameters:
// [in] pMechTypeList - List of MechTypes (OIDs) to include
// [in] MechTypeCnt - Length of MechTypes array
// [in] pbPrincipal - Principal name for MechListMIC
// [out] phSpnegoToken - SPNEGO_TOKEN_HANDLE pointer
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Initializes a SPNEGO_TOKEN_HANDLE for a NegTokenInit type token
// from the supplied parameters. The token created is the "hint"
// used (for example) in the response to an SMB negotiate protocol.
// Returned data structure must be freed by calling spnegoFreeData().
//
// The "hint" tells the client what authentication methods this
// server supports (the ones in the MechTypeList). The Principal
// name historically was the server's own SPN, but recent versions
// of windows only supply: "not_defined_in_RFC4178@please_ignore"
// So if you want to be nice to your clients, provide the host SPN,
// otherwise provide the bogus SPN string like recent windows.
//
////////////////////////////////////////////////////////////////////////////
int spnegoCreateNegTokenHint( SPNEGO_MECH_OID *pMechTypeList, int MechTypeCnt,
unsigned char *pbPrincipal, SPNEGO_TOKEN_HANDLE* phSpnegoToken )
{
int nReturn;
long nTokenLength = 0L;
long nInternalTokenLength = 0L;
unsigned long ulPrincipalLen;
unsigned char* pbMechListMIC;
unsigned long ulMechListMICLen;
unsigned char* pbTokenData = NULL;
SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken;
if ( NULL == ppSpnegoToken || NULL == pbPrincipal )
return (SPNEGO_E_INVALID_PARAMETER);
/*
* Get the actual token size
*/
ulPrincipalLen = strlen((char *)pbPrincipal);
ulMechListMICLen = ASNDerCalcElementLength( ulPrincipalLen, NULL );
nReturn = CalculateMinSpnegoInitTokenSize(
0, /* ulMechTokenLen */
ulMechListMICLen,
pMechTypeList,
MechTypeCnt,
0, /* nReqFlagsAvailable */
&nTokenLength,
&nInternalTokenLength );
if ( nReturn != SPNEGO_E_SUCCESS )
return (nReturn);
// Allocate a buffer to hold the data.
pbTokenData = calloc( 1, nTokenLength );
if ( NULL == pbTokenData )
return ( SPNEGO_E_OUT_OF_MEMORY );
/*
* Construct the MechListMIC
*/
pbMechListMIC = pbTokenData + (nTokenLength - ulMechListMICLen);
(void) ASNDerWriteElement( pbMechListMIC, SPNEGO_NEGINIT_ELEMENT_MECHTYPES,
GENERALSTR, pbPrincipal, ulPrincipalLen );
// Now write the token
nReturn = CreateSpnegoInitToken(
pMechTypeList,
MechTypeCnt,
0, /* ContextFlags */
NULL, 0, /* MechToken, len */
pbMechListMIC,
ulMechListMICLen,
pbTokenData,
nTokenLength,
nInternalTokenLength );
if ( nReturn != SPNEGO_E_SUCCESS ) {
free( pbTokenData );
return (nReturn);
}
// This will copy our allocated pointer, and ensure that the sructure cleans
// up the data later
nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYPTR,
SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA,
pbTokenData, nTokenLength, ppSpnegoToken );
// Cleanup on failure
if ( nReturn != SPNEGO_E_SUCCESS ) {
free( pbTokenData );
return (nReturn);
}
return (SPNEGO_E_SUCCESS);
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoCreateNegTokenInit
//
// Parameters:
// [in] MechType - MechType to specify in MechTypeList element
// [in] ucContextFlags - Context Flags element value
// [in] pbMechToken - Pointer to binary MechToken Data
// [in] ulMechTokenLen - Length of MechToken Data
// [in] pbMechListMIC - Pointer to binary MechListMIC Data
// [in] ulMechListMICLen - Length of MechListMIC Data
// [out] phSpnegoToken - SPNEGO_TOKEN_HANDLE pointer
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Initializes a SPNEGO_TOKEN_HANDLE for a NegTokenInit type
// from the supplied parameters. ucContextFlags may be 0 or must be
// a valid flag combination. MechToken data can be NULL - if not, it
// must correspond to the MechType. MechListMIC can also be NULL.
// Returned data structure must be freed by calling spnegoFreeData().
//
////////////////////////////////////////////////////////////////////////////
int spnegoCreateNegTokenInit( SPNEGO_MECH_OID MechType,
unsigned char ucContextFlags, unsigned char* pbMechToken,
unsigned long ulMechTokenLen, unsigned char* pbMechListMIC,
unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
long nTokenLength = 0L;
long nInternalTokenLength = 0L;
unsigned char* pbTokenData = NULL;
SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken;
if ( NULL != ppSpnegoToken &&
IsValidMechOid( MechType ) &&
IsValidContextFlags( ucContextFlags ) )
{
// Get the actual token size
if ( ( nReturn = CalculateMinSpnegoInitTokenSize( ulMechTokenLen, ulMechListMICLen,
&MechType, 1, ( ucContextFlags != 0L ),
&nTokenLength, &nInternalTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Allocate a buffer to hold the data.
pbTokenData = calloc( 1, nTokenLength );
if ( NULL != pbTokenData )
{
// Now write the token
if ( ( nReturn = CreateSpnegoInitToken( &MechType, 1,
ucContextFlags, pbMechToken,
ulMechTokenLen, pbMechListMIC,
ulMechListMICLen, pbTokenData,
nTokenLength, nInternalTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// This will copy our allocated pointer, and ensure that the sructure cleans
// up the data later
nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYPTR,
SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA,
pbTokenData, nTokenLength, ppSpnegoToken );
}
// Cleanup on failure
if ( SPNEGO_E_SUCCESS != nReturn )
{
free( pbTokenData );
}
} // IF alloc succeeded
else
{
nReturn = SPNEGO_E_OUT_OF_MEMORY;
}
} // If calculated token size
} // IF Valid Parameters
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoCreateNegTokenTarg
//
// Parameters:
// [in] MechType - MechType to specify in supported MechType element
// [in] spnegoNegResult - NegResult value
// [in] pbMechToken - Pointer to response MechToken Data
// [in] ulMechTokenLen - Length of MechToken Data
// [in] pbMechListMIC - Pointer to binary MechListMIC Data
// [in] ulMechListMICLen - Length of MechListMIC Data
// [out] phSpnegoToken - SPNEGO_TOKEN_HANDLE pointer
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Initializes a SPNEGO_TOKEN_HANDLE for a NegTokenTarg type
// from the supplied parameters. MechToken data can be NULL - if not,
// it must correspond to the MechType. MechListMIC can also be NULL.
// Returned data structure must be freed by calling spnegoFreeData().
//
////////////////////////////////////////////////////////////////////////////
int spnegoCreateNegTokenTarg( SPNEGO_MECH_OID MechType,
SPNEGO_NEGRESULT spnegoNegResult, unsigned char* pbMechToken,
unsigned long ulMechTokenLen, unsigned char* pbMechListMIC,
unsigned long ulMechListMICLen, SPNEGO_TOKEN_HANDLE* phSpnegoToken )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
long nTokenLength = 0L;
long nInternalTokenLength = 0L;
unsigned char* pbTokenData = NULL;
SPNEGO_TOKEN** ppSpnegoToken = (SPNEGO_TOKEN**) phSpnegoToken;
//
// spnego_mech_oid_NotUsed and spnego_negresult_NotUsed
// are okay here, however a valid MechOid is required
// if spnego_negresult_success or spnego_negresult_incomplete
// is specified.
//
if ( NULL != ppSpnegoToken &&
( IsValidMechOid( MechType ) ||
spnego_mech_oid_NotUsed == MechType ) &&
( IsValidNegResult( spnegoNegResult ) ||
spnego_negresult_NotUsed == spnegoNegResult ) )
{
// Get the actual token size
if ( ( nReturn = CalculateMinSpnegoTargTokenSize( MechType, spnegoNegResult, ulMechTokenLen,
ulMechListMICLen, &nTokenLength,
&nInternalTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Allocate a buffer to hold the data.
pbTokenData = calloc( 1, nTokenLength );
if ( NULL != pbTokenData )
{
// Now write the token
if ( ( nReturn = CreateSpnegoTargToken( MechType,
spnegoNegResult, pbMechToken,
ulMechTokenLen, pbMechListMIC,
ulMechListMICLen, pbTokenData,
nTokenLength, nInternalTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// This will copy our allocated pointer, and ensure that the sructure cleans
// up the data later
nReturn = InitTokenFromBinary( SPNEGO_TOKEN_INTERNAL_COPYPTR,
SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA,
pbTokenData, nTokenLength, ppSpnegoToken );
}
// Cleanup on failure
if ( SPNEGO_E_SUCCESS != nReturn )
{
free( pbTokenData );
}
} // IF alloc succeeded
else
{
nReturn = SPNEGO_E_OUT_OF_MEMORY;
}
} // If calculated token size
} // IF Valid Parameters
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoTokenGetBinary
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
// [out] pbTokenData - Buffer to copy token into
// [in/out] pulDataLen - Length of pbTokenData buffer, filled out
// with actual size used upon function return.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Copies binary SPNEGO token data from hSpnegoToken into the user
// supplied buffer. If pbTokenData is NULL, or the value in pulDataLen
// is too small, the function will return SPNEGO_E_BUFFER_TOO_SMALL and
// fill out pulDataLen with the minimum required buffer size.
//
////////////////////////////////////////////////////////////////////////////
int spnegoTokenGetBinary( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTokenData,
unsigned long * pulDataLen )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken;
// Check parameters - pbTokenData is optional
if ( IsValidSpnegoToken( pSpnegoToken ) &&
NULL != pulDataLen )
{
// Check for Buffer too small conditions
if ( NULL == pbTokenData ||
pSpnegoToken->ulBinaryDataLen > *pulDataLen )
{
*pulDataLen = pSpnegoToken->ulBinaryDataLen;
nReturn = SPNEGO_E_BUFFER_TOO_SMALL;
}
else
{
memcpy( pbTokenData, pSpnegoToken->pbBinaryData, pSpnegoToken->ulBinaryDataLen );
*pulDataLen = pSpnegoToken->ulBinaryDataLen;
nReturn = SPNEGO_E_SUCCESS;
}
} // IF parameters OK
return nReturn;;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoFreeData
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
//
// Returns:
// void
//
// Comments :
// Frees up resources consumed by hSpnegoToken. The supplied data
// pointer is invalidated by this function.
//
////////////////////////////////////////////////////////////////////////////
void spnegoFreeData( SPNEGO_TOKEN_HANDLE hSpnegoToken )
{
FreeSpnegoToken( (SPNEGO_TOKEN*) hSpnegoToken);
return;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoGetTokenType
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
// [out] piTokenType - Filled out with token type value.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// The function will analyze hSpnegoToken and return the appropriate
// type in piTokenType.
//
////////////////////////////////////////////////////////////////////////////
int spnegoGetTokenType( SPNEGO_TOKEN_HANDLE hSpnegoToken, int * piTokenType )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken;
// Check parameters
if ( IsValidSpnegoToken( pSpnegoToken ) &&
NULL != piTokenType &&
pSpnegoToken)
{
// Check that the type in the structure makes sense
if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ||
SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType )
{
*piTokenType = pSpnegoToken->ucTokenType;
nReturn = SPNEGO_E_SUCCESS;
}
} // IF parameters OK
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoIsMechTypeAvailable
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
// [in] MechOID - MechOID to search MechTypeList for
// [out] piMechTypeIndex - Filled out with index in MechTypeList
// element if MechOID is found.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// hSpnegoToken must reference a token of type NegTokenInit. The
// function will search the MechTypeList element for an OID corresponding
// to the specified MechOID. If one is found, the index (0 based) will
// be passed into the piMechTypeIndex parameter.
//
////////////////////////////////////////////////////////////////////////////
// Returns the Initial Mech Type in the MechList element in the NegInitToken.
int spnegoIsMechTypeAvailable( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID MechOID, int * piMechTypeIndex )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken;
// Check parameters
if ( IsValidSpnegoToken( pSpnegoToken ) &&
NULL != piMechTypeIndex &&
IsValidMechOid( MechOID ) &&
SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
{
// Check if MechList is available
if ( pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTYPES_ELEMENT].iElementPresent
== SPNEGO_TOKEN_ELEMENT_AVAILABLE )
{
// Locate the MechOID in the list element
nReturn = FindMechOIDInMechList(
&pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTYPES_ELEMENT],
MechOID, piMechTypeIndex );
}
else
{
nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE;
}
} // IF parameters OK
return nReturn;;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoGetContextFlags
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
// [out] pucContextFlags - Filled out with ContextFlags value.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// hSpnegoToken must reference a token of type NegTokenInit. The
// function will copy data from the ContextFlags element into the
// location pucContextFlags points to. Note that the function will
// fail if the actual ContextFlags data appears invalid.
//
////////////////////////////////////////////////////////////////////////////
int spnegoGetContextFlags( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pucContextFlags )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken;
// Check parameters
if ( IsValidSpnegoToken( pSpnegoToken ) &&
NULL != pucContextFlags &&
SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
{
// Check if ContextFlags is available
if ( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].iElementPresent
== SPNEGO_TOKEN_ELEMENT_AVAILABLE )
{
// The length should be two, the value should show a 1 bit difference in the difference byte, and
// the value must be valid
if ( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].nDatalength == SPNEGO_NEGINIT_MAXLEN_REQFLAGS &&
pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[0] == SPNEGO_NEGINIT_REQFLAGS_BITDIFF &&
IsValidContextFlags( pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[1] ) )
{
*pucContextFlags = pSpnegoToken->aElementArray[SPNEGO_INIT_REQFLAGS_ELEMENT].pbData[1];
nReturn = SPNEGO_E_SUCCESS;
}
else
{
nReturn = SPNEGO_E_INVALID_ELEMENT;
}
}
else
{
nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE;
}
} // IF parameters OK
return nReturn;;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoGetNegotiationResult
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
// [out] pnegResult - Filled out with NegResult value.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// hSpnegoToken must reference a token of type NegTokenTarg. The
// function will copy data from the NegResult element into the
// location pointed to by pnegResult. Note that the function will
// fail if the actual NegResult data appears invalid.
//
////////////////////////////////////////////////////////////////////////////
int spnegoGetNegotiationResult( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_NEGRESULT* pnegResult )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken;
// Check parameters
if ( IsValidSpnegoToken( pSpnegoToken ) &&
NULL != pnegResult &&
SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType )
{
// Check if NegResult is available
if ( pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].iElementPresent
== SPNEGO_TOKEN_ELEMENT_AVAILABLE )
{
// Must be 1 byte long and a valid value
if ( pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].nDatalength == SPNEGO_NEGTARG_MAXLEN_NEGRESULT &&
IsValidNegResult( *pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].pbData ) )
{
*pnegResult = *pSpnegoToken->aElementArray[SPNEGO_TARG_NEGRESULT_ELEMENT].pbData;
nReturn = SPNEGO_E_SUCCESS;
}
else
{
nReturn = SPNEGO_E_INVALID_ELEMENT;
}
}
else
{
nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE;
}
} // IF parameters OK
return nReturn;;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoGetSupportedMechType
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
// [out] pMechOID - Filled out with Supported MechType value.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// hSpnegoToken must reference a token of type NegTokenTarg. The
// function will check the Supported MechType element, and if it
// corresponds to a supported MechType ( spnego_mech_oid_Kerberos_V5_Legacy
// or spnego_mech_oid_Kerberos_V5 ), will set the location pointed
// to by pMechOID equal to the appropriate value.
//
////////////////////////////////////////////////////////////////////////////
int spnegoGetSupportedMechType( SPNEGO_TOKEN_HANDLE hSpnegoToken, SPNEGO_MECH_OID* pMechOID )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
int nCtr = 0L;
long nLength = 0L;
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken;
// Check parameters
if ( IsValidSpnegoToken( pSpnegoToken ) &&
NULL != pMechOID &&
SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType )
{
// Check if MechList is available
if ( pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].iElementPresent
== SPNEGO_TOKEN_ELEMENT_AVAILABLE )
{
for ( nCtr = 0;
nReturn != SPNEGO_E_SUCCESS &&
g_stcMechOIDList[nCtr].eMechanismOID != spnego_mech_oid_NotUsed;
nCtr++ )
{
if ( ( nReturn = ASNDerCheckOID(
pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].pbData,
nCtr,
pSpnegoToken->aElementArray[SPNEGO_TARG_SUPPMECH_ELEMENT].nDatalength,
&nLength ) ) == SPNEGO_E_SUCCESS )
{
*pMechOID = nCtr;
}
} // For enum MechOIDs
}
else
{
nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE;
}
} // IF parameters OK
return nReturn;;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoTokenGetMechToken
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
// [out] pbTokenData - Buffer to copy MechToken into
// [in/out] pulDataLen - Length of pbTokenData buffer, filled out
// with actual size used upon function return.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// hSpnegoToken can point to either NegTokenInit or a NegTokenTarg token.
// The function will copy the MechToken (the initial MechToken if
// NegTokenInit, the response MechToken if NegTokenTarg) from the
// underlying token into the buffer pointed to by pbTokenData. If
// pbTokenData is NULL, or the value in pulDataLen is too small, the
// function will return SPNEGO_E_BUFFER_TOO_SMALL and fill out pulDataLen
// with the minimum required buffer size. The token can then be passed
// to a GSS-API function for processing.
//
////////////////////////////////////////////////////////////////////////////
int spnegoGetMechToken( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbTokenData, unsigned long* pulDataLen )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken;
SPNEGO_ELEMENT* pSpnegoElement = NULL;
// Check parameters
if ( IsValidSpnegoToken( pSpnegoToken ) &&
NULL != pulDataLen )
{
// Point at the proper Element
if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
{
pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_INIT_MECHTOKEN_ELEMENT];
}
else
{
pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_TARG_RESPTOKEN_ELEMENT];
}
// Check if MechType is available
if ( SPNEGO_TOKEN_ELEMENT_AVAILABLE == pSpnegoElement->iElementPresent )
{
// Check for Buffer too small conditions
if ( NULL == pbTokenData ||
pSpnegoElement->nDatalength > *pulDataLen )
{
*pulDataLen = pSpnegoElement->nDatalength;
nReturn = SPNEGO_E_BUFFER_TOO_SMALL;
}
else
{
// Copy Memory
memcpy( pbTokenData, pSpnegoElement->pbData, pSpnegoElement->nDatalength );
*pulDataLen = pSpnegoElement->nDatalength;
nReturn = SPNEGO_E_SUCCESS;
}
}
else
{
nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE;
}
} // IF parameters OK
return nReturn;;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// spnegoTokenGetMechListMIC
//
// Parameters:
// [in] hSpnegoToken - Initialized SPNEGO_TOKEN_HANDLE
// [out] pbTokenData - Buffer to copy MechListMIC data into
// [in/out] pulDataLen - Length of pbTokenData buffer, filled out
// with actual size used upon function return.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// hSpnegoToken can point to either NegTokenInit or a NegTokenTarg token.
// The function will copy the MechListMIC data from the underlying token
// into the buffer pointed to by pbTokenData. If pbTokenData is NULL,
// or the value in pulDataLen is too small, the function will return
// SPNEGO_E_BUFFER_TOO_SMALL and fill out pulDataLen with the minimum
// required buffer size.
//
////////////////////////////////////////////////////////////////////////////
int spnegoGetMechListMIC( SPNEGO_TOKEN_HANDLE hSpnegoToken, unsigned char* pbMICData, unsigned long* pulDataLen )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) hSpnegoToken;
SPNEGO_ELEMENT* pSpnegoElement = NULL;
// Check parameters
if ( IsValidSpnegoToken( pSpnegoToken ) &&
NULL != pulDataLen )
{
// Point at the proper Element
if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
{
pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_INIT_MECHLISTMIC_ELEMENT];
}
else
{
pSpnegoElement = &pSpnegoToken->aElementArray[SPNEGO_TARG_MECHLISTMIC_ELEMENT];
}
// Check if MechType is available
if ( SPNEGO_TOKEN_ELEMENT_AVAILABLE == pSpnegoElement->iElementPresent )
{
// Check for Buffer too small conditions
if ( NULL == pbMICData ||
pSpnegoElement->nDatalength > *pulDataLen )
{
*pulDataLen = pSpnegoElement->nDatalength;
nReturn = SPNEGO_E_BUFFER_TOO_SMALL;
}
else
{
// Copy Memory
memcpy( pbMICData, pSpnegoElement->pbData, pSpnegoElement->nDatalength );
*pulDataLen = pSpnegoElement->nDatalength;
nReturn = SPNEGO_E_SUCCESS;
}
}
else
{
nReturn = SPNEGO_E_ELEMENT_UNAVAILABLE;
}
} // IF parameters OK
return nReturn;;
}
// Copyright 2022 RackTop Systems, Inc.
// Copyright 2012 Nexenta Systems, Inc. All rights reserved.
// Copyright (C) 2002 Microsoft Corporation
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS"
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
// OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTIBILITY
// AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Date - 10/08/2002
// Author - Sanj Surati
/////////////////////////////////////////////////////////////
//
// SPNEGOPARSE.C
//
// SPNEGO Token Handler Source File
//
// Contains implementation of SPNEGO Token parsing functions.
//
/////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include "spnego.h"
#include "derparse.h"
#include "spnegoparse.h"
//
// Defined in DERPARSE.C
//
extern MECH_OID g_stcMechOIDList [];
/**********************************************************************/
/** **/
/** **/
/** **/
/** **/
/** Local SPNEGO Helper definitions **/
/** **/
/** **/
/** **/
/** **/
/**********************************************************************/
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// CalculateMinSpnegoInitTokenSize
//
// Parameters:
// [in] nMechTokenLength - Length of the MechToken Element
// [in] nMechListMICLength - Length of the MechListMIC Element
// (or negHints, if no MechToken)
// [in] mechOID - OID for MechList
// [in] nReqFlagsAvailable - Is ContextFlags element available
// [out] pnTokenSize - Filled out with total size of token
// [out] pnInternalTokenLength - Filled out with length minus length
// for initial token.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Calculates the required length for a SPNEGO NegTokenInit token based
// on the supplied variable length values and which elements are present.
// Note that because the lengths can be represented by an arbitrary
// number of bytes in DER encodings, we actually calculate the lengths
// backwards, so we always know how many bytes we will potentially be
// writing out.
//
////////////////////////////////////////////////////////////////////////////
int CalculateMinSpnegoInitTokenSize( long nMechTokenLength,
long nMechListMICLength, SPNEGO_MECH_OID *mechOidLst, int mechOidCnt,
int nReqFlagsAvailable, long* pnTokenSize,
long* pnInternalTokenLength )
{
int nReturn = SPNEGO_E_INVALID_LENGTH;
// Start at 0.
long nTotalLength = 0;
long nTempLength= 0L;
// We will calculate this by walking the token backwards
// Start with MIC Element (or negHints)
if ( nMechListMICLength > 0L )
{
nTempLength = ASNDerCalcElementLength( nMechListMICLength, NULL );
// Check for rollover error
if ( nTempLength < nMechListMICLength )
{
goto xEndTokenInitLength;
}
nTotalLength += nTempLength;
}
// Next is the MechToken
if ( nMechTokenLength > 0L )
{
nTempLength += ASNDerCalcElementLength( nMechTokenLength, NULL );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenInitLength;
}
nTotalLength = nTempLength;
}
// Next is the ReqFlags
if ( nReqFlagsAvailable )
{
nTempLength += ASNDerCalcElementLength( SPNEGO_NEGINIT_MAXLEN_REQFLAGS, NULL );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenInitLength;
}
nTotalLength = nTempLength;
}
// Next is the MechList - This is REQUIRED
nTempLength += ASNDerCalcMechListLength( mechOidLst, mechOidCnt, NULL );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenInitLength;
}
nTotalLength = nTempLength;
// Following four fields are the basic header tokens
// Sequence Token
nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenInitLength;
}
nTotalLength = nTempLength;
// Neg Token Identifier Token
nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenInitLength;
}
nTotalLength = nTempLength;
// SPNEGO OID Token
nTempLength += g_stcMechOIDList[spnego_mech_oid_Spnego].iLen;
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenInitLength;
}
nTotalLength = nTempLength;
// App Constructed Token
nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenInitLength;
}
// The internal length doesn't include the number of bytes
// for the initial token
*pnInternalTokenLength = nTotalLength;
nTotalLength = nTempLength;
// We're done
*pnTokenSize = nTotalLength;
nReturn = SPNEGO_E_SUCCESS;
xEndTokenInitLength:
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// CreateSpnegoInitToken
//
// Parameters:
// [in] pMechTypeList - OID array
// [in] MechTypeCnt - OID array length
// [in] ucContextFlags - ContextFlags value
// [in] pbMechToken - Mech Token Binary Data
// [in] ulMechTokenLen - Length of Mech Token
// [in] pbMechListMIC - MechListMIC Binary Data (or negHints)
// [in] ulMechListMICn - Length of MechListMIC
// [out] pbTokenData - Buffer to write token into.
// [in] nTokenLength - Length of pbTokenData buffer
// [in] nInternalTokenLength - Length of full token without leading
// token bytes.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Uses DER to fill out pbTokenData with a SPNEGO NegTokenInit Token
// Note that because the lengths can be represented by an arbitrary
// number of bytes in DER encodings, we actually calculate the lengths
// backwards, so we always know how many bytes we will potentially be
// writing out.
//
// This function is also used to create an SPNEGO "hint", as described in
// [MS-SPNG] sec. 2.2.1 negTokenInit2. The "hint" looks almost identical
// to a NegTokenInit, but has a "negHints" field inserted before the MIC.
// A normal SPNEGO negTokenInit2 contains only the mech list and the
// negHints. To avoid a giant copy/paste of this function, we pass the
// negHints as the MIC arg, and pass NULL as the MechToken to indicate
// that we're creating a Hint rather than an Init, and use the correct
// type when writing out the MIC (or negHints) element.
//
////////////////////////////////////////////////////////////////////////////
int CreateSpnegoInitToken( SPNEGO_MECH_OID *pMechTypeList, long MechTypeCnt,
unsigned char ucContextFlags, unsigned char* pbMechToken,
unsigned long ulMechTokenLen, unsigned char* pbMechListMIC,
unsigned long ulMechListMICLen, unsigned char* pbTokenData,
long nTokenLength, long nInternalTokenLength )
{
int nReturn = SPNEGO_E_INVALID_LENGTH;
// Start at 0.
long nTempLength= 0L;
long nTotalBytesWritten = 0L;
long nInternalLength = 0L;
unsigned char* pbWriteTokenData = pbTokenData + nTokenLength;
// Temporary buffer to hold the REQ Flags as BIT String Data
unsigned char abTempReqFlags[SPNEGO_NEGINIT_MAXLEN_REQFLAGS];
// We will write the token out backwards to properly handle the cases
// where the length bytes become adjustable
// Start with MIC Element (or negHints)
if ( ulMechListMICLen > 0L )
{
unsigned char ucType;
nTempLength = ASNDerCalcElementLength( ulMechListMICLen, &nInternalLength );
// Decrease the pbWriteTokenData, now we know the length and write it out.
// Note: When MechTokenLen == 0, we're writing a negTokenInit2 and the
// MIC arg is really negHints, written as a constructed sequence.
// Otherwise we're writing a negTokenInit, and the MIC is an OCTETSTRING.
ucType = (ulMechTokenLen == 0) ?
SPNEGO_CONSTRUCTED_SEQUENCE : OCTETSTRING;
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC,
ucType, pbMechListMIC, ulMechListMICLen );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenInit;
}
} // IF MechListMIC is present
// Next is the MechToken
if ( ulMechTokenLen > 0L )
{
nTempLength = ASNDerCalcElementLength( ulMechTokenLen, &nInternalLength );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_MECHTOKEN,
OCTETSTRING, pbMechToken, ulMechTokenLen );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenInit;
}
} // IF MechToken Length is present
// Next is the ReqFlags
if ( ucContextFlags > 0L )
{
nTempLength = ASNDerCalcElementLength( SPNEGO_NEGINIT_MAXLEN_REQFLAGS, &nInternalLength );
// We need a byte that indicates how many bits difference between the number
// of bits used in final octet (we only have one) and the max (8)
abTempReqFlags[0] = SPNEGO_NEGINIT_REQFLAGS_BITDIFF;
abTempReqFlags[1] = ucContextFlags;
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGINIT_ELEMENT_REQFLAGS,
BITSTRING, abTempReqFlags, SPNEGO_NEGINIT_MAXLEN_REQFLAGS );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenInit;
}
} // IF ContextFlags
// Next is the MechList - This is REQUIRED
nTempLength = ASNDerCalcMechListLength( pMechTypeList, MechTypeCnt, &nInternalLength );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteMechList( pbWriteTokenData, pMechTypeList, MechTypeCnt );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenInit;
}
// The next tokens we're writing out reflect the total number of bytes
// we have actually written out.
// Sequence Token
nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
NULL, nTotalBytesWritten );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenInit;
}
// Neg Init Token Identifier Token
nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGINIT_TOKEN_IDENTIFIER,
NULL, nTotalBytesWritten );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenInit;
}
// SPNEGO OID Token
nTempLength = g_stcMechOIDList[spnego_mech_oid_Spnego].iLen;
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteOID( pbWriteTokenData, spnego_mech_oid_Spnego );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenInit;
}
// App Constructed Token
nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGINIT_APP_CONSTRUCT,
NULL, nTotalBytesWritten );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
// Don't adjust the internal token length here, it doesn't account
// the initial bytes written out (we really don't need to keep
// a running count here, but for debugging, it helps to be able
// to see the total number of bytes written out as well as the
// number of bytes left to write).
if ( nTotalBytesWritten == nTokenLength && nInternalTokenLength == 0 &&
pbWriteTokenData == pbTokenData )
{
nReturn = SPNEGO_E_SUCCESS;
}
xEndWriteNegTokenInit:
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// CalculateMinSpnegoTargTokenSize
//
// Parameters:
// [in] MechType - Supported MechType
// [in] spnegoNegResult - Neg Result
// [in] nMechTokenLength - Length of the MechToken Element
// [in] nMechListMICLength - Length of the MechListMIC Element
// [out] pnTokenSize - Filled out with total size of token
// [out] pnInternalTokenLength - Filled out with length minus length
// for initial token.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Calculates the required length for a SPNEGO NegTokenTarg token based
// on the supplied variable length values and which elements are present.
// Note that because the lengths can be represented by an arbitrary
// number of bytes in DER encodings, we actually calculate the lengths
// backwards, so we always know how many bytes we will potentially be
// writing out.
//
////////////////////////////////////////////////////////////////////////////
int CalculateMinSpnegoTargTokenSize( SPNEGO_MECH_OID MechType,
SPNEGO_NEGRESULT spnegoNegResult, long nMechTokenLen,
long nMechListMICLen, long* pnTokenSize,
long* pnInternalTokenLength )
{
int nReturn = SPNEGO_E_INVALID_LENGTH;
// Start at 0.
long nTotalLength = 0;
long nTempLength= 0L;
// We will calculate this by walking the token backwards
// Start with MIC Element
if ( nMechListMICLen > 0L )
{
nTempLength = ASNDerCalcElementLength( nMechListMICLen, NULL );
// Check for rollover error
if ( nTempLength < nMechListMICLen )
{
goto xEndTokenTargLength;
}
nTotalLength += nTempLength;
}
// Next is the MechToken
if ( nMechTokenLen > 0L )
{
nTempLength += ASNDerCalcElementLength( nMechTokenLen, NULL );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenTargLength;
}
nTotalLength = nTempLength;
}
// Supported MechType
if ( spnego_mech_oid_NotUsed != MechType )
{
// Supported MechOID element - we use the token function since
// we already know the size of the OID token and value
nTempLength += ASNDerCalcElementLength( g_stcMechOIDList[MechType].iActualDataLen,
NULL );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenTargLength;
}
nTotalLength = nTempLength;
} // IF MechType is available
// NegResult Element
if ( spnego_negresult_NotUsed != spnegoNegResult )
{
nTempLength += ASNDerCalcElementLength( SPNEGO_NEGTARG_MAXLEN_NEGRESULT, NULL );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenTargLength;
}
nTotalLength = nTempLength;
} // IF negResult is available
// Following two fields are the basic header tokens
// Sequence Token
nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenTargLength;
}
nTotalLength = nTempLength;
// Neg Token Identifier Token
nTempLength += ASNDerCalcTokenLength( nTotalLength, 0L );
// Check for rollover error
if ( nTempLength < nTotalLength )
{
goto xEndTokenTargLength;
}
// The internal length doesn't include the number of bytes
// for the initial token
*pnInternalTokenLength = nTotalLength;
nTotalLength = nTempLength;
// We're done
*pnTokenSize = nTotalLength;
nReturn = SPNEGO_E_SUCCESS;
xEndTokenTargLength:
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// CreateSpnegoTargToken
//
// Parameters:
// [in] MechType - Supported MechType
// [in] eNegResult - NegResult value
// [in] pbMechToken - Mech Token Binary Data
// [in] ulMechTokenLen - Length of Mech Token
// [in] pbMechListMIC - MechListMIC Binary Data
// [in] ulMechListMICn - Length of MechListMIC
// [out] pbTokenData - Buffer to write token into.
// [in] nTokenLength - Length of pbTokenData buffer
// [in] nInternalTokenLength - Length of full token without leading
// token bytes.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Uses DER to fill out pbTokenData with a SPNEGO NegTokenTarg Token
// Note that because the lengths can be represented by an arbitrary
// number of bytes in DER encodings, we actually calculate the lengths
// backwards, so we always know how many bytes we will potentially be
// writing out.
//
////////////////////////////////////////////////////////////////////////////
int CreateSpnegoTargToken( SPNEGO_MECH_OID MechType,
SPNEGO_NEGRESULT eNegResult, unsigned char* pbMechToken,
unsigned long ulMechTokenLen, unsigned char* pbMechListMIC,
unsigned long ulMechListMICLen, unsigned char* pbTokenData,
long nTokenLength, long nInternalTokenLength )
{
int nReturn = SPNEGO_E_INVALID_LENGTH;
// Start at 0.
long nTempLength= 0L;
long nTotalBytesWritten = 0L;
long nInternalLength = 0L;
unsigned char ucTemp = 0;
// We will write the token out backwards to properly handle the cases
// where the length bytes become adjustable, so the write location
// is initialized to point *just* past the end of the buffer.
unsigned char* pbWriteTokenData = pbTokenData + nTokenLength;
// Start with MIC Element
if ( ulMechListMICLen > 0L )
{
nTempLength = ASNDerCalcElementLength( ulMechListMICLen, &nInternalLength );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC,
OCTETSTRING, pbMechListMIC, ulMechListMICLen );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenTarg;
}
} // IF MechListMIC is present
// Next is the MechToken
if ( ulMechTokenLen > 0L )
{
nTempLength = ASNDerCalcElementLength( ulMechTokenLen, &nInternalLength );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN,
OCTETSTRING, pbMechToken, ulMechTokenLen );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenTarg;
}
} // IF MechToken Length is present
// Supported Mech Type
if ( spnego_mech_oid_NotUsed != MechType )
{
nTempLength = ASNDerCalcElementLength( g_stcMechOIDList[MechType].iActualDataLen,
&nInternalLength );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH,
g_stcMechOIDList[MechType].ucOid,
g_stcMechOIDList[MechType].iLen );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenTarg;
}
} // IF MechType is present
// Neg Result
// NegResult Element
if ( spnego_negresult_NotUsed != eNegResult )
{
ucTemp = (unsigned char) eNegResult;
nTempLength = ASNDerCalcElementLength( SPNEGO_NEGTARG_MAXLEN_NEGRESULT, &nInternalLength );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteElement( pbWriteTokenData, SPNEGO_NEGTARG_ELEMENT_NEGRESULT,
ENUMERATED, &ucTemp, SPNEGO_NEGTARG_MAXLEN_NEGRESULT );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenTarg;
}
} // If eNegResult is available
// The next tokens we're writing out reflect the total number of bytes
// we have actually written out.
// Sequence Token
nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
NULL, nTotalBytesWritten );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
nInternalTokenLength -= nTempLength;
if ( nTotalBytesWritten > nTokenLength || nInternalTokenLength < 0 )
{
goto xEndWriteNegTokenTarg;
}
// Neg Targ Token Identifier Token
nTempLength = ASNDerCalcTokenLength( nTotalBytesWritten, 0L );
// Decrease the pbWriteTokenData, now we know the length and
// write it out.
pbWriteTokenData -= nTempLength;
nTempLength = ASNDerWriteToken( pbWriteTokenData, SPNEGO_NEGTARG_TOKEN_IDENTIFIER,
NULL, nTotalBytesWritten );
// Adjust Values and sanity check
nTotalBytesWritten += nTempLength;
// Don't adjust the internal token length here, it doesn't account
// the initial bytes written out (we really don't need to keep
// a running count here, but for debugging, it helps to be able
// to see the total number of bytes written out as well as the
// number of bytes left to write).
if ( nTotalBytesWritten == nTokenLength && nInternalTokenLength == 0 &&
pbWriteTokenData == pbTokenData )
{
nReturn = SPNEGO_E_SUCCESS;
}
xEndWriteNegTokenTarg:
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// AllocEmptySpnegoToken
//
// Parameters:
// [in] ucCopyData - Flag to copy data or pointer.
// [in] ulFlags - Flags for SPNEGO_TOKEN data member.
// [in] pbTokenData - Binary token data.
// [in] ulTokenSize - Size of pbTokenData.
//
// Returns:
// SPNEGO_TOKEN* Success - Pointer to initialized SPNEGO_TOKEN struct
// Failure - NULL
//
// Comments :
// Allocates a SPNEGO_TOKEN data structure and initializes it. Based on
// the value of ucCopyData, if non-zero, we copy the data into a buffer
// we allocate in this function, otherwise, we copy the data pointer
// direcly.
//
////////////////////////////////////////////////////////////////////////////
SPNEGO_TOKEN* AllocEmptySpnegoToken( unsigned char ucCopyData, unsigned long ulFlags,
unsigned char * pbTokenData, unsigned long ulTokenSize )
{
SPNEGO_TOKEN* pSpnegoToken = (SPNEGO_TOKEN*) calloc( 1, sizeof(SPNEGO_TOKEN) );
if ( NULL != pSpnegoToken )
{
// Set the token size
pSpnegoToken->nStructSize = SPNEGO_TOKEN_SIZE;
// Initialize the element array
InitSpnegoTokenElementArray( pSpnegoToken );
// Assign the flags value
pSpnegoToken->ulFlags = ulFlags;
//
// IF ucCopyData is TRUE, we will allocate a buffer and copy data into it.
// Otherwise, we will just copy the pointer and the length. This is so we
// can cut out additional allocations for performance reasons
//
if ( SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA == ucCopyData )
{
// Alloc the internal buffer. Cleanup on failure.
pSpnegoToken->pbBinaryData = (unsigned char*) calloc( ulTokenSize, sizeof(unsigned char) );
if ( NULL != pSpnegoToken->pbBinaryData )
{
// We must ALWAYS free this buffer
pSpnegoToken->ulFlags |= SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA;
// Copy the data locally
memcpy( pSpnegoToken->pbBinaryData, pbTokenData, ulTokenSize );
pSpnegoToken->ulBinaryDataLen = ulTokenSize;
}
else
{
free( pSpnegoToken );
pSpnegoToken = NULL;
}
} // IF ucCopyData
else
{
// Copy the pointer and the length directly - ulFlags will control whether or not
// we are allowed to free the value
pSpnegoToken->pbBinaryData = pbTokenData;
pSpnegoToken->ulBinaryDataLen = ulTokenSize;
}
}
return pSpnegoToken;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// FreeSpnegoToken
//
// Parameters:
// [in] pSpnegoToken - Points to SPNEGO_TOKEN to free.
//
// Returns:
// void
//
// Comments :
// If non-NULL, interprets pSpnegoToken, freeing any internal allocations
// and finally the actual structure.
//
////////////////////////////////////////////////////////////////////////////
void FreeSpnegoToken( SPNEGO_TOKEN* pSpnegoToken )
{
if ( NULL != pSpnegoToken )
{
// Cleanup internal allocation per the flags
if ( pSpnegoToken->ulFlags & SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA &&
NULL != pSpnegoToken->pbBinaryData )
{
free( pSpnegoToken->pbBinaryData );
pSpnegoToken->pbBinaryData = NULL;
}
free ( pSpnegoToken );
}
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// InitSpnegoTokenElementArray
//
// Parameters:
// [in] pSpnegoToken - Points to SPNEGO_TOKEN structure.
//
// Returns:
// void
//
// Comments :
// Initializes the element array data member of a SPNEGO_TOKEN data
// structure.
//
////////////////////////////////////////////////////////////////////////////
void InitSpnegoTokenElementArray( SPNEGO_TOKEN* pSpnegoToken )
{
int nCtr;
// Set the number of elemnts
pSpnegoToken->nNumElements = MAX_NUM_TOKEN_ELEMENTS;
//
// Initially, all elements are unavailable
//
for ( nCtr = 0; nCtr < MAX_NUM_TOKEN_ELEMENTS; nCtr++ )
{
// Set the element size as well
pSpnegoToken->aElementArray[ nCtr ].nStructSize = SPNEGO_ELEMENT_SIZE;
pSpnegoToken->aElementArray[ nCtr ].iElementPresent = SPNEGO_TOKEN_ELEMENT_UNAVAILABLE;
}
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// InitSpnegoTokenType
//
// Parameters:
// [in] pSpnegoToken - Points to SPNEGO_TOKEN structure.
// [out] pnTokenLength - Filled out with total token length
// [out] pnRemainingTokenLength - Filled out with remaining length
// after header is parsed
// [out] ppbFirstElement - Filled out with pointer to first
// element after header info.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Walks the underlying binary data for a SPNEGO_TOKEN data structure
// and determines the type of the underlying token based on token header
// information.
//
////////////////////////////////////////////////////////////////////////////
int InitSpnegoTokenType( SPNEGO_TOKEN* pSpnegoToken, long* pnTokenLength,
long* pnRemainingTokenLength, unsigned char** ppbFirstElement )
{
int nReturn = SPNEGO_E_INVALID_TOKEN;
long nActualTokenLength = 0L;
long nBoundaryLength = pSpnegoToken->ulBinaryDataLen;
unsigned char* pbTokenData = pSpnegoToken->pbBinaryData;
//
// First byte MUST be either an APP_CONSTRUCT or the NEGTARG_TOKEN_TARG
//
if ( SPNEGO_NEGINIT_APP_CONSTRUCT == *pbTokenData )
{
// Validate the above token - this will tell us the actual length of the token
// per the encoding (minus the actual token bytes)
if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGINIT_APP_CONSTRUCT, 0L, nBoundaryLength,
pnTokenLength, &nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Initialize the remaining token length value. This will be used
// to tell the caller how much token there is left once we've parsed
// the header (they could calculate it from the other values, but this
// is a bit friendlier)
*pnRemainingTokenLength = *pnTokenLength;
// Make adjustments to next token
pbTokenData += nActualTokenLength;
nBoundaryLength -= nActualTokenLength;
// The next token should be an OID
if ( ( nReturn = ASNDerCheckOID( pbTokenData, spnego_mech_oid_Spnego, nBoundaryLength,
&nActualTokenLength ) ) == SPNEGO_E_SUCCESS )
{
// Make adjustments to next token
pbTokenData += nActualTokenLength;
nBoundaryLength -= nActualTokenLength;
*pnRemainingTokenLength -= nActualTokenLength;
// The next token should specify the NegTokenInit
if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGINIT_TOKEN_IDENTIFIER,
*pnRemainingTokenLength, nBoundaryLength, pnTokenLength,
&nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Make adjustments to next token
pbTokenData += nActualTokenLength;
nBoundaryLength -= nActualTokenLength;
*pnRemainingTokenLength -= nActualTokenLength;
// The next token should specify the start of a sequence
if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
*pnRemainingTokenLength, nBoundaryLength, pnTokenLength,
&nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// NegTokenInit header is now checked out!
// Make adjustments to next token
*pnRemainingTokenLength -= nActualTokenLength;
// Store pointer to first element
*ppbFirstElement = pbTokenData + nActualTokenLength;
pSpnegoToken->ucTokenType = SPNEGO_TOKEN_INIT;
} // IF Check Sequence Token
} // IF Check NegTokenInit token
} // IF Check for SPNEGO OID
} // IF check app construct token
}
else if ( SPNEGO_NEGTARG_TOKEN_IDENTIFIER == *pbTokenData )
{
// The next token should specify the NegTokenInit
if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_NEGTARG_TOKEN_IDENTIFIER,
*pnRemainingTokenLength, nBoundaryLength, pnTokenLength,
&nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Initialize the remaining token length value. This will be used
// to tell the caller how much token there is left once we've parsed
// the header (they could calculate it from the other values, but this
// is a bit friendlier)
*pnRemainingTokenLength = *pnTokenLength;
// Make adjustments to next token
pbTokenData += nActualTokenLength;
nBoundaryLength -= nActualTokenLength;
// The next token should specify the start of a sequence
if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
*pnRemainingTokenLength, nBoundaryLength, pnTokenLength,
&nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// NegTokenInit header is now checked out!
// Make adjustments to next token
*pnRemainingTokenLength -= nActualTokenLength;
// Store pointer to first element
*ppbFirstElement = pbTokenData + nActualTokenLength;
pSpnegoToken->ucTokenType = SPNEGO_TOKEN_TARG;
} // IF Check Sequence Token
} // IF Check NegTokenInit token
} // ELSE IF it's a NegTokenTarg
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// GetSpnegoInitTokenMechList
//
// Parameters:
// [in] pbTokenData - Points to binary MechList element
// in NegTokenInit.
// [in] nMechListLength - Length of the MechList
// [out] pSpnegoElement - Filled out with MechList Element
// data.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Checks that pbTokenData is pointing at something that at least
// *looks* like a MechList and then fills out the supplied
// SPNEGO_ELEMENT structure.
//
////////////////////////////////////////////////////////////////////////////
int GetSpnegoInitTokenMechList( unsigned char* pbTokenData, int nMechListLength,
SPNEGO_ELEMENT* pSpnegoElement )
{
int nReturn = SPNEGO_E_INVALID_TOKEN;
long nLength = 0L;
long nActualTokenLength = 0L;
// Actual MechList is prepended by a Constructed Sequence Token
if ( ( nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
nMechListLength, nMechListLength,
&nLength, &nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Adjust for this token
nMechListLength -= nActualTokenLength;
pbTokenData += nActualTokenLength;
// Perform simple validation of the actual MechList (i.e. ensure that
// the OIDs in the MechList are reasonable).
if ( ( nReturn = ValidateMechList( pbTokenData, nLength ) ) == SPNEGO_E_SUCCESS )
{
// Initialize the element now
pSpnegoElement->eElementType = spnego_init_mechtypes;
pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE;
pSpnegoElement->type = SPNEGO_MECHLIST_TYPE;
pSpnegoElement->nDatalength = nLength;
pSpnegoElement->pbData = pbTokenData;
}
} // IF Check Token
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// InitSpnegoTokenElementFromBasicType
//
// Parameters:
// [in] pbTokenData - Points to binary element data in
// a SPNEGO token.
// [in] nElementLength - Length of the element
// [in] ucExpectedType - Expected DER type.
// [in] spnegoElementType - Which element is this?
// [out] pSpnegoElement - Filled out with element data.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Checks that pbTokenData is pointing at the specified DER type. If so,
// then we verify that lengths are proper and then fill out the
// SPNEGO_ELEMENT data structure.
//
////////////////////////////////////////////////////////////////////////////
int InitSpnegoTokenElementFromBasicType( unsigned char* pbTokenData, int nElementLength,
unsigned char ucExpectedType,
SPNEGO_ELEMENT_TYPE spnegoElementType,
SPNEGO_ELEMENT* pSpnegoElement )
{
int nReturn = SPNEGO_E_UNEXPECTED_TYPE;
long nLength = 0L;
long nActualTokenLength = 0L;
// The type BYTE must match our token data or something is badly wrong
if ( *pbTokenData == ucExpectedType )
{
// Check that we are pointing at the specified type
if ( ( nReturn = ASNDerCheckToken( pbTokenData, ucExpectedType,
nElementLength, nElementLength,
&nLength, &nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Adjust for this token
nElementLength -= nActualTokenLength;
pbTokenData += nActualTokenLength;
// Initialize the element now
pSpnegoElement->eElementType = spnegoElementType;
pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE;
pSpnegoElement->type = ucExpectedType;
pSpnegoElement->nDatalength = nLength;
pSpnegoElement->pbData = pbTokenData;
}
} // IF type makes sense
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// InitSpnegoTokenElementFromOID
//
// Parameters:
// [in] pbTokenData - Points to binary element data in
// a SPNEGO token.
// [in] nElementLength - Length of the element
// [in] spnegoElementType - Which element is this?
// [out] pSpnegoElement - Filled out with element data.
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Initializes a SpnegoElement from an OID - normally, this would have
// used the Basic Type function above, but since we do binary compares
// on the OIDs against the DER information as well as the OID, we need
// to account for that.
//
////////////////////////////////////////////////////////////////////////////
int InitSpnegoTokenElementFromOID( unsigned char* pbTokenData, int nElementLength,
SPNEGO_ELEMENT_TYPE spnegoElementType,
SPNEGO_ELEMENT* pSpnegoElement )
{
int nReturn = SPNEGO_E_UNEXPECTED_TYPE;
long nLength = 0L;
long nActualTokenLength = 0L;
// The type BYTE must match our token data or something is badly wrong
if ( *pbTokenData == OID )
{
// Check that we are pointing at an OID type
if ( ( nReturn = ASNDerCheckToken( pbTokenData, OID,
nElementLength, nElementLength,
&nLength, &nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Don't adjust any values for this function
// Initialize the element now
pSpnegoElement->eElementType = spnegoElementType;
pSpnegoElement->iElementPresent = SPNEGO_TOKEN_ELEMENT_AVAILABLE;
pSpnegoElement->type = OID;
pSpnegoElement->nDatalength = nElementLength;
pSpnegoElement->pbData = pbTokenData;
}
} // IF type makes sense
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// InitSpnegoTokenElements
//
// Parameters:
// [in] pSpnegoToken - Points to SPNEGO_TOKEN struct
// [in] pbTokenData - Points to initial binary element
// data in a SPNEGO token.
// [in] nRemainingTokenLength - Length remaining past header
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Interprets the data at pbTokenData based on the TokenType in
// pSpnegoToken. Since some elements are optional (technically all are
// but the token becomes quite useless if this is so), we check if
// an element exists before filling out the element in the array.
//
////////////////////////////////////////////////////////////////////////////
int InitSpnegoTokenElements( SPNEGO_TOKEN* pSpnegoToken, unsigned char* pbTokenData,
long nRemainingTokenLength )
{
//
// The following arrays contain the token identifiers for the elements
// comprising the actual token. All values are optional, and there are
// no defaults.
//
static unsigned char abNegTokenInitElements[] =
{ SPNEGO_NEGINIT_ELEMENT_MECHTYPES, SPNEGO_NEGINIT_ELEMENT_REQFLAGS,
SPNEGO_NEGINIT_ELEMENT_MECHTOKEN, SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC };
static unsigned char abNegTokenTargElements[] =
{ SPNEGO_NEGTARG_ELEMENT_NEGRESULT, SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH,
SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN, SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC };
int nReturn = SPNEGO_E_SUCCESS;
int nCtr = 0L;
long nElementLength = 0L;
long nActualTokenLength = 0L;
unsigned char* pbElements = NULL;
// Point to the correct array
switch( pSpnegoToken->ucTokenType )
{
case SPNEGO_TOKEN_INIT:
{
pbElements = abNegTokenInitElements;
}
break;
case SPNEGO_TOKEN_TARG:
{
pbElements = abNegTokenTargElements;
}
break;
} // SWITCH tokentype
//
// Enumerate the element arrays and look for the tokens at our current location
//
for ( nCtr = 0L;
SPNEGO_E_SUCCESS == nReturn &&
nCtr < MAX_NUM_TOKEN_ELEMENTS &&
nRemainingTokenLength > 0L;
nCtr++ )
{
// Check if the token exists
if ( ( nReturn = ASNDerCheckToken( pbTokenData, pbElements[nCtr],
0L, nRemainingTokenLength,
&nElementLength, &nActualTokenLength ) )
== SPNEGO_E_SUCCESS )
{
// Token data should skip over the sequence token and then
// call the appropriate function to initialize the element
pbTokenData += nActualTokenLength;
// Lengths in the elements should NOT go beyond the element
// length
// Different tokens mean different elements
if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
{
// Handle each element as appropriate
switch( pbElements[nCtr] )
{
case SPNEGO_NEGINIT_ELEMENT_MECHTYPES:
{
//
// This is a Mech List that specifies which OIDs the
// originator of the Init Token supports.
//
nReturn = GetSpnegoInitTokenMechList( pbTokenData, nElementLength,
&pSpnegoToken->aElementArray[nCtr] );
}
break;
case SPNEGO_NEGINIT_ELEMENT_REQFLAGS:
{
//
// This is a BITSTRING which specifies the flags that the receiver
// pass to the gss_accept_sec_context() function.
//
nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
BITSTRING, spnego_init_reqFlags,
&pSpnegoToken->aElementArray[nCtr] );
}
break;
case SPNEGO_NEGINIT_ELEMENT_MECHTOKEN:
{
//
// This is an OCTETSTRING which contains a GSSAPI token corresponding
// to the first OID in the MechList.
//
nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
OCTETSTRING, spnego_init_mechToken,
&pSpnegoToken->aElementArray[nCtr] );
}
break;
case SPNEGO_NEGINIT_ELEMENT_MECHLISTMIC: // xA3
{
//
// Don't yet know if this is a negTokenInit, or negTokenInit2.
// Unfortunately, both have the same type: SPNEGO_TOKEN_INIT
// If it's negTokenInit, this element should be an OCTETSTRING
// containing the MIC. If it's a negTokenInit2, this element
// should be an SPNEGO_CONSTRUCTED_SEQUENCE containing the
// negHints (GENERALSTR, ignored)
//
nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
OCTETSTRING, spnego_init_mechListMIC,
&pSpnegoToken->aElementArray[nCtr] );
if (nReturn == SPNEGO_E_UNEXPECTED_TYPE) {
// This is really a negHints element. Check the type and length,
// but otherwise just ignore it.
long elen, tlen;
nReturn = ASNDerCheckToken( pbTokenData, SPNEGO_CONSTRUCTED_SEQUENCE,
nElementLength, nElementLength,
&elen, &tlen );
}
}
break;
} // SWITCH Element
}
else
{
/* pSpnegoToken->ucTokenType == SPNEGO_TOKEN_TARG */
switch( pbElements[nCtr] )
{
case SPNEGO_NEGTARG_ELEMENT_NEGRESULT:
{
//
// This is an ENUMERATION which specifies result of the last GSS
// token negotiation call.
//
nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
ENUMERATED, spnego_targ_negResult,
&pSpnegoToken->aElementArray[nCtr] );
}
break;
case SPNEGO_NEGTARG_ELEMENT_SUPPORTEDMECH:
{
//
// This is an OID which specifies a supported mechanism.
//
nReturn = InitSpnegoTokenElementFromOID( pbTokenData, nElementLength,
spnego_targ_mechListMIC,
&pSpnegoToken->aElementArray[nCtr] );
}
break;
case SPNEGO_NEGTARG_ELEMENT_RESPONSETOKEN:
{
//
// This is an OCTETSTRING which specifies results of the last GSS
// token negotiation call.
//
nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
OCTETSTRING, spnego_targ_responseToken,
&pSpnegoToken->aElementArray[nCtr] );
}
break;
case SPNEGO_NEGTARG_ELEMENT_MECHLISTMIC:
{
//
// This is an OCTETSTRING, typically 16 bytes,
// which contains a message integrity BLOB.
//
nReturn = InitSpnegoTokenElementFromBasicType( pbTokenData, nElementLength,
OCTETSTRING, spnego_targ_mechListMIC,
&pSpnegoToken->aElementArray[nCtr] );
}
break;
} // SWITCH Element
} // ELSE !NegTokenInit
// Account for the entire token and following data
nRemainingTokenLength -= ( nActualTokenLength + nElementLength );
// Token data should skip past the element length now
pbTokenData += nElementLength;
} // IF Token found
else if ( SPNEGO_E_TOKEN_NOT_FOUND == nReturn )
{
// For now, this is a benign error (remember, all elements are optional, so
// if we don't find one, it's okay).
nReturn = SPNEGO_E_SUCCESS;
}
} // FOR enum elements
//
// We should always run down to 0 remaining bytes in the token. If not, we've got
// a bad token.
//
if ( SPNEGO_E_SUCCESS == nReturn && nRemainingTokenLength != 0L )
{
nReturn = SPNEGO_E_INVALID_TOKEN;
}
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// FindMechOIDInMechList
//
// Parameters:
// [in] pSpnegoElement - SPNEGO_ELEMENT for MechList
// [in] MechOID - OID we're looking for.
// [out] piMechTypeIndex - Index in the list where OID was
// found
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Walks the MechList for MechOID. When it is found, the index in the
// list is written to piMechTypeIndex.
//
////////////////////////////////////////////////////////////////////////////
int FindMechOIDInMechList( SPNEGO_ELEMENT* pSpnegoElement, SPNEGO_MECH_OID MechOID,
int * piMechTypeIndex )
{
int nReturn = SPNEGO_E_NOT_FOUND;
int nCtr = 0;
long nLength = 0L;
long nBoundaryLength = pSpnegoElement->nDatalength;
unsigned char* pbMechListData = pSpnegoElement->pbData;
while( SPNEGO_E_SUCCESS != nReturn && nBoundaryLength > 0L )
{
// Use the helper function to check the OID
if ( ( nReturn = ASNDerCheckOID( pbMechListData, MechOID, nBoundaryLength, &nLength ) )
== SPNEGO_E_SUCCESS )
{
*piMechTypeIndex = nCtr;
}
// Adjust for the current OID
pbMechListData += nLength;
nBoundaryLength -= nLength;
nCtr++;
} // WHILE enuming OIDs
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// ValidateMechList
//
// Parameters:
// [in] pbMechListData - Pointer to binary MechList data
// [in] nBoundaryLength - Length we must not exceed
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Checks the data at pbMechListData to see if it looks like a MechList.
// As part of this, we walk the list and ensure that none of the OIDs
// have a length that takes us outside of nBoundaryLength.
//
////////////////////////////////////////////////////////////////////////////
int ValidateMechList( unsigned char* pbMechListData, long nBoundaryLength )
{
int nReturn = SPNEGO_E_SUCCESS;
long nLength = 0L;
long nTokenLength = 0L;
while( SPNEGO_E_SUCCESS == nReturn && nBoundaryLength > 0L )
{
// Verify that we have something that at least *looks* like an OID - in other
// words it has an OID identifier and specifies a length that doesn't go beyond
// the size of the list.
nReturn = ASNDerCheckToken( pbMechListData, OID, 0L, nBoundaryLength,
&nLength, &nTokenLength );
// Adjust for the current OID
pbMechListData += ( nLength + nTokenLength );
nBoundaryLength -= ( nLength + nTokenLength );
} // WHILE enuming OIDs
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// IsValidMechOid
//
// Parameters:
// [in] mechOid - mechOID id enumeration
//
// Returns:
// int Success - 1
// Failure - 0
//
// Comments :
// Checks for a valid mechOid value.
//
////////////////////////////////////////////////////////////////////////////
int IsValidMechOid( SPNEGO_MECH_OID mechOid )
{
return ( mechOid >= spnego_mech_oid_Kerberos_V5_Legacy &&
mechOid <= spnego_mech_oid_NTLMSSP );
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// IsValidContextFlags
//
// Parameters:
// [in] ucContextFlags - ContextFlags value
//
// Returns:
// int Success - 1
// Failure - 0
//
// Comments :
// Checks for a valid ContextFlags value.
//
////////////////////////////////////////////////////////////////////////////
int IsValidContextFlags( unsigned char ucContextFlags )
{
// Mask out our valid bits. If there is anything leftover, this
// is not a valid value for Context Flags
return ( ( ucContextFlags & ~SPNEGO_NEGINIT_CONTEXT_MASK ) == 0 );
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// IsValidNegResult
//
// Parameters:
// [in] negResult - NegResult value
//
// Returns:
// int Success - 1
// Failure - 0
//
// Comments :
// Checks for a valid NegResult value.
//
////////////////////////////////////////////////////////////////////////////
int IsValidNegResult( SPNEGO_NEGRESULT negResult )
{
return ( negResult >= spnego_negresult_success &&
negResult <= spnego_negresult_request_mic );
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// IsValidSpnegoToken
//
// Parameters:
// [in] pSpnegoToken - Points to SPNEGO_TOKEN data structure
//
// Returns:
// int Success - 1
// Failure - 0
//
// Comments :
// Performs simple heuristic on location pointed to by pSpnegoToken.
//
////////////////////////////////////////////////////////////////////////////
int IsValidSpnegoToken( SPNEGO_TOKEN* pSpnegoToken )
{
int nReturn = 0;
// Parameter should be non-NULL
if ( NULL != pSpnegoToken )
{
// Length should be at least the size defined in the header
if ( pSpnegoToken->nStructSize >= SPNEGO_TOKEN_SIZE )
{
// Number of elements should be >= our maximum - if it's greater, that's
// okay, since we'll only be accessing the elements up to MAX_NUM_TOKEN_ELEMENTS
if ( pSpnegoToken->nNumElements >= MAX_NUM_TOKEN_ELEMENTS )
{
// Check for proper token type
if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType ||
SPNEGO_TOKEN_TARG == pSpnegoToken->ucTokenType )
{
nReturn = 1;
}
}
} // IF struct size makes sense
} // IF non-NULL spnego Token
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// IsValidSpnegoElement
//
// Parameters:
// [in] pSpnegoToken - Points to SPNEGO_TOKEN data structure
// [in] spnegoElement - spnegoElement Type from enumeration
//
// Returns:
// int Success - 1
// Failure - 0
//
// Comments :
// Checks that spnegoElement has a valid value and is appropriate for
// the SPNEGO token encapsulated by pSpnegoToken.
//
////////////////////////////////////////////////////////////////////////////
int IsValidSpnegoElement( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement )
{
int nReturn = 0;
// Check boundaries
if ( spnegoElement > spnego_element_min &&
spnegoElement < spnego_element_max )
{
// Check for appropriateness to token type
if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
{
nReturn = ( spnegoElement >= spnego_init_mechtypes &&
spnegoElement <= spnego_init_mechListMIC );
}
else
{
nReturn = ( spnegoElement >= spnego_targ_negResult &&
spnegoElement <= spnego_targ_mechListMIC );
}
} // IF boundary conditions are met
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// CalculateElementArrayIndex
//
// Parameters:
// [in] pSpnegoToken - Points to SPNEGO_TOKEN data structure
// [in] spnegoElement - spnegoElement Type from enumeration
//
// Returns:
// int index in the SPNEGO_TOKEN element array that the element can
// can be found
//
// Comments :
// Based on the Token Type, calculates the index in the element array
// at which the specified element can be found.
//
////////////////////////////////////////////////////////////////////////////
int CalculateElementArrayIndex( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement )
{
int nReturn = 0;
// Offset is difference between value and initial element identifier
// (these differ based on ucTokenType)
if ( SPNEGO_TOKEN_INIT == pSpnegoToken->ucTokenType )
{
nReturn = spnegoElement - spnego_init_mechtypes;
}
else
{
nReturn = spnegoElement - spnego_targ_negResult;
}
return nReturn;
}
/////////////////////////////////////////////////////////////////////////////
//
// Function:
// InitTokenFromBinary
//
// Parameters:
// [in] ucCopyData - Flag indicating if data should be copied
// [in] ulFlags - Flags value for structure
// [in] pnTokenData - Binary Token Data
// [in] ulLength - Length of the data
// [out] ppSpnegoToken - Pointer to call allocated SPNEGO Token
// data structure
//
// Returns:
// int Success - SPNEGO_E_SUCCESS
// Failure - SPNEGO API Error code
//
// Comments :
// Allocates a SPNEGO_TOKEN data structure and fills it out as
// appropriate based in the flags passed into the function.
//
////////////////////////////////////////////////////////////////////////////
// Initializes SPNEGO_TOKEN structure from DER encoded binary data
int InitTokenFromBinary( unsigned char ucCopyData, unsigned long ulFlags,
unsigned char* pbTokenData, unsigned long ulLength,
SPNEGO_TOKEN** ppSpnegoToken )
{
int nReturn = SPNEGO_E_INVALID_PARAMETER;
SPNEGO_TOKEN* pSpnegoToken = NULL;
unsigned char* pbFirstElement = NULL;
long nTokenLength = 0L;
long nRemainingTokenLength = 0L;
// Basic Parameter Validation
if ( NULL != pbTokenData &&
NULL != ppSpnegoToken &&
0L != ulLength )
{
//
// Allocate the empty token, then initialize the data structure.
//
pSpnegoToken = AllocEmptySpnegoToken( ucCopyData, ulFlags, pbTokenData, ulLength );
if ( NULL != pSpnegoToken )
{
// Copy the binary data locally
// Initialize the token type
if ( ( nReturn = InitSpnegoTokenType( pSpnegoToken, &nTokenLength,
&nRemainingTokenLength, &pbFirstElement ) )
== SPNEGO_E_SUCCESS )
{
// Initialize the element array
if ( ( nReturn = InitSpnegoTokenElements( pSpnegoToken, pbFirstElement,
nRemainingTokenLength ) )
== SPNEGO_E_SUCCESS )
{
*ppSpnegoToken = pSpnegoToken;
}
} // IF Init Token Type
// Cleanup on error condition
if ( SPNEGO_E_SUCCESS != nReturn )
{
spnegoFreeData( pSpnegoToken );
}
}
else
{
nReturn = SPNEGO_E_OUT_OF_MEMORY;
}
} // IF Valid parameters
return nReturn;
}
// Copyright 2012 Nexenta Systems, Inc. All rights reserved.
// Copyright (C) 2002 Microsoft Corporation
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS"
// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
// OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTIBILITY
// AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Date - 10/08/2002
// Author - Sanj Surati
/////////////////////////////////////////////////////////////
//
// SPNEGOPARSE.H
//
// SPNEGO Token Parser Header File
//
// Contains the definitions required to properly parse a
// SPNEGO token using ASN.1 DER helpers.
//
/////////////////////////////////////////////////////////////
#ifndef __SPNEGOPARSE_H__
#define __SPNEGOPARSE_H__
// C++ Specific
#if defined(__cplusplus)
extern "C"
{
#endif
// Indicates if we copy data when creating a SPNEGO_TOKEN structure or not
#define SPNEGO_TOKEN_INTERNAL_COPYPTR 0
#define SPNEGO_TOKEN_INTERNAL_COPYDATA 0x1
// Internal flag dictates whether or not we will free the binary data when
// the SPNEG_TOKEN structure is destroyed
#define SPNEGO_TOKEN_INTERNAL_FLAGS_FREEDATA 0x1
//
// Each SPNEGO Token Type can be broken down into a
// maximum of 4 separate elements.
//
#define MAX_NUM_TOKEN_ELEMENTS 4
//
// Element offsets in the array
//
// INIT elements
#define SPNEGO_INIT_MECHTYPES_ELEMENT 0
#define SPNEGO_INIT_REQFLAGS_ELEMENT 1
#define SPNEGO_INIT_MECHTOKEN_ELEMENT 2
#define SPNEGO_INIT_MECHLISTMIC_ELEMENT 3
// Response elements
#define SPNEGO_TARG_NEGRESULT_ELEMENT 0
#define SPNEGO_TARG_SUPPMECH_ELEMENT 1
#define SPNEGO_TARG_RESPTOKEN_ELEMENT 2
#define SPNEGO_TARG_MECHLISTMIC_ELEMENT 3
//
// Defines an individual SPNEGO Token Element.
//
typedef struct SpnegoElement
{
size_t nStructSize; // Size of the element structure
int iElementPresent; // Is the field present? Must be either
// SPNEGO_TOKEN_ELEMENT_UNAVAILABLE or
// SPNEGO_TOKEN_ELEMENT_AVAILABLE
SPNEGO_ELEMENT_TYPE eElementType; // The Element Type
unsigned char type; // Data Type
unsigned char* pbData; // Points to actual Data
unsigned long nDatalength; // Actual Data Length
} SPNEGO_ELEMENT;
// Structure size in case we later choose to extend the structure
#define SPNEGO_ELEMENT_SIZE sizeof(SPNEGO_ELEMENT)
//
// Packages a SPNEGO Token Encoding. There are two types of
// encodings: NegTokenInit and NegTokenTarg. Each encoding can
// contain up to four distinct, optional elements.
//
typedef struct SpnegoToken
{
size_t nStructSize; // Size of the Token structure
unsigned long ulFlags; // Internal Structure Flags - Reserved!
int ucTokenType; // Token Type - Must be
// SPNEGO_TOKEN_INIT or
// SPNEGO_TOKEN_TARG
unsigned char* pbBinaryData; // Points to binary token data
unsigned long ulBinaryDataLen; // Length of the actual binary data
int nNumElements; // Number of elements
SPNEGO_ELEMENT aElementArray [MAX_NUM_TOKEN_ELEMENTS]; // Holds the elements for the token
} SPNEGO_TOKEN;
// Structure size in case we later choose to extend the structure
#define SPNEGO_TOKEN_SIZE sizeof(SPNEGO_TOKEN)
//
// Function definitions
//
SPNEGO_TOKEN* AllocEmptySpnegoToken( unsigned char ucCopyData, unsigned long ulFlags,
unsigned char * pbTokenData, unsigned long ulTokenSize );
void FreeSpnegoToken( SPNEGO_TOKEN* pSpnegoToken );
void InitSpnegoTokenElementArray( SPNEGO_TOKEN* pSpnegoToken );
int InitSpnegoTokenType( SPNEGO_TOKEN* pSpnegoToken, long* pnTokenLength,
long* pnRemainingTokenLength, unsigned char** ppbFirstElement );
int InitSpnegoTokenElements( SPNEGO_TOKEN* pSpnegoToken, unsigned char* pbTokenData,
long nRemainingTokenLength );
int GetSpnegoInitTokenMechList( unsigned char* pbTokenData, int nMechListLength,
SPNEGO_ELEMENT* pSpnegoElement );
int InitSpnegoTokenElementFromBasicType( unsigned char* pbTokenData, int nElementLength,
unsigned char ucExpectedType,
SPNEGO_ELEMENT_TYPE spnegoElementType,
SPNEGO_ELEMENT* pSpnegoElement );
int InitSpnegoTokenElementFromOID( unsigned char* pbTokenData, int nElementLength,
SPNEGO_ELEMENT_TYPE spnegoElementType,
SPNEGO_ELEMENT* pSpnegoElement );
int FindMechOIDInMechList( SPNEGO_ELEMENT* pSpnegoElement, SPNEGO_MECH_OID MechOID,
int * piMechTypeIndex );
int ValidateMechList( unsigned char* pbMechListData, long nBoundaryLength );
int CalculateMinSpnegoInitTokenSize( long nMechTokenLength, long nMechListMICLength,
SPNEGO_MECH_OID *mechOid, int mechOidCnt, int nReqFlagsAvailable,
long* plTokenSize, long* plInternalLength );
int CalculateMinSpnegoTargTokenSize( SPNEGO_MECH_OID MechType, SPNEGO_NEGRESULT spnegoNegResult,
long nMechTokenLen,
long nMechTokenMIC, long* pnTokenSize,
long* pnInternalTokenLength );
int CreateSpnegoInitToken( SPNEGO_MECH_OID *MechTypeList, long nMechTypes,
unsigned char ucContextFlags, unsigned char* pbMechToken,
unsigned long ulMechTokenLen, unsigned char* pbMechListMIC,
unsigned long ulMechListMICLen, unsigned char* pbTokenData,
long nTokenLength, long nInternalTokenLength );
int CreateSpnegoTargToken( SPNEGO_MECH_OID MechType,
SPNEGO_NEGRESULT eNegResult, unsigned char* pbMechToken,
unsigned long ulMechTokenLen, unsigned char* pbMechListMIC,
unsigned long ulMechListMICLen, unsigned char* pbTokenData,
long nTokenLength, long nInternalTokenLength );
int IsValidMechOid( SPNEGO_MECH_OID mechOid );
int IsValidContextFlags( unsigned char ucContextFlags );
int IsValidNegResult( SPNEGO_NEGRESULT negResult );
int IsValidSpnegoToken( SPNEGO_TOKEN* pSpnegoToken );
int IsValidSpnegoElement( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement );
int CalculateElementArrayIndex( SPNEGO_TOKEN* pSpnegoToken,SPNEGO_ELEMENT_TYPE spnegoElement );
int InitTokenFromBinary( unsigned char ucCopyData, unsigned long ulFlags,
unsigned char* pbTokenData, unsigned long ulLength,
SPNEGO_TOKEN** ppSpnegoToken );
// C++ Specific
#if defined(__cplusplus)
}
#endif
#endif
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* Security Provider glue
*
* Modeled after SSPI for now, only because we're currently
* using the Microsoft sample spnego code.
*
* ToDo: Port all of this to GSS-API plugins.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <netdb.h>
#include <libintl.h>
#include <xti.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/byteorder.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netsmb/smb_lib.h>
#include <netsmb/mchain.h>
#include "private.h"
#include "charsets.h"
#include "spnego.h"
#include "derparse.h"
#include "ssp.h"
/*
* ssp_ctx_create_client
*
* This is the first function called for SMB "extended security".
* Here we select a security support provider (SSP), or mechanism,
* and build the security context used throughout authentication.
*
* Note that we receive a "hint" in the SMB Negotiate response
* that contains the list of mechanisms supported by the server.
* We use this to help us select a mechanism.
*
* With SSPI this would call:
* ssp->InitSecurityInterface()
* ssp->AcquireCredentialsHandle()
* ssp->InitializeSecurityContext()
* With GSS-API this will become:
* gss_import_name(... service_principal_name)
* gss_init_sec_context(), etc.
*/
int
ssp_ctx_create_client(struct smb_ctx *ctx, struct mbdata *hint_mb)
{
struct ssp_ctx *sp;
mbuf_t *m;
SPNEGO_MECH_OID oid;
int indx, rc;
int err = ENOTSUP; /* in case nothing matches */
sp = malloc(sizeof (*sp));
if (sp == NULL)
return (ENOMEM);
bzero(sp, sizeof (*sp));
ctx->ct_ssp_ctx = sp;
sp->smb_ctx = ctx;
/*
* Parse the SPNEGO "hint" to get the server's list of
* supported mechanisms. If the "hint" is empty,
* assume NTLMSSP. (Or could use "raw NTLMSSP")
*/
m = hint_mb->mb_top;
if (m == NULL)
goto use_ntlm;
rc = spnegoInitFromBinary((uchar_t *)m->m_data, m->m_len,
&sp->sp_hint);
if (rc) {
DPRINT("parse hint, rc %d", rc);
goto use_ntlm;
}
/*
* Did the server offer Kerberos?
* Either spec. OID or legacy is OK,
* but have to remember what we got.
*/
oid = spnego_mech_oid_NotUsed;
if (0 == spnegoIsMechTypeAvailable(sp->sp_hint,
spnego_mech_oid_Kerberos_V5, &indx))
oid = spnego_mech_oid_Kerberos_V5;
else if (0 == spnegoIsMechTypeAvailable(sp->sp_hint,
spnego_mech_oid_Kerberos_V5_Legacy, &indx))
oid = spnego_mech_oid_Kerberos_V5_Legacy;
if (oid != spnego_mech_oid_NotUsed) {
/*
* Yes! Server offers Kerberos.
* Try to init our krb5 mechanism.
* It will fail if the calling user
* does not have krb5 credentials.
*/
sp->sp_mech = oid;
err = krb5ssp_init_client(sp);
if (err == 0) {
DPRINT("using Kerberos");
return (0);
}
/* else fall back to NTLMSSP */
}
/*
* Did the server offer NTLMSSP?
*/
if (0 == spnegoIsMechTypeAvailable(sp->sp_hint,
spnego_mech_oid_NTLMSSP, &indx)) {
/*
* OK, we'll use NTLMSSP
*/
use_ntlm:
sp->sp_mech = spnego_mech_oid_NTLMSSP;
err = ntlmssp_init_client(sp);
if (err == 0) {
DPRINT("using NTLMSSP");
return (0);
}
}
/* No supported mechanisms! */
return (err);
}
/*
* ssp_ctx_destroy
*
* Dispatch to the mechanism-specific destroy.
*/
void
ssp_ctx_destroy(struct smb_ctx *ctx)
{
ssp_ctx_t *sp;
sp = ctx->ct_ssp_ctx;
ctx->ct_ssp_ctx = NULL;
if (sp == NULL)
return;
if (sp->sp_destroy != NULL)
(sp->sp_destroy)(sp);
if (sp->sp_hint != NULL)
spnegoFreeData(sp->sp_hint);
free(sp);
}
/*
* ssp_ctx_next_token
*
* This is the function called to generate the next token to send,
* given a token just received, using the selected back-end method.
* The back-end method is called a security service provider (SSP).
*
* This is also called to generate the first token to send
* (when called with caller_in == NULL) and to handle the last
* token received (when called with caller_out == NULL).
* See caller: smb_ssnsetup_spnego
*
* Note that if the back-end SSP "next token" function ever
* returns an error, the conversation ends, and there are
* no further calls to this function for this context.
*
* General outline of this funcion:
* if (caller_in)
* Unwrap caller_in spnego blob,
* store payload in body_in
* Call back-end SSP "next token" method (body_in, body_out)
* if (caller_out)
* Wrap returned body_out in spnego,
* store in caller_out
*
* With SSPI this would call:
* ssp->InitializeSecurityContext()
* With GSS-API this will become:
* gss_init_sec_context()
*/
int
ssp_ctx_next_token(struct smb_ctx *ctx,
struct mbdata *caller_in,
struct mbdata *caller_out)
{
struct mbdata body_in, body_out;
SPNEGO_TOKEN_HANDLE stok_in, stok_out;
SPNEGO_NEGRESULT result;
ssp_ctx_t *sp;
struct mbuf *m;
ulong_t toklen;
int err, rc;
bzero(&body_in, sizeof (body_in));
bzero(&body_out, sizeof (body_out));
stok_out = stok_in = NULL;
sp = ctx->ct_ssp_ctx;
/*
* If we have an spnego input token, parse it,
* extract the payload for the back-end SSP.
*/
if (caller_in != NULL) {
/*
* Let the spnego code parse it.
*/
m = caller_in->mb_top;
rc = spnegoInitFromBinary((uchar_t *)m->m_data,
m->m_len, &stok_in);
if (rc) {
DPRINT("parse reply, rc %d", rc);
err = EBADRPC;
goto out;
}
/* Note: Allocated stok_in */
/*
* Now get the payload. Two calls:
* first gets the size, 2nd the data.
*
* Expect SPNEGO_E_BUFFER_TOO_SMALL here,
* but if the payload is missing, we'll
* get SPNEGO_E_ELEMENT_UNAVAILABLE.
*/
rc = spnegoGetMechToken(stok_in, NULL, &toklen);
switch (rc) {
case SPNEGO_E_ELEMENT_UNAVAILABLE:
toklen = 0;
break;
case SPNEGO_E_BUFFER_TOO_SMALL:
/* have toklen */
break;
default:
DPRINT("GetMechTok1, rc %d", rc);
err = EBADRPC;
goto out;
}
err = mb_init_sz(&body_in, (size_t)toklen);
if (err)
goto out;
m = body_in.mb_top;
if (toklen > 0) {
rc = spnegoGetMechToken(stok_in,
(uchar_t *)m->m_data, &toklen);
if (rc) {
DPRINT("GetMechTok2, rc %d", rc);
err = EBADRPC;
goto out;
}
body_in.mb_count = m->m_len = (size_t)toklen;
}
}
/*
* Call the back-end security provider (SSP) to
* handle the received token (if present) and
* generate an output token (if requested).
*/
err = sp->sp_nexttok(sp,
caller_in ? &body_in : NULL,
caller_out ? &body_out : NULL);
if (err)
goto out;
/*
* Wrap the outgoing body if requested,
* either negTokenInit on first call, or
* negTokenTarg on subsequent calls.
*/
if (caller_out != NULL) {
m = body_out.mb_top;
if (caller_in == NULL) {
/*
* This is the first call, so create a
* negTokenInit.
*/
rc = spnegoCreateNegTokenInit(
sp->sp_mech, 0,
(uchar_t *)m->m_data, m->m_len,
NULL, 0, &stok_out);
/* Note: allocated stok_out */
} else {
/*
* Note: must pass spnego_mech_oid_NotUsed,
* instead of sp->sp_mech so that the spnego
* code will not marshal a mech OID list.
* The mechanism is determined at this point,
* and some servers won't parse an unexpected
* mech. OID list in a negTokenTarg
*/
rc = spnegoCreateNegTokenTarg(
spnego_mech_oid_NotUsed,
spnego_negresult_NotUsed,
(uchar_t *)m->m_data, m->m_len,
NULL, 0, &stok_out);
/* Note: allocated stok_out */
}
if (rc) {
DPRINT("CreateNegTokenX, rc 0x%x", rc);
err = EBADRPC;
goto out;
}
/*
* Copy binary from stok_out to caller_out
* Two calls: get the size, get the data.
*/
rc = spnegoTokenGetBinary(stok_out, NULL, &toklen);
if (rc != SPNEGO_E_BUFFER_TOO_SMALL) {
DPRINT("GetBinary1, rc 0x%x", rc);
err = EBADRPC;
goto out;
}
err = mb_init_sz(caller_out, (size_t)toklen);
if (err)
goto out;
m = caller_out->mb_top;
rc = spnegoTokenGetBinary(stok_out,
(uchar_t *)m->m_data, &toklen);
if (rc) {
DPRINT("GetBinary2, rc 0x%x", rc);
err = EBADRPC;
goto out;
}
caller_out->mb_count = m->m_len = (size_t)toklen;
} else {
/*
* caller_out == NULL, so this is the "final" call.
* Get final SPNEGO result from the INPUT token.
*/
rc = spnegoGetNegotiationResult(stok_in, &result);
if (rc) {
DPRINT("rc 0x%x", rc);
err = EBADRPC;
goto out;
}
DPRINT("spnego result: 0x%x", result);
if (result != spnego_negresult_success) {
err = EAUTH;
goto out;
}
}
err = 0;
out:
mb_done(&body_in);
mb_done(&body_out);
spnegoFreeData(stok_in);
spnegoFreeData(stok_out);
return (err);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _SSP_H
#define _SSP_H
/*
* Security Support Package (SSP) interface,
* somewhat modeled on Microsoft's SSPI.
*
* XXX: Yes, should use GSS-API. See ssp.c
*/
typedef struct ssp_ctx {
struct smb_ctx *smb_ctx;
SPNEGO_TOKEN_HANDLE sp_hint;
SPNEGO_MECH_OID sp_mech;
/*
* Now the mechanism-specific stuff.
*/
int (*sp_nexttok)(struct ssp_ctx *,
struct mbdata *, struct mbdata *);
void (*sp_destroy)(struct ssp_ctx *);
void *sp_private;
} ssp_ctx_t;
int ntlmssp_init_client(ssp_ctx_t *);
int krb5ssp_init_client(ssp_ctx_t *);
#endif /* _SSP_H */
/*
* Copyright (c) 2000, Boris Popov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Boris Popov.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* $Id: subr.c,v 1.19 2005/02/09 00:23:45 lindak Exp $
*/
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/time.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <sysexits.h>
#include <libintl.h>
#include <netsmb/netbios.h>
#include <netsmb/smb_lib.h>
#include <netsmb/nb_lib.h>
#include <err.h>
#include "private.h"
static int smblib_initialized;
int
smb_lib_init(void)
{
int error;
if (smblib_initialized)
return (0);
if ((error = nls_setlocale("")) != 0) {
fprintf(stdout, dgettext(TEXT_DOMAIN,
"%s: can't initialise locale\n"), __progname);
return (error);
}
smblib_initialized++;
return (0);
}
int
smb_getlocalname(char **namepp)
{
char buf[SMBIOC_MAX_NAME], *cp;
if (gethostname(buf, sizeof (buf)) != 0)
return (errno);
cp = strchr(buf, '.');
if (cp)
*cp = '\0';
cp = strdup(buf);
if (cp == NULL)
return (ENOMEM);
*namepp = cp;
return (0);
}
/*
* Private version of strerror(3C) that
* knows our special error codes.
*/
char *
smb_strerror(int err)
{
char *msg;
switch (err) {
case EBADRPC:
msg = dgettext(TEXT_DOMAIN,
"remote call failed");
break;
case EAUTH:
msg = dgettext(TEXT_DOMAIN,
"authentication failed");
break;
default:
msg = strerror(err);
break;
}
return (msg);
}
/*
* Print a (descriptive) error message
* error values:
* 0 - no specific error code available;
* 1..32767 - system error
*/
void
smb_error(const char *fmt, int error, ...) {
va_list ap;
const char *cp;
int errtype;
fprintf(stderr, "%s: ", __progname);
va_start(ap, error);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (error == -1) {
error = errno;
errtype = SMB_SYS_ERROR;
} else {
errtype = error & SMB_ERRTYPE_MASK;
error &= ~SMB_ERRTYPE_MASK;
}
switch (errtype) {
case SMB_SYS_ERROR:
if (error)
fprintf(stderr, ": syserr = %s\n", smb_strerror(error));
else
fprintf(stderr, "\n");
break;
case SMB_RAP_ERROR:
fprintf(stderr, ": raperr = %d (0x%04x)\n", error, error);
break;
case SMB_NB_ERROR:
cp = nb_strerror(error);
if (cp == NULL)
fprintf(stderr, ": nberr = unknown (0x%04x)\n", error);
else
fprintf(stderr, ": nberr = %s\n", cp);
break;
default:
fprintf(stderr, "\n");
}
}
char *
smb_printb(char *dest, int flags, const struct smb_bitname *bnp) {
int first = 1;
strcpy(dest, "<");
for (; bnp->bn_bit; bnp++) {
if (flags & bnp->bn_bit) {
strcat(dest, bnp->bn_name);
first = 0;
}
if (!first && (flags & bnp[1].bn_bit))
strcat(dest, "|");
}
strcat(dest, ">");
return (dest);
}
void
smb_simplecrypt(char *dst, const char *src)
{
int ch, pos;
*dst++ = '$';
*dst++ = '$';
*dst++ = '1';
pos = 27;
while (*src) {
ch = *src++;
if (isascii(ch))
ch = (isupper(ch) ? ('A' + (ch - 'A' + 13) % 26) :
islower(ch) ? ('a' + (ch - 'a' + 13) % 26) : ch);
ch ^= pos;
pos += 13;
sprintf(dst, "%02x", ch);
dst += 2;
}
*dst = 0;
}
int
smb_simpledecrypt(char *dst, const char *src)
{
char *ep, hexval[3];
int len, ch, pos;
if (strncmp(src, "$$1", 3) != 0)
return (EINVAL);
src += 3;
len = strlen(src);
if (len & 1)
return (EINVAL);
len /= 2;
hexval[2] = 0;
pos = 27;
while (len--) {
hexval[0] = *src++;
hexval[1] = *src++;
ch = strtoul(hexval, &ep, 16);
if (*ep != 0)
return (EINVAL);
ch ^= pos;
pos += 13;
if (isascii(ch))
ch = (isupper(ch) ? ('A' + (ch - 'A' + 13) % 26) :
islower(ch) ? ('a' + (ch - 'a' + 13) % 26) : ch);
*dst++ = ch;
}
*dst = 0;
return (0);
}
/*
* Number of seconds between 1970 and 1601 year
* (134774 * 24 * 60 * 60)
*/
static const uint64_t DIFF1970TO1601 = 11644473600ULL;
void
smb_time_local2server(struct timeval *tsp, int tzoff, long *seconds)
{
*seconds = tsp->tv_sec - tzoff * 60;
}
void
smb_time_server2local(ulong_t seconds, int tzoff, struct timeval *tsp)
{
tsp->tv_sec = seconds + tzoff * 60;
tsp->tv_usec = 0;
}
/*
* Time from server comes as UTC, so no need to use tz
*/
/*ARGSUSED*/
void
smb_time_NT2local(uint64_t nsec, int tzoff, struct timeval *tsp)
{
smb_time_server2local(nsec / 10000000 - DIFF1970TO1601, 0, tsp);
}
/*ARGSUSED*/
void
smb_time_local2NT(struct timeval *tsp, int tzoff, uint64_t *nsec)
{
long seconds;
smb_time_local2server(tsp, 0, &seconds);
*nsec = (((uint64_t)(seconds) & ~1) + DIFF1970TO1601) *
(uint64_t)10000000;
}
void
smb_hexdump(const void *buf, int len)
{
const uchar_t *p = buf;
int ofs = 0;
while (len--) {
if (ofs % 16 == 0)
fprintf(stderr, "%02X: ", ofs);
fprintf(stderr, "%02x ", *p++);
ofs++;
if (ofs % 16 == 0)
fprintf(stderr, "\n");
}
if (ofs % 16 != 0)
fprintf(stderr, "\n");
}
void
dprint(const char *fname, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (smb_debug) {
fprintf(stderr, "%s: ", fname);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
}
va_end(ap);
}
#undef __progname
char *__progname = NULL;
char *
smb_getprogname()
{
char *p;
if (__progname == NULL) {
__progname = (char *)getexecname();
if ((p = strrchr(__progname, '/')) != 0)
__progname = p + 1;
}
return (__progname);
}
/*
* Copyright (c) 2001 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
* Reserved. This file contains Original Code and/or Modifications of
* Original Code as defined in and that are subject to the Apple Public
* Source License Version 1.0 (the 'License'). You may not use this file
* except in compliance with the License. Please obtain a copy of the
* License at http://www.apple.com/publicsource and read it before using
* this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License."
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* Routines for interacting with the user to get credentials
* (workgroup/domain, username, password, etc.)
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <libintl.h>
#include <ctype.h>
#include <netsmb/smb_lib.h>
#include "private.h"
#include "ntlm.h"
#if 0 /* not yet */
#define MAXLINE 127
static void
smb_tty_prompt(char *prmpt,
char *buf, size_t buflen)
{
char temp[MAXLINE+1];
char *cp;
int ch;
memset(temp, 0, sizeof (temp));
fprintf(stderr, "%s", prmpt);
cp = temp;
while ((ch = getc(stdin)) != EOF) {
if (ch == '\n' || ch == '\r')
break;
if (isspace(ch) || iscntrl(ch))
continue;
*cp++ = ch;
if (cp == &temp[MAXLINE])
break;
}
/* If input empty, accept default. */
if (cp == temp)
return;
/* Use input as new value. */
strncpy(buf, temp, buflen);
}
#endif /* not yet */
/*
* Prompt for a new password after auth. failure.
* (and maybe new user+domain, but not yet)
*/
int
smb_get_authentication(struct smb_ctx *ctx)
{
char *npw;
int err;
/*
* If we're getting a password, we must be doing
* some kind of NTLM, possibly after a failure to
* authenticate using Kerberos. Turn off krb5.
*/
ctx->ct_authflags &= ~SMB_AT_KRB5;
if (ctx->ct_flags & SMBCF_KCFOUND) {
/* Tried a keychain hash and failed. */
/* XXX: delete the KC entry? */
ctx->ct_flags |= SMBCF_KCBAD;
}
if (ctx->ct_flags & SMBCF_NOPWD)
return (ENOTTY);
if (isatty(STDIN_FILENO)) {
/* Need command-line prompting. */
npw = getpassphrase(dgettext(TEXT_DOMAIN, "Password:"));
if (npw == NULL)
return (EINTR);
memset(ctx->ct_password, 0, sizeof (ctx->ct_password));
strlcpy(ctx->ct_password, npw, sizeof (ctx->ct_password));
} else {
/*
* XXX: Ask the user for help, possibly via
* GNOME dbus or some such... (todo).
*/
smb_error(dgettext(TEXT_DOMAIN,
"Cannot prompt for a password when input is redirected."), 0);
return (ENOTTY);
}
/*
* Recompute the password hashes.
*/
if (ctx->ct_password[0]) {
err = ntlm_compute_lm_hash(ctx->ct_lmhash, ctx->ct_password);
if (err != 0)
return (err);
err = ntlm_compute_nt_hash(ctx->ct_nthash, ctx->ct_password);
if (err != 0)
return (err);
}
return (0);
}
/*ARGSUSED*/
int
smb_browse(struct smb_ctx *ctx, int anon)
{
/*
* Let user pick a share.
* Not supported.
*/
return (EINTR);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* Unicode conversions (yet more)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <iconv.h>
#include <libintl.h>
#include <sys/u8_textprep.h>
#include <netsmb/smb_lib.h>
#include "charsets.h"
/*
* Number of unicode symbols in the string,
* not including the 2-byte null terminator.
* (multiply by two for storage size)
*/
size_t
unicode_strlen(const uint16_t *us)
{
size_t len = 0;
while (*us++)
len++;
return (len);
}
static char *convert_ucs2xx_to_utf8(iconv_t, const uint16_t *);
/*
* Convert (native) Unicode string to UTF-8.
* Returns allocated memory.
*/
char *
convert_unicode_to_utf8(uint16_t *us)
{
static iconv_t cd1 = (iconv_t)-1;
/* Get conversion descriptor (to, from) */
if (cd1 == (iconv_t)-1)
cd1 = iconv_open("UTF-8", "UCS-2");
return (convert_ucs2xx_to_utf8(cd1, us));
}
/*
* Convert little-endian Unicode string to UTF-8.
* Returns allocated memory.
*/
char *
convert_leunicode_to_utf8(unsigned short *us)
{
static iconv_t cd2 = (iconv_t)-1;
/* Get conversion descriptor (to, from) */
if (cd2 == (iconv_t)-1)
cd2 = iconv_open("UTF-8", "UCS-2LE");
return (convert_ucs2xx_to_utf8(cd2, us));
}
static char *
convert_ucs2xx_to_utf8(iconv_t cd, const uint16_t *us)
{
char *obuf, *optr;
const char *iptr;
size_t ileft, obsize, oleft, ret;
if (cd == (iconv_t)-1) {
smb_error(dgettext(TEXT_DOMAIN,
"iconv_open(UTF-8/UCS-2)"), -1);
return (NULL);
}
iptr = (const char *)us;
ileft = unicode_strlen(us);
ileft *= 2; /* now bytes */
/* Worst-case output size is 2x input size. */
oleft = ileft * 2;
obsize = oleft + 2; /* room for null */
obuf = malloc(obsize);
if (!obuf)
return (NULL);
optr = obuf;
ret = iconv(cd, &iptr, &ileft, &optr, &oleft);
*optr = '\0';
if (ret == (size_t)-1) {
smb_error(dgettext(TEXT_DOMAIN,
"iconv(%s) failed"), errno, obuf);
}
if (ileft) {
smb_error(dgettext(TEXT_DOMAIN,
"iconv(%s) failed"), -1, obuf);
/*
* XXX: What's better? return NULL?
* The truncated string? << for now
*/
}
return (obuf);
}
static uint16_t *convert_utf8_to_ucs2xx(iconv_t, const char *);
/*
* Convert UTF-8 string to Unicode.
* Returns allocated memory.
*/
uint16_t *
convert_utf8_to_unicode(const char *utf8_string)
{
static iconv_t cd3 = (iconv_t)-1;
/* Get conversion descriptor (to, from) */
if (cd3 == (iconv_t)-1)
cd3 = iconv_open("UCS-2", "UTF-8");
return (convert_utf8_to_ucs2xx(cd3, utf8_string));
}
/*
* Convert UTF-8 string to little-endian Unicode.
* Returns allocated memory.
*/
uint16_t *
convert_utf8_to_leunicode(const char *utf8_string)
{
static iconv_t cd4 = (iconv_t)-1;
/* Get conversion descriptor (to, from) */
if (cd4 == (iconv_t)-1)
cd4 = iconv_open("UCS-2LE", "UTF-8");
return (convert_utf8_to_ucs2xx(cd4, utf8_string));
}
static uint16_t *
convert_utf8_to_ucs2xx(iconv_t cd, const char *utf8_string)
{
uint16_t *obuf, *optr;
const char *iptr;
size_t ileft, obsize, oleft, ret;
if (cd == (iconv_t)-1) {
smb_error(dgettext(TEXT_DOMAIN,
"iconv_open(UCS-2/UTF-8)"), -1);
return (NULL);
}
iptr = utf8_string;
ileft = strlen(iptr);
/* Worst-case output size is 2x input size. */
oleft = ileft * 2;
obsize = oleft + 2; /* room for null */
obuf = malloc(obsize);
if (!obuf)
return (NULL);
optr = obuf;
ret = iconv(cd, &iptr, &ileft, (char **)&optr, &oleft);
*optr = '\0';
if (ret == (size_t)-1) {
smb_error(dgettext(TEXT_DOMAIN,
"iconv(%s) failed"), errno, utf8_string);
}
if (ileft) {
smb_error(dgettext(TEXT_DOMAIN,
"iconv(%s) failed"), -1, utf8_string);
/*
* XXX: What's better? return NULL?
* The truncated string? << for now
*/
}
return (obuf);
}
/*
* A simple wrapper around u8_textprep_str() that returns the Unicode
* upper-case version of some string. Returns memory from malloc.
* Borrowed from idmapd.
*/
static char *
utf8_str_to_upper_or_lower(const char *s, int upper_lower)
{
char *res = NULL;
char *outs;
size_t inlen, outlen, inbleft, outbleft;
int rc, err;
/*
* u8_textprep_str() does not allocate memory. The input and
* output buffers may differ in size (though that would be more
* likely when normalization is done). We have to loop over it...
*
* To improve the chances that we can avoid looping we add 10
* bytes of output buffer room the first go around.
*/
inlen = inbleft = strlen(s);
outlen = outbleft = inlen + 10;
if ((res = malloc(outlen)) == NULL)
return (NULL);
outs = res;
while ((rc = u8_textprep_str((char *)s, &inbleft, outs,
&outbleft, upper_lower, U8_UNICODE_LATEST, &err)) < 0 &&
err == E2BIG) {
if ((res = realloc(res, outlen + inbleft)) == NULL)
return (NULL);
/* adjust input/output buffer pointers */
s += (inlen - inbleft);
outs = res + outlen - outbleft;
/* adjust outbleft and outlen */
outlen += inbleft;
outbleft += inbleft;
}
if (rc < 0) {
free(res);
res = NULL;
return (NULL);
}
res[outlen - outbleft] = '\0';
return (res);
}
char *
utf8_str_toupper(const char *s)
{
return (utf8_str_to_upper_or_lower(s, U8_TEXTPREP_TOUPPER));
}
char *
utf8_str_tolower(const char *s)
{
return (utf8_str_to_upper_or_lower(s, U8_TEXTPREP_TOLOWER));
}
|