public CimActivityImplementationContext(ActivityImplementationContext activityImplementationContext, string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism? authenticationMechanism, bool useSsl, uint port, PSSessionOption sessionOption, CimSession session, CimSessionOptions cimSessionOptions, string moduleDefinition, Uri resourceUri)
		{
			if (activityImplementationContext != null)
			{
				base.PowerShellInstance = activityImplementationContext.PowerShellInstance;
				this.ResourceUri = resourceUri;
				this.ComputerName = computerName;
				base.PSCredential = credential;
				base.PSCertificateThumbprint = certificateThumbprint;
				base.PSAuthentication = authenticationMechanism;
				base.PSUseSsl = new bool?(useSsl);
				base.PSPort = new uint?(port);
				base.PSSessionOption = sessionOption;
				this.Session = session;
				this.SessionOptions = cimSessionOptions;
				if (moduleDefinition != null)
				{
					CimActivityImplementationContext._moduleScriptBlock = ScriptBlock.Create(moduleDefinition);
					this._moduleDefinition = moduleDefinition;
				}
				return;
			}
			else
			{
				throw new ArgumentNullException("activityImplementationContext");
			}
		}
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            if (Node != null)
            {
                ResourceGroupName = Node.ResourceGroupName;
                NodeName = Node.Name;
                if (Node.Credential != null && Credential == null)
                {
                    Credential = Node.Credential;
                }
                WriteVerbose("Using Node object to for resourcegroup/node name");
            }

            if (SessionName == null)
            {
                SessionName = Guid.NewGuid().ToString();
                WriteVerbose(string.Format("Generating Session name {0}", SessionName));
            }

            WriteVerbose(string.Format("Getting Session resource for {0}/{1}/{2}",
                ResourceGroupName,
                NodeName,
                SessionName));
            WriteObject(
                Session.Create(Client.Session.Create(ResourceGroupName,
                    NodeName,
                    SessionName,
                    Credential.UserName,
                    ToPlainText(Credential.Password))));
        }
        //Constructor with parameters applicable to all ParameterSets
        private SetAzureServiceDomainJoinExtensionCmdletInfo(DomainJoinExtensionParameterSetType type, string value,
            string[] role, string slot, string serviceName, string thumbprintAlgorithm, bool restart,
            PSCredential credential)
        {
            this.cmdletName = Utilities.SetAzureServiceDomainJoinExtension;

            this.cmdletParams.Add(new CmdletParam(type.ToString(), value));
            if (role != null)
            {
                this.cmdletParams.Add(new CmdletParam("Role", role));
            }
            if (!string.IsNullOrEmpty(slot))
            {
                this.cmdletParams.Add(new CmdletParam("Slot", slot));
            }
            if (!string.IsNullOrEmpty(serviceName))
            {
                this.cmdletParams.Add(new CmdletParam("ServiceName",serviceName));
            }
            if (!string.IsNullOrEmpty(thumbprintAlgorithm))
            {
                this.cmdletParams.Add(new CmdletParam("ThumbprintAlgorithm", thumbprintAlgorithm));
            }
            if (restart)
            {
                this.cmdletParams.Add(new CmdletParam("Restart"));
            }
            if (credential != null)
            {
                this.cmdletParams.Add(new CmdletParam("Credential", credential));
            }
        }
 internal UpdatableHelpSystemDrive(PSCmdlet cmdlet, string path, PSCredential credential)
 {
     for (int i = 0; i < 6; i++)
     {
         this._driveName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
         this._cmdlet = cmdlet;
         if (path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase) || path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
         {
             path = path.Remove(path.Length - 1);
         }
         PSDriveInfo atScope = cmdlet.SessionState.Drive.GetAtScope(this._driveName, "local");
         if (atScope != null)
         {
             if (atScope.Root.Equals(path))
             {
                 return;
             }
             if (i < 5)
             {
                 continue;
             }
             cmdlet.SessionState.Drive.Remove(this._driveName, true, "local");
         }
         atScope = new PSDriveInfo(this._driveName, cmdlet.SessionState.Internal.GetSingleProvider("FileSystem"), path, string.Empty, credential);
         cmdlet.SessionState.Drive.New(atScope, "local");
         return;
     }
 }
        public virtual string OnPremisesEncryptString(SecureString value, string resourceGroupName, string dataFactoryName, string gatewayName, PSCredential credential)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            var response = DataPipelineManagementClient.Gateways.RetrieveConnectionInfo(resourceGroupName, dataFactoryName, gatewayName);
            var gatewayEncryptionInfos = new[]
                {
                    new GatewayEncryptionInfo
                        {
                            ServiceToken = response.ConnectionInfo.ServiceToken,
                            IdentityCertThumbprint = response.ConnectionInfo.IdentityCertThumbprint,
                            HostServiceUri = response.ConnectionInfo.HostServiceUri,
                            InstanceVersionString = response.ConnectionInfo.Version 
                        }
                };

            string userName = credential != null ? credential.UserName : null;
            SecureString password = credential != null ? credential.Password : null;
            UserInputConnectionString connectionString = new UserInputConnectionString(value, userName, password);
            var gatewayEncryptionClient = new GatewayEncryptionClient();
            return gatewayEncryptionClient.Encrypt(connectionString, gatewayEncryptionInfos);
        }
