Example #1
0
        public static PSCredential GetRepositoryCredentialFromSecretManagement(
            string repositoryName,
            PSCredentialInfo repositoryCredentialInfo,
            PSCmdlet cmdletPassedIn)
        {
            if (!IsSecretManagementVaultAccessible(repositoryName, repositoryCredentialInfo, cmdletPassedIn))
            {
                cmdletPassedIn.ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException($"Cannot access Microsoft.PowerShell.SecretManagement vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication."),
                        "RepositoryCredentialSecretManagementInaccessibleVault",
                        ErrorCategory.ResourceUnavailable,
                        cmdletPassedIn));
                return(null);
            }

            var results = PowerShellInvoker.InvokeScriptWithHost <object>(
                cmdlet: cmdletPassedIn,
                script: @"
                    param (
                        [string] $VaultName,
                        [string] $SecretName
                    )
                    $module = Microsoft.PowerShell.Core\Import-Module -Name Microsoft.PowerShell.SecretManagement -PassThru
                    if ($null -eq $module) {
                        return
                    }
                    & $module ""Get-Secret"" -Name $SecretName -Vault $VaultName
                ",
                args: new object[] { repositoryCredentialInfo.VaultName, repositoryCredentialInfo.SecretName },
                out Exception terminatingError);

            var secretValue = (results.Count == 1) ? results[0] : null;

            if (secretValue == null)
            {
                cmdletPassedIn.ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: $"Microsoft.PowerShell.SecretManagement\\Get-Secret encountered an error while reading secret \"{repositoryCredentialInfo.SecretName}\" from vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication.",
                            innerException: terminatingError),
                        "RepositoryCredentialCannotGetSecretFromVault",
                        ErrorCategory.InvalidOperation,
                        cmdletPassedIn));
            }

            if (secretValue is PSCredential secretCredential)
            {
                return(secretCredential);
            }

            cmdletPassedIn.ThrowTerminatingError(
                new ErrorRecord(
                    new PSNotSupportedException($"Secret \"{repositoryCredentialInfo.SecretName}\" from vault \"{repositoryCredentialInfo.VaultName}\" has an invalid type. The only supported type is PSCredential."),
                    "RepositoryCredentialInvalidSecretType",
                    ErrorCategory.InvalidType,
                    cmdletPassedIn));

            return(null);
        }
        /// <summary>
        /// Gets a resolved or unresolved path from PSPath.
        /// </summary>
        /// <param name="cmdlet">The calling <see cref="PSCmdlet"/>.</param>
        /// <param name="filePath">The file path to get a provider path for.</param>
        /// <param name="isResolvedPath">Determines whether get a resolved or unresolved provider path.</param>
        /// <returns>The provider path from PSPath.</returns>
        internal static string GetProviderPath(this PSCmdlet cmdlet, string filePath, bool isResolvedPath)
        {
            string       providerPath = null;
            ProviderInfo provider;

            try
            {
                var paths = new Collection <string>();
                if (isResolvedPath)
                {
                    paths = cmdlet.SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider);
                }
                else
                {
                    paths.Add(cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(filePath, out provider, out _));
                }

                if (provider.Name != "FileSystem" || paths.Count == 0)
                {
                    cmdlet.ThrowTerminatingError(new ErrorRecord(new Exception($"Invalid path {filePath}."), string.Empty, ErrorCategory.InvalidArgument, filePath));
                }
                if (paths.Count > 1)
                {
                    cmdlet.ThrowTerminatingError(new ErrorRecord(new Exception("Multiple paths not allowed."), string.Empty, ErrorCategory.InvalidArgument, filePath));
                }
                providerPath = paths[0];
            }
            catch (Exception ex)
            {
                cmdlet.ThrowTerminatingError(new ErrorRecord(ex, string.Empty, ErrorCategory.InvalidArgument, filePath));
            }

            return(providerPath);
        }
Example #3
0
        private PathInfo ResolvePath(
            string pathToResolve,
            bool allowNonexistingPaths,
            PSCmdlet cmdlet)
        {
            CmdletProviderContext context    = new CmdletProviderContext((Cmdlet)cmdlet);
            Collection <PathInfo> collection = new Collection <PathInfo>();

            try
            {
                foreach (PathInfo pathInfo in cmdlet.SessionState.Path.GetResolvedPSPathFromPSPath(pathToResolve, context))
                {
                    collection.Add(pathInfo);
                }
            }
            catch (PSNotSupportedException ex)
            {
                cmdlet.ThrowTerminatingError(new ErrorRecord(ex.ErrorRecord, (Exception)ex));
            }
            catch (DriveNotFoundException ex)
            {
                cmdlet.ThrowTerminatingError(new ErrorRecord(ex.ErrorRecord, (Exception)ex));
            }
            catch (ProviderNotFoundException ex)
            {
                cmdlet.ThrowTerminatingError(new ErrorRecord(ex.ErrorRecord, (Exception)ex));
            }
            catch (ItemNotFoundException ex)
            {
                if (allowNonexistingPaths)
                {
                    ProviderInfo provider = (ProviderInfo)null;
                    PSDriveInfo  drive    = (PSDriveInfo)null;
                    string       providerPathFromPsPath = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(pathToResolve, context, out provider, out drive);
                    PathInfo     pathInfo = new PathInfo(drive, provider, providerPathFromPsPath, cmdlet.SessionState);
                    collection.Add(pathInfo);
                }
                else
                {
                    cmdlet.ThrowTerminatingError(new ErrorRecord(ex.ErrorRecord, (Exception)ex));
                }
            }
            if (collection.Count == 1)
            {
                return(collection[0]);
            }
            Exception exception = (Exception)PathResolver.tracer.NewNotSupportedException();

            cmdlet.ThrowTerminatingError(new ErrorRecord(exception, "NotSupported", ErrorCategory.NotImplemented, (object)collection));
            return((PathInfo)null);
        }
