Exemplo n.º 1
0
 public object VisitThrowStatement(ThrowStatementAst throwStatementAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 2
0
 public object VisitParamBlock(ParamBlockAst paramBlockAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(paramBlockAst));
 }
Exemplo n.º 3
0
 public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(typeConstraintAst));
 }
Exemplo n.º 4
0
 public object VisitMemberExpression(MemberExpressionAst memberExpressionAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(memberExpressionAst));
 }
Exemplo n.º 5
0
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(errorExpressionAst));
 }
        /// <summary>
        /// Removes pssnapins from the current console file.
        /// </summary>
        /// <remarks>
        /// The pssnapin is not unloaded from the current engine. So all the cmdlets that are
        /// represented by this pssnapin will continue to work.
        /// </remarks>
        protected override void ProcessRecord()
        {
            foreach (string psSnapIn in _pssnapins)
            {
                Collection <PSSnapInInfo> snapIns = GetSnapIns(psSnapIn);

                // snapIns won't be null..
                Diagnostics.Assert(snapIns != null, "GetSnapIns() returned null");
                if (snapIns.Count == 0)
                {
                    WriteNonTerminatingError(psSnapIn, "NoPSSnapInsFound",
                                             PSTraceSource.NewArgumentException(psSnapIn,
                                                                                MshSnapInCmdletResources.NoPSSnapInsFound, psSnapIn),
                                             ErrorCategory.InvalidArgument);

                    continue;
                }

                foreach (PSSnapInInfo snapIn in snapIns)
                {
                    // confirm the operation first
                    // this is always false if WhatIf is set
                    if (ShouldProcess(snapIn.Name))
                    {
                        Exception exception = null;

                        if (this.Runspace == null && this.Context.InitialSessionState != null)
                        {
                            try
                            {
                                // Check if this snapin can be removed

                                // Monad has specific restrictions on the mshsnapinid like
                                // mshsnapinid should be A-Za-z0-9.-_ etc.
                                PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(snapIn.Name);

                                if (MshConsoleInfo.IsDefaultPSSnapIn(snapIn.Name, this.Context.InitialSessionState.defaultSnapins))
                                {
                                    throw PSTraceSource.NewArgumentException(snapIn.Name, ConsoleInfoErrorStrings.CannotRemoveDefault, snapIn.Name);
                                }

                                // Handle the initial session state case...
                                InitialSessionState iss = InitialSessionState.Create();
                                PSSnapInException   warning;

                                // Get the snapin information...
                                iss.ImportPSSnapIn(snapIn, out warning);
                                iss.Unbind(Context);
                                Context.InitialSessionState.ImportedSnapins.Remove(snapIn.Name);
                            }
                            catch (PSArgumentException ae)
                            {
                                exception = ae;
                            }

                            if (exception != null)
                            {
                                WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument);
                            }
                        }
                        else
                        {
                            try
                            {
                                PSSnapInException warning = null;

                                PSSnapInInfo psSnapInInfo = this.Runspace.RemovePSSnapIn(snapIn.Name, out warning);

                                if (warning != null)
                                {
                                    WriteNonTerminatingError(snapIn.Name, "RemovePSSnapInRead", warning, ErrorCategory.InvalidData);
                                }

                                if (_passThru)
                                {
                                    // Load the pssnapin info properties that are localizable and redirected in the registry
                                    psSnapInInfo.LoadIndirectResources(ResourceReader);
                                    WriteObject(psSnapInInfo);
                                }
                            }
                            catch (PSArgumentException ae)
                            {
                                exception = ae;
                            }

                            if (exception != null)
                            {
                                WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument);
                            }
                        }
                    } // ShouldContinue
                }
            }
        }
        /// <summary>
        /// Joins two strings with a path a provider specific path separator.
        /// </summary>
        /// <param name="parent">
        /// The parent segment of a path to be joined with the child.
        /// </param>
        /// <param name="child">
        /// The child segment of a path to be joined with the parent.
        /// </param>
        /// <param name="childIsLeaf">
        /// Indicate that the <paramref name="child"/> is the name of a child item that's guaranteed to exist
        /// </param>
        /// <remarks>
        /// If the <paramref name="childIsLeaf"/> is True, then we don't normalize the child path, and would do
        /// some checks to decide whether to normalize the parent path.
        /// </remarks>
        /// <returns>New path string.</returns>
        protected string MakePath(string parent, string child, bool childIsLeaf)
        {
            using (PSTransactionManager.GetEngineProtectionScope())
            {
                string result = null;

                if (parent is null &&
                    child is null)
                {
                    throw PSTraceSource.NewArgumentException(nameof(parent));
                }

                if (string.IsNullOrEmpty(parent) &&
                    string.IsNullOrEmpty(child))
                {
                    result = string.Empty;
                }
                else if (string.IsNullOrEmpty(parent) &&
                         !string.IsNullOrEmpty(child))
                {
                    result = NormalizePath(child);
                }
                else if (!string.IsNullOrEmpty(parent) &&
                         (string.IsNullOrEmpty(child) ||
                          child.Equals(StringLiterals.DefaultPathSeparatorString, StringComparison.Ordinal) ||
                          child.Equals(StringLiterals.AlternatePathSeparatorString, StringComparison.Ordinal)))
                {
                    if (parent.EndsWith(StringLiterals.DefaultPathSeparator))
                    {
                        result = parent;
                    }
                    else
                    {
                        result = parent + StringLiterals.DefaultPathSeparator;
                    }
                }
                else
                {
                    // Both parts are not empty so join them
                    // 'childIsLeaf == true' indicates that 'child' is actually the name of a child item and
                    // guaranteed to exist. In this case, we don't normalize the child path.
                    if (childIsLeaf)
                    {
                        parent = NormalizePath(parent);
                    }
                    else
                    {
                        // Normalize the path so that only the default path separator is used as a
                        // separator even if the user types the alternate slash.
                        parent = NormalizePath(parent);
                        child  = NormalizePath(child);
                    }

                    ReadOnlySpan <char> appendChild = child.AsSpan();
                    if (child.StartsWith(StringLiterals.DefaultPathSeparator))
                    {
                        appendChild = appendChild.Slice(1);
                    }

                    result = IO.Path.Join(parent.AsSpan(), appendChild);
                }

                return(result);
            }
        }