Example #6
0
 internal CmdletProviderContext(CmdletProviderContext contextToCopyFrom)
 {
     this.credentials = PSCredential.Empty;
     this._origin = CommandOrigin.Internal;
     this.accumulatedObjects = new Collection<PSObject>();
     this.accumulatedErrorObjects = new Collection<ErrorRecord>();
     this.stopReferrals = new Collection<CmdletProviderContext>();
     if (contextToCopyFrom == null)
     {
         throw PSTraceSource.NewArgumentNullException("contextToCopyFrom");
     }
     this.executionContext = contextToCopyFrom.ExecutionContext;
     this.command = contextToCopyFrom.command;
     if (contextToCopyFrom.Credential != null)
     {
         this.credentials = contextToCopyFrom.Credential;
     }
     this.drive = contextToCopyFrom.Drive;
     this.force = (bool) contextToCopyFrom.Force;
     this.CopyFilters(contextToCopyFrom);
     this.suppressWildcardExpansion = contextToCopyFrom.SuppressWildcardExpansion;
     this.dynamicParameters = contextToCopyFrom.DynamicParameters;
     this._origin = contextToCopyFrom._origin;
     this.stopping = contextToCopyFrom.Stopping;
     contextToCopyFrom.StopReferrals.Add(this);
     this.copiedContext = contextToCopyFrom;
 }
Example #7
0
        /// <summary>
        /// Constructor to initialize filed.
        /// </summary>
        /// <param name="conn">Endpoint for VTN-coordinator API.</param>
        /// <param name="ip_addr">ODL controller IP.</param>
        /// <param name="credential">Credential to use.</param>
        public Controller(string conn, string ip_addr, PSCredential credential)
        {
            if (string.IsNullOrEmpty(conn))
            {
                throw new ArgumentException("connection string empty");
            }

            if (credential == null)
            {
                throw new ArgumentException("No credential provided.");
            }

            if (string.IsNullOrEmpty(ip_addr))
            {
                throw new ArgumentException("NO Controller IP provided");
            }
            if (!conn.StartsWith(@"https://", StringComparison.Ordinal))
            {
                conn = string.Format(CultureInfo.CurrentCulture,
                    @"https://{0}",
                    conn);
            }
            if (conn.EndsWith(@"/", StringComparison.Ordinal))
            {
                conn = conn.Substring(0, conn.Length - 1);
            }
            NetworkCredential cred = new NetworkCredential(credential.UserName,
                    credential.Password);
            this.Ip = ip_addr.Split(':').FirstOrDefault();
            this.Base_uri = conn;
            this.Credential = cred;
            this.Ctr_type = Constants.CTR_TYPE;
            this.Version = Constants.CTR_VERSION;
            this.Audit_status = Constants.CTR_AUDIT;
        }
