protected override void ProcessRecord()
        {
            string shellID         = base.Context.ShellID;
            string executionPolicy = SecuritySupport.GetExecutionPolicy(this.ExecutionPolicy);

            if (this.ShouldProcessPolicyChange(executionPolicy))
            {
                SecuritySupport.SetExecutionPolicy(this.executionPolicyScope, this.ExecutionPolicy, shellID);
                if (this.ExecutionPolicy != ExecutionPolicy.Undefined)
                {
                    string str = SecuritySupport.GetExecutionPolicy(shellID).ToString();
                    if (!string.Equals(str, executionPolicy, StringComparison.OrdinalIgnoreCase))
                    {
                        string      str1 = StringUtil.Format(ExecutionPolicyCommands.ExecutionPolicyOverridden, str);
                        string      executionPolicyOverriddenRecommendedAction = ExecutionPolicyCommands.ExecutionPolicyOverriddenRecommendedAction;
                        ErrorRecord errorRecord = new ErrorRecord(new SecurityException(), "ExecutionPolicyOverride", ErrorCategory.PermissionDenied, null);
                        errorRecord.ErrorDetails = new ErrorDetails(str1);
                        errorRecord.ErrorDetails.RecommendedAction = executionPolicyOverriddenRecommendedAction;
                        base.ThrowTerminatingError(errorRecord);
                    }
                }
                PSSQMAPI.UpdateExecutionPolicy(shellID, this.ExecutionPolicy);
                PSEtwLog.LogSettingsEvent(MshLog.GetLogContext(base.Context, base.MyInvocation), EtwLoggingStrings.ExecutionPolicyName, executionPolicy, null);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Set the desired execution policy.
        /// </summary>
        protected override void ProcessRecord()
        {
            string shellId         = base.Context.ShellID;
            string executionPolicy = SecuritySupport.GetExecutionPolicy(ExecutionPolicy);

            if (ShouldProcessPolicyChange(executionPolicy))
            {
                try
                {
                    SecuritySupport.SetExecutionPolicy(_executionPolicyScope, ExecutionPolicy, shellId);
                }
                catch (UnauthorizedAccessException exception)
                {
                    OnAccessDeniedError(exception);
                }
                catch (System.Security.SecurityException exception)
                {
                    OnAccessDeniedError(exception);
                }

                // Ensure it is now the effective execution policy
                if (ExecutionPolicy != ExecutionPolicy.Undefined)
                {
                    string effectiveExecutionPolicy = SecuritySupport.GetExecutionPolicy(shellId).ToString();
                    if (!string.Equals(effectiveExecutionPolicy, executionPolicy, StringComparison.OrdinalIgnoreCase))
                    {
                        string message           = StringUtil.Format(ExecutionPolicyCommands.ExecutionPolicyOverridden, effectiveExecutionPolicy);
                        string recommendedAction = ExecutionPolicyCommands.ExecutionPolicyOverriddenRecommendedAction;

                        ErrorRecord errorRecord = new ErrorRecord(
                            new System.Security.SecurityException(),
                            "ExecutionPolicyOverride",
                            ErrorCategory.PermissionDenied,
                            null);

                        errorRecord.ErrorDetails = new ErrorDetails(message);
                        errorRecord.ErrorDetails.RecommendedAction = recommendedAction;
                        ThrowTerminatingError(errorRecord);
                    }
                }

#if !CORECLR
                PSEtwLog.LogSettingsEvent(MshLog.GetLogContext(Context, MyInvocation),
                                          EtwLoggingStrings.ExecutionPolicyName, executionPolicy, null);
#endif
            }
        }//End ProcessRecord()
Esempio n. 3
0
        /// <summary>
        /// Outputs the execution policy.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (_list && _scopeSpecified)
            {
                string message = ExecutionPolicyCommands.ListAndScopeSpecified;

                ErrorRecord errorRecord = new ErrorRecord(
                    new InvalidOperationException(),
                    "ListAndScopeSpecified",
                    ErrorCategory.InvalidOperation,
                    null);

                errorRecord.ErrorDetails = new ErrorDetails(message);
                ThrowTerminatingError(errorRecord);

                return;
            }

            string shellId = base.Context.ShellID;

            if (_list)
            {
                foreach (ExecutionPolicyScope scope in SecuritySupport.ExecutionPolicyScopePreferences)
                {
                    PSObject outputObject = new PSObject();

                    ExecutionPolicy policy    = SecuritySupport.GetExecutionPolicy(shellId, scope);
                    PSNoteProperty  inputNote = new PSNoteProperty(
                        "Scope", scope);
                    outputObject.Properties.Add(inputNote);
                    inputNote = new PSNoteProperty(
                        "ExecutionPolicy", policy);
                    outputObject.Properties.Add(inputNote);

                    WriteObject(outputObject);
                }
            }
            else if (_scopeSpecified)
            {
                WriteObject(SecuritySupport.GetExecutionPolicy(shellId, _executionPolicyScope));
            }
            else
            {
                WriteObject(SecuritySupport.GetExecutionPolicy(shellId));
            }
        } //End BeginProcess()
 protected override void BeginProcessing()
 {
     if (!this.list || !this.scopeSpecified)
     {
         string shellID = base.Context.ShellID;
         if (!this.list)
         {
             if (!this.scopeSpecified)
             {
                 base.WriteObject(SecuritySupport.GetExecutionPolicy(shellID));
                 return;
             }
             else
             {
                 base.WriteObject(SecuritySupport.GetExecutionPolicy(shellID, this.executionPolicyScope));
                 return;
             }
         }
         else
         {
             ExecutionPolicyScope[] executionPolicyScopePreferences = SecuritySupport.ExecutionPolicyScopePreferences;
             for (int i = 0; i < (int)executionPolicyScopePreferences.Length; i++)
             {
                 ExecutionPolicyScope executionPolicyScope = executionPolicyScopePreferences[i];
                 PSObject             pSObject             = new PSObject();
                 ExecutionPolicy      executionPolicy      = SecuritySupport.GetExecutionPolicy(shellID, executionPolicyScope);
                 PSNoteProperty       pSNoteProperty       = new PSNoteProperty("Scope", (object)executionPolicyScope);
                 pSObject.Properties.Add(pSNoteProperty);
                 pSNoteProperty = new PSNoteProperty("ExecutionPolicy", (object)executionPolicy);
                 pSObject.Properties.Add(pSNoteProperty);
                 base.WriteObject(pSObject);
             }
             return;
         }
     }
     else
     {
         string      listAndScopeSpecified = ExecutionPolicyCommands.ListAndScopeSpecified;
         ErrorRecord errorRecord           = new ErrorRecord(new InvalidOperationException(), "ListAndScopeSpecified", ErrorCategory.InvalidOperation, null);
         errorRecord.ErrorDetails = new ErrorDetails(listAndScopeSpecified);
         base.ThrowTerminatingError(errorRecord);
         return;
     }
 }
Esempio n. 5
0
        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);

            // See if they want to bypass the authorization manager
            if (_executionPolicy == ExecutionPolicy.Bypass)
            {
                return(true);
            }

            // 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);
                }
            }

            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[]
                    { Platform.GetFolderPath(Environment.SpecialFolder.System),
                      Platform.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);
        }