Example #4
0
        private PathInfo ResolvePath(string pathToResolve, bool isLiteralPath, bool allowNonexistingPaths, PSCmdlet cmdlet)
        {
            CmdletProviderContext context = new CmdletProviderContext(cmdlet)
            {
                SuppressWildcardExpansion = isLiteralPath
            };
            Collection <PathInfo> targetObject = new Collection <PathInfo>();

            try
            {
                foreach (PathInfo info in cmdlet.SessionState.Path.GetResolvedPSPathFromPSPath(pathToResolve, context))
                {
                    targetObject.Add(info);
                }
            }
            catch (PSNotSupportedException exception)
            {
                cmdlet.ThrowTerminatingError(new ErrorRecord(exception.ErrorRecord, exception));
            }
            catch (DriveNotFoundException exception2)
            {
                cmdlet.ThrowTerminatingError(new ErrorRecord(exception2.ErrorRecord, exception2));
            }
            catch (ProviderNotFoundException exception3)
            {
                cmdlet.ThrowTerminatingError(new ErrorRecord(exception3.ErrorRecord, exception3));
            }
            catch (ItemNotFoundException exception4)
            {
                if (allowNonexistingPaths)
                {
                    ProviderInfo provider = null;
                    PSDriveInfo  drive    = null;
                    string       path     = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(pathToResolve, context, out provider, out drive);
                    PathInfo     item     = new PathInfo(drive, provider, path, cmdlet.SessionState);
                    targetObject.Add(item);
                }
                else
                {
                    cmdlet.ThrowTerminatingError(new ErrorRecord(exception4.ErrorRecord, exception4));
                }
            }
            if (targetObject.Count == 1)
            {
                return(targetObject[0]);
            }
            Exception exception5 = PSTraceSource.NewNotSupportedException();

            cmdlet.ThrowTerminatingError(new ErrorRecord(exception5, "NotSupported", ErrorCategory.NotImplemented, targetObject));
            return(null);
        }
Example #5
0
        public static bool IsSecretManagementModuleAvailable(
            string repositoryName,
            PSCmdlet cmdletPassedIn)
        {
            var results = PowerShellInvoker.InvokeScriptWithHost <int>(
                cmdlet: cmdletPassedIn,
                script: @"
                    $module = Microsoft.PowerShell.Core\Get-Module -Name Microsoft.PowerShell.SecretManagement -ErrorAction Ignore
                    if ($null -eq $module) {
                        $module = Microsoft.PowerShell.Core\Import-Module -Name Microsoft.PowerShell.SecretManagement -PassThru -ErrorAction Ignore
                    }
                    if ($null -eq $module) {
                        return 1
                    }
                    return 0
                ",
                args: new object[] {},
                out Exception terminatingError);

            if (terminatingError != null)
            {
                cmdletPassedIn.ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: $"Cannot validate Microsoft.PowerShell.SecretManagement module setup for PSResourceRepository ({repositoryName}) authentication.",
                            innerException: terminatingError),
                        "RepositoryCredentialSecretManagementInvalidModule",
                        ErrorCategory.InvalidOperation,
                        cmdletPassedIn));
            }

            int result = (results.Count > 0) ? results[0] : 1;

            return(result == 0);
        }
Example #6
0
        private static void ThrowOutLsaError(uint ret, PSCmdlet cmdlet)
        {
            Win32Exception win32Exception = new Win32Exception(SAMAPI.LsaNtStatusToWinError(ret));
            string         str            = StringUtil.Format(ComputerResources.FailToResetPasswordOnLocalMachine, win32Exception.Message);
            ErrorRecord    errorRecord    = new ErrorRecord(new InvalidOperationException(str), "FailToResetPasswordOnLocalMachine", ErrorCategory.OperationStopped, Dns.GetHostName());

            cmdlet.ThrowTerminatingError(errorRecord);
        }
Example #7
0
        public static void SaveRepositoryCredentialToSecretManagementVault(
            string repositoryName,
            PSCredentialInfo repositoryCredentialInfo,
            PSCmdlet cmdletPassedIn)
        {
            if (!IsSecretManagementVaultAccessible(repositoryName, repositoryCredentialInfo, cmdletPassedIn))
            {
                cmdletPassedIn.ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException($"Cannot access Microsoft.PowerShell.SecretManagement vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication."),
                        "RepositoryCredentialSecretManagementInaccessibleVault",
                        ErrorCategory.ResourceUnavailable,
                        cmdletPassedIn));
                return;
            }

            PowerShellInvoker.InvokeScriptWithHost(
                cmdlet: cmdletPassedIn,
                script: @"
                    param (
                        [string] $VaultName,
                        [string] $SecretName,
                        [object] $SecretValue
                    )
                    $module = Microsoft.PowerShell.Core\Import-Module -Name Microsoft.PowerShell.SecretManagement -PassThru
                    if ($null -eq $module) {
                        return
                    }
                    & $module ""Set-Secret"" -Name $SecretName -Vault $VaultName -Secret $SecretValue
                ",
                args: new object[] { repositoryCredentialInfo.VaultName, repositoryCredentialInfo.SecretName, repositoryCredentialInfo.Credential },
                out Exception terminatingError);

            if (terminatingError != null)
            {
                cmdletPassedIn.ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: $"Microsoft.PowerShell.SecretManagement\\Set-Secret encountered an error while adding secret \"{repositoryCredentialInfo.SecretName}\" to vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication.",
                            innerException: terminatingError),
                        "RepositoryCredentialCannotAddSecretToVault",
                        ErrorCategory.InvalidOperation,
                        cmdletPassedIn));
            }
        }
Example #8
0
 internal static void ThrowError(this PSCmdlet cmdlet, string message, ErrorCategory errorCategory)
 {
     cmdlet.ThrowTerminatingError(
         new ErrorRecord(
             new ArgumentException(message),
             Guid.NewGuid().ToString(),
             errorCategory,
             null)
         );
 }
Example #9
0
        internal string ReadFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new ArgumentException(GetResourceMsgFromResourcetext("InvalidFileName"));
            }

            string strOut = null;

            try
            {
                _fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                // create stream Reader
                _sr    = new StreamReader(_fs);
                strOut = _sr.ReadToEnd();
            }
            catch (ArgumentNullException e)
            {
                ErrorRecord er = new ErrorRecord(e, "ArgumentNullException", ErrorCategory.InvalidArgument, null);
                cmdletname.ThrowTerminatingError(er);
            }
            catch (UnauthorizedAccessException e)
            {
                ErrorRecord er = new ErrorRecord(e, "UnauthorizedAccessException", ErrorCategory.PermissionDenied, null);
                cmdletname.ThrowTerminatingError(er);
            }
            catch (FileNotFoundException e)
            {
                ErrorRecord er = new ErrorRecord(e, "FileNotFoundException", ErrorCategory.ObjectNotFound, null);
                cmdletname.ThrowTerminatingError(er);
            }
            catch (DirectoryNotFoundException e)
            {
                ErrorRecord er = new ErrorRecord(e, "DirectoryNotFoundException", ErrorCategory.ObjectNotFound, null);
                cmdletname.ThrowTerminatingError(er);
            }
            catch (System.Security.SecurityException e)
            {
                ErrorRecord er = new ErrorRecord(e, "SecurityException", ErrorCategory.SecurityError, null);
                cmdletname.ThrowTerminatingError(er);
            }
            finally
            {
                if (_sr != null)
                {
                    // _sr.Close();
                    _sr.Dispose();
                }

                if (_fs != null)
                {
                    // _fs.Close();
                    _fs.Dispose();
                }
            }

            return(strOut);
        }
 public void ThrowTerminatingError(ErrorRecord errorRecord)
 {
     if (caller != null)
     {
         caller.ThrowTerminatingError(errorRecord);
     }
     else
     {
         throw new Exception("ThrowTerminatingError received a proxy error: " + errorRecord.ErrorDetails, errorRecord.Exception);
     }
 }