Example #8
0
		internal static bool CompareCredential(PSCredential credential1, PSCredential credential2)
		{
			if (credential1 != null || credential2 != null)
			{
				if (!(credential1 == null ^ credential2 == null))
				{
					if (string.Compare(credential1.UserName, credential2.UserName, StringComparison.OrdinalIgnoreCase) == 0)
					{
						if (WorkflowUtils.ComparePassword(credential1.Password, credential2.Password))
						{
							return true;
						}
						else
						{
							return false;
						}
					}
					else
					{
						return false;
					}
				}
				else
				{
					return false;
				}
			}
			else
			{
				return true;
			}
		}
        public virtual string OnPremisesEncryptString(SecureString value, string resourceGroupName, string dataFactoryName, string gatewayName, PSCredential credential, string type, string nonCredentialValue, string authenticationType)
        {
            LinkedServiceType linkedServiceType = type == null ? LinkedServiceType.OnPremisesSqlLinkedService : (LinkedServiceType)Enum.Parse(typeof(LinkedServiceType), type, true);

            if (linkedServiceType != LinkedServiceType.OnPremisesOdbcLinkedService && (value == null || value.Length == 0))
            {
                throw new ArgumentNullException("value");
            }

            AuthenticationType authType = authenticationType == null ? AuthenticationType.None : (AuthenticationType)Enum.Parse(typeof(AuthenticationType), authenticationType, true);

            var response = DataPipelineManagementClient.Gateways.RetrieveConnectionInfo(resourceGroupName, dataFactoryName, gatewayName);
            var gatewayEncryptionInfos = new[]
                {
                    new GatewayEncryptionInfo
                        {
                            ServiceToken = response.ConnectionInfo.ServiceToken,
                            IdentityCertThumbprint = response.ConnectionInfo.IdentityCertThumbprint,
                            HostServiceUri = response.ConnectionInfo.HostServiceUri,
                            InstanceVersionString = response.ConnectionInfo.Version 
                        }
                };

            string userName = credential != null ? credential.UserName : null;
            SecureString password = credential != null ? credential.Password : null;
            UserInputConnectionString connectionString = new UserInputConnectionString(value, nonCredentialValue, userName, password, linkedServiceType, authType);
            return GatewayEncryptionClient.Encrypt(connectionString, gatewayEncryptionInfos);
        }
        public void TestOnPremDatasourceEncryptionWinAuth()
        {
            SecureString secureString = new SecureString();
            string expectedOutput = "My encrypted string " + Guid.NewGuid();
            string winAuthUserName = "******";
            SecureString winAuthPassword = new SecureString();
            PSCredential credential = new PSCredential(winAuthUserName, winAuthPassword);
            string linkedServiceType = "OnPremisesFileSystemLinkedService";
            string nonCredentialValue = "Driver=mydriver;server=myserver";
            string authenticationType = "Basic";

            var cmdlet = new NewAzureDataFactoryEncryptValueCommand
            {
                CommandRuntime = this.commandRuntimeMock.Object,
                DataFactoryClient = this.dataFactoriesClientMock.Object,
                Value = secureString,
                ResourceGroupName = ResourceGroupName,
                DataFactoryName = DataFactoryName,
                GatewayName = GatewayName,
                Credential = credential,
                Type = linkedServiceType,
                NonCredentialValue = nonCredentialValue,
                AuthenticationType = authenticationType
            };

            // Arrange
            this.dataFactoriesClientMock.Setup(f => f.OnPremisesEncryptString(secureString, ResourceGroupName, DataFactoryName, GatewayName, credential, linkedServiceType, nonCredentialValue, authenticationType)).Returns(expectedOutput);

            // Action
            cmdlet.ExecuteCmdlet();

            // Assert
            this.dataFactoriesClientMock.Verify(f => f.OnPremisesEncryptString(secureString, ResourceGroupName, DataFactoryName, GatewayName, credential, linkedServiceType, nonCredentialValue, authenticationType), Times.Once());
            this.commandRuntimeMock.Verify(f => f.WriteObject(expectedOutput), Times.Once());
        }
