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
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.DirectoryServices.ActiveDirectory;
using System.Globalization;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.Net.Security;
using System.Runtime;
using System.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
using System.Xml;
using Microsoft.Win32;
using AuthIdentityEx = System.IdentityModel.AuthIdentityEx;
using CredentialUse = System.IdentityModel.CredentialUse;
using DictionaryManager = System.IdentityModel.DictionaryManager;
using SafeFreeCredentials = System.IdentityModel.SafeFreeCredentials;
using SspiWrapper = System.IdentityModel.SspiWrapper;
static class StoreLocationHelper
{
internal static bool IsDefined(StoreLocation value)
{
return (value == StoreLocation.CurrentUser
|| value == StoreLocation.LocalMachine);
}
}
static class ProtectionLevelHelper
{
internal static bool IsDefined(ProtectionLevel value)
{
return (value == ProtectionLevel.None
|| value == ProtectionLevel.Sign
|| value == ProtectionLevel.EncryptAndSign);
}
internal static void Validate(ProtectionLevel value)
{
if (!IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value,
typeof(ProtectionLevel)));
}
}
internal static bool IsStronger(ProtectionLevel v1, ProtectionLevel v2)
{
return ((v1 == ProtectionLevel.EncryptAndSign && v2 != ProtectionLevel.EncryptAndSign)
|| (v1 == ProtectionLevel.Sign && v2 == ProtectionLevel.None));
}
internal static bool IsStrongerOrEqual(ProtectionLevel v1, ProtectionLevel v2)
{
return (v1 == ProtectionLevel.EncryptAndSign
|| (v1 == ProtectionLevel.Sign && v2 != ProtectionLevel.EncryptAndSign));
}
internal static ProtectionLevel Max(ProtectionLevel v1, ProtectionLevel v2)
{
return IsStronger(v1, v2) ? v1 : v2;
}
internal static int GetOrdinal(Nullable<ProtectionLevel> p)
{
if (p.HasValue)
{
switch ((ProtectionLevel)p)
{
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("p", (int)p,
typeof(ProtectionLevel)));
case ProtectionLevel.None:
return 2;
case ProtectionLevel.Sign:
return 3;
case ProtectionLevel.EncryptAndSign:
return 4;
}
}
else
return 1;
}
}
static class SslProtocolsHelper
{
internal static bool IsDefined(SslProtocols value)
{
SslProtocols allValues = SslProtocols.None;
foreach (var protocol in Enum.GetValues(typeof(SslProtocols)))
{
allValues |= (SslProtocols)protocol;
}
return (value & allValues) == value;
}
internal static void Validate(SslProtocols value)
{
if (!IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value,
typeof(SslProtocols)));
}
}
}
static class TokenImpersonationLevelHelper
{
internal static bool IsDefined(TokenImpersonationLevel value)
{
return (value == TokenImpersonationLevel.None
|| value == TokenImpersonationLevel.Anonymous
|| value == TokenImpersonationLevel.Identification
|| value == TokenImpersonationLevel.Impersonation
|| value == TokenImpersonationLevel.Delegation);
}
internal static void Validate(TokenImpersonationLevel value)
{
if (!IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value,
typeof(TokenImpersonationLevel)));
}
}
static TokenImpersonationLevel[] TokenImpersonationLevelOrder = new TokenImpersonationLevel[]
{
TokenImpersonationLevel.None,
TokenImpersonationLevel.Anonymous,
TokenImpersonationLevel.Identification,
TokenImpersonationLevel.Impersonation,
TokenImpersonationLevel.Delegation
};
internal static string ToString(TokenImpersonationLevel impersonationLevel)
{
if (impersonationLevel == TokenImpersonationLevel.Identification)
{
return "identification";
}
else if (impersonationLevel == TokenImpersonationLevel.None)
{
return "none";
}
else if (impersonationLevel == TokenImpersonationLevel.Anonymous)
{
return "anonymous";
}
else if (impersonationLevel == TokenImpersonationLevel.Impersonation)
{
return "impersonation";
}
else if (impersonationLevel == TokenImpersonationLevel.Delegation)
{
return "delegation";
}
Fx.Assert("unknown token impersonation level");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("impersonationLevel", (int)impersonationLevel,
typeof(TokenImpersonationLevel)));
}
internal static bool IsGreaterOrEqual(TokenImpersonationLevel x, TokenImpersonationLevel y)
{
TokenImpersonationLevelHelper.Validate(x);
TokenImpersonationLevelHelper.Validate(y);
if (x == y)
return true;
int px = 0;
int py = 0;
for (int i = 0; i < TokenImpersonationLevelOrder.Length; i++)
{
if (x == TokenImpersonationLevelOrder[i])
px = i;
if (y == TokenImpersonationLevelOrder[i])
py = i;
}
return (px > py);
}
internal static int Compare(TokenImpersonationLevel x, TokenImpersonationLevel y)
{
int result = 0;
if (x != y)
{
switch (x)
{
case TokenImpersonationLevel.Identification:
result = -1;
break;
case TokenImpersonationLevel.Impersonation:
switch (y)
{
case TokenImpersonationLevel.Identification:
result = 1;
break;
case TokenImpersonationLevel.Delegation:
result = -1;
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("y", (int)y,
typeof(TokenImpersonationLevel)));
}
break;
case TokenImpersonationLevel.Delegation:
result = 1;
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("x", (int)x,
typeof(TokenImpersonationLevel)));
}
}
return result;
}
}
internal class ServiceModelDictionaryManager
{
static DictionaryManager dictionaryManager;
public static DictionaryManager Instance
{
get
{
if (dictionaryManager == null)
dictionaryManager = new DictionaryManager(BinaryMessageEncoderFactory.XmlDictionary);
return dictionaryManager;
}
}
}
static class SecurityUtils
{
public const string Principal = "Principal";
public const string Identities = "Identities";
static bool computedDomain;
static string currentDomain;
static byte[] combinedHashLabel;
static IIdentity anonymousIdentity;
static NetworkCredential dummyNetworkCredential;
static object dummyNetworkCredentialLock = new object();
static X509SecurityTokenAuthenticator nonValidatingX509Authenticator;
static SecurityIdentifier administratorsSid;
const int WindowsServerMajorNumber = 5;
const int WindowsServerMinorNumber = 2;
const int XPMajorNumber = 5;
const int XPMinorNumber = 1;
const string ServicePack1 = "Service Pack 1";
const string ServicePack2 = "Service Pack 2";
volatile static bool shouldValidateSslCipherStrength;
volatile static bool isSslValidationRequirementDetermined = false;
static readonly int MinimumSslCipherStrength = 128;
// these are kept in [....] with IIS70
public const string AuthTypeNTLM = "NTLM";
public const string AuthTypeNegotiate = "Negotiate";
public const string AuthTypeKerberos = "Kerberos";
public const string AuthTypeAnonymous = "";
public const string AuthTypeCertMap = "SSL/PCT"; // mapped from a cert
public const string AuthTypeBasic = "Basic"; //LogonUser
public static ChannelBinding GetChannelBindingFromMessage(Message message)
{
if (message == null)
{
return null;
}
ChannelBindingMessageProperty channelBindingMessageProperty = null;
ChannelBindingMessageProperty.TryGet(message, out channelBindingMessageProperty);
ChannelBinding channelBinding = null;
if (channelBindingMessageProperty != null)
{
channelBinding = channelBindingMessageProperty.ChannelBinding;
}
return channelBinding;
}
internal static bool IsOsGreaterThanXP()
{
return ((Environment.OSVersion.Version.Major >= SecurityUtils.XPMajorNumber && Environment.OSVersion.Version.Minor > SecurityUtils.XPMinorNumber) ||
Environment.OSVersion.Version.Major > SecurityUtils.XPMajorNumber);
}
internal static bool IsOSGreaterThanOrEqualToWin7()
{
Version windows7Version = new Version(6, 1, 0, 0);
return (Environment.OSVersion.Version.Major >= windows7Version.Major && Environment.OSVersion.Version.Minor >= windows7Version.Minor);
}
internal static bool IsCurrentlyTimeEffective(DateTime effectiveTime, DateTime expirationTime, TimeSpan maxClockSkew)
{
DateTime curEffectiveTime = (effectiveTime < DateTime.MinValue.Add(maxClockSkew)) ? effectiveTime : effectiveTime.Subtract(maxClockSkew);
DateTime curExpirationTime = (expirationTime > DateTime.MaxValue.Subtract(maxClockSkew)) ? expirationTime : expirationTime.Add(maxClockSkew);
DateTime curTime = DateTime.UtcNow;
return (curEffectiveTime.ToUniversalTime() <= curTime) && (curTime < curExpirationTime.ToUniversalTime());
}
internal static X509SecurityTokenAuthenticator NonValidatingX509Authenticator
{
get
{
if (nonValidatingX509Authenticator == null)
{
nonValidatingX509Authenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None);
}
return nonValidatingX509Authenticator;
}
}
public static SecurityIdentifier AdministratorsSid
{
get
{
if (administratorsSid == null)
administratorsSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
return administratorsSid;
}
}
internal static IIdentity AnonymousIdentity
{
get
{
if (anonymousIdentity == null)
{
anonymousIdentity = SecurityUtils.CreateIdentity(String.Empty);
}
return anonymousIdentity;
}
}
public static DateTime MaxUtcDateTime
{
get
{
// + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow.
return new DateTime(DateTime.MaxValue.Ticks - TimeSpan.TicksPerDay, DateTimeKind.Utc);
}
}
public static DateTime MinUtcDateTime
{
get
{
// + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow.
return new DateTime(DateTime.MinValue.Ticks + TimeSpan.TicksPerDay, DateTimeKind.Utc);
}
}
internal static IIdentity CreateIdentity(string name, string authenticationType)
{
return new GenericIdentity(name, authenticationType);
}
internal static IIdentity CreateIdentity(string name)
{
return new GenericIdentity(name);
}
internal static EndpointIdentity CreateWindowsIdentity()
{
return CreateWindowsIdentity(false);
}
internal static EndpointIdentity CreateWindowsIdentity(NetworkCredential serverCredential)
{
if (serverCredential != null && !NetworkCredentialHelper.IsDefault(serverCredential))
{
string upn;
if (serverCredential.Domain != null && serverCredential.Domain.Length > 0)
{
upn = serverCredential.UserName + "@" + serverCredential.Domain;
}
else
{
upn = serverCredential.UserName;
}
return EndpointIdentity.CreateUpnIdentity(upn);
}
else
{
return SecurityUtils.CreateWindowsIdentity();
}
}
static bool IsSystemAccount(WindowsIdentity self)
{
SecurityIdentifier sid = self.User;
if (sid == null)
{
return false;
}
// S-1-5-82 is the prefix for the sid that represents the identity that IIS 7.5 Apppool thread runs under.
return (sid.IsWellKnown(WellKnownSidType.LocalSystemSid)
|| sid.IsWellKnown(WellKnownSidType.NetworkServiceSid)
|| sid.IsWellKnown(WellKnownSidType.LocalServiceSid)
|| self.User.Value.StartsWith("S-1-5-82", StringComparison.OrdinalIgnoreCase));
}
internal static EndpointIdentity CreateWindowsIdentity(bool spnOnly)
{
EndpointIdentity identity = null;
using (WindowsIdentity self = WindowsIdentity.GetCurrent())
{
bool isSystemAccount = IsSystemAccount(self);
if (spnOnly || isSystemAccount)
{
identity = EndpointIdentity.CreateSpnIdentity(String.Format(CultureInfo.InvariantCulture, "host/{0}", DnsCache.MachineName));
}
else
{
// Save windowsIdentity for delay lookup
identity = new UpnEndpointIdentity(CloneWindowsIdentityIfNecessary(self));
}
}
return identity;
}
[Fx.Tag.SecurityNote(Critical = "Calls two critical methods: UnsafeGetWindowsIdentityToken and UnsafeCreateWindowsIdentityFromToken.",
Safe = "'Clone' operation is considered safe despite using WindowsIdentity IntPtr token. Must not let IntPtr token leak in or out.")]
[SecuritySafeCritical]
internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid)
{
return SecurityUtils.CloneWindowsIdentityIfNecessary(wid, null);
}
[Fx.Tag.SecurityNote(Critical = "Calls two critical methods: UnsafeGetWindowsIdentityToken and UnsafeCreateWindowsIdentityFromToken.",
Safe = "'Clone' operation is considered safe despite using WindowsIdentity IntPtr token. Must not let IntPtr token leak in or out.")]
[SecuritySafeCritical]
internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid, string authType)
{
if (wid != null)
{
IntPtr token = UnsafeGetWindowsIdentityToken(wid);
if (token != IntPtr.Zero)
{
return UnsafeCreateWindowsIdentityFromToken(token, authType);
}
}
return wid;
}
[Fx.Tag.SecurityNote(Critical = "Elevates in order to return the WindowsIdentity.Token property, caller must protect return value.")]
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
static IntPtr UnsafeGetWindowsIdentityToken(WindowsIdentity wid)
{
return wid.Token;
}
[Fx.Tag.SecurityNote(Critical = "Elevates in order to return the SecurityIdentifier of the current user as a string, caller must protect return value.")]
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlPrincipal)]
static string UnsafeGetCurrentUserSidAsString()
{
using (WindowsIdentity self = WindowsIdentity.GetCurrent())
{
return self.User.Value;
}
}
[Fx.Tag.SecurityNote(Critical = "Elevates in order to return the WindowsIdentity.Token property, caller must protect return value.")]
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, ControlPrincipal = true, UnmanagedCode = true)]
static WindowsIdentity UnsafeCreateWindowsIdentityFromToken(IntPtr token, string authType)
{
if (authType != null)
return new WindowsIdentity(token, authType);
else
return new WindowsIdentity(token);
}
internal static bool AllowsImpersonation(WindowsIdentity windowsIdentity, TokenImpersonationLevel impersonationLevel)
{
if (windowsIdentity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
TokenImpersonationLevelHelper.Validate(impersonationLevel);
if (impersonationLevel == TokenImpersonationLevel.Identification)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("impersonationLevel"));
bool result = true;
switch (windowsIdentity.ImpersonationLevel)
{
case TokenImpersonationLevel.None:
case TokenImpersonationLevel.Anonymous:
case TokenImpersonationLevel.Identification:
result = false; break;
case TokenImpersonationLevel.Impersonation:
if (impersonationLevel == TokenImpersonationLevel.Delegation)
result = false;
break;
case TokenImpersonationLevel.Delegation:
break;
default:
result = false;
break;
}
return result;
}
internal static byte[] CombinedHashLabel
{
get
{
if (combinedHashLabel == null)
combinedHashLabel = Encoding.UTF8.GetBytes(TrustApr2004Strings.CombinedHashLabel);
return combinedHashLabel;
}
}
internal static T GetSecurityKey<T>(SecurityToken token)
where T : SecurityKey
{
T result = null;
if (token.SecurityKeys != null)
{
for (int i = 0; i < token.SecurityKeys.Count; ++i)
{
T temp = (token.SecurityKeys[i] as T);
if (temp != null)
{
if (result != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.MultipleMatchingCryptosFound, typeof(T).ToString())));
}
else
{
result = temp;
}
}
}
}
return result;
}
internal static bool HasSymmetricSecurityKey(SecurityToken token)
{
return GetSecurityKey<SymmetricSecurityKey>(token) != null;
}
internal static void EnsureExpectedSymmetricMatch(SecurityToken t1, SecurityToken t2, Message message)
{
// nulls are not mismatches
if (t1 == null || t2 == null || ReferenceEquals(t1, t2))
{
return;
}
// check for interop flexibility
SymmetricSecurityKey c1 = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(t1);
SymmetricSecurityKey c2 = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(t2);
if (c1 == null || c2 == null || !CryptoHelper.IsEqual(c1.GetSymmetricKey(), c2.GetSymmetricKey()))
{
throw System.ServiceModel.Diagnostics.TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenNotExpectedInSecurityHeader, t2)), message);
}
}
internal static SymmetricAlgorithm GetSymmetricAlgorithm(string algorithm, SecurityToken token)
{
SymmetricSecurityKey securityKey = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(token);
if (securityKey != null && securityKey.IsSupportedAlgorithm(algorithm))
{
return securityKey.GetSymmetricAlgorithm(algorithm);
}
else
{
return null;
}
}
internal static KeyedHashAlgorithm GetKeyedHashAlgorithm(string algorithm, SecurityToken token)
{
SymmetricSecurityKey securityKey = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(token);
if (securityKey != null && securityKey.IsSupportedAlgorithm(algorithm))
{
return securityKey.GetKeyedHashAlgorithm(algorithm);
}
else
{
return null;
}
}
internal static ReadOnlyCollection<SecurityKey> CreateSymmetricSecurityKeys(byte[] key)
{
List<SecurityKey> temp = new List<SecurityKey>(1);
temp.Add(new InMemorySymmetricSecurityKey(key));
return temp.AsReadOnly();
}
internal static byte[] DecryptKey(SecurityToken unwrappingToken, string encryptionMethod, byte[] wrappedKey, out SecurityKey unwrappingSecurityKey)
{
unwrappingSecurityKey = null;
if (unwrappingToken.SecurityKeys != null)
{
for (int i = 0; i < unwrappingToken.SecurityKeys.Count; ++i)
{
if (unwrappingToken.SecurityKeys[i].IsSupportedAlgorithm(encryptionMethod))
{
unwrappingSecurityKey = unwrappingToken.SecurityKeys[i];
break;
}
}
}
if (unwrappingSecurityKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.CannotFindMatchingCrypto, encryptionMethod)));
}
return unwrappingSecurityKey.DecryptKey(encryptionMethod, wrappedKey);
}
internal static byte[] EncryptKey(SecurityToken wrappingToken, string encryptionMethod, byte[] keyToWrap)
{
SecurityKey wrappingSecurityKey = null;
if (wrappingToken.SecurityKeys != null)
{
for (int i = 0; i < wrappingToken.SecurityKeys.Count; ++i)
{
if (wrappingToken.SecurityKeys[i].IsSupportedAlgorithm(encryptionMethod))
{
wrappingSecurityKey = wrappingToken.SecurityKeys[i];
break;
}
}
}
if (wrappingSecurityKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.CannotFindMatchingCrypto, encryptionMethod));
}
return wrappingSecurityKey.EncryptKey(encryptionMethod, keyToWrap);
}
internal static byte[] ReadContentAsBase64(XmlDictionaryReader reader, long maxBufferSize)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
// Code cloned from System.Xml.XmlDictionaryReder.
byte[][] buffers = new byte[32][];
byte[] buffer;
// Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
int count = 384;
int bufferCount = 0;
int totalRead = 0;
while (true)
{
buffer = new byte[count];
buffers[bufferCount++] = buffer;
int read = 0;
while (read < buffer.Length)
{
int actual = reader.ReadContentAsBase64(buffer, read, buffer.Length - read);
if (actual == 0)
break;
read += actual;
}
if (totalRead > maxBufferSize - read)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(SR.GetString(SR.BufferQuotaExceededReadingBase64, maxBufferSize)));
totalRead += read;
if (read < buffer.Length)
break;
count = count * 2;
}
buffer = new byte[totalRead];
int offset = 0;
for (int i = 0; i < bufferCount - 1; i++)
{
Buffer.BlockCopy(buffers[i], 0, buffer, offset, buffers[i].Length);
offset += buffers[i].Length;
}
Buffer.BlockCopy(buffers[bufferCount - 1], 0, buffer, offset, totalRead - offset);
return buffer;
}
internal static byte[] GenerateDerivedKey(SecurityToken tokenToDerive, string derivationAlgorithm, byte[] label, byte[] nonce,
int keySize, int offset)
{
SymmetricSecurityKey symmetricSecurityKey = SecurityUtils.GetSecurityKey<SymmetricSecurityKey>(tokenToDerive);
if (symmetricSecurityKey == null || !symmetricSecurityKey.IsSupportedAlgorithm(derivationAlgorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.CannotFindMatchingCrypto, derivationAlgorithm)));
}
return symmetricSecurityKey.GenerateDerivedKey(derivationAlgorithm, label, nonce, keySize, offset);
}
internal static string GetSpnFromIdentity(EndpointIdentity identity, EndpointAddress target)
{
bool foundSpn = false;
string spn = null;
if (identity != null)
{
if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
{
spn = (string)identity.IdentityClaim.Resource;
foundSpn = true;
}
else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
{
spn = (string)identity.IdentityClaim.Resource;
foundSpn = true;
}
else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
{
spn = String.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
foundSpn = true;
}
}
if (!foundSpn)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.CannotDetermineSPNBasedOnAddress, target)));
}
return spn;
}
internal static string GetSpnFromTarget(EndpointAddress target)
{
if (target == null)
{
throw Fx.AssertAndThrow("target should not be null - expecting an EndpointAddress");
}
return string.Format(CultureInfo.InvariantCulture, "host/{0}", target.Uri.DnsSafeHost);
}
internal static bool IsSupportedAlgorithm(string algorithm, SecurityToken token)
{
if (token.SecurityKeys == null)
{
return false;
}
for (int i = 0; i < token.SecurityKeys.Count; ++i)
{
if (token.SecurityKeys[i].IsSupportedAlgorithm(algorithm))
{
return true;
}
}
return false;
}
internal static Claim GetPrimaryIdentityClaim(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
return GetPrimaryIdentityClaim(AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies));
}
internal static Claim GetPrimaryIdentityClaim(AuthorizationContext authContext)
{
if (authContext != null)
{
for (int i = 0; i < authContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = authContext.ClaimSets[i];
foreach (Claim claim in claimSet.FindClaims(null, Rights.Identity))
{
return claim;
}
}
}
return null;
}
internal static int GetServiceAddressAndViaHash(EndpointAddress sr)
{
if (sr == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sr");
}
return sr.GetHashCode();
}
internal static string GenerateId()
{
return SecurityUniqueId.Create().Value;
}
internal static string GenerateIdWithPrefix(string prefix)
{
return SecurityUniqueId.Create(prefix).Value;
}
internal static UniqueId GenerateUniqueId()
{
return new UniqueId();
}
internal static string GetPrimaryDomain()
{
using (WindowsIdentity wid = WindowsIdentity.GetCurrent())
{
return GetPrimaryDomain(IsSystemAccount(wid));
}
}
internal static string GetPrimaryDomain(bool isSystemAccount)
{
if (computedDomain == false)
{
try
{
if (isSystemAccount)
{
currentDomain = Domain.GetComputerDomain().Name;
}
else
{
currentDomain = Domain.GetCurrentDomain().Name;
}
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
}
finally
{
computedDomain = true;
}
}
return currentDomain;
}
internal static void EnsureCertificateCanDoKeyExchange(X509Certificate2 certificate)
{
if (certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
}
bool canDoKeyExchange = false;
Exception innerException = null;
if (certificate.HasPrivateKey)
{
try
{
canDoKeyExchange = CanKeyDoKeyExchange(certificate);
}
// exceptions can be due to ACLs on the key etc
catch (System.Security.SecurityException e)
{
innerException = e;
}
catch (CryptographicException e)
{
innerException = e;
}
}
if (!canDoKeyExchange)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SslCertMayNotDoKeyExchange, certificate.SubjectName.Name), innerException));
}
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method GetKeyContainerInfo.",
Safe = "Info is not leaked.")]
[SecuritySafeCritical]
static bool CanKeyDoKeyExchange(X509Certificate2 certificate)
{
CspKeyContainerInfo info = GetKeyContainerInfo(certificate);
return info != null && info.KeyNumber == KeyNumber.Exchange;
}
[Fx.Tag.SecurityNote(Critical = "Elevates to call properties: X509Certificate2.PrivateKey and CspKeyContainerInfo. Caller must protect the return value.")]
[SecurityCritical]
[KeyContainerPermission(SecurityAction.Assert, Flags = KeyContainerPermissionFlags.Open)]
static CspKeyContainerInfo GetKeyContainerInfo(X509Certificate2 certificate)
{
RSACryptoServiceProvider rsa = certificate.PrivateKey as RSACryptoServiceProvider;
if (rsa != null)
{
return rsa.CspKeyContainerInfo;
}
return null;
}
internal static string GetCertificateId(X509Certificate2 certificate)
{
StringBuilder str = new StringBuilder(256);
AppendCertificateIdentityName(str, certificate);
return str.ToString();
}
internal static ReadOnlyCollection<IAuthorizationPolicy> CreatePrincipalNameAuthorizationPolicies(string principalName)
{
if (principalName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("principalName");
Claim identityClaim;
Claim primaryPrincipal;
if (principalName.Contains("@") || principalName.Contains(@"\"))
{
identityClaim = new Claim(ClaimTypes.Upn, principalName, Rights.Identity);
primaryPrincipal = Claim.CreateUpnClaim(principalName);
}
else
{
identityClaim = new Claim(ClaimTypes.Spn, principalName, Rights.Identity);
primaryPrincipal = Claim.CreateSpnClaim(principalName);
}
List<Claim> claims = new List<Claim>(2);
claims.Add(identityClaim);
claims.Add(primaryPrincipal);
List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1);
policies.Add(new UnconditionalPolicy(SecurityUtils.CreateIdentity(principalName), new DefaultClaimSet(ClaimSet.Anonymous, claims)));
return policies.AsReadOnly();
}
internal static string GetIdentityNamesFromPolicies(IList<IAuthorizationPolicy> authPolicies)
{
return GetIdentityNamesFromContext(AuthorizationContext.CreateDefaultAuthorizationContext(authPolicies));
}
internal static string GetIdentityNamesFromContext(AuthorizationContext authContext)
{
if (authContext == null)
return String.Empty;
StringBuilder str = new StringBuilder(256);
for (int i = 0; i < authContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = authContext.ClaimSets[i];
// Windows
WindowsClaimSet windows = claimSet as WindowsClaimSet;
if (windows != null)
{
if (str.Length > 0)
str.Append(", ");
AppendIdentityName(str, windows.WindowsIdentity);
}
else
{
// X509
X509CertificateClaimSet x509 = claimSet as X509CertificateClaimSet;
if (x509 != null)
{
if (str.Length > 0)
str.Append(", ");
AppendCertificateIdentityName(str, x509.X509Certificate);
}
}
}
if (str.Length <= 0)
{
List<IIdentity> identities = null;
object obj;
if (authContext.Properties.TryGetValue(SecurityUtils.Identities, out obj))
{
identities = obj as List<IIdentity>;
}
if (identities != null)
{
for (int i = 0; i < identities.Count; ++i)
{
IIdentity identity = identities[i];
if (identity != null)
{
if (str.Length > 0)
str.Append(", ");
AppendIdentityName(str, identity);
}
}
}
}
return str.Length <= 0 ? String.Empty : str.ToString();
}
internal static void AppendCertificateIdentityName(StringBuilder str, X509Certificate2 certificate)
{
string value = certificate.SubjectName.Name;
if (String.IsNullOrEmpty(value))
{
value = certificate.GetNameInfo(X509NameType.DnsName, false);
if (String.IsNullOrEmpty(value))
{
value = certificate.GetNameInfo(X509NameType.SimpleName, false);
if (String.IsNullOrEmpty(value))
{
value = certificate.GetNameInfo(X509NameType.EmailName, false);
if (String.IsNullOrEmpty(value))
{
value = certificate.GetNameInfo(X509NameType.UpnName, false);
}
}
}
}
// Same format as X509Identity
str.Append(String.IsNullOrEmpty(value) ? "<x509>" : value);
str.Append("; ");
str.Append(certificate.Thumbprint);
}
internal static void AppendIdentityName(StringBuilder str, IIdentity identity)
{
string name = null;
try
{
name = identity.Name;
}
#pragma warning suppress 56500
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
// suppress exception, this is just info.
}
str.Append(String.IsNullOrEmpty(name) ? "<null>" : name);
WindowsIdentity windows = identity as WindowsIdentity;
if (windows != null)
{
if (windows.User != null)
{
str.Append("; ");
str.Append(windows.User.ToString());
}
}
else
{
WindowsSidIdentity sid = identity as WindowsSidIdentity;
if (sid != null)
{
str.Append("; ");
str.Append(sid.SecurityIdentifier.ToString());
}
}
}
[Fx.Tag.SecurityNote(Critical = "Calls critical methods UnsafeGetDomain, UnsafeGetUserName, UnsafeGetPassword and UnsafeGetCurrentUserSidAsString.")]
[SecurityCritical]
internal static string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
{
const string delimiter = "\0"; // nonprintable characters are invalid for SSPI Domain/UserName/Password
if (IsDefaultNetworkCredential(credential))
{
string sid = UnsafeGetCurrentUserSidAsString();
return string.Concat(inputString, delimiter,
sid, delimiter,
AuthenticationLevelHelper.ToString(authenticationLevel), delimiter,
TokenImpersonationLevelHelper.ToString(impersonationLevel));
}
else
{
return string.Concat(inputString, delimiter,
NetworkCredentialHelper.UnsafeGetDomain(credential), delimiter,
NetworkCredentialHelper.UnsafeGetUsername(credential), delimiter,
NetworkCredentialHelper.UnsafeGetPassword(credential), delimiter,
AuthenticationLevelHelper.ToString(authenticationLevel), delimiter,
TokenImpersonationLevelHelper.ToString(impersonationLevel));
}
}
internal static string GetIdentityName(IIdentity identity)
{
StringBuilder str = new StringBuilder(256);
AppendIdentityName(str, identity);
return str.ToString();
}
/// <SecurityNote>
/// Critical - Calls an UnsafeNativeMethod and a Critical method (GetFipsAlgorithmPolicyKeyFromRegistry)
/// Safe - processes the return and just returns a bool, which is safe
/// </SecurityNote>
internal static bool IsChannelBindingDisabled
{
[SecuritySafeCritical]
get
{
return ((GetSuppressChannelBindingValue() & 0x1) != 0);
}
}
const string suppressChannelBindingRegistryKey = @"System\CurrentControlSet\Control\Lsa";
/// <SecurityNote>
/// Critical - Asserts to get a value from the registry
/// </SecurityNote>
[SecurityCritical]
[RegistryPermission(SecurityAction.Assert, Read = @"HKEY_LOCAL_MACHINE\" + suppressChannelBindingRegistryKey)]
internal static int GetSuppressChannelBindingValue()
{
int channelBindingPolicyKeyValue = 0;
try
{
using (RegistryKey channelBindingPolicyKey = Registry.LocalMachine.OpenSubKey(suppressChannelBindingRegistryKey, false))
{
if (channelBindingPolicyKey != null)
{
object data = channelBindingPolicyKey.GetValue("SuppressChannelBindingInfo");
if (data != null)
channelBindingPolicyKeyValue = (int)data;
}
}
}
#pragma warning suppress 56500
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
}
return channelBindingPolicyKeyValue;
}
internal static bool IsSecurityBindingSuitableForChannelBinding(TransportSecurityBindingElement securityBindingElement)
{
if (securityBindingElement == null)
{
return false;
}
// channel binding of OperationSupportingTokenParameters, OptionalEndpointSupportingTokenParameters, or OptionalOperationSupportingTokenParameters
// is not supported in Win7
if (AreSecurityTokenParametersSuitableForChannelBinding(securityBindingElement.EndpointSupportingTokenParameters.Endorsing))
{
return true;
}
if (AreSecurityTokenParametersSuitableForChannelBinding(securityBindingElement.EndpointSupportingTokenParameters.Signed))
{
return true;
}
if (AreSecurityTokenParametersSuitableForChannelBinding(securityBindingElement.EndpointSupportingTokenParameters.SignedEncrypted))
{
return true;
}
if (AreSecurityTokenParametersSuitableForChannelBinding(securityBindingElement.EndpointSupportingTokenParameters.SignedEndorsing))
{
return true;
}
return false;
}
internal static bool AreSecurityTokenParametersSuitableForChannelBinding(Collection<SecurityTokenParameters> tokenParameters)
{
if (tokenParameters == null)
{
return false;
}
foreach (SecurityTokenParameters stp in tokenParameters)
{
if (stp is SspiSecurityTokenParameters || stp is KerberosSecurityTokenParameters)
{
return true;
}
SecureConversationSecurityTokenParameters scstp = stp as SecureConversationSecurityTokenParameters;
if (scstp != null)
{
return IsSecurityBindingSuitableForChannelBinding(scstp.BootstrapSecurityBindingElement as TransportSecurityBindingElement);
}
}
return false;
}
internal static void ThrowIfNegotiationFault(Message message, EndpointAddress target)
{
if (message.IsFault)
{
MessageFault fault = MessageFault.CreateFault(message, TransportDefaults.MaxSecurityFaultSize);
Exception faultException = new FaultException(fault, message.Headers.Action);
if (fault.Code != null && fault.Code.IsReceiverFault && fault.Code.SubCode != null)
{
FaultCode subCode = fault.Code.SubCode;
if (subCode.Name == DotNetSecurityStrings.SecurityServerTooBusyFault && subCode.Namespace == DotNetSecurityStrings.Namespace)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServerTooBusyException(SR.GetString(SR.SecurityServerTooBusy, target), faultException));
}
else if (subCode.Name == AddressingStrings.EndpointUnavailable && subCode.Namespace == message.Version.Addressing.Namespace)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.GetString(SR.SecurityEndpointNotFound, target), faultException));
}
}
throw TraceUtility.ThrowHelperError(faultException, message);
}
}
internal static bool IsSecurityFault(MessageFault fault, SecurityStandardsManager standardsManager)
{
if (fault.Code.IsSenderFault)
{
FaultCode subCode = fault.Code.SubCode;
if (subCode != null)
{
return (subCode.Namespace == standardsManager.SecurityVersion.HeaderNamespace.Value
|| subCode.Namespace == standardsManager.SecureConversationDriver.Namespace.Value
|| subCode.Namespace == standardsManager.TrustDriver.Namespace.Value
|| subCode.Namespace == DotNetSecurityStrings.Namespace);
}
}
return false;
}
internal static Exception CreateSecurityFaultException(Message unverifiedMessage)
{
MessageFault fault = MessageFault.CreateFault(unverifiedMessage, TransportDefaults.MaxSecurityFaultSize);
return CreateSecurityFaultException(fault);
}
internal static Exception CreateSecurityFaultException(MessageFault fault)
{
FaultException faultException = FaultException.CreateFault(fault, typeof(string), typeof(object));
return new MessageSecurityException(SR.GetString(SR.UnsecuredMessageFaultReceived), faultException);
}
internal static MessageFault CreateSecurityContextNotFoundFault(SecurityStandardsManager standardsManager, string action)
{
SecureConversationDriver scDriver = standardsManager.SecureConversationDriver;
FaultCode subCode = new FaultCode(scDriver.BadContextTokenFaultCode.Value, scDriver.Namespace.Value);
FaultReason reason;
if (action != null)
{
reason = new FaultReason(SR.GetString(SR.BadContextTokenOrActionFaultReason, action), CultureInfo.CurrentCulture);
}
else
{
reason = new FaultReason(SR.GetString(SR.BadContextTokenFaultReason), CultureInfo.CurrentCulture);
}
FaultCode senderCode = FaultCode.CreateSenderFaultCode(subCode);
return MessageFault.CreateFault(senderCode, reason);
}
internal static MessageFault CreateSecurityMessageFault(Exception e, SecurityStandardsManager standardsManager)
{
bool isSecurityError = false;
bool isTokenValidationError = false;
bool isGenericTokenError = false;
FaultException faultException = null;
while (e != null)
{
if (e is SecurityTokenValidationException)
{
if (e is SecurityContextTokenValidationException)
{
return CreateSecurityContextNotFoundFault(SecurityStandardsManager.DefaultInstance, null);
}
isSecurityError = true;
isTokenValidationError = true;
break;
}
else if (e is SecurityTokenException)
{
isSecurityError = true;
isGenericTokenError = true;
break;
}
else if (e is MessageSecurityException)
{
MessageSecurityException ms = (MessageSecurityException)e;
if (ms.Fault != null)
{
return ms.Fault;
}
isSecurityError = true;
}
else if (e is FaultException)
{
faultException = (FaultException)e;
break;
}
e = e.InnerException;
}
if (!isSecurityError && faultException == null)
{
return null;
}
FaultCode subCode;
FaultReason reason;
SecurityVersion wss = standardsManager.SecurityVersion;
if (isTokenValidationError)
{
subCode = new FaultCode(wss.FailedAuthenticationFaultCode.Value, wss.HeaderNamespace.Value);
reason = new FaultReason(SR.GetString(SR.FailedAuthenticationFaultReason), CultureInfo.CurrentCulture);
}
else if (isGenericTokenError)
{
subCode = new FaultCode(wss.InvalidSecurityTokenFaultCode.Value, wss.HeaderNamespace.Value);
reason = new FaultReason(SR.GetString(SR.InvalidSecurityTokenFaultReason), CultureInfo.CurrentCulture);
}
else if (faultException != null)
{
// Only support Code and Reason. No detail or action customization.
return MessageFault.CreateFault(faultException.Code, faultException.Reason);
}
else
{
subCode = new FaultCode(wss.InvalidSecurityFaultCode.Value, wss.HeaderNamespace.Value);
reason = new FaultReason(SR.GetString(SR.InvalidSecurityFaultReason), CultureInfo.CurrentCulture);
}
FaultCode senderCode = FaultCode.CreateSenderFaultCode(subCode);
return MessageFault.CreateFault(senderCode, reason);
}
internal static bool IsCompositeDuplexBinding(BindingContext context)
{
return ((context.Binding.Elements.Find<CompositeDuplexBindingElement>() != null)
|| (context.Binding.Elements.Find<InternalDuplexBindingElement>() != null));
}
// The method checks TransportToken, ProtectionToken and all SupportingTokens to find a
// UserNameSecurityToken. If found, it sets the password of the UserNameSecurityToken to null.
// Custom UserNameSecurityToken are skipped.
internal static void ErasePasswordInUsernameTokenIfPresent(SecurityMessageProperty messageProperty)
{
if (messageProperty == null)
{
// Nothing to fix.
return;
}
if (messageProperty.TransportToken != null)
{
UserNameSecurityToken token = messageProperty.TransportToken.SecurityToken as UserNameSecurityToken;
if ((token != null) && !messageProperty.TransportToken.SecurityToken.GetType().IsSubclassOf(typeof(UserNameSecurityToken)))
{
messageProperty.TransportToken = new SecurityTokenSpecification(new UserNameSecurityToken(token.UserName, null, token.Id), messageProperty.TransportToken.SecurityTokenPolicies);
}
}
if (messageProperty.ProtectionToken != null)
{
UserNameSecurityToken token = messageProperty.ProtectionToken.SecurityToken as UserNameSecurityToken;
if ((token != null) && !messageProperty.ProtectionToken.SecurityToken.GetType().IsSubclassOf(typeof(UserNameSecurityToken)))
{
messageProperty.ProtectionToken = new SecurityTokenSpecification(new UserNameSecurityToken(token.UserName, null, token.Id), messageProperty.ProtectionToken.SecurityTokenPolicies);
}
}
if (messageProperty.HasIncomingSupportingTokens)
{
for (int i = 0; i < messageProperty.IncomingSupportingTokens.Count; ++i)
{
SupportingTokenSpecification supportingTokenSpecification = messageProperty.IncomingSupportingTokens[i];
UserNameSecurityToken token = supportingTokenSpecification.SecurityToken as UserNameSecurityToken;
if ((token != null) && !supportingTokenSpecification.SecurityToken.GetType().IsSubclassOf(typeof(UserNameSecurityToken)))
{
messageProperty.IncomingSupportingTokens[i] = new SupportingTokenSpecification(new UserNameSecurityToken(token.UserName, null, token.Id), supportingTokenSpecification.SecurityTokenPolicies, supportingTokenSpecification.SecurityTokenAttachmentMode, supportingTokenSpecification.SecurityTokenParameters);
}
}
}
}
// work-around to Windows SE Bug 141614
[Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method UnsafeGetPassword to access the credential password without a Demand.",
Safe = "Only uses the password to construct a cloned NetworkCredential instance, does not leak password value.")]
[SecuritySafeCritical]
internal static void FixNetworkCredential(ref NetworkCredential credential)
{
if (credential == null)
{
return;
}
string username = NetworkCredentialHelper.UnsafeGetUsername(credential);
string domain = NetworkCredentialHelper.UnsafeGetDomain(credential);
if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(domain))
{
// do the splitting only if there is exactly 1 \ or exactly 1 @
string[] partsWithSlashDelimiter = username.Split('\\');
string[] partsWithAtDelimiter = username.Split('@');
if (partsWithSlashDelimiter.Length == 2 && partsWithAtDelimiter.Length == 1)
{
if (!string.IsNullOrEmpty(partsWithSlashDelimiter[0]) && !string.IsNullOrEmpty(partsWithSlashDelimiter[1]))
{
credential = new NetworkCredential(partsWithSlashDelimiter[1], NetworkCredentialHelper.UnsafeGetPassword(credential), partsWithSlashDelimiter[0]);
}
}
else if (partsWithSlashDelimiter.Length == 1 && partsWithAtDelimiter.Length == 2)
{
if (!string.IsNullOrEmpty(partsWithAtDelimiter[0]) && !string.IsNullOrEmpty(partsWithAtDelimiter[1]))
{
credential = new NetworkCredential(partsWithAtDelimiter[0], NetworkCredentialHelper.UnsafeGetPassword(credential), partsWithAtDelimiter[1]);
}
}
}
}
// WORKAROUND, [....], VSWhidbey 561276: The first NetworkCredential must be created in a lock.
internal static void PrepareNetworkCredential()
{
if (dummyNetworkCredential == null)
{
PrepareNetworkCredentialWorker();
}
}
// Since this takes a lock, it probably won't be inlined, but the typical case will be.
static void PrepareNetworkCredentialWorker()
{
lock (dummyNetworkCredentialLock)
{
dummyNetworkCredential = new NetworkCredential("dummy", "dummy");
}
}
// This is the workaround, Since store.Certificates returns a full collection
// of certs in store. These are holding native resources.
internal static void ResetAllCertificates(X509Certificate2Collection certificates)
{
if (certificates != null)
{
for (int i = 0; i < certificates.Count; ++i)
{
ResetCertificate(certificates[i]);
}
}
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method X509Certificate2.Reset.",
Safe = "Per review from CLR security team, this method does nothing unsafe.")]
[SecuritySafeCritical]
internal static void ResetCertificate(X509Certificate2 certificate)
{
certificate.Reset();
}
internal static bool IsDefaultNetworkCredential(NetworkCredential credential)
{
return NetworkCredentialHelper.IsDefault(credential);
}
internal static void OpenTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout)
{
OpenCommunicationObject(tokenProvider as ICommunicationObject, timeout);
}
internal static IAsyncResult BeginOpenTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout,
AsyncCallback callback, object state)
{
return new OpenCommunicationObjectAsyncResult(tokenProvider, timeout, callback, state);
}
internal static void EndOpenTokenProviderIfRequired(IAsyncResult result)
{
OpenCommunicationObjectAsyncResult.End(result);
}
internal static IAsyncResult BeginCloseTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout,
AsyncCallback callback, object state)
{
return new CloseCommunicationObjectAsyncResult(tokenProvider, timeout, callback, state);
}
internal static void EndCloseTokenProviderIfRequired(IAsyncResult result)
{
CloseCommunicationObjectAsyncResult.End(result);
}
internal static void CloseTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout)
{
CloseCommunicationObject(tokenProvider, false, timeout);
}
internal static void CloseTokenProviderIfRequired(SecurityTokenProvider tokenProvider, bool aborted, TimeSpan timeout)
{
CloseCommunicationObject(tokenProvider, aborted, timeout);
}
internal static void AbortTokenProviderIfRequired(SecurityTokenProvider tokenProvider)
{
CloseCommunicationObject(tokenProvider, true, TimeSpan.Zero);
}
internal static void OpenTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout)
{
OpenCommunicationObject(tokenAuthenticator as ICommunicationObject, timeout);
}
internal static void CloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout)
{
CloseTokenAuthenticatorIfRequired(tokenAuthenticator, false, timeout);
}
internal static void CloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, bool aborted, TimeSpan timeout)
{
CloseCommunicationObject(tokenAuthenticator, aborted, timeout);
}
internal static IAsyncResult BeginOpenTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout,
AsyncCallback callback, object state)
{
return new OpenCommunicationObjectAsyncResult(tokenAuthenticator, timeout, callback, state);
}
internal static void EndOpenTokenAuthenticatorIfRequired(IAsyncResult result)
{
OpenCommunicationObjectAsyncResult.End(result);
}
internal static IAsyncResult BeginCloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout,
AsyncCallback callback, object state)
{
return new CloseCommunicationObjectAsyncResult(tokenAuthenticator, timeout, callback, state);
}
internal static void EndCloseTokenAuthenticatorIfRequired(IAsyncResult result)
{
CloseCommunicationObjectAsyncResult.End(result);
}
internal static void AbortTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator)
{
CloseCommunicationObject(tokenAuthenticator, true, TimeSpan.Zero);
}
static void OpenCommunicationObject(ICommunicationObject obj, TimeSpan timeout)
{
if (obj != null)
obj.Open(timeout);
}
static void CloseCommunicationObject(Object obj, bool aborted, TimeSpan timeout)
{
if (obj != null)
{
ICommunicationObject co = obj as ICommunicationObject;
if (co != null)
{
if (aborted)
{
try
{
co.Abort();
}
catch (CommunicationException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
}
else
{
co.Close(timeout);
}
}
else if (obj is IDisposable)
{
((IDisposable)obj).Dispose();
}
}
}
class OpenCommunicationObjectAsyncResult : AsyncResult
{
ICommunicationObject communicationObject;
static AsyncCallback onOpen;
public OpenCommunicationObjectAsyncResult(object obj, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.communicationObject = obj as ICommunicationObject;
bool completeSelf = false;
if (this.communicationObject == null)
{
completeSelf = true;
}
else
{
if (onOpen == null)
{
onOpen = Fx.ThunkCallback(new AsyncCallback(OnOpen));
}
IAsyncResult result = this.communicationObject.BeginOpen(timeout, onOpen, this);
if (result.CompletedSynchronously)
{
this.communicationObject.EndOpen(result);
completeSelf = true;
}
}
if (completeSelf)
{
base.Complete(true);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<OpenCommunicationObjectAsyncResult>(result);
}
static void OnOpen(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
OpenCommunicationObjectAsyncResult thisPtr =
(OpenCommunicationObjectAsyncResult)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.communicationObject.EndOpen(result);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Complete(false, completionException);
}
}
class CloseCommunicationObjectAsyncResult : AsyncResult
{
ICommunicationObject communicationObject;
static AsyncCallback onClose;
public CloseCommunicationObjectAsyncResult(object obj, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.communicationObject = obj as ICommunicationObject;
bool completeSelf = false;
if (this.communicationObject == null)
{
IDisposable disposable = obj as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
completeSelf = true;
}
else
{
if (onClose == null)
{
onClose = Fx.ThunkCallback(new AsyncCallback(OnClose));
}
IAsyncResult result = this.communicationObject.BeginClose(timeout, onClose, this);
if (result.CompletedSynchronously)
{
this.communicationObject.EndClose(result);
completeSelf = true;
}
}
if (completeSelf)
{
base.Complete(true);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CloseCommunicationObjectAsyncResult>(result);
}
static void OnClose(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
CloseCommunicationObjectAsyncResult thisPtr =
(CloseCommunicationObjectAsyncResult)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.communicationObject.EndClose(result);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Complete(false, completionException);
}
}
internal static void MatchRstWithEndpointFilter(Message rst, IMessageFilterTable<EndpointAddress> endpointFilterTable, Uri listenUri)
{
if (endpointFilterTable == null)
{
return;
}
Collection<EndpointAddress> result = new Collection<EndpointAddress>();
if (!endpointFilterTable.GetMatchingValues(rst, result))
{
throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.RequestSecurityTokenDoesNotMatchEndpointFilters, listenUri)), rst);
}
}
// match the RST with the endpoint filters in case there is at least 1 asymmetric signature in the message
internal static bool ShouldMatchRstWithEndpointFilter(SecurityBindingElement sbe)
{
foreach (SecurityTokenParameters parameters in new SecurityTokenParametersEnumerable(sbe, true))
{
if (parameters.HasAsymmetricKey)
{
return true;
}
}
return false;
}
internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenManager tokenManager)
{
SecurityTokenSerializer tokenSerializer = tokenManager.CreateSecurityTokenSerializer(securityVersion.SecurityTokenVersion);
return new SecurityStandardsManager(securityVersion, tokenSerializer);
}
internal static SecurityStandardsManager CreateSecurityStandardsManager(SecurityTokenRequirement requirement, SecurityTokenManager tokenManager)
{
MessageSecurityTokenVersion securityVersion = (MessageSecurityTokenVersion)requirement.GetProperty<MessageSecurityTokenVersion>(ServiceModelSecurityTokenRequirement.MessageSecurityVersionProperty);
if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10)
return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager);
else if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005)
return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11, tokenManager);
else if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10)
return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager);
else if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10)
return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager);
else if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13)
return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, tokenManager);
else if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10)
return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager);
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenSerializer securityTokenSerializer)
{
if (securityVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("securityVersion"));
}
if (securityTokenSerializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer");
}
return new SecurityStandardsManager(securityVersion, securityTokenSerializer);
}
static bool TryCreateIdentity(ClaimSet claimSet, string claimType, out EndpointIdentity identity)
{
identity = null;
foreach (Claim claim in claimSet.FindClaims(claimType, null))
{
identity = EndpointIdentity.CreateIdentity(claim);
return true;
}
return false;
}
internal static EndpointIdentity GetServiceCertificateIdentity(X509Certificate2 certificate)
{
using (X509CertificateClaimSet claimSet = new X509CertificateClaimSet(certificate))
{
EndpointIdentity identity;
if (!TryCreateIdentity(claimSet, ClaimTypes.Dns, out identity))
{
TryCreateIdentity(claimSet, ClaimTypes.Rsa, out identity);
}
return identity;
}
}
[Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method UnsafeGetPassword to access the credential password without a Demand.",
Safe = "Only uses the password to construct a new NetworkCredential which will then protect access, password does not leak from this method.")]
[SecuritySafeCritical]
internal static NetworkCredential GetNetworkCredentialsCopy(NetworkCredential networkCredential)
{
NetworkCredential result;
if (networkCredential != null && !NetworkCredentialHelper.IsDefault(networkCredential))
{
result = new NetworkCredential(NetworkCredentialHelper.UnsafeGetUsername(networkCredential), NetworkCredentialHelper.UnsafeGetPassword(networkCredential), NetworkCredentialHelper.UnsafeGetDomain(networkCredential));
}
else
{
result = networkCredential;
}
return result;
}
internal static NetworkCredential GetNetworkCredentialOrDefault(NetworkCredential credential)
{
// because of VSW 564452, we dont use CredentialCache.DefaultNetworkCredentials in our OM. Instead we
// use an empty NetworkCredential to denote the default credentials
if (NetworkCredentialHelper.IsNullOrEmpty(credential))
{
// FYI: this will fail with SecurityException in PT due to Demand for EnvironmentPermission.
// Typically a PT app should not have access to DefaultNetworkCredentials. If there is a valid reason,
// see UnsafeGetDefaultNetworkCredentials.
return CredentialCache.DefaultNetworkCredentials;
}
else
{
return credential;
}
}
static class NetworkCredentialHelper
{
[Fx.Tag.SecurityNote(Critical = "Uses unsafe critical methods UnsafeGetUsername, UnsafeGetPassword, and UnsafeGetDomain to access the credential details without a Demand.",
Safe = "Only uses the protected values to test for null/empty. Does not leak.")]
[SecuritySafeCritical]
static internal bool IsNullOrEmpty(NetworkCredential credential)
{
return credential == null ||
(
String.IsNullOrEmpty(UnsafeGetUsername(credential)) &&
String.IsNullOrEmpty(UnsafeGetDomain(credential)) &&
String.IsNullOrEmpty(UnsafeGetPassword(credential))
);
}
[Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method UnsafeGetDefaultNetworkCredentials to access the default network credentials without a Demand.",
Safe = "Only uses the default credentials to test for equality and uses the system credential's .Equals, not the caller's.")]
[SecuritySafeCritical]
static internal bool IsDefault(NetworkCredential credential)
{
return UnsafeGetDefaultNetworkCredentials().Equals(credential);
}
[Fx.Tag.SecurityNote(Critical = "Asserts SecurityPermission(UnmanagedCode) in order to get the NetworkCredential password."
+ "This is used for example to test for empty/null or to construct a cloned NetworkCredential."
+ "Callers absolutely must not leak the return value.")]
[SecurityCritical]
[EnvironmentPermission(SecurityAction.Assert, Read = "USERNAME")]
static internal string UnsafeGetUsername(NetworkCredential credential)
{
return credential.UserName;
}
[Fx.Tag.SecurityNote(Critical = "Asserts SecurityPermission(UnmanagedCode) in order to get the NetworkCredential password."
+ "This is used for example to test for empty/null or to construct a cloned NetworkCredential."
+ "Callers absolutely must not leak the return value.")]
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
static internal string UnsafeGetPassword(NetworkCredential credential)
{
return credential.Password;
}
[Fx.Tag.SecurityNote(Critical = "Asserts SecurityPermission(UnmanagedCode) in order to get the NetworkCredential password."
+ "This is used for example to test for empty/null or to construct a cloned NetworkCredential."
+ "Callers absolutely must not leak the return value.")]
[SecurityCritical]
[EnvironmentPermission(SecurityAction.Assert, Read = "USERDOMAIN")]
static internal string UnsafeGetDomain(NetworkCredential credential)
{
return credential.Domain;
}
[Fx.Tag.SecurityNote(Critical = "Asserts EnvironmentPermission(Read='USERNAME') in order to get the DefaultNetworkCredentials in PT."
+ "This is used for example to test for instance equality with a specific NetworkCredential."
+ "Callers absolutely must not leak the return value.")]
[SecurityCritical]
[EnvironmentPermission(SecurityAction.Assert, Read = "USERNAME")]
static NetworkCredential UnsafeGetDefaultNetworkCredentials()
{
return CredentialCache.DefaultNetworkCredentials;
}
}
internal static SafeFreeCredentials GetCredentialsHandle(string package, NetworkCredential credential, bool isServer, params string[] additionalPackages)
{
SafeFreeCredentials credentialsHandle;
CredentialUse credentialUse = isServer ? CredentialUse.Inbound : CredentialUse.Outbound;
if (credential == null || NetworkCredentialHelper.IsDefault(credential))
{
AuthIdentityEx authIdentity = new AuthIdentityEx(null, null, null, additionalPackages);
credentialsHandle = SspiWrapper.AcquireCredentialsHandle(package, credentialUse, ref authIdentity);
}
else
{
SecurityUtils.FixNetworkCredential(ref credential);
// we're not using DefaultCredentials, we need a
// AuthIdentity struct to contain credentials
AuthIdentityEx authIdentity = new AuthIdentityEx(credential.UserName, credential.Password, credential.Domain);
credentialsHandle = SspiWrapper.AcquireCredentialsHandle(package, credentialUse, ref authIdentity);
}
return credentialsHandle;
}
internal static SafeFreeCredentials GetCredentialsHandle(Binding binding, KeyedByTypeCollection<IEndpointBehavior> behaviors)
{
ClientCredentials clientCredentials = (behaviors == null) ? null : behaviors.Find<ClientCredentials>();
return GetCredentialsHandle(binding, clientCredentials);
}
internal static SafeFreeCredentials GetCredentialsHandle(Binding binding, ClientCredentials clientCredentials)
{
SecurityBindingElement sbe = (binding == null) ? null : binding.CreateBindingElements().Find<SecurityBindingElement>();
return GetCredentialsHandle(sbe, clientCredentials);
}
internal static SafeFreeCredentials GetCredentialsHandle(SecurityBindingElement sbe, BindingContext context)
{
ClientCredentials clientCredentials = (context == null) ? null : context.BindingParameters.Find<ClientCredentials>();
return GetCredentialsHandle(sbe, clientCredentials);
}
internal static SafeFreeCredentials GetCredentialsHandle(SecurityBindingElement sbe, ClientCredentials clientCredentials)
{
if (sbe == null)
{
return null;
}
bool isSspi = false;
bool isKerberos = false;
foreach (SecurityTokenParameters stp in new SecurityTokenParametersEnumerable(sbe, true))
{
if (stp is SecureConversationSecurityTokenParameters)
{
SafeFreeCredentials result = GetCredentialsHandle(((SecureConversationSecurityTokenParameters)stp).BootstrapSecurityBindingElement, clientCredentials);
if (result != null)
{
return result;
}
continue;
}
else if (stp is IssuedSecurityTokenParameters)
{
SafeFreeCredentials result = GetCredentialsHandle(((IssuedSecurityTokenParameters)stp).IssuerBinding, clientCredentials);
if (result != null)
{
return result;
}
continue;
}
else if (stp is SspiSecurityTokenParameters)
{
isSspi = true;
break;
}
else if (stp is KerberosSecurityTokenParameters)
{
isKerberos = true;
break;
}
}
if (!isSspi && !isKerberos)
{
return null;
}
NetworkCredential credential = null;
if (clientCredentials != null)
{
credential = SecurityUtils.GetNetworkCredentialOrDefault(clientCredentials.Windows.ClientCredential);
}
if (isKerberos)
{
return SecurityUtils.GetCredentialsHandle("Kerberos", credential, false);
}
// if OS is less that Vista cannot use !NTLM, Windows SE 142400
// To disable AllowNtlm warning.
#pragma warning disable 618
else if (clientCredentials != null && !clientCredentials.Windows.AllowNtlm)
{
if (SecurityUtils.IsOsGreaterThanXP())
{
return SecurityUtils.GetCredentialsHandle("Negotiate", credential, false, "!NTLM");
}
else
{
return SecurityUtils.GetCredentialsHandle("Kerberos", credential, false);
}
}
#pragma warning restore 618
return SecurityUtils.GetCredentialsHandle("Negotiate", credential, false);
}
internal static byte[] CloneBuffer(byte[] buffer)
{
byte[] copy = DiagnosticUtility.Utility.AllocateByteArray(buffer.Length);
Buffer.BlockCopy(buffer, 0, copy, 0, buffer.Length);
return copy;
}
internal static X509Certificate2 GetCertificateFromStore(StoreName storeName, StoreLocation storeLocation,
X509FindType findType, object findValue, EndpointAddress target)
{
X509Certificate2 certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, true);
if (certificate == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotFindCert, storeName, storeLocation, findType, findValue)));
return certificate;
}
internal static bool TryGetCertificateFromStore(StoreName storeName, StoreLocation storeLocation,
X509FindType findType, object findValue, EndpointAddress target, out X509Certificate2 certificate)
{
certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, false);
return (certificate != null);
}
static X509Certificate2 GetCertificateFromStoreCore(StoreName storeName, StoreLocation storeLocation,
X509FindType findType, object findValue, EndpointAddress target, bool throwIfMultipleOrNoMatch)
{
if (findValue == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
}
X509CertificateStore store = new X509CertificateStore(storeName, storeLocation);
X509Certificate2Collection certs = null;
try
{
store.Open(OpenFlags.ReadOnly);
certs = store.Find(findType, findValue, false);
if (certs.Count == 1)
{
return new X509Certificate2(certs[0]);
}
if (throwIfMultipleOrNoMatch)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateCertificateLoadException(
storeName, storeLocation, findType, findValue, target, certs.Count));
}
else
{
return null;
}
}
finally
{
SecurityUtils.ResetAllCertificates(certs);
store.Close();
}
}
static Exception CreateCertificateLoadException(StoreName storeName, StoreLocation storeLocation,
X509FindType findType, object findValue, EndpointAddress target, int certCount)
{
if (certCount == 0)
{
if (target == null)
{
return new InvalidOperationException(SR.GetString(SR.CannotFindCert, storeName, storeLocation, findType, findValue));
}
else
{
return new InvalidOperationException(SR.GetString(SR.CannotFindCertForTarget, storeName, storeLocation, findType, findValue, target));
}
}
else
{
if (target == null)
{
return new InvalidOperationException(SR.GetString(SR.FoundMultipleCerts, storeName, storeLocation, findType, findValue));
}
else
{
return new InvalidOperationException(SR.GetString(SR.FoundMultipleCertsForTarget, storeName, storeLocation, findType, findValue, target));
}
}
}
public static SecurityBindingElement GetIssuerSecurityBindingElement(ServiceModelSecurityTokenRequirement requirement)
{
SecurityBindingElement bindingElement = requirement.SecureConversationSecurityBindingElement;
if (bindingElement != null)
{
return bindingElement;
}
Binding binding = requirement.IssuerBinding;
if (binding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.IssuerBindingNotPresentInTokenRequirement, requirement));
}
BindingElementCollection bindingElements = binding.CreateBindingElements();
return bindingElements.Find<SecurityBindingElement>();
}
public static int GetMaxNegotiationBufferSize(BindingContext bindingContext)
{
TransportBindingElement transport = bindingContext.RemainingBindingElements.Find<TransportBindingElement>();
Fx.Assert(transport != null, "TransportBindingElement is null!");
int maxNegoMessageSize;
if (transport is ConnectionOrientedTransportBindingElement)
{
maxNegoMessageSize = ((ConnectionOrientedTransportBindingElement)transport).MaxBufferSize;
}
else if (transport is HttpTransportBindingElement)
{
maxNegoMessageSize = ((HttpTransportBindingElement)transport).MaxBufferSize;
}
else
{
maxNegoMessageSize = TransportDefaults.MaxBufferSize;
}
return maxNegoMessageSize;
}
public static bool TryCreateKeyFromIntrinsicKeyClause(SecurityKeyIdentifierClause keyIdentifierClause, SecurityTokenResolver resolver, out SecurityKey key)
{
key = null;
if (keyIdentifierClause.CanCreateKey)
{
key = keyIdentifierClause.CreateKey();
return true;
}
if (keyIdentifierClause is EncryptedKeyIdentifierClause)
{
EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
// PreSharp Bug: Parameter 'keyClause' to this public method must be validated: A null-dereference can occur here.
#pragma warning suppress 56506 // keyClause will not be null due to the if condition above.
for (int i = 0; i < keyClause.EncryptingKeyIdentifier.Count; i++)
{
SecurityKey unwrappingSecurityKey = null;
if (resolver.TryResolveSecurityKey(keyClause.EncryptingKeyIdentifier[i], out unwrappingSecurityKey))
{
byte[] wrappedKey = keyClause.GetEncryptedKey();
string wrappingAlgorithm = keyClause.EncryptionMethod;
byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
key = new InMemorySymmetricSecurityKey(unwrappedKey, false);
return true;
}
}
}
return false;
}
public static WrappedKeySecurityToken CreateTokenFromEncryptedKeyClause(EncryptedKeyIdentifierClause keyClause, SecurityToken unwrappingToken)
{
SecurityKeyIdentifier wrappingTokenReference = keyClause.EncryptingKeyIdentifier;
byte[] wrappedKey = keyClause.GetEncryptedKey();
SecurityKey unwrappingSecurityKey = unwrappingToken.SecurityKeys[0];
string wrappingAlgorithm = keyClause.EncryptionMethod;
byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
return new WrappedKeySecurityToken(SecurityUtils.GenerateId(), unwrappedKey, wrappingAlgorithm,
unwrappingToken, wrappingTokenReference, wrappedKey, unwrappingSecurityKey
);
}
public static void ValidateAnonymityConstraint(WindowsIdentity identity, bool allowUnauthenticatedCallers)
{
if (!allowUnauthenticatedCallers && identity.User.IsWellKnown(WellKnownSidType.AnonymousSid))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(
new SecurityTokenValidationException(SR.GetString(SR.AnonymousLogonsAreNotAllowed)));
}
}
static bool ComputeSslCipherStrengthRequirementFlag()
{
// validate only for XP versions < XP SP3 and windows server versions < Win2K3 SP2
if ((Environment.OSVersion.Version.Major > WindowsServerMajorNumber)
|| (Environment.OSVersion.Version.Major == WindowsServerMajorNumber && Environment.OSVersion.Version.Minor > WindowsServerMinorNumber))
{
return false;
}
// version <= Win2K3
if (Environment.OSVersion.Version.Major == XPMajorNumber && Environment.OSVersion.Version.Minor == XPMinorNumber)
{
if ((Environment.OSVersion.ServicePack == string.Empty) || String.Equals(Environment.OSVersion.ServicePack, ServicePack1, StringComparison.OrdinalIgnoreCase) || String.Equals(Environment.OSVersion.ServicePack, ServicePack2, StringComparison.OrdinalIgnoreCase))
{
return true;
}
else
{
// the OS is XP SP3 or higher
return false;
}
}
else if (Environment.OSVersion.Version.Major == WindowsServerMajorNumber && Environment.OSVersion.Version.Minor == WindowsServerMinorNumber)
{
if (Environment.OSVersion.ServicePack == string.Empty || String.Equals(Environment.OSVersion.ServicePack, ServicePack1, StringComparison.OrdinalIgnoreCase))
{
return true;
}
else
{
// the OS is Win2K3 SP2 or higher
return false;
}
}
else
{
// this is <= XP. We should never get here but if we do validate SSL strength
return true;
}
}
public static bool ShouldValidateSslCipherStrength()
{
if (!isSslValidationRequirementDetermined)
{
shouldValidateSslCipherStrength = ComputeSslCipherStrengthRequirementFlag();
Thread.MemoryBarrier();
isSslValidationRequirementDetermined = true;
}
return shouldValidateSslCipherStrength;
}
public static void ValidateSslCipherStrength(int keySizeInBits)
{
if (ShouldValidateSslCipherStrength() && keySizeInBits < MinimumSslCipherStrength)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.SslCipherKeyTooSmall, keySizeInBits, MinimumSslCipherStrength)));
}
}
public static bool TryCreateX509CertificateFromRawData(byte[] rawData, out X509Certificate2 certificate)
{
certificate = (rawData == null || rawData.Length == 0) ? null : new X509Certificate2(rawData);
return certificate != null && certificate.Handle != IntPtr.Zero;
}
internal static string GetKeyDerivationAlgorithm(SecureConversationVersion version)
{
string derivationAlgorithm = null;
if (version == SecureConversationVersion.WSSecureConversationFeb2005)
{
derivationAlgorithm = SecurityAlgorithms.Psha1KeyDerivation;
}
else if (version == SecureConversationVersion.WSSecureConversation13)
{
derivationAlgorithm = SecurityAlgorithms.Psha1KeyDerivationDec2005;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
return derivationAlgorithm;
}
}
struct SecurityUniqueId
{
static long nextId = 0;
static string commonPrefix = "uuid-" + Guid.NewGuid().ToString() + "-";
long id;
string prefix;
string val;
SecurityUniqueId(string prefix, long id)
{
this.id = id;
this.prefix = prefix;
this.val = null;
}
public static SecurityUniqueId Create()
{
return SecurityUniqueId.Create(commonPrefix);
}
public static SecurityUniqueId Create(string prefix)
{
return new SecurityUniqueId(prefix, Interlocked.Increment(ref nextId));
}
public string Value
{
get
{
if (this.val == null)
this.val = this.prefix + this.id.ToString(CultureInfo.InvariantCulture);
return this.val;
}
}
}
static class EmptyReadOnlyCollection<T>
{
public static ReadOnlyCollection<T> Instance = new ReadOnlyCollection<T>(new List<T>());
}
class OperationWithTimeoutAsyncResult : TraceAsyncResult
{
static readonly Action<object> scheduledCallback = new Action<object>(OnScheduled);
TimeoutHelper timeoutHelper;
OperationWithTimeoutCallback operationWithTimeout;
public OperationWithTimeoutAsyncResult(OperationWithTimeoutCallback operationWithTimeout, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.operationWithTimeout = operationWithTimeout;
this.timeoutHelper = new TimeoutHelper(timeout);
ActionItem.Schedule(scheduledCallback, this);
}
static void OnScheduled(object state)
{
OperationWithTimeoutAsyncResult thisResult = (OperationWithTimeoutAsyncResult)state;
Exception completionException = null;
try
{
using (thisResult.CallbackActivity == null ? null : ServiceModelActivity.BoundOperation(thisResult.CallbackActivity))
{
thisResult.operationWithTimeout(thisResult.timeoutHelper.RemainingTime());
}
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisResult.Complete(false, completionException);
}
public static void End(IAsyncResult result)
{
AsyncResult.End<OperationWithTimeoutAsyncResult>(result);
}
}
}
|