Example #11
0
        /// <summary>
        /// Invokes a PowerShell command given a PowerShell instance and a PSCmdlet instance. If an error is found while invoking
        /// the command, the PSCmdlet pipeline is stopped by invoking PSCmdlet.ThrowTerminatingError with the first error found.
        /// </summary>
        /// <param name="ps">The PowerShell instance</param>
        /// <param name="psCmdlet">The PSCmdlet instance</param>
        /// <returns>An Enumerable of PSObjects representing the results of invoking the PowerShell instance</returns>
        public static IEnumerable <PSObject> InvokePowershellCommandOrThrowIfUnsuccessful(PowerShell ps, PSCmdlet psCmdlet)
        {
            var res = ps.Invoke();

            if (ps.HadErrors)
            {
                psCmdlet.ThrowTerminatingError(ps.Streams.Error[0]);
            }

            return(res);
        }
        public static void ThrowTerminatingError(ErrorRecord error, PSCmdlet cmdlet)
        {
            if (cmdlet.MyInvocation.BoundParameters.ContainsKey("ErrorAction"))
            {
                var action = (ActionPreference)cmdlet.MyInvocation.BoundParameters["ErrorAction"];
                if (action == ActionPreference.Ignore || action == ActionPreference.SilentlyContinue)
                {
                    return;
                }
            }

            cmdlet.ThrowTerminatingError(error);
        }
        internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName, string featureName)
        {
            GraphicalHostReflectionWrapper wrapper = new GraphicalHostReflectionWrapper();

            if (IsInputFromRemoting(parentCmdlet))
            {
                ErrorRecord errorRecord = new ErrorRecord(new NotSupportedException(StringUtil.Format(HelpErrors.RemotingNotSupportedForFeature, featureName)), "RemotingNotSupported", ErrorCategory.InvalidOperation, parentCmdlet);
                parentCmdlet.ThrowTerminatingError(errorRecord);
            }
            AssemblyName assemblyRef = new AssemblyName {
                Name        = "Microsoft.PowerShell.GraphicalHost",
                Version     = new Version(3, 0, 0, 0),
                CultureInfo = new CultureInfo(string.Empty)
            };

            assemblyRef.SetPublicKeyToken(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 });
            try
            {
                wrapper.graphicalHostAssembly = Assembly.Load(assemblyRef);
            }
            catch (FileNotFoundException exception)
            {
                string message = StringUtil.Format(HelpErrors.GraphicalHostAssemblyIsNotFound, featureName, exception.Message);
                parentCmdlet.ThrowTerminatingError(new ErrorRecord(new NotSupportedException(message, exception), "ErrorLoadingAssembly", ErrorCategory.ObjectNotFound, assemblyRef));
            }
            catch (Exception exception2)
            {
                CommandProcessorBase.CheckForSevereException(exception2);
                parentCmdlet.ThrowTerminatingError(new ErrorRecord(exception2, "ErrorLoadingAssembly", ErrorCategory.ObjectNotFound, assemblyRef));
            }
            wrapper.graphicalHostHelperType = wrapper.graphicalHostAssembly.GetType(graphicalHostHelperTypeName);
            ConstructorInfo info = wrapper.graphicalHostHelperType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);

            if (info != null)
            {
                wrapper.graphicalHostHelperObject = info.Invoke(new object[0]);
            }
            return(wrapper);
        }
Example #14
0
        public static AzureHDInsightClusterConnection AssertValidConnection(this PSCmdlet cmdlet)
        {
            IAzureHDInsightConnectionSessionManager sessionManager =
                ServiceLocator.Instance.Locate <IAzureHDInsightConnectionSessionManagerFactory>().Create(cmdlet.SessionState);
            AzureHDInsightClusterConnection currentConnection = sessionManager.GetCurrentCluster();

            if (currentConnection == null)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new NotSupportedException("Please connect to a valid Azure HDInsight cluster before calling this cmdlet."),
                        "1024",
                        ErrorCategory.ConnectionError,
                        cmdlet));
            }

            return(currentConnection);
        }
Example #15
0
        public static void Start(string title, OutputModeOption outputMode, PSCmdlet cmdlet)
        {
            _gridViewerProcess = new Process();

            _gridViewerProcess.StartInfo.FileName  = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Contents", "MacOS", "GridViewer");
            _gridViewerProcess.StartInfo.Arguments = string.Format("\"{0}\"", title.Replace("\"", "\\\""));

            _gridViewerProcess.StartInfo.CreateNoWindow  = true;
            _gridViewerProcess.StartInfo.UseShellExecute = false;

            _gridViewerProcess.StartInfo.RedirectStandardInput  = true;
            _gridViewerProcess.StartInfo.RedirectStandardOutput = true;
            _gridViewerProcess.StartInfo.RedirectStandardError  = true;

            // Just Console.WriteLine it.
            _gridViewerProcess.OutputDataReceived += (sender, data) =>
            {
                if (!string.IsNullOrWhiteSpace(data.Data))
                {
                    selectedIndexes.Add(Convert.ToInt32(data.Data));
                }
            };
            _gridViewerProcess.ErrorDataReceived += (sender, data) =>
            {
                Console.WriteLine(data.Data);
            };

            try
            {
                _gridViewerProcess.Start();
                _gridViewerProcess.BeginOutputReadLine();
                _gridViewerProcess.BeginErrorReadLine();
            }
            catch (Exception ex)
            {
                cmdlet.ThrowTerminatingError(new ErrorRecord(ex, "GridViewException", ErrorCategory.OperationStopped, null));
            }
        }
Example #16
0
        public static bool IsSecretManagementVaultAccessible(
            string repositoryName,
            PSCredentialInfo repositoryCredentialInfo,
            PSCmdlet cmdletPassedIn)
        {
            var results = PowerShellInvoker.InvokeScriptWithHost <bool>(
                cmdlet: cmdletPassedIn,
                script: @"
                    param (
                        [string] $VaultName
                    )
                    $module = Microsoft.PowerShell.Core\Import-Module -Name Microsoft.PowerShell.SecretManagement -PassThru
                    if ($null -eq $module) {
                        return
                    }
                    & $module ""Test-SecretVault"" -Name $VaultName
                ",
                args: new object[] { repositoryCredentialInfo.VaultName },
                out Exception terminatingError);

            if (terminatingError != null)
            {
                cmdletPassedIn.ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(
                            message: $"Microsoft.PowerShell.SecretManagement\\Test-SecretVault encountered an error while validating the vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication.",
                            innerException: terminatingError),
                        "RepositoryCredentialSecretManagementInvalidVault",
                        ErrorCategory.InvalidOperation,
                        cmdletPassedIn));
            }

            bool result = (results.Count > 0) ? results[0] : false;

            return(result);
        }