Example #11
0
        private CimSessionProxy CreateSessionProxy(string computerName, GetCimClassCommand cmdlet)
        {
            CimSessionProxy cimSessionProxyGetCimClass = null;

            if (!string.IsNullOrEmpty(computerName) && !computerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
            {
                /* Set on the fly credentials */
                System.Management.Automation.PSCredential credential = GetOnTheFlyCredentials(cmdlet);
                if (credential == null)
                {
                    cimSessionProxyGetCimClass = new CimSessionProxyGetCimClass(computerName);
                }
                else
                {
                    CimSessionOptions options = new WSManSessionOptions();
                    options.AddDestinationCredentials(cmdlet.CreateCimCredentials(credential, PasswordAuthenticationMechanism.Default, "Get-CimClass", "Authentication"));
                    cimSessionProxyGetCimClass = new CimSessionProxyGetCimClass(computerName, options);
                }
            }
            else
            {
                cimSessionProxyGetCimClass = new CimSessionProxyGetCimClass(computerName);
            }
            base.SubscribeEventAndAddProxytoCache(cimSessionProxyGetCimClass);
            this.SetSessionProxyProperties(ref cimSessionProxyGetCimClass, cmdlet);
            return(cimSessionProxyGetCimClass);
        }
Example #12
0
        /// <summary>
        /// Constructor to initialize filed.
        /// </summary>
        /// <param name="conn">Endpoint for VTN-coordinator API.</param>
        /// <param name="credential">Credential to use.</param>
        public Controller(string conn, PSCredential credential)
        {
            if (string.IsNullOrEmpty(conn))
            {
                throw new ArgumentException("connection string empty");
            }

            if (credential == null)
            {
                throw new ArgumentException("No credential provided.");
            }
            if (!conn.StartsWith(@"https://", StringComparison.Ordinal))
            {
                conn = string.Format(CultureInfo.CurrentCulture,
                    @"https://{0}",
                    conn);
            }
            if (conn.EndsWith(@"/", StringComparison.Ordinal))
            {
                conn = conn.Substring(0, conn.Length - 1);
            }
            NetworkCredential cred = new NetworkCredential(credential.UserName,
                    credential.Password);
            this.Base_uri = conn;
            this.Credential = cred;
        }
Example #13
0
        /// <summary>
        /// Constructor to initialize fields.
        /// </summary>
        /// <param name="apiEndpoint">Endpoint for ODL API.</param>
        /// <param name="credential">Credential to use.</param>
        public Vtn(string apiEndpoint, PSCredential credential)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"apiEndpoint\":" + JavaScriptSerializer.Serialize(apiEndpoint));
            ODLVSEMETW.EventWriteStartODLLibrary(
                MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                json.ToString());
            if (string.IsNullOrEmpty(apiEndpoint)) {
                throw new ArgumentException("No API endpoint specified.");
            }

            if (credential == null) {
                throw new ArgumentException("No credential provided.");
            }

            NetworkCredential cred = new NetworkCredential(credential.UserName,
                credential.Password);
            if (!apiEndpoint.StartsWith(@"https://", StringComparison.Ordinal)) {
                apiEndpoint = string.Format(CultureInfo.CurrentCulture,
                    @"https://{0}",
                    apiEndpoint);
            }
            if (apiEndpoint.EndsWith(@"/", StringComparison.Ordinal)) {
                apiEndpoint = apiEndpoint.Substring(0, apiEndpoint.Length - 1);
            }

            this.ApiEndpoint = apiEndpoint;
            this.Credential = cred;
            ODLVSEMETW.EventWriteEndODLLibrary(
                MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(), string.Empty);
        }
        public void SetAzureAutomationCredentialByNameWithParametersSuccessfull()
        {
            // Setup
            string accountName = "automation";
            string credentialName = "credential";
            string username = "******";
            string password = "******";
            string description = "desc";

            var secureString = new SecureString();
            Array.ForEach(password.ToCharArray(), secureString.AppendChar);
            secureString.MakeReadOnly();

            var value = new PSCredential(username, secureString);

            this.mockAutomationClient.Setup(f => f.UpdateCredential(accountName, credentialName, username, password, description));

            // Test
            this.cmdlet.AutomationAccountName = accountName;
            this.cmdlet.Name = credentialName;
            this.cmdlet.Description = description;
            this.cmdlet.Value = value;
            this.cmdlet.ExecuteCmdlet();

            // Assert
            this.mockAutomationClient.Verify(f => f.UpdateCredential(accountName, credentialName, username, password, description), Times.Once());
        }
 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
     if (context == null || context.Instance == null)
     {
         return base.EditValue(context, provider, value);
     }
     else
     {
         value = null;
         NetworkCredential creds = GetCredential();
         if (creds != null)
         {
             System.Security.SecureString pwd = new System.Security.SecureString();
             foreach(var c in creds.Password) 
             {
                 pwd.AppendChar(c);
             }
             PSCredential rtncrds = new PSCredential(creds.UserName, pwd);
             creds = null;
             pwd = null;
             GC.Collect();
             value = rtncrds;
         }
         return value;
     }
 }