Esempio n. 6
0
        private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason)
        {
            bool flag1 = false;

            reason = (Exception)null;
            string path = script.Path;

            if (path.IndexOf('\\') < 0)
            {
                throw PSAuthorizationManager.tracer.NewArgumentException("path");
            }
            FileInfo fileInfo = path.LastIndexOf('\\') != path.Length - 1 ? new FileInfo(path) : throw PSAuthorizationManager.tracer.NewArgumentException("path");

            if (!fileInfo.Exists)
            {
                return(false);
            }
            if (!PSAuthorizationManager.IsSupportedExtension(fileInfo.Extension) || this.IsProductBinary(path))
            {
                return(true);
            }
            this.executionPolicy = SecuritySupport.GetExecutionPolicy(this.shellId);
            if (this.executionPolicy == ExecutionPolicy.Bypass)
            {
                return(true);
            }
            if (SecuritySupport.GetSaferPolicy(path) == SaferPolicy.Disallowed)
            {
                string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_DisallowedBySafer", (object)path);
                reason = (Exception) new UnauthorizedAccessException(message);
                return(false);
            }
            if (this.executionPolicy == ExecutionPolicy.Unrestricted)
            {
                if (!this.IsLocalFile(fileInfo.FullName))
                {
                    if (string.IsNullOrEmpty(script.ScriptContents))
                    {
                        string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_FileContentUnavailable", (object)path);
                        reason = (Exception) new UnauthorizedAccessException(message);
                        return(false);
                    }
                    System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script);
                    if (withEncodingRetry.Status == SignatureStatus.Valid && this.IsTrustedPublisher(withEncodingRetry, path))
                    {
                        flag1 = true;
                    }
                    if (!flag1)
                    {
                        PSAuthorizationManager.RunPromptDecision runPromptDecision;
                        do
                        {
                            runPromptDecision = this.RemoteFilePrompt(path, host);
                            if (runPromptDecision == PSAuthorizationManager.RunPromptDecision.Suspend)
                            {
                                host.EnterNestedPrompt();
                            }
                        }while (runPromptDecision == PSAuthorizationManager.RunPromptDecision.Suspend);
                        switch (runPromptDecision - 1)
                        {
                        case PSAuthorizationManager.RunPromptDecision.DoNotRun:
                            flag1 = true;
                            break;

                        default:
                            flag1 = false;
                            string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_DoNotRun", (object)path);
                            reason = (Exception) new UnauthorizedAccessException(message);
                            break;
                        }
                    }
                }
                else
                {
                    flag1 = true;
                }
            }
            else if (this.IsLocalFile(fileInfo.FullName) && this.executionPolicy == ExecutionPolicy.RemoteSigned)
            {
                flag1 = true;
            }
            else if (this.executionPolicy == ExecutionPolicy.AllSigned || this.executionPolicy == ExecutionPolicy.RemoteSigned)
            {
                if (string.IsNullOrEmpty(script.ScriptContents))
                {
                    string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_FileContentUnavailable", (object)path);
                    reason = (Exception) new UnauthorizedAccessException(message);
                    return(false);
                }
                System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script);
                if (withEncodingRetry.Status == SignatureStatus.Valid)
                {
                    flag1 = this.IsTrustedPublisher(withEncodingRetry, path) || this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, withEncodingRetry);
                }
                else
                {
                    flag1 = false;
                    if (withEncodingRetry.Status == SignatureStatus.NotTrusted)
                    {
                        reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_NotTrusted", (object)path, (object)withEncodingRetry.SignerCertificate.SubjectName.Name));
                    }
                    else
                    {
                        reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_Unknown", (object)path, (object)withEncodingRetry.StatusMessage));
                    }
                }
            }
            else
            {
                flag1 = false;
                bool flag2 = false;
                if (string.Equals(fileInfo.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase))
                {
                    string[] strArray = new string[2]
                    {
                        Environment.GetFolderPath(Environment.SpecialFolder.System),
                        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
                    };
                    foreach (string str in strArray)
                    {
                        if (fileInfo.FullName.StartsWith(str, StringComparison.OrdinalIgnoreCase))
                        {
                            flag1 = true;
                        }
                    }
                    if (!flag1)
                    {
                        System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script);
                        if (withEncodingRetry.Status == SignatureStatus.Valid)
                        {
                            if (this.IsTrustedPublisher(withEncodingRetry, path))
                            {
                                flag1 = true;
                            }
                            else
                            {
                                flag1 = this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, withEncodingRetry);
                                flag2 = true;
                            }
                        }
                    }
                }
                if (!flag1 && !flag2)
                {
                    reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_RestrictedMode", (object)path));
                }
            }
            return(flag1);
        }
        private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason)
        {
            string str2;
            bool   flag = false;

            reason = null;
            string path = script.Path;

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                if (path.IndexOf('\\') < 0)
                {
                    throw PSTraceSource.NewArgumentException("path");
                }
                if (path.LastIndexOf('\\') == (path.Length - 1))
                {
                    throw PSTraceSource.NewArgumentException("path");
                }
            }
            FileInfo info = new FileInfo(path);

            if (!info.Exists)
            {
                reason = new FileNotFoundException(path);
                return(false);
            }
            if (!IsSupportedExtension(info.Extension))
            {
                return(true);
            }
            if (this.IsProductBinary(path))
            {
                return(true);
            }
            this.executionPolicy = SecuritySupport.GetExecutionPolicy(this.shellId);
            if (this.executionPolicy == ExecutionPolicy.Bypass)
            {
                return(true);
            }
            SaferPolicy disallowed = SaferPolicy.Disallowed;
            int         num        = 0;
            bool        flag2      = false;

            while (!flag2 && (num < 5))
            {
                try
                {
                    disallowed = SecuritySupport.GetSaferPolicy(path);
                    flag2      = true;
                    continue;
                }
                catch (Win32Exception)
                {
                    if (num > 4)
                    {
                        throw;
                    }
                    num++;
                    Thread.Sleep(100);
                    continue;
                }
            }
            if (disallowed == SaferPolicy.Disallowed)
            {
                str2   = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path);
                reason = new UnauthorizedAccessException(str2);
                return(false);
            }
            if (this.executionPolicy != ExecutionPolicy.Unrestricted)
            {
                if (this.IsLocalFile(info.FullName) && (this.executionPolicy == ExecutionPolicy.RemoteSigned))
                {
                    return(true);
                }
                if ((this.executionPolicy == ExecutionPolicy.AllSigned) || (this.executionPolicy == ExecutionPolicy.RemoteSigned))
                {
                    if (string.IsNullOrEmpty(script.ScriptContents))
                    {
                        str2   = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
                        reason = new UnauthorizedAccessException(str2);
                        return(false);
                    }
                    System.Management.Automation.Signature signature = this.GetSignatureWithEncodingRetry(path, script);
                    if (signature.Status == SignatureStatus.Valid)
                    {
                        return(this.IsTrustedPublisher(signature, path) || this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature));
                    }
                    flag = false;
                    if (signature.Status == SignatureStatus.NotTrusted)
                    {
                        reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_NotTrusted, path, signature.SignerCertificate.SubjectName.Name));
                        return(flag);
                    }
                    reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_Unknown, path, signature.StatusMessage));
                    return(flag);
                }
                flag = false;
                bool flag3 = false;
                if (string.Equals(info.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase))
                {
                    string[] strArray = new string[] { Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) };
                    foreach (string str3 in strArray)
                    {
                        if (info.FullName.StartsWith(str3, StringComparison.OrdinalIgnoreCase))
                        {
                            flag = true;
                        }
                    }
                    if (!flag)
                    {
                        System.Management.Automation.Signature signature3 = this.GetSignatureWithEncodingRetry(path, script);
                        if (signature3.Status == SignatureStatus.Valid)
                        {
                            if (this.IsTrustedPublisher(signature3, path))
                            {
                                flag = true;
                            }
                            else
                            {
                                flag  = this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature3);
                                flag3 = true;
                            }
                        }
                    }
                }
                if (!flag && !flag3)
                {
                    reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_RestrictedMode, path));
                }
                return(flag);
            }
            if (this.IsLocalFile(info.FullName))
            {
                return(true);
            }
            if (string.IsNullOrEmpty(script.ScriptContents))
            {
                str2   = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
                reason = new UnauthorizedAccessException(str2);
                return(false);
            }
            System.Management.Automation.Signature signatureWithEncodingRetry = this.GetSignatureWithEncodingRetry(path, script);
            if ((signatureWithEncodingRetry.Status == SignatureStatus.Valid) && this.IsTrustedPublisher(signatureWithEncodingRetry, path))
            {
                flag = true;
            }
            if (flag)
            {
                return(flag);
            }
            RunPromptDecision doNotRun = RunPromptDecision.DoNotRun;