Example #17
0
        public List <PSResourceInfo> FindByResourceName(
            string[] name,
            ResourceType type,
            string version,
            SwitchParameter prerelease,
            string[] tag,
            string[] repository,
            PSCredential credential,
            SwitchParameter includeDependencies)
        {
            _type                = type;
            _version             = version;
            _prerelease          = prerelease;
            _tag                 = tag;
            _credential          = credential;
            _includeDependencies = includeDependencies;

            List <PSResourceInfo> foundPackages = new List <PSResourceInfo>();

            if (name.Length == 0)
            {
                return(foundPackages);
            }

            _pkgsLeftToFind = name.ToList();

            // Error out if repository array of names to be searched contains wildcards.
            if (repository != null)
            {
                repository = Utils.ProcessNameWildcards(repository, out string[] errorMsgs, out _repositoryNameContainsWildcard);
                foreach (string error in errorMsgs)
                {
                    _cmdletPassedIn.WriteError(new ErrorRecord(
                                                   new PSInvalidOperationException(error),
                                                   "ErrorFilteringNamesForUnsupportedWildcards",
                                                   ErrorCategory.InvalidArgument,
                                                   this));
                }
            }

            // Get repositories to search.
            List <PSRepositoryInfo> repositoriesToSearch;

            try
            {
                repositoriesToSearch = RepositorySettings.Read(repository, out string[] errorList);
                foreach (string error in errorList)
                {
                    _cmdletPassedIn.WriteError(new ErrorRecord(
                                                   new PSInvalidOperationException(error),
                                                   "ErrorGettingSpecifiedRepo",
                                                   ErrorCategory.InvalidOperation,
                                                   this));
                }
            }
            catch (Exception e)
            {
                _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
                                                          new PSInvalidOperationException(e.Message),
                                                          "ErrorLoadingRepositoryStoreFile",
                                                          ErrorCategory.InvalidArgument,
                                                          this));

                return(foundPackages);
            }

            // Loop through repositoriesToSearch and if PSGallery or PoshTestGallery add its Scripts endpoint repo
            // to list with same priority as PSGallery repo.
            // This special casing is done to handle PSGallery and PoshTestGallery having 2 endpoints currently for different resources.
            for (int i = 0; i < repositoriesToSearch.Count; i++)
            {
                if (String.Equals(repositoriesToSearch[i].Uri.AbsoluteUri, _psGalleryUri, StringComparison.InvariantCultureIgnoreCase))
                {
                    // special case: for PowerShellGallery, Module and Script resources have different endpoints so separate repositories have to be registered
                    // with those endpoints in order for the NuGet APIs to search across both in the case where name includes '*'

                    // detect if Script repository needs to be added and/or Module repository needs to be skipped
                    Uri psGalleryScriptsUri           = new Uri("http://www.powershellgallery.com/api/v2/items/psscript/");
                    PSRepositoryInfo psGalleryScripts = new PSRepositoryInfo(_psGalleryScriptsRepoName, psGalleryScriptsUri, repositoriesToSearch[i].Priority, trusted: false, credentialInfo: null);
                    if (_type == ResourceType.None)
                    {
                        _cmdletPassedIn.WriteVerbose("Null Type provided, so add PSGalleryScripts repository");
                        repositoriesToSearch.Insert(i + 1, psGalleryScripts);
                    }
                    else if (_type != ResourceType.None && _type == ResourceType.Script)
                    {
                        _cmdletPassedIn.WriteVerbose("Type Script provided, so add PSGalleryScripts and remove PSGallery (Modules only) from search consideration");
                        repositoriesToSearch.Insert(i + 1, psGalleryScripts);
                        repositoriesToSearch.RemoveAt(i); // remove PSGallery
                    }
                }
                else if (String.Equals(repositoriesToSearch[i].Uri.AbsoluteUri, _poshTestGalleryUri, StringComparison.InvariantCultureIgnoreCase))
                {
                    // special case: for PoshTestGallery, Module and Script resources have different endpoints so separate repositories have to be registered
                    // with those endpoints in order for the NuGet APIs to search across both in the case where name includes '*'

                    // detect if Script repository needs to be added and/or Module repository needs to be skipped
                    Uri poshTestGalleryScriptsUri           = new Uri("https://www.poshtestgallery.com/api/v2/items/psscript/");
                    PSRepositoryInfo poshTestGalleryScripts = new PSRepositoryInfo(_poshTestGalleryScriptsRepoName, poshTestGalleryScriptsUri, repositoriesToSearch[i].Priority, trusted: false, credentialInfo: null);
                    if (_type == ResourceType.None)
                    {
                        _cmdletPassedIn.WriteVerbose("Null Type provided, so add PoshTestGalleryScripts repository");
                        repositoriesToSearch.Insert(i + 1, poshTestGalleryScripts);
                    }
                    else if (_type != ResourceType.None && _type == ResourceType.Script)
                    {
                        _cmdletPassedIn.WriteVerbose("Type Script provided, so add PoshTestGalleryScripts and remove PoshTestGallery (Modules only) from search consideration");
                        repositoriesToSearch.Insert(i + 1, poshTestGalleryScripts);
                        repositoriesToSearch.RemoveAt(i); // remove PoshTestGallery
                    }
                }
            }

            for (int i = 0; i < repositoriesToSearch.Count && _pkgsLeftToFind.Any(); i++)
            {
                _cmdletPassedIn.WriteVerbose(string.Format("Searching in repository {0}", repositoriesToSearch[i].Name));
                foreach (var pkg in SearchFromRepository(
                             repositoryName: repositoriesToSearch[i].Name,
                             repositoryUri: repositoriesToSearch[i].Uri,
                             repositoryCredentialInfo: repositoriesToSearch[i].CredentialInfo))
                {
                    foundPackages.Add(pkg);
                }
            }

            return(foundPackages);
        }
