File size: 33,247 Bytes
8c763fb | 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Security;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell
{
/// <summary>
/// Defines the authorization policy that controls the way scripts
/// (and other command types) are handled by PowerShell. This authorization
/// policy enforces one of four levels, as defined by the 'ExecutionPolicy'
/// value in one of the following locations:
///
/// In priority-order (highest priority first,) these come from:
///
/// - Machine-wide Group Policy
/// HKLM\Software\Policies\Microsoft\Windows\PowerShell
/// - Current-user Group Policy
/// HKCU\Software\Policies\Microsoft\Windows\PowerShell.
/// - Current session preference
/// ENV:PSExecutionPolicyPreference
/// - Current user machine preference
/// HKEY_CURRENT_USER\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
/// - Local machine preference
/// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
///
/// Restricted - All .ps1 files are blocked. ps1xml files must be digitally
/// signed, and by a trusted publisher. If you haven't made a trust decision
/// on the publisher yet, prompting is done as in AllSigned mode.
/// AllSigned - All .ps1 and .ps1xml files must be digitally signed. If
/// signed and executed, PowerShell prompts to determine if files from the
/// signing publisher should be run or not.
/// RemoteSigned - Only .ps1 and .ps1xml files originating from the internet
/// must be digitally signed. If remote, signed, and executed, PowerShell
/// prompts to determine if files from the signing publisher should be
/// run or not. This is the default setting.
/// Unrestricted - No files must be signed. If a file originates from the
/// internet, PowerShell provides a warning prompt to alert the user. To
/// suppress this warning message, right-click on the file in File Explorer,
/// select "Properties," and then "Unblock." Requires Shell.
/// Bypass - No files must be signed, and internet origin is not verified.
/// </summary>
public sealed class PSAuthorizationManager : AuthorizationManager
{
internal enum RunPromptDecision
{
NeverRun = 0,
DoNotRun = 1,
RunOnce = 2,
AlwaysRun = 3,
Suspend = 4
}
#region constructor
// execution policy that dictates what can run in msh
private ExecutionPolicy _executionPolicy;
// shellId supplied by runspace configuration
private readonly string _shellId;
/// <summary>
/// Initializes a new instance of the PSAuthorizationManager
/// class, for a given ShellId.
/// </summary>
/// <param name="shellId">
/// The shell identifier that the authorization manager applies
/// to. For example, Microsoft.PowerShell
/// </param>
public PSAuthorizationManager(string shellId)
: base(shellId)
{
if (string.IsNullOrEmpty(shellId))
{
throw PSTraceSource.NewArgumentNullException(nameof(shellId));
}
_shellId = shellId;
}
#endregion constructor
#region signing check
private static bool IsSupportedExtension(string ext)
{
return (
ext.Equals(".ps1", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".ps1xml", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".psm1", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".psd1", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".xaml", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".cdxml", StringComparison.OrdinalIgnoreCase));
}
private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason)
{
bool policyCheckPassed = false;
reason = null;
string path = script.Path;
string reasonMessage;
// path is assumed to be fully qualified here
if (path.IndexOf(System.IO.Path.DirectorySeparatorChar) < 0)
{
throw PSTraceSource.NewArgumentException("path");
}
if (path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) == (path.Length - 1))
{
throw PSTraceSource.NewArgumentException("path");
}
FileInfo fi = new FileInfo(path);
// Return false if the file does not exist, so that
// we don't introduce a race condition
if (!fi.Exists)
{
reason = new FileNotFoundException(path);
return false;
}
// Quick exit if we don't support the file type
if (!IsSupportedExtension(fi.Extension))
return true;
// Get the execution policy
_executionPolicy = SecuritySupport.GetExecutionPolicy(_shellId);
// Always check the SAFER APIs if code integrity isn't being handled system-wide through
// WLDP or AppLocker. In those cases, the scripts will be run in ConstrainedLanguage.
// Otherwise, block.
// SAFER APIs are not on CSS or OneCore
if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce)
{
SaferPolicy saferPolicy = SaferPolicy.Disallowed;
int saferAttempt = 0;
bool gotSaferPolicy = false;
// We need to put in a retry workaround, as the SAFER APIs fail when under stress.
while ((!gotSaferPolicy) && (saferAttempt < 5))
{
try
{
saferPolicy = SecuritySupport.GetSaferPolicy(path, null);
gotSaferPolicy = true;
}
catch (System.ComponentModel.Win32Exception)
{
if (saferAttempt > 4)
{
throw;
}
saferAttempt++;
System.Threading.Thread.Sleep(100);
}
}
// If the script is disallowed via AppLocker, block the file
// unless the system-wide lockdown policy is "Enforce" (where all PowerShell
// scripts are in blocked). If the system policy is "Enforce", then the
// script will be allowed (but ConstrainedLanguage will be applied).
if (saferPolicy == SaferPolicy.Disallowed)
{
reasonMessage = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path);
reason = new UnauthorizedAccessException(reasonMessage);
return false;
}
}
// WLDP and Applocker takes priority over powershell execution policy.
// See if they want to bypass the authorization manager
if (_executionPolicy == ExecutionPolicy.Bypass)
{
return true;
}
if (_executionPolicy == ExecutionPolicy.Unrestricted)
{
// Product binaries are always trusted
// This avoids signature and security zone checks
if (SecuritySupport.IsProductBinary(path))
return true;
// We need to give the "Remote File" warning
// if the file originated from the internet
if (!IsLocalFile(fi.FullName))
{
// Get the signature of the file.
if (string.IsNullOrEmpty(script.ScriptContents))
{
reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
reason = new UnauthorizedAccessException(reasonMessage);
return false;
}
Signature signature = GetSignatureWithEncodingRetry(path, script);
// The file is signed, with a publisher that
// we trust
if (signature.Status == SignatureStatus.Valid)
{
// The file is signed by a trusted publisher
if (IsTrustedPublisher(signature, path))
{
policyCheckPassed = true;
}
}
// We don't care about the signature. If you distrust them,
// or the signature does not exist, we prompt you only
// because it's remote.
if (!policyCheckPassed)
{
RunPromptDecision decision = RunPromptDecision.DoNotRun;
// Get their remote prompt answer, allowing them to
// enter nested prompts, if wanted.
do
{
decision = RemoteFilePrompt(path, host);
if (decision == RunPromptDecision.Suspend)
host.EnterNestedPrompt();
} while (decision == RunPromptDecision.Suspend);
switch (decision)
{
case RunPromptDecision.RunOnce:
policyCheckPassed = true;
break;
case RunPromptDecision.DoNotRun:
default:
policyCheckPassed = false;
reasonMessage = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
reason = new UnauthorizedAccessException(reasonMessage);
break;
}
}
}
else
{
policyCheckPassed = true;
}
}
// Don't need to check the signature if the file is local
// and we're in "RemoteSigned" mode
else if ((IsLocalFile(fi.FullName)) &&
(_executionPolicy == ExecutionPolicy.RemoteSigned))
{
policyCheckPassed = true;
}
else if ((_executionPolicy == ExecutionPolicy.AllSigned) ||
(_executionPolicy == ExecutionPolicy.RemoteSigned))
{
// if policy requires signature verification,
// make it so.
// Get the signature of the file.
if (string.IsNullOrEmpty(script.ScriptContents))
{
reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
reason = new UnauthorizedAccessException(reasonMessage);
return false;
}
Signature signature = GetSignatureWithEncodingRetry(path, script);
// The file is signed.
if (signature.Status == SignatureStatus.Valid)
{
// The file is signed by a trusted publisher
if (IsTrustedPublisher(signature, path))
{
policyCheckPassed = true;
}
// The file is signed by an unknown publisher,
// So prompt.
else
{
policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature);
}
}
// The file is UnknownError, NotSigned, HashMismatch,
// NotTrusted, NotSupportedFileFormat
else
{
policyCheckPassed = false;
if (signature.Status == SignatureStatus.NotTrusted)
{
reason = new UnauthorizedAccessException(
StringUtil.Format(Authenticode.Reason_NotTrusted,
path,
signature.SignerCertificate.SubjectName.Name));
}
else
{
reason = new UnauthorizedAccessException(
StringUtil.Format(Authenticode.Reason_Unknown,
path,
signature.StatusMessage));
}
}
}
else // if(executionPolicy == ExecutionPolicy.Restricted)
{
// Deny everything
policyCheckPassed = false;
// But accept mshxml files from publishers that we
// trust, or files in the system protected directories
bool reasonSet = false;
if (string.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase))
{
string[] trustedDirectories = new string[]
{
Environment.GetFolderPath(Environment.SpecialFolder.System),
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
};
foreach (string trustedDirectory in trustedDirectories)
{
if (fi.FullName.StartsWith(trustedDirectory, StringComparison.OrdinalIgnoreCase))
policyCheckPassed = true;
}
if (!policyCheckPassed)
{
// Get the signature of the file.
Signature signature = GetSignatureWithEncodingRetry(path, script);
// The file is signed by a trusted publisher
if (signature.Status == SignatureStatus.Valid)
{
if (IsTrustedPublisher(signature, path))
{
policyCheckPassed = true;
}
// The file is signed by an unknown publisher,
// So prompt.
else
{
policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature);
reasonSet = true;
}
}
}
}
if (!policyCheckPassed && !reasonSet)
{
reason = new UnauthorizedAccessException(
StringUtil.Format(Authenticode.Reason_RestrictedMode,
path));
}
}
return policyCheckPassed;
}
private static bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, Signature signature)
{
bool policyCheckPassed = false;
string reasonMessage;
RunPromptDecision decision = AuthenticodePrompt(path, signature, host);
switch (decision)
{
case RunPromptDecision.RunOnce:
policyCheckPassed = true; break;
case RunPromptDecision.AlwaysRun:
{
TrustPublisher(signature);
policyCheckPassed = true;
}
break;
case RunPromptDecision.DoNotRun:
policyCheckPassed = false;
reasonMessage = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
reason = new UnauthorizedAccessException(reasonMessage);
break;
case RunPromptDecision.NeverRun:
{
UntrustPublisher(signature);
reasonMessage = StringUtil.Format(Authenticode.Reason_NeverRun, path);
reason = new UnauthorizedAccessException(reasonMessage);
policyCheckPassed = false;
}
break;
}
return policyCheckPassed;
}
private static bool IsLocalFile(string filename)
{
#if UNIX
return true;
#else
SecurityZone zone = ClrFacade.GetFileSecurityZone(filename);
if (zone == SecurityZone.MyComputer ||
zone == SecurityZone.Intranet ||
zone == SecurityZone.Trusted)
{
return true;
}
return false;
#endif
}
// Checks that a publisher is trusted by the system or is one of
// the signed product binaries
private static bool IsTrustedPublisher(Signature signature, string file)
{
// Get the thumbprint of the current signature
X509Certificate2 signerCertificate = signature.SignerCertificate;
string thumbprint = signerCertificate.Thumbprint;
// See if it matches any in the list of trusted publishers
X509Store trustedPublishers = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
trustedPublishers.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 trustedCertificate in trustedPublishers.Certificates)
{
if (string.Equals(trustedCertificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase))
{
if (!IsUntrustedPublisher(signature, file))
{
return true;
}
}
}
return false;
}
private static bool IsUntrustedPublisher(Signature signature, string file)
{
// Get the thumbprint of the current signature
X509Certificate2 signerCertificate = signature.SignerCertificate;
string thumbprint = signerCertificate.Thumbprint;
// See if it matches any in the list of trusted publishers
X509Store trustedPublishers = new X509Store(StoreName.Disallowed, StoreLocation.CurrentUser);
trustedPublishers.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 trustedCertificate in trustedPublishers.Certificates)
{
if (string.Equals(trustedCertificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// Trust a publisher by adding it to the "Trusted Publishers" store.
/// </summary>
/// <param name="signature"></param>
private static void TrustPublisher(Signature signature)
{
// Get the certificate of the signer
X509Certificate2 signerCertificate = signature.SignerCertificate;
X509Store trustedPublishers = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
try
{
// Add it to the list of trusted publishers
trustedPublishers.Open(OpenFlags.ReadWrite);
trustedPublishers.Add(signerCertificate);
}
finally
{
trustedPublishers.Close();
}
}
private static void UntrustPublisher(Signature signature)
{
// Get the certificate of the signer
X509Certificate2 signerCertificate = signature.SignerCertificate;
X509Store untrustedPublishers = new X509Store(StoreName.Disallowed, StoreLocation.CurrentUser);
X509Store trustedPublishers = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
// Remove it from the list of trusted publishers
try
{
// Remove the signer, if it's there
trustedPublishers.Open(OpenFlags.ReadWrite);
trustedPublishers.Remove(signerCertificate);
}
finally
{
trustedPublishers.Close();
}
try
{
// Add it to the list of untrusted publishers
untrustedPublishers.Open(OpenFlags.ReadWrite);
untrustedPublishers.Add(signerCertificate);
}
finally
{
untrustedPublishers.Close();
}
}
// Check the signature via the SIP which should never erroneously validate an invalid signature
// or altered script.
private static Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script)
{
// Invoke the SIP directly with the most simple method
Signature signature = SignatureHelper.GetSignature(path, fileContent: null);
if (signature.Status == SignatureStatus.Valid)
{
return signature;
}
// try harder to validate the signature by being explicit about encoding
// and providing the script contents
byte[] bytesWithBom = GetContentBytesWithBom(script.OriginalEncoding, script.ScriptContents);
signature = SignatureHelper.GetSignature(path, bytesWithBom);
// A last ditch effort -
// If the file was originally ASCII or UTF8, the SIP may have added the Unicode BOM
if (signature.Status != SignatureStatus.Valid
&& script.OriginalEncoding != Encoding.Unicode)
{
bytesWithBom = GetContentBytesWithBom(Encoding.Unicode, script.ScriptContents);
Signature fallbackSignature = SignatureHelper.GetSignature(path, bytesWithBom);
if (fallbackSignature.Status == SignatureStatus.Valid)
signature = fallbackSignature;
}
return signature;
}
private static byte[] GetContentBytesWithBom(Encoding encoding, string scriptContent)
{
ReadOnlySpan<byte> bomBytes = encoding.Preamble;
byte[] contentBytes = encoding.GetBytes(scriptContent);
byte[] bytesWithBom = new byte[bomBytes.Length + contentBytes.Length];
bomBytes.CopyTo(bytesWithBom);
contentBytes.CopyTo(bytesWithBom, index: bomBytes.Length);
return bytesWithBom;
}
#endregion signing check
/// <summary>
/// Determines if should run the specified command. Please see the
/// class summary for an overview of the semantics enforced by this
/// authorization manager.
/// </summary>
/// <param name="commandInfo">
/// The command to be run.
/// </param>
/// <param name="origin">
/// The origin of the command.
/// </param>
/// <param name="host">
/// The PSHost executing the command.
/// </param>
/// <param name="reason">
/// If access is denied, this parameter provides a specialized
/// Exception as the reason.
/// </param>
/// <returns>
/// True if the command should be run. False otherwise.
/// </returns>
/// <exception cref="System.ArgumentException">
/// CommandInfo is invalid. This may occur if
/// commandInfo.Name is null or empty.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// CommandInfo is null.
/// </exception>
/// <exception cref="System.IO.FileNotFoundException">
/// The file specified by commandInfo.Path is not found.
/// </exception>
protected internal override bool ShouldRun(CommandInfo commandInfo,
CommandOrigin origin,
PSHost host,
out Exception reason)
{
Dbg.Diagnostics.Assert(commandInfo != null, "caller should validate the parameter");
bool allowRun = false;
reason = null;
Utils.CheckArgForNull(commandInfo, "commandInfo");
Utils.CheckArgForNullOrEmpty(commandInfo.Name, "commandInfo.Name");
switch (commandInfo.CommandType)
{
case CommandTypes.Cmdlet:
// Always allow cmdlets to run
allowRun = true;
break;
case CommandTypes.Alias:
//
// we do not care about verifying an alias as we will
// get subsequent call(s) for commands/scripts
// when the alias is expanded.
//
allowRun = true;
break;
case CommandTypes.Function:
case CommandTypes.Filter:
case CommandTypes.Configuration:
//
// we do not check functions/filters.
// we only perform script level check.
//
allowRun = true;
break;
case CommandTypes.Script:
//
// Allow scripts that are built into the
// runspace configuration to run.
//
allowRun = true;
break;
case CommandTypes.ExternalScript:
if (commandInfo is not ExternalScriptInfo si)
{
reason = PSTraceSource.NewArgumentException("scriptInfo");
}
else
{
bool etwEnabled = ParserEventSource.Log.IsEnabled();
if (etwEnabled)
{
ParserEventSource.Log.CheckSecurityStart(si.Path);
}
allowRun = CheckPolicy(si, host, out reason);
if (etwEnabled)
{
ParserEventSource.Log.CheckSecurityStop(si.Path);
}
}
break;
case CommandTypes.Application:
//
// We do not check executables -- that is done by Windows
//
allowRun = true;
break;
}
return allowRun;
}
private static RunPromptDecision AuthenticodePrompt(string path,
Signature signature,
PSHost host)
{
if ((host == null) || (host.UI == null))
{
return RunPromptDecision.DoNotRun;
}
RunPromptDecision decision = RunPromptDecision.DoNotRun;
if (signature == null)
{
return decision;
}
switch (signature.Status)
{
//
// we do not allow execution in any one of the
// following cases
//
case SignatureStatus.UnknownError:
case SignatureStatus.NotSigned:
case SignatureStatus.HashMismatch:
case SignatureStatus.NotSupportedFileFormat:
decision = RunPromptDecision.DoNotRun;
break;
case SignatureStatus.Valid:
Collection<ChoiceDescription> choices = GetAuthenticodePromptChoices();
string promptCaption =
Authenticode.AuthenticodePromptCaption;
string promptText;
if (signature.SignerCertificate == null)
{
promptText =
StringUtil.Format(Authenticode.AuthenticodePromptText_UnknownPublisher,
path);
}
else
{
promptText =
StringUtil.Format(Authenticode.AuthenticodePromptText,
path,
signature.SignerCertificate.SubjectName.Name
);
}
int userChoice =
host.UI.PromptForChoice(promptCaption,
promptText,
choices,
(int)RunPromptDecision.DoNotRun);
decision = (RunPromptDecision)userChoice;
break;
//
// if the publisher is not trusted, we prompt and
// ask the user if s/he wants to allow it to run
//
default:
decision = RunPromptDecision.DoNotRun;
break;
}
return decision;
}
private static RunPromptDecision RemoteFilePrompt(string path, PSHost host)
{
if ((host == null) || (host.UI == null))
{
return RunPromptDecision.DoNotRun;
}
Collection<ChoiceDescription> choices = GetRemoteFilePromptChoices();
string promptCaption =
Authenticode.RemoteFilePromptCaption;
string promptText =
StringUtil.Format(Authenticode.RemoteFilePromptText,
path);
int userChoice = host.UI.PromptForChoice(promptCaption,
promptText,
choices,
0);
switch (userChoice)
{
case 0: return RunPromptDecision.DoNotRun;
case 1: return RunPromptDecision.RunOnce;
case 2: return RunPromptDecision.Suspend;
default: return RunPromptDecision.DoNotRun;
}
}
private static Collection<ChoiceDescription> GetAuthenticodePromptChoices()
{
Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
string neverRun = Authenticode.Choice_NeverRun;
string neverRunHelp = Authenticode.Choice_NeverRun_Help;
string doNotRun = Authenticode.Choice_DoNotRun;
string doNotRunHelp = Authenticode.Choice_DoNotRun_Help;
string runOnce = Authenticode.Choice_RunOnce;
string runOnceHelp = Authenticode.Choice_RunOnce_Help;
string alwaysRun = Authenticode.Choice_AlwaysRun;
string alwaysRunHelp = Authenticode.Choice_AlwaysRun_Help;
choices.Add(new ChoiceDescription(neverRun, neverRunHelp));
choices.Add(new ChoiceDescription(doNotRun, doNotRunHelp));
choices.Add(new ChoiceDescription(runOnce, runOnceHelp));
choices.Add(new ChoiceDescription(alwaysRun, alwaysRunHelp));
return choices;
}
private static Collection<ChoiceDescription> GetRemoteFilePromptChoices()
{
Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
string doNotRun = Authenticode.Choice_DoNotRun;
string doNotRunHelp = Authenticode.Choice_DoNotRun_Help;
string runOnce = Authenticode.Choice_RunOnce;
string runOnceHelp = Authenticode.Choice_RunOnce_Help;
string suspend = Authenticode.Choice_Suspend;
string suspendHelp = Authenticode.Choice_Suspend_Help;
choices.Add(new ChoiceDescription(doNotRun, doNotRunHelp));
choices.Add(new ChoiceDescription(runOnce, runOnceHelp));
choices.Add(new ChoiceDescription(suspend, suspendHelp));
return choices;
}
}
}
|