Exemplo n.º 8
0
 public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 9
0
 public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 10
0
 public object VisitCommandParameter(CommandParameterAst commandParameterAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 11
0
 public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 12
0
 public object VisitCommandExpression(CommandExpressionAst commandExpressionAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 13
0
 public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 14
0
 public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 15
0
        /// <summary>
        /// Adds pssnapins to console file and loads the pssnapin dlls into
        /// the current monad runtime.
        /// </summary>
        /// <remarks>
        /// The new pssnapin information is not stored in the console file until
        /// the file is saved.
        /// </remarks>
        protected override void ProcessRecord()
        {
            // Cache for the information stored in the registry
            // update the cache the first time a wildcard is found..
            Collection <PSSnapInInfo> listToSearch = null;

            foreach (string pattern in _pssnapins)
            {
                Exception           exception = null;
                Collection <string> listToAdd = new Collection <string>();

                try
                {
                    // check whether there are any wildcard characters
                    bool doWildCardSearch = WildcardPattern.ContainsWildcardCharacters(pattern);
                    if (doWildCardSearch)
                    {
                        // wildcard found in the pattern
                        // Get all the possible candidates for current monad version
                        if (listToSearch == null)
                        {
                            // cache snapin registry information...

                            // For 3.0 PowerShell, we still use "1" as the registry version key for
                            // Snapin and Custom shell lookup/discovery.
                            // For 3.0 PowerShell, we use "3" as the registry version key only for Engine
                            // related data like ApplicationBase etc.
                            listToSearch = PSSnapInReader.ReadAll(PSVersionInfo.RegistryVersion1Key);
                        }

                        listToAdd = SearchListForPattern(listToSearch, pattern);

                        // listToAdd wont be null..
                        Diagnostics.Assert(listToAdd != null, "Pattern matching returned null");
                        if (listToAdd.Count == 0)
                        {
                            if (_passThru)
                            {
                                // passThru is specified and we have nothing to add...
                                WriteNonTerminatingError(pattern, "NoPSSnapInsFound",
                                                         PSTraceSource.NewArgumentException(pattern,
                                                                                            MshSnapInCmdletResources.NoPSSnapInsFound, pattern),
                                                         ErrorCategory.InvalidArgument);
                            }

                            continue;
                        }
                    }
                    else
                    {
                        listToAdd.Add(pattern);
                    }

                    // now add all the snapins for this pattern...
                    AddPSSnapIns(listToAdd);
                }
                catch (PSArgumentException ae)
                {
                    exception = ae;
                }
                catch (System.Security.SecurityException se)
                {
                    exception = se;
                }

                if (exception != null)
                {
                    WriteNonTerminatingError(pattern,
                                             "AddPSSnapInRead",
                                             exception,
                                             ErrorCategory.InvalidArgument);
                }
            }
        }
Exemplo n.º 16
0
 public object VisitBlockStatement(BlockStatementAst blockStatementAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 17
0
        /// <summary>
        /// Adds one or more snapins
        /// </summary>
        /// <param name="snapInList">List of snapin IDs</param>
        /// <remarks>
        /// This is a helper method and should not throw any
        /// exceptions. All exceptions are caught and displayed
        /// to the user using write* methods
        /// </remarks>
        private void AddPSSnapIns(Collection <string> snapInList)
        {
            if (snapInList == null)
            {
                // nothing to add
                return;
            }

            //BUGBUG TODO - brucepay - this is a workaround for not being able to dynamically update
            // the set of cmdlets in a runspace if there is no RunspaceConfiguration object.
            // This is a temporary fix to unblock remoting tests and need to be corrected/completed
            // before we can ship...

            // If there is no RunspaceConfig object, then
            // use an InitialSessionState object to gather and
            // bind the cmdlets from the snapins...
            if (Context.RunspaceConfiguration == null)
            {
                Collection <PSSnapInInfo> loadedSnapins = base.GetSnapIns(null);
                InitialSessionState       iss           = InitialSessionState.Create();
                bool isAtleastOneSnapinLoaded           = false;
                foreach (string snapIn in snapInList)
                {
                    if (InitialSessionState.IsEngineModule(snapIn))
                    {
                        WriteNonTerminatingError(snapIn, "LoadSystemSnapinAsModule",
                                                 PSTraceSource.NewArgumentException(snapIn,
                                                                                    MshSnapInCmdletResources.LoadSystemSnapinAsModule, snapIn),
                                                 ErrorCategory.InvalidArgument);
                    }
                    else
                    {
                        PSSnapInException warning;
                        try
                        {
                            // Read snapin data
                            PSSnapInInfo newPSSnapIn  = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), snapIn);
                            PSSnapInInfo psSnapInInfo = IsSnapInLoaded(loadedSnapins, newPSSnapIn);

                            // that means snapin is not already loaded ..so load the snapin
                            // now.
                            if (null == psSnapInInfo)
                            {
                                psSnapInInfo             = iss.ImportPSSnapIn(snapIn, out warning);
                                isAtleastOneSnapinLoaded = true;
                                Context.InitialSessionState.ImportedSnapins.Add(psSnapInInfo.Name, psSnapInInfo);
                            }
                            // Write psSnapInInfo object only if passthru is specified.
                            if (_passThru)
                            {
                                // Load the pssnapin info properties that are localizable and redirected in the registry
                                psSnapInInfo.LoadIndirectResources(ResourceReader);
                                WriteObject(psSnapInInfo);
                            }
                        }

                        catch (PSSnapInException pse)
                        {
                            WriteNonTerminatingError(snapIn, "AddPSSnapInRead", pse, ErrorCategory.InvalidData);
                        }
                    }
                }

                if (isAtleastOneSnapinLoaded)
                {
                    // Now update the session state with the new stuff...
                    iss.Bind(Context, /*updateOnly*/ true);
                }

                return;
            }

            foreach (string psSnapIn in snapInList)
            {
                Exception exception = null;

                try
                {
                    PSSnapInException warning = null;

                    PSSnapInInfo psSnapInInfo = this.Runspace.AddPSSnapIn(psSnapIn, out warning);

                    if (warning != null)
                    {
                        WriteNonTerminatingError(psSnapIn, "AddPSSnapInRead", warning, ErrorCategory.InvalidData);
                    }

                    // Write psSnapInInfo object only if passthru is specified.
                    if (_passThru)
                    {
                        // Load the pssnapin info properties that are localizable and redirected in the registry
                        psSnapInInfo.LoadIndirectResources(ResourceReader);
                        WriteObject(psSnapInInfo);
                    }
                }
                catch (PSArgumentException ae)
                {
                    exception = ae;
                }
                catch (PSSnapInException sle)
                {
                    exception = sle;
                }
                catch (System.Security.SecurityException se)
                {
                    exception = se;
                }

                if (exception != null)
                {
                    WriteNonTerminatingError(psSnapIn,
                                             "AddPSSnapInRead",
                                             exception,
                                             ErrorCategory.InvalidArgument);
                }
            }
        }
Exemplo n.º 18
0
 public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 19
0
        /// <summary>
        /// Constructs PSSnapInfo objects as requested by the user and writes them to the
        /// output buffer.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (_pssnapins != null)
            {
                foreach (string psSnapIn in _pssnapins)
                {
                    Exception exception = null;

                    try
                    {
                        Collection <PSSnapInInfo> psSnapInInfoList = GetSnapIns(psSnapIn);

                        // psSnapInInfoList wont be null..
                        Diagnostics.Assert(psSnapInInfoList != null, "ConsoleInfo.GetPSSnapIn returned null");
                        if (psSnapInInfoList.Count == 0)
                        {
                            WriteNonTerminatingError(psSnapIn, "NoPSSnapInsFound",
                                                     PSTraceSource.NewArgumentException(psSnapIn,
                                                                                        MshSnapInCmdletResources.NoPSSnapInsFound, psSnapIn),
                                                     ErrorCategory.InvalidArgument);

                            continue;
                        }

                        foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList)
                        {
                            // Load the pssnapin info properties that are localizable and redirected in the registry
                            pssnapinInfo.LoadIndirectResources(ResourceReader);
                            WriteObject(pssnapinInfo);
                        }
                    }
                    catch (System.Security.SecurityException se)
                    {
                        exception = se;
                    }
                    catch (PSArgumentException ae)
                    {
                        exception = ae;
                    }

                    if (exception != null)
                    {
                        WriteNonTerminatingError(psSnapIn, "GetPSSnapInRead", exception, ErrorCategory.InvalidArgument);
                    }
                }
            }
            else if (ShouldGetAll)
            {
                Exception exception = null;

                try
                {
                    Collection <PSSnapInInfo> psSnapInInfoList = PSSnapInReader.ReadAll();
                    foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList)
                    {
                        // Load the pssnapin info properties that are localizable and redirected in the registry
                        pssnapinInfo.LoadIndirectResources(ResourceReader);
                        WriteObject(pssnapinInfo);
                    }
                }
                catch (System.Security.SecurityException se)
                {
                    exception = se;
                }
                catch (PSArgumentException ae)
                {
                    exception = ae;
                }

                if (exception != null)
                {
                    WriteNonTerminatingError(this, "GetPSSnapInRead", exception, ErrorCategory.InvalidArgument);
                }
            }
            else
            {
                // this should never throw..
                Collection <PSSnapInInfo> psSnapInInfoList = GetSnapIns(null);
                foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList)
                {
                    // Load the pssnapin info properties that are localizable and redirected in the registry
                    pssnapinInfo.LoadIndirectResources(ResourceReader);
                    WriteObject(pssnapinInfo);
                }
            }
        }