Example #18
0
        internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName, string featureName)
        {
            GraphicalHostReflectionWrapper returnValue = new GraphicalHostReflectionWrapper();

            if (GraphicalHostReflectionWrapper.IsInputFromRemoting(parentCmdlet))
            {
                ErrorRecord error = new ErrorRecord(
                    new NotSupportedException(StringUtil.Format(HelpErrors.RemotingNotSupportedForFeature, featureName)),
                    "RemotingNotSupported",
                    ErrorCategory.InvalidOperation,
                    parentCmdlet);

                parentCmdlet.ThrowTerminatingError(error);
            }

            // Prepare the full assembly name.
            AssemblyName graphicalHostAssemblyName = new AssemblyName();

            graphicalHostAssemblyName.Name        = "Microsoft.PowerShell.GraphicalHost";
            graphicalHostAssemblyName.Version     = new Version(3, 0, 0, 0);
            graphicalHostAssemblyName.CultureInfo = new CultureInfo(string.Empty); // Neutral culture
            graphicalHostAssemblyName.SetPublicKeyToken(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 });

            try
            {
                returnValue._graphicalHostAssembly = Assembly.Load(graphicalHostAssemblyName);
            }
            catch (FileNotFoundException fileNotFoundEx)
            {
                // This exception is thrown if the Microsoft.PowerShell.GraphicalHost.dll could not be found (was not installed).
                string errorMessage = StringUtil.Format(
                    HelpErrors.GraphicalHostAssemblyIsNotFound,
                    featureName,
                    fileNotFoundEx.Message);

                parentCmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new NotSupportedException(errorMessage, fileNotFoundEx),
                        "ErrorLoadingAssembly",
                        ErrorCategory.ObjectNotFound,
                        graphicalHostAssemblyName));
            }
            catch (Exception e)
            {
                parentCmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        e,
                        "ErrorLoadingAssembly",
                        ErrorCategory.ObjectNotFound,
                        graphicalHostAssemblyName));
            }

            returnValue._graphicalHostHelperType = returnValue._graphicalHostAssembly.GetType(graphicalHostHelperTypeName);

            Diagnostics.Assert(returnValue._graphicalHostHelperType != null, "the type exists in Microsoft.PowerShell.GraphicalHost");
            ConstructorInfo constructor = returnValue._graphicalHostHelperType.GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                Array.Empty <Type>(),
                null);

            if (constructor != null)
            {
                returnValue._graphicalHostHelperObject = constructor.Invoke(Array.Empty <object>());
                Diagnostics.Assert(returnValue._graphicalHostHelperObject != null, "the constructor does not throw anything");
            }

            return(returnValue);
        }