Label_0149:
            doNotRun = this.RemoteFilePrompt(path, host);
            if (doNotRun == RunPromptDecision.Suspend)
            {
                host.EnterNestedPrompt();
            }
            switch (doNotRun)
            {
            case RunPromptDecision.RunOnce:
                return(true);

            case RunPromptDecision.Suspend:
                goto Label_0149;
            }
            flag   = false;
            str2   = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
            reason = new UnauthorizedAccessException(str2);
            return(flag);
        }
        internal List <string> GenerateProxyModule(DirectoryInfo moduleRootDirectory, string fileNamePrefix, Encoding encoding, bool force, List <CommandMetadata> listOfCommandMetadata, Dictionary <string, string> alias2resolvedCommandName, List <ExtendedTypeDefinition> listOfFormatData, X509Certificate2 certificate)
        {
            List <string> list = new List <string>();
            string        str  = Path.Combine(moduleRootDirectory.FullName, fileNamePrefix);
            FileMode      mode = force ? FileMode.OpenOrCreate : FileMode.CreateNew;

            list.Add(str + ".psm1");
            FileStream stream = new FileStream(str + ".psm1", mode, FileAccess.Write, FileShare.None);

            using (TextWriter writer = new StreamWriter(stream, encoding))
            {
                if (listOfCommandMetadata == null)
                {
                    listOfCommandMetadata = new List <CommandMetadata>();
                }
                this.GenerateModuleHeader(writer);
                this.GenerateHelperFunctions(writer);
                this.GenerateCommandProxy(writer, listOfCommandMetadata);
                this.GenerateExportDeclaration(writer, listOfCommandMetadata);
                this.GenerateAliases(writer, alias2resolvedCommandName);
                stream.SetLength(stream.Position);
            }
            list.Add(str + ".format.ps1xml");
            FileStream stream2 = new FileStream(str + ".format.ps1xml", mode, FileAccess.Write, FileShare.None);

            using (TextWriter writer2 = new StreamWriter(stream2, encoding))
            {
                if (listOfFormatData == null)
                {
                    listOfFormatData = new List <ExtendedTypeDefinition>();
                }
                this.GenerateFormatFile(writer2, listOfFormatData);
                stream2.SetLength(stream2.Position);
            }
            switch (SecuritySupport.GetExecutionPolicy(Utils.DefaultPowerShellShellID))
            {
            case ExecutionPolicy.Restricted:
            case ExecutionPolicy.AllSigned:
            {
                if (certificate == null)
                {
                    throw new PSInvalidOperationException(ImplicitRemotingStrings.CertificateNeeded);
                }
                string fileName = str + ".psm1";
                try
                {
                    SignatureHelper.SignFile(SigningOption.AddFullCertificateChainExceptRoot, fileName, certificate, string.Empty, null);
                    fileName = str + ".format.ps1xml";
                    SignatureHelper.SignFile(SigningOption.AddFullCertificateChainExceptRoot, fileName, certificate, string.Empty, null);
                }
                catch (Exception exception)
                {
                    throw new PSInvalidOperationException(StringUtil.Format(ImplicitRemotingStrings.InvalidSigningOperation, fileName), exception);
                }
                break;
            }
            }
            list.Add(str + ".psd1");
            FileInfo   info    = new FileInfo(str + ".psd1");
            FileStream stream3 = new FileStream(info.FullName, mode, FileAccess.Write, FileShare.None);

            using (TextWriter writer3 = new StreamWriter(stream3, encoding))
            {
                this.GenerateManifest(writer3, str + ".psm1", str + ".format.ps1xml");
                stream3.SetLength(stream3.Position);
            }
            PSPrimitiveDictionary applicationArguments = this.GetApplicationArguments();

            if (applicationArguments != null)
            {
                string item = Path.Combine(moduleRootDirectory.FullName, "ApplicationArguments.xml");
                list.Add(item);
                using (XmlWriter writer4 = XmlWriter.Create(item))
                {
                    Serializer serializer = new Serializer(writer4);
                    serializer.Serialize(applicationArguments);
                    serializer.Done();
                }
            }
            return(list);
        }