Exemplo n.º 20
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);
            }
#if !CORECLR
            // 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);
                }
            }
#endif
            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);
        }
        /// <summary>
        /// Removes the child segment of a path and returns the remaining parent
        /// portion.
        /// </summary>
        /// <param name="path">
        /// A fully qualified provider specific path to an item. The item may or
        /// may not exist.
        /// </param>
        /// <param name="root">
        /// The fully qualified path to the root of a drive. This parameter may be null
        /// or empty if a mounted drive is not in use for this operation. If this parameter
        /// is not null or empty the result of the method should not be a path to a container
        /// that is a parent or in a different tree than the root.
        /// </param>
        /// <returns>
        /// The path of the parent of the path parameter.
        /// </returns>
        /// <remarks>
        /// This should be a lexical splitting of the path on the path separator character
        /// for the provider namespace. For example, the file system provider should look
        /// for the last "\" and return everything to the left of the "\".
        /// </remarks>
        protected virtual string GetParentPath(string path, string root)
        {
            using (PSTransactionManager.GetEngineProtectionScope())
            {
                string parentPath = null;

                // Verify the parameters

                if (string.IsNullOrEmpty(path))
                {
                    throw PSTraceSource.NewArgumentException(nameof(path));
                }

                if (root is null)
                {
                    if (PSDriveInfo != null)
                    {
                        root = PSDriveInfo.Root;
                    }
                }

                // Normalize the path

                path = NormalizePath(path);
                path = path.TrimEnd(StringLiterals.DefaultPathSeparator);
                string rootPath = string.Empty;

                if (root != null)
                {
                    rootPath = NormalizePath(root);
                }

                // Check to see if the path is equal to the root
                // of the virtual drive

                if (string.Equals(
                        path,
                        rootPath,
                        StringComparison.OrdinalIgnoreCase))
                {
                    parentPath = string.Empty;
                }
                else
                {
                    int lastIndex = path.LastIndexOf(StringLiterals.DefaultPathSeparator);

                    if (lastIndex != -1)
                    {
                        if (lastIndex == 0)
                        {
                            ++lastIndex;
                        }
                        // Get the parent directory

                        parentPath = path.Substring(0, lastIndex);
                    }
                    else
                    {
                        parentPath = string.Empty;
                    }
                }

                return(parentPath);
            }
        }