Example #19
0
        /// <summary>
        /// Install provided list of packages, which include Dependent packages if requested.
        /// </summary>
        private List <PSResourceInfo> InstallPackage(
            List <PSResourceInfo> pkgsToInstall,
            string repoName,
            string repoUri,
            PSCredentialInfo repoCredentialInfo,
            PSCredential credential,
            bool isLocalRepo)
        {
            List <PSResourceInfo> pkgsSuccessfullyInstalled = new List <PSResourceInfo>();
            int totalPkgs = pkgsToInstall.Count;

            // Counters for tracking current package out of total
            int currentInstalledPkgCount = 0;

            foreach (PSResourceInfo pkg in pkgsToInstall)
            {
                currentInstalledPkgCount++;
                var tempInstallPath = Path.Combine(_tmpPath, Guid.NewGuid().ToString());
                try
                {
                    // Create a temp directory to install to
                    var dir = Directory.CreateDirectory(tempInstallPath);  // should check it gets created properly
                                                                           // To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator
                                                                           // with a mask (bitwise complement of desired attributes combination).
                                                                           // TODO: check the attributes and if it's read only then set it
                                                                           // attribute may be inherited from the parent
                                                                           // TODO:  are there Linux accommodations we need to consider here?
                    dir.Attributes &= ~FileAttributes.ReadOnly;

                    _cmdletPassedIn.WriteVerbose(string.Format("Begin installing package: '{0}'", pkg.Name));

                    if (!_quiet)
                    {
                        int    activityId        = 0;
                        int    percentComplete   = ((currentInstalledPkgCount * 100) / totalPkgs);
                        string activity          = string.Format("Installing {0}...", pkg.Name);
                        string statusDescription = string.Format("{0}% Complete", percentComplete);
                        _cmdletPassedIn.WriteProgress(
                            new ProgressRecord(activityId, activity, statusDescription));
                    }

                    // Create PackageIdentity in order to download
                    string createFullVersion = pkg.Version.ToString();
                    if (pkg.IsPrerelease)
                    {
                        createFullVersion = pkg.Version.ToString() + "-" + pkg.Prerelease;
                    }

                    if (!NuGetVersion.TryParse(createFullVersion, out NuGetVersion pkgVersion))
                    {
                        var message = String.Format("{0} package could not be installed with error: could not parse package '{0}' version '{1} into a NuGetVersion",
                                                    pkg.Name,
                                                    pkg.Version.ToString());
                        var ex = new ArgumentException(message);
                        var packageIdentityVersionParseError = new ErrorRecord(ex, "psdataFileNotExistError", ErrorCategory.ReadError, null);
                        _cmdletPassedIn.WriteError(packageIdentityVersionParseError);
                        _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
                        continue;
                    }

                    var pkgIdentity  = new PackageIdentity(pkg.Name, pkgVersion);
                    var cacheContext = new SourceCacheContext();

                    if (isLocalRepo)
                    {
                        /* Download from a local repository -- this is slightly different process than from a server */
                        var localResource = new FindLocalPackagesResourceV2(repoUri);
                        var resource      = new LocalDownloadResource(repoUri, localResource);

                        // Actually downloading the .nupkg from a local repo
                        var result = resource.GetDownloadResourceResultAsync(
                            identity: pkgIdentity,
                            downloadContext: new PackageDownloadContext(cacheContext),
                            globalPackagesFolder: tempInstallPath,
                            logger: NullLogger.Instance,
                            token: _cancellationToken).GetAwaiter().GetResult();

                        // Create the package extraction context
                        PackageExtractionContext packageExtractionContext = new PackageExtractionContext(
                            packageSaveMode: PackageSaveMode.Nupkg,
                            xmlDocFileSaveMode: PackageExtractionBehavior.XmlDocFileSaveMode,
                            clientPolicyContext: null,
                            logger: NullLogger.Instance);

                        // Extracting from .nupkg and placing files into tempInstallPath
                        result.PackageReader.CopyFiles(
                            destination: tempInstallPath,
                            packageFiles: result.PackageReader.GetFiles(),
                            extractFile: new PackageFileExtractor(
                                result.PackageReader.GetFiles(),
                                packageExtractionContext.XmlDocFileSaveMode).ExtractPackageFile,
                            logger: NullLogger.Instance,
                            token: _cancellationToken);
                        result.Dispose();
                    }
                    else
                    {
                        /* Download from a non-local repository */
                        // Set up NuGet API resource for download
                        PackageSource source = new PackageSource(repoUri);

                        // Explicitly passed in Credential takes precedence over repository CredentialInfo
                        if (credential != null)
                        {
                            string password = new NetworkCredential(string.Empty, credential.Password).Password;
                            source.Credentials = PackageSourceCredential.FromUserInput(repoUri, credential.UserName, password, true, null);
                        }
                        else if (repoCredentialInfo != null)
                        {
                            PSCredential repoCredential = Utils.GetRepositoryCredentialFromSecretManagement(
                                repoName,
                                repoCredentialInfo,
                                _cmdletPassedIn);

                            string password = new NetworkCredential(string.Empty, repoCredential.Password).Password;
                            source.Credentials = PackageSourceCredential.FromUserInput(repoUri, repoCredential.UserName, password, true, null);
                        }
                        var provider = FactoryExtensionsV3.GetCoreV3(NuGet.Protocol.Core.Types.Repository.Provider);
                        SourceRepository repository = new SourceRepository(source, provider);

                        /* Download from a non-local repository -- ie server */
                        var downloadResource          = repository.GetResourceAsync <DownloadResource>().GetAwaiter().GetResult();
                        DownloadResourceResult result = null;
                        try
                        {
                            result = downloadResource.GetDownloadResourceResultAsync(
                                identity: pkgIdentity,
                                downloadContext: new PackageDownloadContext(cacheContext),
                                globalPackagesFolder: tempInstallPath,
                                logger: NullLogger.Instance,
                                token: _cancellationToken).GetAwaiter().GetResult();
                        }
                        catch (Exception e)
                        {
                            _cmdletPassedIn.WriteVerbose(string.Format("Error attempting download: '{0}'", e.Message));
                        }
                        finally
                        {
                            // Need to close the .nupkg
                            if (result != null)
                            {
                                result.Dispose();
                            }
                        }
                    }

                    _cmdletPassedIn.WriteVerbose(string.Format("Successfully able to download package from source to: '{0}'", tempInstallPath));

                    // pkgIdentity.Version.Version gets the version without metadata or release labels.
                    string newVersion = pkgIdentity.Version.ToNormalizedString();
                    string normalizedVersionNoPrerelease = newVersion;
                    if (pkgIdentity.Version.IsPrerelease)
                    {
                        // eg: 2.0.2
                        normalizedVersionNoPrerelease = pkgIdentity.Version.ToNormalizedString().Substring(0, pkgIdentity.Version.ToNormalizedString().IndexOf('-'));
                    }

                    string tempDirNameVersion        = isLocalRepo ? tempInstallPath : Path.Combine(tempInstallPath, pkgIdentity.Id.ToLower(), newVersion);
                    var    version4digitNoPrerelease = pkgIdentity.Version.Version.ToString();
                    string moduleManifestVersion     = string.Empty;
                    var    scriptPath = Path.Combine(tempDirNameVersion, pkg.Name + PSScriptFileExt);
                    var    modulePath = Path.Combine(tempDirNameVersion, pkg.Name + PSDataFileExt);
                    // Check if the package is a module or a script
                    var isModule = File.Exists(modulePath);

                    string installPath;
                    if (_savePkg)
                    {
                        // For save the installation path is what is passed in via -Path
                        installPath = _pathsToInstallPkg.FirstOrDefault();

                        // If saving as nupkg simply copy the nupkg and move onto next iteration of loop
                        // asNupkg functionality only applies to Save-PSResource
                        if (_asNupkg)
                        {
                            var nupkgFile = pkgIdentity.ToString().ToLower() + ".nupkg";
                            File.Copy(Path.Combine(tempDirNameVersion, nupkgFile), Path.Combine(installPath, nupkgFile));

                            _cmdletPassedIn.WriteVerbose(string.Format("'{0}' moved into file path '{1}'", nupkgFile, installPath));
                            pkgsSuccessfullyInstalled.Add(pkg);

                            continue;
                        }
                    }
                    else
                    {
                        // PSModules:
                        /// ./Modules
                        /// ./Scripts
                        /// _pathsToInstallPkg is sorted by desirability, Find will pick the pick the first Script or Modules path found in the list
                        installPath = isModule ? _pathsToInstallPkg.Find(path => path.EndsWith("Modules", StringComparison.InvariantCultureIgnoreCase))
                                : _pathsToInstallPkg.Find(path => path.EndsWith("Scripts", StringComparison.InvariantCultureIgnoreCase));
                    }

                    if (_authenticodeCheck && !AuthenticodeSignature.CheckAuthenticodeSignature(
                            pkg.Name,
                            tempDirNameVersion,
                            _cmdletPassedIn,
                            out ErrorRecord errorRecord))
                    {
                        _cmdletPassedIn.ThrowTerminatingError(errorRecord);
                    }

                    if (isModule)
                    {
                        var moduleManifest = Path.Combine(tempDirNameVersion, pkgIdentity.Id + PSDataFileExt);
                        if (!File.Exists(moduleManifest))
                        {
                            var message = String.Format("{0} package could not be installed with error: Module manifest file: {1} does not exist. This is not a valid PowerShell module.", pkgIdentity.Id, moduleManifest);

                            var ex = new ArgumentException(message);
                            var psdataFileDoesNotExistError = new ErrorRecord(ex, "psdataFileNotExistError", ErrorCategory.ReadError, null);
                            _cmdletPassedIn.WriteError(psdataFileDoesNotExistError);
                            _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
                            continue;
                        }

                        if (!Utils.TryReadManifestFile(
                                manifestFilePath: moduleManifest,
                                manifestInfo: out Hashtable parsedMetadataHashtable,
                                error: out Exception manifestReadError))
                        {
                            _cmdletPassedIn.WriteError(
                                new ErrorRecord(
                                    exception: manifestReadError,
                                    errorId: "ManifestFileReadParseError",
                                    errorCategory: ErrorCategory.ReadError,
                                    this));

                            continue;
                        }

                        moduleManifestVersion = parsedMetadataHashtable["ModuleVersion"] as string;

                        // Accept License verification
                        if (!_savePkg && !CallAcceptLicense(pkg, moduleManifest, tempInstallPath, newVersion))
                        {
                            continue;
                        }

                        // If NoClobber is specified, ensure command clobbering does not happen
                        if (_noClobber && !DetectClobber(pkg.Name, parsedMetadataHashtable))
                        {
                            continue;
                        }
                    }

                    // Delete the extra nupkg related files that are not needed and not part of the module/script
                    DeleteExtraneousFiles(pkgIdentity, tempDirNameVersion);

                    if (_includeXml)
                    {
                        CreateMetadataXMLFile(tempDirNameVersion, installPath, pkg, isModule);
                    }

                    MoveFilesIntoInstallPath(
                        pkg,
                        isModule,
                        isLocalRepo,
                        tempDirNameVersion,
                        tempInstallPath,
                        installPath,
                        newVersion,
                        moduleManifestVersion,
                        scriptPath);

                    _cmdletPassedIn.WriteVerbose(String.Format("Successfully installed package '{0}' to location '{1}'", pkg.Name, installPath));
                    pkgsSuccessfullyInstalled.Add(pkg);
                }
                catch (Exception e)
                {
                    _cmdletPassedIn.WriteError(
                        new ErrorRecord(
                            new PSInvalidOperationException(
                                message: $"Unable to successfully install package '{pkg.Name}': '{e.Message}'",
                                innerException: e),
                            "InstallPackageFailed",
                            ErrorCategory.InvalidOperation,
                            _cmdletPassedIn));
                    _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
                }
                finally
                {
                    // Delete the temp directory and all its contents
                    _cmdletPassedIn.WriteVerbose(string.Format("Attempting to delete '{0}'", tempInstallPath));

                    if (Directory.Exists(tempInstallPath))
                    {
                        if (!TryDeleteDirectory(tempInstallPath, out ErrorRecord errorMsg))
                        {
                            _cmdletPassedIn.WriteError(errorMsg);
                        }
                        else
                        {
                            _cmdletPassedIn.WriteVerbose(String.Format("Successfully deleted '{0}'", tempInstallPath));
                        }
                    }
                }
            }

            return(pkgsSuccessfullyInstalled);
        }
