Carbon.Cryptography.psm1
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 |
# Copyright Aaron Jensen and WebMD Health Services # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License #Requires -Version 5.1 Set-StrictMode -Version 'Latest' Add-Type -AssemblyName 'System.Security' # Functions should use $moduleRoot as the relative root from which to find # things. A published module has its function appended to this file, while a # module in development has its functions in the Functions directory. $moduleRoot = $PSScriptRoot $moduleBinRoot = Join-Path -Path $moduleRoot -ChildPath 'bin' $moduleBinRoot | Out-Null # To make the PSScriptAnalyzer squiggle go away. $privateModulesRoot = Join-Path -Path $moduleRoot -ChildPath 'Modules' Import-Module -Name (Join-Path -Path $privateModulesRoot -ChildPath 'Carbon.Core') # Store each of your module's functions in its own file in the Functions # directory. On the build server, your module's functions will be appended to # this file, so only dot-source files that exist on the file system. This allows # developers to work on a module without having to build it first. Grab all the # functions that are in their own files. $functionsPath = Join-Path -Path $moduleRoot -ChildPath 'Functions\*.ps1' if( (Test-Path -Path $functionsPath) ) { foreach( $functionPath in (Get-Item $functionsPath) ) { . $functionPath.FullName } } function Convert-CSecureStringToByte { <# .SYNOPSIS Converts a secure string to an array of bytes. .DESCRIPTION The `Convert-CSecureStringToByte` converts a `[securestring]` to an array of bytes that represents the original decrypted string. The secure string is never left in memory as a string, but is kept as an array of bytes during the conversion, and all arrays used during the conversion are cleared. The decrypted secure string is returned as an array of bytes. You are resonsible for clearing the array when you're done, otherwise you risk exposing your secret in memory or on the file system. .EXAMPLE Convert-CSecureStringToByte -SecureString $credential.Password Demonstrates how to convert a secure string into an array of bytes representing the original password. #> [CmdletBinding()] [OutputType([Byte[]])] param( [Parameter(Mandatory)] [securestring]$SecureString ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState $ptrDecryptedString = [Runtime.Interopservices.Marshal]::SecureStringToGlobalAllocUnicode($SecureString); try { [byte[]]$bytes = [byte[]]::New($SecureString.Length * 2) for( $idx = 0; $idx -lt $bytes.Length; ++$idx ) { $bytes[$idx] = [Runtime.InteropServices.Marshal]::ReadByte($ptrDecryptedString, $idx) } return $bytes } finally { [Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptrDecryptedString) } } function Convert-CSecureStringToString { <# .SYNOPSIS Converts a secure string into a plain text string. .DESCRIPTION The `Convert-CSecureStringToString` function converts a secure string to a plaintexxt string. Try really, really, really hard not to do this. Once you do, the plaintext string will be *all over memory* and, perhaps, the file system. The function creates a new `[pscredential]` with the password and uses it to convert the password to plaintext (i.e. it calls `$credential.GetNetworkCredential().Password`). .OUTPUTS System.String. .EXAMPLE Convert-CSecureStringToString -SecureString $mySuperSecretPasswordIAmAboutToExposeToEveryone Returns the plain text/decrypted value of the secure string. .EXAMPLE $ISureHopeIKnowWhatIAmDoing | Convert-CSecureStringToString Demonstrates that you can pipe a secure string to `Convert-CSecureStringToString`. #> [CmdletBinding()] [OutputType([String])] param( [Parameter(Mandatory, ValueFromPipeline)] # The secure string to convert. [securestring]$SecureString ) process { Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState $bytes = Convert-CSecureStringToByte -SecureString $SecureString try { return [Text.Encoding]::Unicode.GetString($bytes) } finally { $bytes.Clear() } } } function ConvertTo-AesKey { [CmdletBinding()] [OutputType([byte[]])] param( [Parameter(Mandatory)] [String]$From, [Parameter(Mandatory)] [Object]$InputObject ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState $Key = $InputObject $bytesKey = $true if( $InputObject -isnot [byte[]] ) { $bytesKey = $false if( $InputObject -is [SecureString] ) { $unicodeKey = Convert-CSecureStringToByte -SecureString $InputObject try { # SecureString is two bytes per char. We need an encoding that is typically one byte per char, otherwise # the key will be twice as big as it should be. In the end, the user is responsible for ensuring the # key is the property size (in bytes). $Key = [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, $unicodeKey) } finally { $unicodeKey.Clear() # Keep it out of memory! } } else { $msg = "An encryption key must be a [securestring] or an array of bytes, but $($From) got passed a " + """$($InputObject.GetType().FullName)"". If you are passing an array of bytes, make sure you " + "explicitly cast it as a ``byte[]`, e.g. `([byte[]])@( ... )` when passing to $($From)." Write-Error -Message $msg return } } if( $Key.Length -ne 128/8 -and $Key.Length -ne 192/8 -and $Key.Length -ne 256/8 ) { $commonMsg = "Key is the wrong length. The $($From) function is using AES, which requires a 128-bit, " + '192-bit, or 256-bit key (16, 24, or 32 bytes, respectively). ' # Did we receive an array of bytes for a key or a secure string? if( $bytesKey ) { $msg = "$($commonMsg) Make sure your byte array key is 16, 24, or 32 bytes long." } # Got a secure string. else { $msg = "$($commonMsg) Make sure that when the secure string key is UTF-8 encoded and converted to a byte " + "array, that array is 16, 32, or 64 bytes long. $($From) received a secure string key that is " + "$($Key.Length) bytes long." } Write-Error -Message $msg return } return $Key } function Get-CCertificate { <# .SYNOPSIS Gets a certificate from a file or the Windows certificate store. .DESCRIPTION The `Get-CCertificate` function gets an X509 certificate from a file or the Windows certificate store. When you want to get a certificate from a file, pass the path to the `Path` parameter (wildcards allowed). If the certificate is password-protected, pass its password, as a `[securestring]`, to the `Password` parameter. If you plan on installing the certificate in a Windows certificate store, and you want to customize the key storage flags, pass the flags to the `KeyStorageFlags` parameter. If the path is to a certificate in PowerShell's certificate drive (i.e. the path begins with `cert:\`), the `Password` and `KeyStorageFlags` are ignored. The certificate is returned. Wildcards allowed. You can search the Windows certificate stores for a certificate a specific thumbprint or friendly name by passing with the `Thumbprint` and `FriendlyName` parameters, respectively. `Get-CCertificate` will search all stores for all locations. If you know the store or location of the certificate, pass those to the `StoreName` and `StoreLocation` parameters, respectively. If the certificate is in a custom store, pass the store's name to the `CustomStoreName` parameter. `Get-CCertificate` adds a `Path` parameter which is the path where the certificate was loaded from the file system or the `cert:` path to the certificate in the Windows certificate store. .OUTPUTS System.Security.Cryptography.x509Certificates.X509Certificate2. The X509Certificate2 certificates that were found, or `$null`. .EXAMPLE Get-CCertificate -Path C:\Certificates\certificate.cer -Password MySuperSecurePassword Gets an X509Certificate2 object representing the certificate.cer file. Wildcards *not* supported when using a file system path. .EXAMPLE Get-CCertificate -Thumbprint a909502dd82ae41433e6f83886b00d4277a32a7b -StoreName My -StoreLocation LocalMachine Gets an X509Certificate2 object for the certificate in the Personal store with a specific thumbprint under the Local Machine. .EXAMPLE Get-CCertificate -FriendlyName 'Development Certificate' -StoreLocation CurrentUser -StoreName TrustedPeople Gets the X509Certificate2 whose friendly name is Development Certificate from the Current User's Trusted People certificate store. .EXAMPLE Get-CCertificate -Thumbprint $thumbprint -CustomStoreName 'SharePoint' -StoreLocation LocalMachine Demonstrates how to get a certificate from a custom store, i.e. one that is not part of the standard `StoreName` enumeration. .EXAMPLE Get-CCertificate -Path 'cert:\CurrentUser\a909502dd82ae41433e6f83886b00d4277a32a7b' Demonstrates how to get a certificate out of a Windows certificate store with its certificate path. Wildcards supported. #> [CmdletBinding(DefaultParameterSetName='ByPath')] [OutputType([Security.Cryptography.X509Certificates.X509Certificate2])] param( [Parameter(Mandatory, ParameterSetName='ByPath', Position=0)] # The path to the certificate. Can be a file system path or a certificate path, e.g. `cert:\`. Wildcards supported. [String]$Path, [Parameter(ParameterSetName='ByPath')] # The password to the certificate. Must be a `[securestring]`. [securestring]$Password, [Parameter(ParameterSetName='ByPath')] # The storage flags to use when loading a certificate file. This controls where/how you can store the certificate in the certificate stores later. Use the `-bor` operator to combine flags. [Security.Cryptography.X509Certificates.X509KeyStorageFlags]$KeyStorageFlags, [Parameter(Mandatory, ParameterSetName='ByThumbprint')] [Parameter(Mandatory, ParameterSetName='ByThumbprintCustomStoreName')] # The certificate's thumbprint. [String]$Thumbprint, [Parameter(Mandatory, ParameterSetName='ByFriendlyName')] [Parameter(Mandatory, ParameterSetName='ByFriendlyNameCustomStoreName')] # The friendly name of the certificate. [String]$FriendlyName, [Parameter(Mandatory, ParameterSetName='ByFriendlyName')] [Parameter(Mandatory, ParameterSetName='ByFriendlyNameCustomStoreName')] [Parameter(Mandatory, ParameterSetName='ByThumbprint')] [Parameter(Mandatory, ParameterSetName='ByThumbprintCustomStoreName')] # The location of the certificate's store. [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation, [Parameter(Mandatory, ParameterSetName='ByFriendlyName')] [Parameter(Mandatory, ParameterSetName='ByThumbprint')] # The name of the certificate's store. [Security.Cryptography.X509Certificates.StoreName]$StoreName, [Parameter(Mandatory, ParameterSetName='ByFriendlyNameCustomStoreName')] [Parameter(Mandatory, ParameterSetName='ByThumbprintCustomStoreName')] # The name of the non-standard, custom store. [String]$CustomStoreName ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState function Add-PathMember { param( [Parameter(Mandatory,VAlueFromPipeline=$true)] [Security.Cryptography.X509Certificates.X509Certificate2] $Certificate, [Parameter(Mandatory)] [string] $Path ) process { $Certificate | Add-Member -MemberType NoteProperty -Name 'Path' -Value $Path -PassThru } } function Resolve-CertificateProviderFriendlyPath { param( [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [string] $PSPath, [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [Management.Automation.PSDriveInfo] $PSDrive ) process { $qualifier = '{0}:' -f $PSDrive.Name $path = $PSPath | Split-Path -NoQualifier Join-Path -Path $qualifier -ChildPath $path } } if( $PSCmdlet.ParameterSetName -eq 'ByPath' ) { if( -not (Test-Path -Path $Path -PathType Leaf) ) { Write-Error -Message "Certificate ""$($Path)"" not found." return } foreach( $item in (Get-Item -Path $Path) ) { Write-Debug -Message $PSCmdlet.GetUnresolvedProviderPathFromPSPath($item.PSPath) if( $item -is [Security.Cryptography.X509Certificates.X509Certificate2] ) { $certFriendlyPath = $item | Resolve-CertificateProviderFriendlyPath $item | Add-PathMember -Path $certFriendlyPath | Write-Output } elseif( $item -is [IO.FileInfo] ) { try { $ctorParams = @( $item.FullName, $Password ) if( $KeyStorageFlags ) { $ctorParams += $KeyStorageFlags } New-Object 'Security.Cryptography.X509Certificates.X509Certificate2' $ctorParams | Add-PathMember -Path $item.FullName | Write-Output } catch { $ex = $_.Exception while( $ex.InnerException ) { $ex = $ex.InnerException } Write-Error -Message ('Failed to create X509Certificate2 object from file ''{0}'': {1}' -f $item.FullName,$ex.Message) } } } } else { $storeLocationPath = '*' if( $StoreLocation ) { $storeLocationPath = $StoreLocation } $storeNamePath = '*' if( $PSCmdlet.ParameterSetName -like '*CustomStoreName' ) { $storeNamePath = $CustomStoreName } else { $storeNamePath = $StoreName if( $StoreName -eq [Security.Cryptography.X509Certificates.StoreName]::CertificateAuthority ) { $storeNamePath = 'CA' } } if( $pscmdlet.ParameterSetName -like 'ByThumbprint*' ) { $certPath = 'cert:\{0}\{1}\{2}' -f $storeLocationPath,$storeNamePath,$Thumbprint if( (Test-Path -Path $certPath) ) { foreach( $certPathItem in (Get-ChildItem -Path $certPath) ) { $path = $certPathItem | Resolve-CertificateProviderFriendlyPath $certPathItem | Add-PathMember -Path $path } } return } elseif( $PSCmdlet.ParameterSetName -like 'ByFriendlyName*' ) { $certPath = Join-Path -Path 'cert:' -ChildPath $storeLocationPath $certPath = Join-Path -Path $certPath -ChildPath $storeNamePath $certPath = Join-Path -Path $certPath -ChildPath '*' return Get-ChildItem -Path $certPath | Where-Object { $_.FriendlyName -eq $FriendlyName } | ForEach-Object { $friendlyPath = $_ | Resolve-CertificateProviderFriendlyPath $_ | Add-PathMember -Path $friendlyPath } } Write-Error "Unknown parameter set '$($pscmdlet.ParameterSetName)'." } } function Install-CCertificate { <# .SYNOPSIS Installs an X509 certificate. .DESCRIPTION The `Install-CCertificate` function installs an X509 certificate. It uses the .NET X509 certificates API. The user performing the action must have permission to modify the store or the installation will fail. You can install from a file (pass the path to the file to the `-Path` parameter), or from an `X509Certificate2` object (pass it to the `-Certificate` parameter). Pass the store location (LocalMachine or CurrentUser) to the `-StoreLocation` parameter. Pass the store name (e.g. My, Root) to the `-StoreName` parameter. If the certificate has a private key and you want the private key exportable, use the `-Exportable` switch. If the certificate already exists in the store, nothing happens. If you want to re-install the certificate over any existing certificates, use the `-Force` switch. If installing a certificate from a file, and the file is password-protected, use the `-Password` parameter to pass the certificate's password. The password must be a `[securestring]`. This function only works on Windows. To install a certificate on a remote computer, create a remoting session with the `New-PSSession` cmdlet, and pass the session object to this function's `Session` parameter. When installing to a remote computer, the certificate's binary data is converted to a base64 encoded string and sent to the remote computer, where it is converted back into a certificate. If installing a certificate from a file, the file's bytes are converted to base64, sent to the remote computer, saved as a temporary file, installed, and the temporary file is removed. .OUTPUTS System.Security.Cryptography.X509Certificates.X509Certificate2. An X509Certificate2 object representing the newly installed certificate. .EXAMPLE Install-CCertificate -Path 'C:\Users\me\certificate.cer' -StoreLocation LocalMachine -StoreName My -Exportable -Password $securePassword Demonstrates how to install a password-protected certificate from a file and to allow its private key to be exportable. .EXAMPLE Install-CCertificate -Path C:\Users\me\certificate.cer -StoreLocation LocalMachine -StoreName My -Session $session Demonstrates how to install a certificate from a file on the local computer into the local machine's personal store on a remote cmoputer. You can pass multiple sessions to the `Session` parameter. #> [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName='FromFileInWindowsStore')] [OutputType([Security.Cryptography.X509Certificates.X509Certificate2])] param( [Parameter(Mandatory, Position=0, ParameterSetName='FromFileInWindowsStore')] [Parameter(Mandatory, Position=0, ParameterSetName='FromFileInCustomStore')] # The path to the certificate file. [String]$Path, [Parameter(Mandatory, Position=0, ParameterSetName='FromCertificateInWindowsStore')] [Parameter(Mandatory, Position=0, ParameterSetName='FromCertificateInCustomStore')] # The certificate to install. [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory)] # The location of the certificate's store. To see a list of acceptable values, run: # # > [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreLocation]) [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation, [Parameter(Mandatory, ParameterSetName='FromFileInWindowsStore')] [Parameter(Mandatory, ParameterSetName='FromCertificateInWindowsStore')] # The name of the certificate's store. To see a list of acceptable values run: # # > [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreName]) [Security.Cryptography.X509Certificates.StoreName]$StoreName, [Parameter(Mandatory, ParameterSetName='FromFileInCustomStore')] [Parameter(Mandatory, ParameterSetName='FromCertificateInCustomStore')] # The name of the non-standard, custom store where the certificate should be installed. [String]$CustomStoreName, [Parameter(ParameterSetName='FromFileInWindowsStore')] [Parameter(ParameterSetName='FromFileInCustomStore')] # Mark the private key as exportable. Only valid if loading the certificate from a file. [switch]$Exportable, [Parameter(ParameterSetName='FromFileInWindowsStore')] [Parameter(ParameterSetName='FromFileInCustomStore')] # The password for the certificate. Should be a `System.Security.SecureString`. [securestring]$Password, # Use the `Session` parameter to install a certificate on remote computer(s) using PowerShell remoting. Use # `New-PSSession` to create a session. [Management.Automation.Runspaces.PSSession[]]$Session, # Re-install the certificate, even if it is already installed. Calls the `Add()` method for store even if the # certificate is in the store. This function assumes that the `Add()` method replaces existing certificates. [switch]$Force, # Return the installed certificate. [switch]$PassThru ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState if( $PSCmdlet.ParameterSetName -like 'FromFile*' ) { $resolvedPath = Resolve-Path -Path $Path if( -not $resolvedPath ) { return } $Path = $resolvedPath.ProviderPath $fileBytes = [IO.File]::ReadAllBytes($Path) $encodedCert = [Convert]::ToBase64String($fileBytes) # Make sure loading the certificate doesn't leave temporary cruft around on the file system. We're only loading # the cert to get its thumbprint. $keyStorageFlags = @{} if( $StoreLocation -eq [Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser ) { $keyStorageFlags['KeyStorageFlags'] = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet } $Certificate = Get-CCertificate -Path $Path -Password $Password @keyStorageFlags } else { $encodedCert = [Convert]::ToBase64String( $Certificate.RawData ) } $keyFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet if( $StoreLocation -eq [Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser ) { $keyFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::UserKeySet } $keyFlags = $keyFlags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet if( $Exportable ) { $keyFlags = $keyFlags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable } $invokeCommandArgs = @{ } if( $Session ) { $invokeCommandArgs['Session'] = $Session } Invoke-Command @invokeCommandArgs -ScriptBlock { [CmdletBinding()] param( [Parameter(Mandatory)] # The base64 encoded certificate to install. [String]$EncodedCertificate, # The password for the certificate. [securestring]$Password, [Parameter(Mandatory)] [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation, $StoreName, [string]$CustomStoreName, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]$KeyStorageFlags, [bool]$Force, [bool]$WhatIf, [Management.Automation.ActionPreference]$Verbosity, [String]$Thumbprint ) Set-StrictMode -Version 'Latest' $WhatIfPreference = $WhatIf $VerbosePreference = $Verbosity $certFilePath = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([IO.Path]::GetRandomFileName()) try { if( $CustomStoreName ) { $store = [Security.Cryptography.X509Certificates.X509Store]::New($CustomStoreName, $StoreLocation) } else { $StoreName = [Security.Cryptography.X509Certificates.StoreName]$StoreName $store = [Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation) } if( -not $Force ) { $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly) ) try { if( $store.Certificates | Where-Object 'Thumbprint' -eq $Thumbprint ) { return } } finally { $store.Close() } } $certBytes = [Convert]::FromBase64String( $EncodedCertificate ) [IO.File]::WriteAllBytes( $certFilePath, $certBytes ) $cert = [Security.Cryptography.X509Certificates.X509Certificate2]::New($certFilePath, $Password, $KeyStorageFlags) $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) ) $description = $cert.FriendlyName if( -not $description ) { $description = $cert.Subject } $action = "install into $($StoreLocation)'s $($StoreName) store" $target = "$($description) ($($cert.Thumbprint))" if( $PSCmdlet.ShouldProcess($action, $target) ) { $msg = "Installing certificate ""$($description)"" ($($cert.Thumbprint)) into $($StoreLocation)'s " + "$($StoreName) store." Write-Verbose -Message $msg $store.Add( $cert ) } $store.Close() } finally { Remove-Item -Path $certFilePath -ErrorAction Ignore -WhatIf:$false -Force } } -ArgumentList $encodedCert,$Password,$StoreLocation,$StoreName,$CustomStoreName,$keyFlags,$Force,$WhatIfPreference,$VerbosePreference, $Certificate.Thumbprint if( $PassThru ) { return $Certificate } } function Protect-CString { <# .SYNOPSIS Encrypts a string. .DESCRIPTION The `Protect-CString` function encrypts a string using the Windows Data Protection API (DPAPI), RSA, or AES. Pass a plaintext string or a secure string to the `String` parameter. When encrypting a `SecureString`, it is converted to an array of bytes, encrypted, then the array of bytes is cleared from memory (i.e. the plaintext version of the `SecureString` is only in memory long enough to encrypt it). All strings and secure string bytes are re-encoded from UTF-16/Unicode to UTF-8 before encrypting. ## Windows Data Protection API (DPAPI) The DPAPI hides the encryptiong/decryption keys. There is a unique key for each user and a machine key. Anything encrypted with a user's key, can only be decrypted by that user. Anything encrypted with the machine key can be decrypted by anyone on that machine. Use the `ForUser` switch to encrypt with the current user's key. Use the `ForComputer` switch to encrypt at the machine level. If you want to encrypt something as a different user, pass that user's credentials to the `Credential` parameter. `Protect-CString` will launch a PowerShell process as that user to do the encryption. Encrypting as another user doesn't work over PowerShell Remoting. ## RSA RSA is an assymetric encryption/decryption algorithm, which requires a public/private key pair. The secret is encrypted with the public key, and can only be decrypted with the corresponding private key. The secret being encrypted can't be larger than the RSA key pair's size/length, usually 1024, 2048, or 4096 bits (128, 256, and 512 bytes, respectively). `Protect-CString` encrypts with .NET's `System.Security.Cryptography.RSACryptoServiceProvider` class. You can specify the public key in three ways: * by passing the `System.Security.Cryptography.X509Certificates.X509Certificate2` object to use to the `Certificate` parameter. * with a certificate in one of the Windows certificate stores. Pass its thumbprint to the `Thumbprint` parameter. * with an X509 certificate file. Pass the file's path to the `PublicKeyPath` parameter. You can also pass a certificate provider path to the `PublicKeyPath` parameter (e.g. `cert:`). You can generate an RSA public/private key pair with the `New-CRsaKeyPair` function. ## AES AES is a symmetric encryption/decryption algorithm. You supply a 16-, 24-, or 32-byte key/password/passphrase with the `Key` parameter, and that key is used to encrypt. There is no limit on the size of the data you want to encrypt. `Protect-CString` encrypts with the object returned by `[Security.Cryptography.Aes]::Create()` You can only pass a `[securestring]` or array of bytes as the key. The array of bytes must be 16, 24, or 32 bytes long. When passing a secure string, when UTF-8 encoded and converted to a byte array, it must also be 16, 24, or 32 bytes long. You can use this code to check on the byte length of a plain text string (where $key is the plain text key): [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length Symmetric encryption requires a random, unique initialization vector (i.e. IV) everytime you encrypt something. `Protect-CString` generates one for you. This IV must be known to decrypt the secret, so it is pre-pendeded to the encrypted text. This code demonstrates how to generate a key: $key = [Security.Cryptography.AesManaged]::New().Key You can save this key as a string by encoding it as a base64 string: $base64EncodedKey = [Convert]::ToBase64String($key) If you base64 encode your key's bytes, they must be converted back to bytes before passing it to `Protect-CString`. Protect-CString -String 'the secret sauce' -Key ([Convert]::FromBase64String($base64EncodedKey)) .LINK New-CRsaKeyPair .LINK Unprotect-CString .LINK http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx .EXAMPLE Protect-CString -String 'TheStringIWantToEncrypt' -ForUser | Out-File MySecret.txt Encrypts the given string and saves the encrypted string into MySecret.txt. Only the user who encrypts the string can unencrypt it. .EXAMPLE Protect-CString -String $credential.Password -ForUser | Out-File MySecret.txt Demonstrates that `Protect-CString` can encrypt a `SecureString`. .EXAMPLE Protect-CString -String "MySuperSecretIdentity" -ForComputer Demonstrates how to encrypt a value that can only be decrypted on the current computer. .EXAMPLE Protect-CString -String 's0000p33333r s33333cr33333t' -Credential (Get-Credential 'builduser') Demonstrates how to use `Protect-CString` to encrypt a secret as a specific user. This is useful for situation where a secret needs to be encrypted by a user other than the user running `Protect-CString`. Encrypting as a specific user won't work over PowerShell remoting. .EXAMPLE Protect-CString -String 'the secret sauce' -Certificate $myCert Demonstrates how to encrypt a secret using RSA with a `System.Security.Cryptography.X509Certificates.X509Certificate2` object. You're responsible for creating/loading the certificate. The `New-CRsaKeyPair` function will create a key pair for you, if you've got a Windows SDK installed. .EXAMPLE Protect-CString -String 'the secret sauce' -Thumbprint '44A7C27F3353BC53F82318C14490D7E2500B6D9E' Demonstrates how to encrypt a secret using RSA with a certificate in one of the Windows certificate stores. All local machine and user stores are searched for the certificate with the given thumbprint that has a private key. .EXAMPLE Protect-CString -String 'the secret sauce' -PublicKeyPath 'C:\Projects\Security\publickey.cer' Demonstrates how to encrypt a secret using RSA with a certificate file. The file must be loadable by the `System.Security.Cryptography.X509Certificates.X509Certificate` class. .EXAMPLE Protect-CString -String 'the secret sauce' -PublicKeyPath 'cert:\LocalMachine\My\44A7C27F3353BC53F82318C14490D7E2500B6D9E' Demonstrates how to encrypt a secret using RSA with a certificate in the Windows certificate store, giving its exact path. .EXAMPLE Protect-CString -String 'the secret sauce' -Key 'gT4XPfvcJmHkQ5tYjY3fNgi7uwG4FB9j' Demonstrates how to encrypt a secret with a key, password, or passphrase. In this case, we are encrypting with a plaintext password. .EXAMPLE Protect-CString -String 'the secret sauce' -Key (Read-Host -Prompt 'Enter password (must be 16, 24, or 32 characters long):' -AsSecureString) Demonstrates that you can use a `SecureString` as the key, password, or passphrase. .EXAMPLE Protect-CString -String 'the secret sauce' -Key ([byte[]]@(163,163,185,174,205,55,157,219,121,146,251,116,43,203,63,38,73,154,230,112,82,112,151,29,189,135,254,187,164,104,45,30)) Demonstrates that you can use an array of bytes as the key, password, or passphrase. #> [CmdletBinding()] param( [Parameter(Mandatory, Position=0, ValueFromPipeline)] # The string to encrypt. Any non-string object you pass will be converted to a string before encrypting by # calling the object's `ToString` method. # # This can also be a `SecureString` object. The `SecureString` is converted to an array of bytes, the bytes are # encrypted, then the plaintext bytes are cleared from memory (i.e. the plaintext password is in memory for the # amount of time it takes to encrypt it). Passing a secure string is the most secure usage. # # The string and secure string bytes are re-encoded as UTF-8 before encrypting. [Object]$String, [Parameter(Mandatory, ParameterSetName='DPAPICurrentUser')] # Encrypts for the current user so that only they can decrypt. [switch]$ForUser, [Parameter(Mandatory, ParameterSetName='DPAPILocalMachine')] # Encrypts for the current computer so that any user logged into the computer can decrypt. [switch]$ForComputer, [Parameter(Mandatory, ParameterSetName='DPAPIForUser')] # Encrypts for a specific user. [pscredential]$Credential, [Parameter(Mandatory, ParameterSetName='RsaByCertificate')] # The public key to use for encrypting. [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory, ParameterSetName='RsaByThumbprint')] # The thumbprint of the certificate, found in one of the Windows certificate stores, to use when encrypting. All # certificate stores are searched. [String]$Thumbprint, [Parameter(Mandatory, ParameterSetName='RsaByPath')] # The path to the public key to use for encrypting. Must be to an `X509Certificate2` object. [String]$PublicKeyPath, [Parameter(ParameterSetName='RsaByCertificate')] [Parameter(ParameterSetName='RsaByPath')] [Parameter(ParameterSetName='RsaByThumbprint')] # The padding mode to use when encrypting. When using an RSA public key, defaults to # [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1. [Security.Cryptography.RSAEncryptionPadding]$Padding, [Parameter(Mandatory, ParameterSetName='Symmetric')] # The key to use to encrypt the secret. Must be a `[securestring]` or an array of bytes. If passing a byte # array, # must be 16, 24, or 32 bytes long. If passing a secure string, when it is UTF-8 encoded and converted # to a byte # array, that array must also be 16, 24, or 32 bytes long. This code will tell you the length, in # bytes, of your plain text key (stored in the `$key`variable): # # [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length [Object]$Key ) process { Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState # We find and validate the certificate/key here so our try/catch block around actual encryption doesn't catch # these errors. [byte[]]$keyBytes = [byte[]]::New(0) if( $PSCmdlet.ParameterSetName -like 'Rsa*' ) { if( $PSCmdlet.ParameterSetName -eq 'RsaByThumbprint' ) { $Certificate = Get-Item -Path ('cert:\*\*\{0}' -f $Thumbprint) | Select-Object -First 1 if( -not $Certificate ) { Write-Error "Certificate with thumbprint ""$($Thumbprint)"" not found." return } } elseif( $PSCmdlet.ParameterSetName -eq 'RsaByPath' ) { $Certificate = Get-CCertificate -Path $PublicKeyPath if( -not $Certificate ) { return } } $rsaKey = $Certificate.PublicKey.Key if( -not $rsaKey.GetType().IsSubclassOf([Security.Cryptography.RSA]) ) { $msg = "Certificate ""$($Certificate.Subject)"" ($($Certificate.Thumbprint)) is not an RSA public " + "key. Found a public key of type ""$($rsaKey.GetType().FullName)"", but expected type " + """$([Security.Cryptography.RSACryptoServiceProvider].FullName)""." Write-Error $msg return } } elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' ) { $keyBytes = ConvertTo-AesKey -InputObject $Key -From 'Protect-CString' if( -not $keyBytes ) { return } } $stringBytes = [byte[]]::New(0) $unicodeBytes = [Text.Encoding]::Unicode.GetBytes( $String.ToString() ) [byte[]]$encryptedBytes = [byte[]]::New(0) try { if( $String -is [securestring] ) { $unicodeBytes = Convert-CSecureStringToByte -SecureString $String } # Unicode takes up two bytes, so the max length of strings we can encrypt is cut from about 472 characters # to 236. Let's re-encode in UTF-8, which only uses one byte per character. This also maintains # backwards-compatability with Carbon 2. $stringBytes = [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, $unicodeBytes) } finally { $unicodeBytes.Clear() } try { if( $PSCmdlet.ParameterSetName -like 'DPAPI*' ) { if( $PSCmdlet.ParameterSetName -eq 'DPAPIForUser' ) { $protectStringPath = Join-Path -Path $moduleBinRoot -ChildPath 'Protect-String.ps1' -Resolve $encodedString = Protect-CString -String $String -ForComputer $powershellArgs = @( '-ExecutionPolicy', 'ByPass', '-NonInteractive', '-File', $protectStringPath, '-ProtectedString', $encodedString ) return Invoke-CPowerShell -ArgumentList $powershellArgs -Credential $Credential | Select-Object -First 1 } else { $scope = [Security.Cryptography.DataProtectionScope]::CurrentUser if( $PSCmdlet.ParameterSetName -eq 'DPAPILocalMachine' ) { $scope = [Security.Cryptography.DataProtectionScope]::LocalMachine } $encryptedBytes = [Security.Cryptography.ProtectedData]::Protect( $stringBytes, $null, $scope ) } } elseif( $PSCmdlet.ParameterSetName -like 'Rsa*' ) { if( -not $Padding ) { $Padding = [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1 } $encryptedBytes = $Certificate.PublicKey.Key.Encrypt($stringBytes, $Padding) } elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' ) { $aes = [Security.Cryptography.Aes]::Create() try { $aes.Padding = [Security.Cryptography.PaddingMode]::PKCS7 $aes.KeySize = $keyBytes.Length * 8 $aes.Key = $keyBytes $memoryStream = [IO.MemoryStream]::New() try { $cryptoStream = [Security.Cryptography.CryptoStream]::New( $memoryStream, $aes.CreateEncryptor(), ([Security.Cryptography.CryptoStreamMode]::Write) ) try { $cryptoStream.Write($stringBytes, 0, $stringBytes.Length) } finally { $cryptoStream.Dispose() } $encryptedBytes = & { $aes.IV $memoryStream.ToArray() } } finally { $memoryStream.Dispose() } } finally { $aes.Dispose() } } return [Convert]::ToBase64String( $encryptedBytes ) } catch { Write-Error -ErrorRecord $_ -ErrorAction $ErrorActionPreference } finally { if( $encryptedBytes ) { $encryptedBytes.Clear() } if( $stringBytes ) { $stringBytes.Clear() } if( $keyBytes ) { $keyBytes.Clear() } } } } function Uninstall-CCertificate { <# .SYNOPSIS Removes a certificate from a certificate store. .DESCRIPTION The `Uninstall-CCertificate` function uses .NET's certificates API to remove a certificate from a certificate store for the machine or current user. Use the thumbprint to identify which certificate to remove. The thumbprint is unique to each certificate. The user performing the removal must have read and write permission on the store where the certificate is located. If the certificate isn't in the store, nothing happens, not even an error. To uninstall a certificate from a remote computer, use the `Session`parameter. You can create a new session with the `New-PSSession` cmdlet. You can pass multiple sessions. You can uninstall a certificate using just its thumbprint. `Uninstall-CCertificate` will search through all certificate locations and stores and uninstall all certificates that have the thumbprint. When you enumerate all certificates over a remoting session, you get a terminating `The system cannot open the device or file specified` error, so you can't delete a certificate with just a thumbprint over remoting. .EXAMPLE Uninstall-CCertificate -Thumbprint '570895470234023dsaaefdbcgbefa' Demonstrates how to delete a certificate from all stores it is installed in. `Uninstall-CCertificate` searches every certificate stores and deletes all certificates with the given thumbprint. .EXAMPLE '570895470234023dsaaefdbcgbefa' | Uninstall-CCertificate Demonstrates that you can pipe a thumbprint to `Uninstall-CCertificate`. The certificate is uninstall from all stores it is in. .EXAMPLE Get-Item -Path 'cert:\LocalMachine\My\570895470234023dsaaefdbcgbefa' | Uninstall-CCertificate Demonstrates that you can pipe a certificate `Uninstall-CCertificate`. The certificate is uninstalled from all stores it is in. .EXAMPLE Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation CurrentUser -StoreName My Removes the 570895470234023dsaaefdbcgbefa certificate from the current user's Personal certificate store. .EXAMPLE Uninstall-CCertificate -Certificate $cert -StoreLocation LocalMachine -StoreName Root Demonstrates how you can remove a certificate by passing it to the `Certificate` parameter. .EXAMPLE Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation LocalMachine -StoreName 'SharePoint' Demonstrates how to uninstall a certificate from a custom, non-standard store. .EXAMPLE Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation CurrentUser -StoreName My -Session $session Demonstrates how to uninstall a certificate from a remote computer. #> [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName='ByThumbprint')] param( [Parameter(Mandatory, ParameterSetName='ByThumbprint',ValueFromPipelineByPropertyName, ValueFromPipeline)] [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')] [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')] # The thumbprint of the certificate to remove. # # If you want to uninstall the certificate from all stores it is installed in, you can pipe the thumbprint to this parameter or you can pipe a certificate object. (This functionality was added in Carbon 2.5.0.) [String]$Thumbprint, [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')] [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')] # The certificate to remove [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')] [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')] [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')] [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')] # The location of the certificate's store. [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation, [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')] [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')] # The name of the certificate's store. [Security.Cryptography.X509Certificates.StoreName]$StoreName, [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')] [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')] # The name of the non-standard, custom store where the certificate should be un-installed. [String]$CustomStoreName, [Parameter(ParameterSetName='ByThumbprintAndStoreName')] [Parameter(ParameterSetName='ByThumbprintAndCustomStoreName')] [Parameter(ParameterSetName='ByCertificateAndStoreName')] [Parameter(ParameterSetName='ByCertificateAndCustomStoreName')] # Use the `Session` parameter to uninstall a certificate on remote computer(s) using PowerShell remoting. Use # `New-PSSession` to create a session. # # Due to a bug in PowerShell, you can't remove a certificate by just its thumbprint over remoting. Using just a # thumbprint requires us to enumerate through all installed certificates. When you do this over remoting, # PowerShell throws a terminating `The system cannot open the device or file specified` error. [Management.Automation.Runspaces.PSSession[]]$Session ) process { Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState if( $PSCmdlet.ParameterSetName -like 'ByCertificate*' ) { $Thumbprint = $Certificate.Thumbprint } $invokeCommandParameters = @{} if( $Session ) { $invokeCommandParameters['Session'] = $Session } if( $PSCmdlet.ParameterSetName -eq 'ByThumbprint' ) { # Must be in this order. Delete LocalMachine certs *first* so they don't show # up in CurrentUser stores. If you delete a certificate that "cascades" into # the CurrentUser store first, you'll get errors when running non- # interactively as SYSTEM. if( (Test-Path -Path 'cert:') ) { Get-ChildItem -Path 'Cert:\LocalMachine','Cert:\CurrentUser' -Recurse | Where-Object { -not $_.PsIsContainer } | Where-Object { $_.Thumbprint -eq $Thumbprint } | ForEach-Object { $cert = $_ $description = $cert.FriendlyName if( -not $description ) { $description = $cert.Subject } $certPath = $_.PSPath | Split-Path -NoQualifier Write-Verbose ('Uninstalling certificate ''{0}'' ({1}) at {2}.' -f $description,$cert.Thumbprint,$certPath) $_ } | Remove-Item } return } Invoke-Command @invokeCommandParameters -ScriptBlock { [CmdletBinding()] param( # The thumbprint of the certificate to remove. [String]$Thumbprint, # The location of the certificate's store. [Security.Cryptography.X509Certificates.StoreLocation]$StoreLocation, # The name of the certificate's store. $StoreName, # The name of the non-standard, custom store where the certificate should be un-installed. [String]$CustomStoreName ) Set-StrictMode -Version 'Latest' if( $CustomStoreName ) { $storeNamePath = $CustomStoreName } else { $storeNamePath = $StoreName if( $StoreName -eq [Security.Cryptography.X509Certificates.StoreName]::CertificateAuthority ) { $storeNamePath = 'CA' } } $certPath = Join-Path -Path 'Cert:\' -ChildPath $StoreLocation $certPath = Join-Path -Path $certPath -ChildPath $storeNamePath $certPath = Join-Path -Path $certPath -ChildPath $Thumbprint if( -not (Test-Path -Path $certPath -PathType Leaf) ) { Write-Debug -Message ('Certificate {0} not found.' -f $certPath) return } $cert = Get-Item -Path $certPath if( $CustomStoreName ) { $store = New-Object 'Security.Cryptography.X509Certificates.X509Store' $CustomStoreName,$StoreLocation } else { $store = New-Object 'Security.Cryptography.X509Certificates.X509Store' ([Security.Cryptography.X509Certificates.StoreName]$StoreName),$StoreLocation } $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) ) try { $target = $cert.FriendlyName if( -not $target ) { $target = $cert.Subject } if( $PSCmdlet.ShouldProcess( ("certificate {0} ({1})" -f $certPath,$target), "remove" ) ) { Write-Verbose ('Uninstalling certificate ''{0}'' ({1}) at {2}.' -f $target,$cert.Thumbprint,$certPath) $store.Remove( $cert ) } } finally { $store.Close() } } -ArgumentList $Thumbprint,$StoreLocation,$StoreName,$CustomStoreName } } Set-Alias -Name 'Remove-Certificate' -Value 'Uninstall-CCertificate' function Unprotect-CString { <# .SYNOPSIS Decrypts a string. .DESCRIPTION `Unprotect-CString` decrypts a string encrypted via the Data Protection API (DPAPI), RSA, or AES into an array of bytes, which is then converted to an array of chars, which are stored in a `[securestring]`. All arrays of bytes and chars are cleared from memory once decryption completes. Use the `AsPlainText` switch to return a plain text string instead. When you do this, your decrypted string will remain in memory (and maybe disk) for an unknowable amount of time. `Unprotect-CString` can decrypt using the following techniques. ## Data Protection API The DPAPI only works on Windows. The encrypted string must have also been encrypted with the DPAPI. The string must have been encrypted at the current user's scope or the local machine scope. ## RSA RSA is an assymetric encryption/decryption algorithm, which requires a public/private key pair. It uses a private key to decrypt a secret encrypted with the public key. Only the private key can decrypt secrets. You can specify the private key in these ways: * with a `[Security.Cryptography.X509Certificates.X509Certificate2]` object, via the `Certificate` parameter * with an X509 certificate file, via the `PrivateKeyPath` parameter. On Windows, you can use paths to items in the `cert:\` drive. On Windows, you can also pass the thumbprint to a certificate to the `Thumbprint` parameter, and `Unprotect-CString` will search the `cert:\` store for a matching certificate with a private key. ## AES AES is a symmetric encryption/decryption algorithm. You supply a 16-, 24-, or 32-byte key, password, or passphrase with the `Key` parameter, and that key is used to decrypt. You must decrypt with the same key you used to encrypt. `Unprotect-CString` uses `[Security.Cryptography.Aes]::Create()` to get an object that can do the decryption. You can only pass a `[securestring]` or byte array as the key. When passing a secure string, make sure that when encoded as UTF-8 and converted to a byte array, it is 16, 24, or 32 bytes long. This code will tell you how long your plain text password is, in UTF-8 bytes: [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length Symmetric encryption requires a random, unique initialization vector (i.e. IV) everytime you encrypt something. If you encrypted the string with `Protect-CString`, one was generated for you and prepended to the encrypted string. If you encrypted the original string yourself, make sure the first 16 bytes of the encrypted text is the IV (since the encrypted bytes are base64 encoded, that means the first 24 characters of the encrypted string should be the IV). The help topic for `Protect-CString` demonstrates how to generate an AES key and how to encode it as a base64 string. .LINK New-CRsaKeyPair .LINK Protect-CString .LINK http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx .EXAMPLE Unprotect-CString -ProtectedString $encryptedPassword Demonstrates how to decrypt a protected string which was encrypted with Microsoft's DPAPI. Windows only. .EXAMPLE Unprotect-CString -ProtectedString $ciphertext -Certificate $myCert Demonstrates how to decrypt a secret using RSA with a `[Security.Cryptography.X509Certificates.X509Certificate2]` object. You're responsible for creating/loading it. (Carbon's `New-CRsaKeyPair` function can create public/private key pairs for you.) .EXAMPLE $ciphertext | Unprotect-CString -Certificate $certWithPrivateKey Demonstrates that you can pipe encrypted strings to `Unprotect-CString`. .EXAMPLE $ciphertext | Unprotect-CString -Certificate $certWithPrivateKey -AsSecureString Demonstrates that you can get a secure string returned to you by using the `AsSecureString` switch. This is the most secure way to decrypt, as the decrypted text is only in memory as arrays of bytes/chars during decryption. The arrays are immediately cleared after decryption. The decrypted text is never stored as a `[String]` (which remain in memory). .EXAMPLE Unprotect-CString -ProtectedString $ciphertext -Thumbprint '44A7C27F3353BC53F82318C14490D7E2500B6D9E' Demonstrates how to decrypt a secret with a certificate by passing its thumbprint to the `Thumbprint` parameter. `Unprotect-CString` will search the Windows certificate stores to find the certificate. All local machine and user stores are searched. The current user must have permission/access to the certificate's private key. Windows only. .EXAMPLE Unprotect -ProtectedString $ciphertext -PrivateKeyPath 'C:\Projects\Security\publickey.cer' Demonstrates how to decrypt a secret by passing the path to an RSA private key to the `PrivateKeyPath` parameter. The private key file must be loadable by the `[Security.Cryptography.X509Certificates.X509Certificate]` class. .EXAMPLE Unprotect -ProtectedString $ciphertext -PrivateKeyPath 'cert:\LocalMachine\My\44A7C27F3353BC53F82318C14490D7E2500B6D9E' Demonstrates how to decrypt a secret using a certificate in the Windows store by passing the path to the certificate in PowerShell's `cert:` drive. The certificate must have a private key. Windows only. .EXAMPLE Unprotect-CString -ProtectedString $ciphertext -Key 'gT4XPfvcJmHkQ5tYjY3fNgi7uwG4FB9j' Demonstrates how to decrypt a secret that was encrypted with a key, password, or passphrase. In this case, we are decrypting with a plaintext password. .EXAMPLE Unprotect-CString -ProtectedString $ciphertext -Key (Read-Host -Prompt 'Enter password (must be 16, 24, or 32 characters long):') -AsSecureString) Demonstrates how to decrypt a secret with a secure string that is the key, password, or passphrase. In this case, the user is prompted for the password securely. .EXAMPLE Unprotect-CString -ProtectedString $ciphertext -Key ([byte[]]@(163,163,185,174,205,55,157,219,121,146,251,116,43,203,63,38,73,154,230,112,82,112,151,29,189,135,254,187,164,104,45,30)) Demonstrates that you can pass in an array of bytes as the key to the `Key` parameter. Those bytes will be used to decrypt the ciphertext. #> [CmdletBinding(DefaultParameterSetName='DPAPI')] param( [Parameter(Mandatory, Position=0, ValueFromPipeline)] # The text to decrypt. [String]$ProtectedString, [Parameter(Mandatory, ParameterSetName='RSAByCertificate')] # The private key to use for decrypting. [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory, ParameterSetName='RSAByThumbprint')] # The thumbprint of the certificate, found in one of the Windows certificate stores, to use when decrypting. All # certificate stores are searched. The current user must have permission to the private key. Windows only. [String]$Thumbprint, [Parameter(Mandatory, ParameterSetName='RSAByPath')] # The path to the private key to use for decrypting. If given a path on the file system, the file must be # loadable as a `[Security.X509Certificates.X509Certificate2]` object. On Windows, you can also pass the path # to a certificate in PowerShell's `cert:` drive. [String]$PrivateKeyPath, [Parameter(ParameterSetName='RSAByPath')] # The password for the private key, if it has one. Must be a `[securestring]`. [securestring]$Password, [Parameter(ParameterSetName='RSAByCertificate')] [Parameter(ParameterSetName='RSAByThumbprint')] [Parameter(ParameterSetName='RSAByPath')] # The padding mode to use when decrypting. Defaults to `[Security.Cryptography.RSAEncryptionPadding]::OaepSHA1`. [Security.Cryptography.RSAEncryptionPadding]$Padding, [Parameter(Mandatory, ParameterSetName='Symmetric')] # The key to use to decrypt the secret. Must be a `[securestring]` or an array of bytes. The characters in the # secure string are converted to UTF-8 encoding before being converted into bytes. Make sure the key is the # correct length when UTF-8 encoded, i.e. make sure the following code returns a 16, 24, or 32 byte byte array # (where $key is the plain text key). # # [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length [Object]$Key, # Returns the decrypted value as plain text. The default is to return the decrypted value as a `[securestring]`. # When returned as a secure string, the decrypted bytes are only stored in memory as arrays of bytes and chars, # which are all cleared once the decrypted text is in the secure string. Once a secure string is converted to a # string, that string stays in memory (and possibly disk) for an unknowable amout of time. [switch]$AsPlainText ) process { Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState [byte[]]$keyBytes = [byte[]]::New(0) # Find and validate the RSA certificate, if needed. We do it here so our try/catch around the actual # decryption doesn't handle these errors. if( $PSCmdlet.ParameterSetName -like 'RSA*' ) { if( $PSCmdlet.ParameterSetName -notlike '*ByCertificate' ) { if( $PSCmdlet.ParameterSetName -like '*ByThumbprint' ) { $PrivateKeyPath = "cert:\*\*\$($Thumbprint)" } $passwordParam = @{ } if( $Password ) { $passwordParam = @{ Password = $Password } } $certificates = Get-CCertificate -Path $PrivateKeyPath @passwordParam $count = $certificates | Measure-Object | Select-Object -ExpandProperty 'Count' if( $count -gt 1 ) { $msg = "Found $($count) certificates at ""$($PrivateKeyPath)"". Arbitrarily choosing the first " + 'one. If you get errors, consider passing the exact path to the certificate you want to ' + 'the "Unprotect-CString" function''s "PrivateKeyPath" parameter.' Write-Warning -Message $msg } $Certificate = $certificates | Select-Object -First 1 if( -not $Certificate ) { return } } $certDesc = "Certificate ""$($Certificate.Subject)"" ($($Certificate.Thumbprint))" if( -not $Certificate.HasPrivateKey ) { $msg = "$($certDesc) doesn't have a private key. When decrypting with RSA, secrets are encrypted with " + 'the public key, and decrypted with a private key.' Write-Error -Message $msg -ErrorAction $ErrorActionPreference return } if( -not $Certificate.PrivateKey ) { $msg = "$($certDesc) has a private key, but it is null or not set. This usually means your certificate " + 'was imported incorrectly or was created without a private key. Make sure you''ve generated an ' + 'RSA public/private key pair and are using the private key. If the private key is in the Windows ' + 'certificate store, make sure the current user has permission to read the private key (use ' + 'Carbon''s `Grant-CPermission` function).' Write-Error -Message $msg -ErrorAction $ErrorActionPreference return } } elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' ) { $keyBytes = ConvertTo-AesKey -InputObject $Key -From 'Unprotect-CString' if( -not $keyBytes ) { return } } [byte[]]$decryptedBytes = [byte[]]::New(0) [byte[]]$encryptedBytes = [Convert]::FromBase64String($ProtectedString) try { if( $PSCmdlet.ParameterSetName -eq 'DPAPI' ) { $decryptedBytes = [Security.Cryptography.ProtectedData]::Unprotect( $encryptedBytes, $null, 0 ) } elseif( $PSCmdlet.ParameterSetName -like 'RSA*' ) { [Security.Cryptography.RSA]$privateKey = $null $privateKeyType = $Certificate.PrivateKey.GetType() $isRsa = $privateKeyType.IsSubclassOf([Security.Cryptography.RSA]) if( -not $isRsa ) { $msg = "$($certDesc) is not an RSA key. Found a private key of type " + """$($privateKeyType.FullName)"", but expected type " + """$([Security.Cryptography.RSA].FullName)"" or one of its sub-types." Write-Error -Message $msg -ErrorAction $ErrorActionPreference return } if( -not $Padding ) { $Padding = [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1 } $privateKey = $Certificate.PrivateKey $decryptedBytes = $privateKey.Decrypt($encryptedBytes, $padding) } elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' ) { $aes = [Security.Cryptography.Aes]::Create() try { $aes.Padding = [Security.Cryptography.PaddingMode]::PKCS7 $aes.KeySize = $keyBytes.Length * 8 $aes.Key = $keyBytes $iv = [byte[]]::New($aes.IV.Length) [Array]::Copy($encryptedBytes, $iv, 16) $encryptedBytes = $encryptedBytes[16..($encryptedBytes.Length - 1)] $encryptedStream = New-Object -TypeName 'IO.MemoryStream' -ArgumentList (,$encryptedBytes) try { $cryptoStream = [Security.Cryptography.CryptoStream]::New($encryptedStream, $aes.CreateDecryptor($aes.Key, $iv), ([Security.Cryptography.CryptoStreamMode]::Read)) try { $streamReader = [IO.StreamReader]::New($cryptoStream) try { [byte[]]$decryptedBytes = [Text.Encoding]::UTF8.GetBytes($streamReader.ReadToEnd()) } finally { $streamReader.Dispose() } } finally { $cryptoStream.Dispose() } } finally { $encryptedStream.Dispose() } } finally { $aes.Dispose() } } $decryptedBytes = [Text.Encoding]::Convert([Text.Encoding]::UTF8, [Text.Encoding]::Unicode, $decryptedBytes) if( $AsPlainText ) { return [Text.Encoding]::Unicode.GetString($decryptedBytes) } else { $secureString = [Security.SecureString]::New() [char[]]$chars = [Text.Encoding]::Unicode.GetChars( $decryptedBytes ) for( $idx = 0; $idx -lt $chars.Count ; $idx++ ) { $secureString.AppendChar( $chars[$idx] ) $chars[$idx] = 0 } $secureString.MakeReadOnly() return $secureString } } catch { Write-Error -ErrorRecord $_ -ErrorAction $ErrorActionPreference } finally { if( $decryptedBytes ) { $decryptedBytes.Clear() } if( $encryptedBytes ) { $encryptedBytes.Clear() } if( $keyBytes ) { $keyBytes.Clear() } } } } function Use-CallerPreference { <# .SYNOPSIS Sets the PowerShell preference variables in a module's function based on the callers preferences. .DESCRIPTION Script module functions do not automatically inherit their caller's variables, including preferences set by common parameters. This means if you call a script with switches like `-Verbose` or `-WhatIf`, those that parameter don't get passed into any function that belongs to a module. When used in a module function, `Use-CallerPreference` will grab the value of these common parameters used by the function's caller: * ErrorAction * Debug * Confirm * InformationAction * Verbose * WarningAction * WhatIf This function should be used in a module's function to grab the caller's preference variables so the caller doesn't have to explicitly pass common parameters to the module function. This function is adapted from the [`Get-CallerPreference` function written by David Wyatt](https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d). There is currently a [bug in PowerShell](https://connect.microsoft.com/PowerShell/Feedback/Details/763621) that causes an error when `ErrorAction` is implicitly set to `Ignore`. If you use this function, you'll need to add explicit `-ErrorAction $ErrorActionPreference` to every `Write-Error` call. Please vote up this issue so it can get fixed. .LINK about_Preference_Variables .LINK about_CommonParameters .LINK https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d .LINK http://powershell.org/wp/2014/01/13/getting-your-script-module-functions-to-inherit-preference-variables-from-the-caller/ .EXAMPLE Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Demonstrates how to set the caller's common parameter preference variables in a module function. #> [CmdletBinding()] param ( [Parameter(Mandatory)] #[Management.Automation.PSScriptCmdlet] # The module function's `$PSCmdlet` object. Requires the function be decorated with the `[CmdletBinding()]` # attribute. $Cmdlet, [Parameter(Mandatory)] # The module function's `$ExecutionContext.SessionState` object. Requires the function be decorated with the # `[CmdletBinding()]` attribute. # # Used to set variables in its callers' scope, even if that caller is in a different script module. [Management.Automation.SessionState]$SessionState ) Set-StrictMode -Version 'Latest' # List of preference variables taken from the about_Preference_Variables and their common parameter name (taken # from about_CommonParameters). $commonPreferences = @{ 'ErrorActionPreference' = 'ErrorAction'; 'DebugPreference' = 'Debug'; 'ConfirmPreference' = 'Confirm'; 'InformationPreference' = 'InformationAction'; 'VerbosePreference' = 'Verbose'; 'WarningPreference' = 'WarningAction'; 'WhatIfPreference' = 'WhatIf'; } foreach( $prefName in $commonPreferences.Keys ) { $parameterName = $commonPreferences[$prefName] # Don't do anything if the parameter was passed in. if( $Cmdlet.MyInvocation.BoundParameters.ContainsKey($parameterName) ) { continue } $variable = $Cmdlet.SessionState.PSVariable.Get($prefName) # Don't do anything if caller didn't use a common parameter. if( -not $variable ) { continue } if( $SessionState -eq $ExecutionContext.SessionState ) { Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false } else { $SessionState.PSVariable.Set($variable.Name, $variable.Value) } } } |