Exemplo n.º 22
0
        /// <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.Workflow:
            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:
                ExternalScriptInfo si = commandInfo as ExternalScriptInfo;
                if (si == null)
                {
                    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);
        }
Exemplo n.º 23
0
 public object VisitErrorStatement(ErrorStatementAst errorStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(errorStatementAst));
 }
Exemplo n.º 24
0
        /// <summary>
        /// This is the handler for MessageReceived event. It dispatches the data to various components
        /// that uses the data.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="fsmEventArg">
        /// This parameter contains the FSM event.
        /// </param>
        ///
        /// <exception cref="ArgumentNullException">
        /// If the parameter <paramref name="fsmEventArg"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If the parameter <paramref name="fsmEventArg"/> does not contain remote data.
        /// </exception>
        internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
        {
            using (s_trace.TraceEventHandlers())
            {
                if (fsmEventArg == null)
                {
                    throw PSTraceSource.NewArgumentNullException("fsmEventArg");
                }

                if (fsmEventArg.RemoteData == null)
                {
                    throw PSTraceSource.NewArgumentException("fsmEventArg");
                }

                Dbg.Assert(_state == RemoteSessionState.Established ||
                           _state == RemoteSessionState.EstablishedAndKeyExchanged ||
                           _state == RemoteSessionState.EstablishedAndKeyReceived ||
                           _state == RemoteSessionState.EstablishedAndKeySent,  //server session will never be in this state.. TODO- remove this
                           "State must be Established or EstablishedAndKeySent or EstablishedAndKeyReceived or EstablishedAndKeyExchanged");

                RemotingTargetInterface targetInterface = fsmEventArg.RemoteData.TargetInterface;
                RemotingDataType        dataType        = fsmEventArg.RemoteData.DataType;

                Guid clientRunspacePoolId;
                ServerRunspacePoolDriver runspacePoolDriver;
                //string errorMessage = null;

                RemoteDataEventArgs remoteDataForSessionArg = null;

                switch (targetInterface)
                {
                case RemotingTargetInterface.Session:
                {
                    switch (dataType)
                    {
                    // GETBACK
                    case RemotingDataType.CreateRunspacePool:
                        remoteDataForSessionArg = new RemoteDataEventArgs(fsmEventArg.RemoteData);
                        _session.SessionDataStructureHandler.RaiseDataReceivedEvent(remoteDataForSessionArg);
                        break;

                    default:
                        Dbg.Assert(false, "Should never reach here");
                        break;
                    }
                }
                break;

                case RemotingTargetInterface.RunspacePool:
                    // GETBACK
                    clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId;
                    runspacePoolDriver   = _session.GetRunspacePoolDriver(clientRunspacePoolId);

                    if (runspacePoolDriver != null)
                    {
                        runspacePoolDriver.DataStructureHandler.ProcessReceivedData(fsmEventArg.RemoteData);
                    }
                    else
                    {
                        s_trace.WriteLine(@"Server received data for Runspace (id: {0}), 
                                but the Runspace cannot be found", clientRunspacePoolId);

                        PSRemotingDataStructureException reasonOfFailure = new
                                                                           PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceCannotBeFound,
                                                                                                            clientRunspacePoolId);
                        RemoteSessionStateMachineEventArgs runspaceNotFoundArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure);
                        RaiseEvent(runspaceNotFoundArg);
                    }

                    break;

                case RemotingTargetInterface.PowerShell:
                    clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId;
                    runspacePoolDriver   = _session.GetRunspacePoolDriver(clientRunspacePoolId);

                    runspacePoolDriver.DataStructureHandler.DispatchMessageToPowerShell(fsmEventArg.RemoteData);
                    break;

                default:
                    s_trace.WriteLine("Server received data unknown targetInterface: {0}", targetInterface);

                    PSRemotingDataStructureException   reasonOfFailure2 = new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedRemotingTargetInterfaceType, targetInterface);
                    RemoteSessionStateMachineEventArgs unknownTargetArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure2);
                    RaiseEvent(unknownTargetArg);
                    break;
                }
            }
        }