Example #20
0
        internal static void ResetMachineAccountPassword(string domain, string localMachineName, string server, PSCredential credential, PSCmdlet cmdlet)
        {
            SAMAPI.LSA_UNICODE_STRING structure;
            string            userName;
            string            stringFromSecureString;
            string            cannotFindMachineAccountFromServer;
            DirectoryEntry    directoryEntry    = null;
            DirectoryEntry    directoryEntry1   = null;
            DirectorySearcher directorySearcher = null;
            string            randomPassword    = null;
            string            str  = server;
            string            str1 = str;

            if (str == null)
            {
                str1 = domain;
            }
            string str2 = str1;

            try
            {
                try
                {
                    if (credential != null)
                    {
                        userName = credential.UserName;
                    }
                    else
                    {
                        userName = null;
                    }
                    string str3 = userName;
                    if (credential != null)
                    {
                        stringFromSecureString = Utils.GetStringFromSecureString(credential.Password);
                    }
                    else
                    {
                        stringFromSecureString = null;
                    }
                    string str4 = stringFromSecureString;
                    directoryEntry    = new DirectoryEntry(string.Concat("LDAP://", str2), str3, str4, AuthenticationTypes.Secure);
                    directorySearcher = new DirectorySearcher(directoryEntry);
                    string[] strArrays = new string[5];
                    strArrays[0]             = "(&(objectClass=computer)(|(cn=";
                    strArrays[1]             = localMachineName;
                    strArrays[2]             = ")(dn=";
                    strArrays[3]             = localMachineName;
                    strArrays[4]             = ")))";
                    directorySearcher.Filter = string.Concat(strArrays);
                    SearchResult searchResult = directorySearcher.FindOne();
                    if (searchResult != null)
                    {
                        directoryEntry1 = searchResult.GetDirectoryEntry();
                        randomPassword  = ComputerWMIHelper.GetRandomPassword(120);
                        object[] objArray = new object[1];
                        objArray[0] = randomPassword;
                        directoryEntry1.Invoke("SetPassword", objArray);
                        directoryEntry1.Properties["LockOutTime"].Value = 0;
                    }
                    else
                    {
                        if (server != null)
                        {
                            cannotFindMachineAccountFromServer = ComputerResources.CannotFindMachineAccountFromServer;
                        }
                        else
                        {
                            cannotFindMachineAccountFromServer = ComputerResources.CannotFindMachineAccountFromDomain;
                        }
                        string      str5        = cannotFindMachineAccountFromServer;
                        string      str6        = StringUtil.Format(str5, str2);
                        ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(str6), "CannotFindMachineAccount", ErrorCategory.OperationStopped, localMachineName);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
#if !MONO
                catch (DirectoryServicesCOMException directoryServicesCOMException1)
                {
                    DirectoryServicesCOMException directoryServicesCOMException = directoryServicesCOMException1;
                    string      str7         = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, directoryServicesCOMException.Message);
                    ErrorRecord errorRecord1 = new ErrorRecord(new InvalidOperationException(str7), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName);
                    cmdlet.ThrowTerminatingError(errorRecord1);
                }
#endif
                catch (TargetInvocationException targetInvocationException1)
                {
                    TargetInvocationException targetInvocationException = targetInvocationException1;
                    string      str8         = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, targetInvocationException.InnerException.Message);
                    ErrorRecord errorRecord2 = new ErrorRecord(new InvalidOperationException(str8), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName);
                    cmdlet.ThrowTerminatingError(errorRecord2);
                }
                catch (COMException cOMException1)
                {
                    COMException cOMException = cOMException1;
                    string       str9         = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, cOMException.Message);
                    ErrorRecord  errorRecord3 = new ErrorRecord(new InvalidOperationException(str9), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName);
                    cmdlet.ThrowTerminatingError(errorRecord3);
                }
            }
            finally
            {
                if (directoryEntry != null)
                {
                    directoryEntry.Close();
                    directoryEntry.Dispose();
                }
                if (directorySearcher != null)
                {
                    directorySearcher.Dispose();
                }
                if (directoryEntry1 != null)
                {
                    directoryEntry1.Close();
                    directoryEntry1.Dispose();
                }
            }
            SAMAPI.LSA_OBJECT_ATTRIBUTES zero = new SAMAPI.LSA_OBJECT_ATTRIBUTES();
            zero.RootDirectory            = IntPtr.Zero;
            zero.ObjectName               = IntPtr.Zero;
            zero.Attributes               = 0;
            zero.SecurityDescriptor       = IntPtr.Zero;
            zero.SecurityQualityOfService = IntPtr.Zero;
            zero.Length = Marshal.SizeOf(typeof(SAMAPI.LSA_OBJECT_ATTRIBUTES));
            IntPtr intPtr  = IntPtr.Zero;
            IntPtr zero1   = IntPtr.Zero;
            IntPtr intPtr1 = IntPtr.Zero;
            SAMAPI.LSA_UNICODE_STRING lSAUNICODESTRING = new SAMAPI.LSA_UNICODE_STRING();
            lSAUNICODESTRING.Buffer = IntPtr.Zero;
            SAMAPI.LSA_UNICODE_STRING lSAUNICODESTRING1 = lSAUNICODESTRING;
            SAMAPI.LSA_UNICODE_STRING zero2             = new SAMAPI.LSA_UNICODE_STRING();
            zero2.Buffer = IntPtr.Zero;
            SAMAPI.LSA_UNICODE_STRING lSAUNICODESTRING2 = zero2;
            SAMAPI.LSA_UNICODE_STRING zero3             = new SAMAPI.LSA_UNICODE_STRING();
            zero3.Buffer        = IntPtr.Zero;
            zero3.Length        = 0;
            zero3.MaximumLength = 0;
            try
            {
                uint num = SAMAPI.LsaOpenPolicy(ref zero3, ref zero, 0xf0fff, out intPtr);
                if (num == -1073741790)
                {
                    string      needAdminPrivilegeToResetPassword = ComputerResources.NeedAdminPrivilegeToResetPassword;
                    ErrorRecord errorRecord4 = new ErrorRecord(new InvalidOperationException(needAdminPrivilegeToResetPassword), "UnauthorizedAccessException", ErrorCategory.InvalidOperation, localMachineName);
                    cmdlet.ThrowTerminatingError(errorRecord4);
                }
                if (num != 0)
                {
                    ResetComputerMachinePasswordCommand.ThrowOutLsaError(num, cmdlet);
                }
                SAMAPI.InitLsaString("$MACHINE.ACC", ref lSAUNICODESTRING1);
                SAMAPI.InitLsaString(randomPassword, ref lSAUNICODESTRING2);
                bool flag = false;
                num = SAMAPI.LsaOpenSecret(intPtr, ref lSAUNICODESTRING1, 3, out zero1);
                if (num == -1073741772)
                {
                    num  = SAMAPI.LsaCreateSecret(intPtr, ref lSAUNICODESTRING1, 1, out zero1);
                    flag = true;
                }
                if (num != 0)
                {
                    ResetComputerMachinePasswordCommand.ThrowOutLsaError(num, cmdlet);
                }
                if (!flag)
                {
                    num = SAMAPI.LsaQuerySecret(zero1, out intPtr1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                    if (num != 0)
                    {
                        ResetComputerMachinePasswordCommand.ThrowOutLsaError(num, cmdlet);
                    }
                    structure = (SAMAPI.LSA_UNICODE_STRING)Marshal.PtrToStructure(intPtr1, typeof(SAMAPI.LSA_UNICODE_STRING));
                }
                else
                {
                    structure = lSAUNICODESTRING2;
                }
                num = SAMAPI.LsaSetSecret(zero1, ref lSAUNICODESTRING2, ref structure);
                if (num != 0)
                {
                    ResetComputerMachinePasswordCommand.ThrowOutLsaError(num, cmdlet);
                }
            }
            finally
            {
                if (intPtr1 != IntPtr.Zero)
                {
                    SAMAPI.LsaFreeMemory(intPtr1);
                }
                if (intPtr != IntPtr.Zero)
                {
                    SAMAPI.LsaClose(intPtr);
                }
                if (zero1 != IntPtr.Zero)
                {
                    SAMAPI.LsaClose(zero1);
                }
                SAMAPI.FreeLsaString(ref lSAUNICODESTRING1);
                SAMAPI.FreeLsaString(ref lSAUNICODESTRING2);
            }
        }