Example #16
0
 public PSDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential)
 {
     this.credentials = PSCredential.Empty;
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     if (provider == null)
     {
         throw PSTraceSource.NewArgumentNullException("provider");
     }
     if (root == null)
     {
         throw PSTraceSource.NewArgumentNullException("root");
     }
     this.name = name;
     this.provider = provider;
     this.root = root;
     this.description = description;
     if (credential != null)
     {
         this.credentials = credential;
     }
     this.currentWorkingDirectory = string.Empty;
     this.Trace();
 }
 public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
 {
     this._syncObject = new object();
     string pSExePath = PSExePath;
     if (useWow64)
     {
         string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
         if (!string.IsNullOrEmpty(environmentVariable) && (environmentVariable.Equals("amd64", StringComparison.OrdinalIgnoreCase) || environmentVariable.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
         {
             pSExePath = PSExePath.ToLowerInvariant().Replace(@"\system32\", @"\syswow64\");
             if (!System.IO.File.Exists(pSExePath))
             {
                 throw new PSInvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.IPCWowComponentNotPresent, new object[] { pSExePath }));
             }
         }
     }
     string str4 = string.Empty;
     Version version = powerShellVersion ?? PSVersionInfo.PSVersion;
     if (null == version)
     {
         version = new Version(3, 0);
     }
     str4 = string.Format(CultureInfo.InvariantCulture, "-Version {0}", new object[] { new Version(version.Major, version.Minor) });
     str4 = string.Format(CultureInfo.InvariantCulture, "{0} -s -NoLogo -NoProfile", new object[] { str4 });
     if (initializationScript != null)
     {
         string str5 = initializationScript.ToString();
         if (!string.IsNullOrEmpty(str5))
         {
             string str6 = Convert.ToBase64String(Encoding.Unicode.GetBytes(str5));
             str4 = string.Format(CultureInfo.InvariantCulture, "{0} -EncodedCommand {1}", new object[] { str4, str6 });
         }
     }
     ProcessStartInfo info = new ProcessStartInfo {
         FileName = useWow64 ? pSExePath : PSExePath,
         Arguments = str4,
         UseShellExecute = false,
         RedirectStandardInput = true,
         RedirectStandardOutput = true,
         RedirectStandardError = true,
         WindowStyle = ProcessWindowStyle.Hidden,
         CreateNoWindow = true,
         LoadUserProfile = true
     };
     this._startInfo = info;
     if (credential != null)
     {
         NetworkCredential networkCredential = credential.GetNetworkCredential();
         this._startInfo.UserName = networkCredential.UserName;
         this._startInfo.Domain = string.IsNullOrEmpty(networkCredential.Domain) ? "." : networkCredential.Domain;
         this._startInfo.Password = credential.Password;
     }
     System.Diagnostics.Process process = new System.Diagnostics.Process {
         StartInfo = this._startInfo,
         EnableRaisingEvents = true
     };
     this._process = process;
 }
 public NewAzureServiceRemoteDesktopExtensionConfigCmdletInfo(PSCredential credential, string thumbprint, string algorithm, DateTime? expiration, string[] roles)
     : this(credential, expiration, roles)
 {
     this.cmdletParams.Add(new CmdletParam("CertificateThumbprint", thumbprint));
     if (!string.IsNullOrEmpty(algorithm))
     {
         this.cmdletParams.Add(new CmdletParam("ThumbprintAlgorithm", algorithm));
     }
 }
Example #19
0
 public PSDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential)
 {
     Name = name;
     Provider = provider;
     Root = root;
     Description = description;
     Credential = credential;
     CurrentLocation = string.Empty;
 }
 private NewAzureServiceDomainJoinExtensionConfigCmdletInfo(string domainName, JoinOptions? options, string oUPath, PSCredential unjoinDomainCredential,
     string[] role, string thumbprintAlgorithm, bool restart, PSCredential credential)
     : this(domainName, oUPath, unjoinDomainCredential, role, thumbprintAlgorithm, restart, credential)
 {
     if (options.HasValue)
     {
         this.cmdletParams.Add(new CmdletParam("Options", options.Value));
     }
 }
 // WorkgroupThumbprintParameterSet
 public NewAzureServiceDomainJoinExtensionConfigCmdletInfo(string workGroupName, string certificateThumbprint, string[] role, string thumbprintAlgorithm, bool restart, PSCredential credential)
     : this(role, thumbprintAlgorithm, restart, credential)
 {
     this.cmdletParams.Add(new CmdletParam("WorkGroupName", workGroupName));
     if (!string.IsNullOrEmpty(certificateThumbprint))
     {
         this.cmdletParams.Add(new CmdletParam("CertificateThumbprint", certificateThumbprint));
     }
 }
 // WorkgroupParameterSet
 public NewAzureServiceDomainJoinExtensionConfigCmdletInfo(string workGroupName, X509Certificate2 certificate,string[] role, string thumbprintAlgorithm, bool restart, PSCredential credential)
     : this(role, thumbprintAlgorithm, restart, credential)
 {
     this.cmdletParams.Add(new CmdletParam("WorkGroupName", workGroupName));
     if (certificate != null)
     {
         this.cmdletParams.Add(new CmdletParam("X509Certificate", certificate));
     }
 }
 public SetAzureServiceRemoteDesktopExtensionCmdletInfo
     (string serviceName, PSCredential credential, string thumbprint, string algorithm, DateTime? expiration, string[] roles, string slot, string version)
     : this(serviceName, credential, expiration, roles, slot, version)
 {
     this.cmdletParams.Add(new CmdletParam("CertificateThumbprint", thumbprint));
     if (!string.IsNullOrEmpty(algorithm))
     {
         this.cmdletParams.Add(new CmdletParam("ThumbprintAlgorithm", algorithm));
     }
 }
 public FabrikamCauPlugin(string clusterName,
                          PSCredential credential,
                          Hashtable arguments,
                          CancellationToken cancelToken)
 {
     m_clusterName = clusterName;
     m_credential = credential;
     m_arguments = arguments;
     m_cancelToken = cancelToken;
 }
 public PremiumClusterTests()
 {
     base.SetupTestsForManagement();
     _httpCred = new PSCredential("hadoopuser", string.Format("Password1!").ConvertToSecureString());
     cmdlet = new NewAzureHDInsightClusterCommand
     {
         CommandRuntime = commandRuntimeMock.Object,
         HDInsightManagementClient = hdinsightManagementMock.Object
     };
 }