Exemplo n.º 25
0
 public object VisitScriptBlock(ScriptBlockAst scriptBlockAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(scriptBlockAst));
 }
        /// <summary>
        /// This method is added to be backward compatible with V1 hosts w.r.t
        /// new PromptForChoice method added in PowerShell V2.
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="message"></param>
        /// <param name="choices"></param>
        /// <param name="defaultChoices"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">
        /// 1. Choices is null.
        /// 2. Choices.Count = 0
        /// 3. DefaultChoice is either less than 0 or greater than Choices.Count
        /// </exception>
        private Collection <int> EmulatePromptForMultipleChoice(string caption,
                                                                string message,
                                                                Collection <ChoiceDescription> choices,
                                                                IEnumerable <int> defaultChoices)
        {
            Dbg.Assert(_externalUI != null, "externalUI cannot be null.");

            if (choices == null)
            {
                throw PSTraceSource.NewArgumentNullException("choices");
            }

            if (choices.Count == 0)
            {
                throw PSTraceSource.NewArgumentException("choices",
                                                         InternalHostUserInterfaceStrings.EmptyChoicesError, "choices");
            }

            Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>();

            if (defaultChoices != null)
            {
                foreach (int defaultChoice in defaultChoices)
                {
                    if ((defaultChoice < 0) || (defaultChoice >= choices.Count))
                    {
                        throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice,
                                                                           InternalHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection,
                                                                           "defaultChoice",
                                                                           "choices",
                                                                           defaultChoice);
                    }

                    defaultChoiceKeys.TryAdd(defaultChoice, true);
                }
            }

            // Construct the caption + message + list of choices + default choices
            Text.StringBuilder choicesMessage = new Text.StringBuilder();
            char newLine = '\n';

            if (!string.IsNullOrEmpty(caption))
            {
                choicesMessage.Append(caption);
                choicesMessage.Append(newLine);
            }

            if (!string.IsNullOrEmpty(message))
            {
                choicesMessage.Append(message);
                choicesMessage.Append(newLine);
            }

            string[,] hotkeysAndPlainLabels = null;
            HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels);

            string choiceTemplate = "[{0}] {1}  ";

            for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i)
            {
                string choice =
                    string.Format(
                        Globalization.CultureInfo.InvariantCulture,
                        choiceTemplate,
                        hotkeysAndPlainLabels[0, i],
                        hotkeysAndPlainLabels[1, i]);
                choicesMessage.Append(choice);
                choicesMessage.Append(newLine);
            }

            // default choices
            string defaultPrompt = string.Empty;

            if (defaultChoiceKeys.Count > 0)
            {
                string             prepend = string.Empty;
                Text.StringBuilder defaultChoicesBuilder = new Text.StringBuilder();
                foreach (int defaultChoice in defaultChoiceKeys.Keys)
                {
                    string defaultStr = hotkeysAndPlainLabels[0, defaultChoice];
                    if (string.IsNullOrEmpty(defaultStr))
                    {
                        defaultStr = hotkeysAndPlainLabels[1, defaultChoice];
                    }

                    defaultChoicesBuilder.Append(string.Format(Globalization.CultureInfo.InvariantCulture,
                                                               "{0}{1}", prepend, defaultStr));
                    prepend = ",";
                }

                string defaultChoicesStr = defaultChoicesBuilder.ToString();

                if (defaultChoiceKeys.Count == 1)
                {
                    defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice,
                                                      defaultChoicesStr);
                }
                else
                {
                    defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoicesForMultipleChoices,
                                                      defaultChoicesStr);
                }
            }

            string messageToBeDisplayed = choicesMessage.ToString() + defaultPrompt + newLine;
            // read choices from the user
            Collection <int> result = new Collection <int>();
            int choicesSelected     = 0;

            do
            {
                string choiceMsg = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, choicesSelected);
                messageToBeDisplayed += choiceMsg;
                _externalUI.WriteLine(messageToBeDisplayed);
                string response = _externalUI.ReadLine();

                // they just hit enter
                if (response.Length == 0)
                {
                    // this may happen when
                    // 1. user wants to go with the defaults
                    // 2. user selected some choices and wanted those
                    // choices to be picked.

                    // user did not pick up any choices..choose the default
                    if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0))
                    {
                        // if there's a default, pick that one.
                        foreach (int defaultChoice in defaultChoiceKeys.Keys)
                        {
                            result.Add(defaultChoice);
                        }
                    }
                    // allow for no choice selection.
                    break;
                }

                int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels);

                if (choicePicked >= 0)
                {
                    result.Add(choicePicked);
                    choicesSelected++;
                }
                // reset messageToBeDisplayed
                messageToBeDisplayed = string.Empty;
            } while (true);

            return(result);
        }