Example #21
0
        public IEnumerable <PSResourceInfo> FindByResourceName(
            string[] name,
            ResourceType type,
            string version,
            SwitchParameter prerelease,
            string[] tag,
            string[] repository,
            PSCredential credential,
            SwitchParameter includeDependencies)
        {
            _type                = type;
            _version             = version;
            _prerelease          = prerelease;
            _tag                 = tag;
            _credential          = credential;
            _includeDependencies = includeDependencies;

            Dbg.Assert(name.Length != 0, "Name length cannot be 0");

            _pkgsLeftToFind = name.ToList();

            List <PSRepositoryInfo> repositoriesToSearch;

            try
            {
                repositoriesToSearch = RepositorySettings.Read(repository, out string[] errorList);

                foreach (string error in errorList)
                {
                    _cmdletPassedIn.WriteError(new ErrorRecord(
                                                   new PSInvalidOperationException(error),
                                                   "ErrorGettingSpecifiedRepo",
                                                   ErrorCategory.InvalidOperation,
                                                   this));
                }
            }
            catch (Exception e)
            {
                _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
                                                          new PSInvalidOperationException(e.Message),
                                                          "ErrorLoadingRepositoryStoreFile",
                                                          ErrorCategory.InvalidArgument,
                                                          this));
                yield break;
            }

            // loop through repositoriesToSearch and if PSGallery add it to list with same priority as PSGallery repo
            for (int i = 0; i < repositoriesToSearch.Count; i++)
            {
                if (String.Equals(repositoriesToSearch[i].Name, _psGalleryRepoName, StringComparison.InvariantCultureIgnoreCase))
                {
                    // for PowerShellGallery, Module and Script resources have different endpoints so separate repositories have to be registered
                    // with those endpoints in order for the NuGet APIs to search across both in the case where name includes '*'

                    // detect if Script repository needs to be added and/or Module repository needs to be skipped
                    Uri psGalleryScriptsUrl           = new Uri("http://www.powershellgallery.com/api/v2/items/psscript/");
                    PSRepositoryInfo psGalleryScripts = new PSRepositoryInfo(_psGalleryScriptsRepoName, psGalleryScriptsUrl, repositoriesToSearch[i].Priority, false);
                    if (_type == ResourceType.None)
                    {
                        _cmdletPassedIn.WriteDebug("Null Type provided, so add PSGalleryScripts repository");
                        repositoriesToSearch.Insert(i + 1, psGalleryScripts);
                    }
                    else if (_type != ResourceType.None && _type == ResourceType.Script)
                    {
                        _cmdletPassedIn.WriteDebug("Type Script provided, so add PSGalleryScripts and remove PSGallery (Modules only)");
                        repositoriesToSearch.Insert(i + 1, psGalleryScripts);
                        repositoriesToSearch.RemoveAt(i); // remove PSGallery
                    }
                }
            }

            for (int i = 0; i < repositoriesToSearch.Count && _pkgsLeftToFind.Any(); i++)
            {
                _cmdletPassedIn.WriteDebug(string.Format("Searching in repository {0}", repositoriesToSearch[i].Name));
                foreach (var pkg in SearchFromRepository(
                             repositoryName: repositoriesToSearch[i].Name,
                             repositoryUrl: repositoriesToSearch[i].Url))
                {
                    yield return(pkg);
                }
            }
        }