Example #26
0
		public static bool MatchCredentials(PSCredential cacheCred, PSCredential userCred)
		{
			if (!ADPasswordUtils.MatchPassword(cacheCred.Password, userCred.Password))
			{
				return false;
			}
			else
			{
				return string.Equals(cacheCred.UserName, userCred.UserName, StringComparison.OrdinalIgnoreCase);
			}
		}
Example #27
0
 public AzureDriveInfo(Rule aliasRule, ProviderInfo providerInfo, PSCredential psCredential = null)
     : base(GetDriveInfo(aliasRule, providerInfo, psCredential))
 {
     Path = new Path {
         Account = aliasRule.HasProperty("key") ? aliasRule["key"].Value : aliasRule.Parameter,
         Container = aliasRule.HasProperty("container") ? aliasRule["container"].Value : "",
         SubPath = aliasRule.HasProperty("root") ? aliasRule["root"].Value.Replace('/', '\\').Replace("\\\\", "\\").Trim('\\') : "",
     };
     Path.Validate();
     Secret = aliasRule.HasProperty("secret") ? aliasRule["secret"].Value : psCredential != null ? psCredential.Password.ToString() : null;
 }
 public NewClusterTests(Xunit.Abstractions.ITestOutputHelper output)
 {
     ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
     base.SetupTestsForManagement();
     _httpCred = new PSCredential("hadoopuser", string.Format("Password1!").ConvertToSecureString());
     cmdlet = new NewAzureHDInsightClusterCommand
     {
         CommandRuntime = commandRuntimeMock.Object,
         HDInsightManagementClient = hdinsightManagementMock.Object
     };
 }
 static PowerShellSupport()
 {
     var password = new SecureString();
     var plainPassword
         = Properties.Settings.Default["PowershellPassword"].ToString();
     foreach (var c in plainPassword)
     {
         password.AppendChar(c);
     }
     PsCredential = new PSCredential(Properties.Settings.Default["PowershellUsername"].ToString(), password);
 }
Example #30
0
 public SPOnlineConnection(ClientContext context, ConnectionTypes connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential)
 {
     if (context == null)
         throw new ArgumentNullException("context");
     this.Context = context;
     this.ConnectionType = connectionType;
     this.MinimalHealthScore = minimalHealthScore;
     this.RetryCount = retryCount;
     this.RetryWait = retryWait;
     this.PSCredential = credential;
 }
 public static CookieContainer GetCookies(string url, PSCredential credential)
 {
     if (credential == null || string.IsNullOrEmpty(credential.UserName) ||
         credential.Password == null || credential.Password.Length == 0)
         throw new ArgumentException(
             "Explicit credentials are needed to connect to Office 365.");
     var credentials = credential.GetCredentials();
     var helper = new MsOnlineClaimsHelper(credential.UserName,
         credential.Password.ToInsecureString(), url);
     return helper.CookieContainer;
 }
Example #32
0
 public PSCredential(PSCredential credential)
 {
     username = credential.username;
     password = credential.Password.Copy();
 }
Example #33
0
 public PSDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential)
 {
     Name            = name;
     Provider        = provider;
     Root            = root;
     Description     = description;
     Credential      = credential;
     CurrentLocation = string.Empty;
 }
Example #34
0
        internal static PSCredential CredUIPromptForCredential(
            string caption,
            string message,
            string userName,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options,
            IntPtr parentHWND)
        {
            PSCredential cred = null;

            // From WinCred.h
            const int CRED_MAX_USERNAME_LENGTH      = (256 + 1 + 256);
            const int CRED_MAX_CREDENTIAL_BLOB_SIZE = 512;
            const int CRED_MAX_PASSWORD_LENGTH      = CRED_MAX_CREDENTIAL_BLOB_SIZE / 2;
            const int CREDUI_MAX_MESSAGE_LENGTH     = 1024;
            const int CREDUI_MAX_CAPTION_LENGTH     = 128;

            // Populate the UI text with defaults, if required
            if (string.IsNullOrEmpty(caption))
            {
                caption = CredUI.PromptForCredential_DefaultCaption;
            }

            if (string.IsNullOrEmpty(message))
            {
                message = CredUI.PromptForCredential_DefaultMessage;
            }

            if (caption.Length > CREDUI_MAX_CAPTION_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidCaption, CREDUI_MAX_CAPTION_LENGTH));
            }

            if (message.Length > CREDUI_MAX_MESSAGE_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidMessage, CREDUI_MAX_MESSAGE_LENGTH));
            }

            if (userName != null && userName.Length > CRED_MAX_USERNAME_LENGTH)
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, CredUI.PromptForCredential_InvalidUserName, CRED_MAX_USERNAME_LENGTH));
            }

            CREDUI_INFO credUiInfo = new CREDUI_INFO();

            credUiInfo.pszCaptionText = caption;
            credUiInfo.pszMessageText = message;

            StringBuilder usernameBuilder = new StringBuilder(userName, CRED_MAX_USERNAME_LENGTH);
            StringBuilder passwordBuilder = new StringBuilder(CRED_MAX_PASSWORD_LENGTH);

            bool save            = false;
            int  saveCredentials = Convert.ToInt32(save);

            credUiInfo.cbSize     = Marshal.SizeOf(credUiInfo);
            credUiInfo.hwndParent = parentHWND;

            CREDUI_FLAGS flags = CREDUI_FLAGS.DO_NOT_PERSIST;

            // Set some of the flags if they have not requested a domain credential
            if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain)
            {
                flags |= CREDUI_FLAGS.GENERIC_CREDENTIALS;

                // If they've asked to always prompt, do so.
                if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
                {
                    flags |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
                }
            }

            // To prevent buffer overrun attack, only attempt call if buffer lengths are within bounds.
            CredUIReturnCodes result = CredUIReturnCodes.ERROR_INVALID_PARAMETER;

            if (usernameBuilder.Length <= CRED_MAX_USERNAME_LENGTH && passwordBuilder.Length <= CRED_MAX_PASSWORD_LENGTH)
            {
                result = CredUIPromptForCredentials(
                    ref credUiInfo,
                    targetName,
                    IntPtr.Zero,
                    0,
                    usernameBuilder,
                    CRED_MAX_USERNAME_LENGTH,
                    passwordBuilder,
                    CRED_MAX_PASSWORD_LENGTH,
                    ref saveCredentials,
                    flags);
            }

            if (result == CredUIReturnCodes.NO_ERROR)
            {
                // Extract the username
                string credentialUsername = null;
                if (usernameBuilder != null)
                {
                    credentialUsername = usernameBuilder.ToString();
                }

                // Trim the leading '\' from the username, which CredUI automatically adds
                // if you don't specify a domain.
                // This is a really common bug in V1 and V2, causing everybody to have to do
                // it themselves.
                // This could be a breaking change for hosts that do hard-coded hacking:
                // $cred.UserName.SubString(1, $cred.Username.Length - 1)
                // But that's OK, because they would have an even worse bug when you've
                // set the host (ConsolePrompting = true) configuration (which does not do this).
                credentialUsername = credentialUsername.TrimStart('\\');

                // Extract the password into a SecureString, zeroing out the memory
                // as soon as possible.
                SecureString password = new SecureString();
                for (int counter = 0; counter < passwordBuilder.Length; counter++)
                {
                    password.AppendChar(passwordBuilder[counter]);
                    passwordBuilder[counter] = (char)0;
                }

                if (!String.IsNullOrEmpty(credentialUsername))
                {
                    cred = new PSCredential(credentialUsername, password);
                }
                else
                {
                    cred = null;
                }
            }
            else // result is not CredUIReturnCodes.NO_ERROR
            {
                cred = null;
            }

            return(cred);
        }
        private static CimCredential GetCimCredentials(PasswordAuthenticationMechanism authenticationMechanism, PSCredential credential)
        {
            NetworkCredential networkCredential = credential.GetNetworkCredential();

            return(new CimCredential(authenticationMechanism, networkCredential.Domain, networkCredential.UserName, credential.Password));
        }
        private static CimCredential GetCimCredentials(string authentication, PSCredential credential)
        {
            if (authentication is null || (authentication.Equals("Default", StringComparison.OrdinalIgnoreCase)))
            {
                if (credential is null)
                {
                    return(null);
                }
                else
                {
                    return(GetCimCredentials(PasswordAuthenticationMechanism.Default, credential));
                }
            }

            if (authentication.Equals("Basic", StringComparison.OrdinalIgnoreCase))
            {
                if (credential is null)
                {
                    throw GetExceptionWhenAuthenticationRequiresCredential(authentication);
                }
                else
                {
                    return(GetCimCredentials(PasswordAuthenticationMechanism.Basic, credential));
                }
            }

            if (authentication.Equals("Negotiate", StringComparison.OrdinalIgnoreCase))
            {
                if (credential is null)
                {
                    return(new CimCredential(ImpersonatedAuthenticationMechanism.Negotiate));
                }
                else
                {
                    return(GetCimCredentials(PasswordAuthenticationMechanism.Negotiate, credential));
                }
            }

            if (authentication.Equals("CredSSP", StringComparison.OrdinalIgnoreCase))
            {
                if (credential is null)
                {
                    throw GetExceptionWhenAuthenticationRequiresCredential(authentication);
                }
                else
                {
                    return(GetCimCredentials(PasswordAuthenticationMechanism.CredSsp, credential));
                }
            }

            if (authentication.Equals("Digest", StringComparison.OrdinalIgnoreCase))
            {
                if (credential is null)
                {
                    throw GetExceptionWhenAuthenticationRequiresCredential(authentication);
                }
                else
                {
                    return(GetCimCredentials(PasswordAuthenticationMechanism.Digest, credential));
                }
            }

            if (authentication.Equals("Kerberos", StringComparison.OrdinalIgnoreCase))
            {
                if (credential is null)
                {
                    return(new CimCredential(ImpersonatedAuthenticationMechanism.Kerberos));
                }
                else
                {
                    return(GetCimCredentials(PasswordAuthenticationMechanism.Kerberos, credential));
                }
            }

            Dbg.Assert(false, "Unrecognized authentication mechanism [ValidateSet should prevent that from happening]");
            throw new ArgumentOutOfRangeException(nameof(authentication));
        }