Exemplo n.º 27
0
 public object VisitNamedBlock(NamedBlockAst namedBlockAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(namedBlockAst));
 }
Exemplo n.º 28
0
        protected override void BeginProcessing()
        {
            Type result = null;
            PSArgumentException exception = null;

            if (string.Compare(base.ParameterSetName, "Net", StringComparison.Ordinal) == 0)
            {
                object o = null;
                if (!LanguagePrimitives.TryConvertTo <Type>(this.typeName, out result))
                {
                    exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "TypeNotFound", new object[] { this.typeName });
                    base.ThrowTerminatingError(new ErrorRecord(exception, "TypeNotFound", ErrorCategory.InvalidType, null));
                }
                if ((base.Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && !CoreTypes.Contains(result))
                {
                    base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                }
                if (WinRTHelper.IsWinRTType(result) && (typeof(Attribute).IsAssignableFrom(result) || typeof(Delegate).IsAssignableFrom(result)))
                {
                    base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(NewObjectStrings.CannotInstantiateWinRTType), "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null));
                }
                if ((this.arguments == null) || (this.arguments.Length == 0))
                {
                    ConstructorInfo constructor = result.GetConstructor(Type.EmptyTypes);
                    if ((constructor != null) && constructor.IsPublic)
                    {
                        o = this.CallConstructor(result, new ConstructorInfo[] { constructor }, new object[0]);
                        if ((o != null) && (this.property != null))
                        {
                            o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true);
                        }
                        base.WriteObject(o);
                        return;
                    }
                    if (result.IsValueType)
                    {
                        try
                        {
                            o = Activator.CreateInstance(result, false);
                            if ((o != null) && (this.property != null))
                            {
                                o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true);
                            }
                        }
                        catch (TargetInvocationException exception2)
                        {
                            base.ThrowTerminatingError(new ErrorRecord((exception2.InnerException == null) ? exception2 : exception2.InnerException, "ConstructorCalledThrowException", ErrorCategory.InvalidOperation, null));
                        }
                        base.WriteObject(o);
                        return;
                    }
                }
                else
                {
                    ConstructorInfo[] constructors = result.GetConstructors();
                    if (constructors.Length != 0)
                    {
                        o = this.CallConstructor(result, constructors, this.arguments);
                        if ((o != null) && (this.property != null))
                        {
                            o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true);
                        }
                        base.WriteObject(o);
                        return;
                    }
                }
                exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "CannotFindAppropriateCtor", new object[] { this.typeName });
                base.ThrowTerminatingError(new ErrorRecord(exception, "CannotFindAppropriateCtor", ErrorCategory.ObjectNotFound, null));
            }
            else
            {
                NewObjectNativeMethods.CLSIDFromProgID(this.comObject, out this.comObjectClsId);
                if (base.Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                {
                    bool flag2 = false;
                    if ((SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) && SystemPolicy.IsClassInApprovedList(this.comObjectClsId))
                    {
                        flag2 = true;
                    }
                    if (!flag2)
                    {
                        base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateComTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                        return;
                    }
                }
                PSSQMAPI.IncrementDataPoint((int)0x2099);
                object targetObject = this.CreateComObject();
                string fullName     = targetObject.GetType().FullName;
                if (!fullName.Equals("System.__ComObject"))
                {
                    exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "ComInteropLoaded", new object[] { fullName });
                    base.WriteVerbose(exception.Message);
                    if (this.Strict != 0)
                    {
                        base.WriteError(new ErrorRecord(exception, "ComInteropLoaded", ErrorCategory.InvalidArgument, targetObject));
                    }
                }
                if ((targetObject != null) && (this.property != null))
                {
                    targetObject = LanguagePrimitives.SetObjectProperties(targetObject, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true);
                }
                base.WriteObject(targetObject);
            }
        }
Exemplo n.º 29
0
 public object VisitAttribute(AttributeAst attributeAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(attributeAst));
 }
Exemplo n.º 30
0
 public object VisitExitStatement(ExitStatementAst exitStatementAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }