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"); } }
internal AuthenticationMechanismServiceModel(AuthenticationMechanism azureModel) { switch (azureModel.Type) { case Microsoft.Azure.Devices.AuthenticationType.Sas: PrimaryKey = azureModel.SymmetricKey.PrimaryKey; SecondaryKey = azureModel.SymmetricKey.SecondaryKey; break; case Microsoft.Azure.Devices.AuthenticationType.SelfSigned: AuthenticationType = AuthenticationType.SelfSigned; PrimaryThumbprint = azureModel.X509Thumbprint.PrimaryThumbprint; SecondaryThumbprint = azureModel.X509Thumbprint.SecondaryThumbprint; break; case Microsoft.Azure.Devices.AuthenticationType.CertificateAuthority: AuthenticationType = AuthenticationType.CertificateAuthority; PrimaryThumbprint = azureModel.X509Thumbprint.PrimaryThumbprint; SecondaryThumbprint = azureModel.X509Thumbprint.SecondaryThumbprint; break; default: throw new ArgumentException("Not supported authentcation type"); } }
protected override void ValidateWithDataObject(IConfigurable dataObject) { base.ValidateWithDataObject(dataObject); PopSubscriptionProxy popSubscriptionProxy = (PopSubscriptionProxy)dataObject; AuthenticationMechanism authenticationMechanism = base.Fields.IsModified("IncomingAuth") ? this.IncomingAuth : popSubscriptionProxy.IncomingAuthentication; SecureString password = this.password ?? popSubscriptionProxy.Subscription.LogonPasswordSecured; string text = base.Fields.IsModified("IncomingUserName") ? base.IncomingUserName : popSubscriptionProxy.IncomingUserName; AggregationTaskUtils.ValidateUserName(text, new Task.TaskErrorLoggingDelegate(base.WriteDebugInfoAndError)); if (authenticationMechanism == AuthenticationMechanism.Basic) { AggregationTaskUtils.ValidateUnicodeInfoOnUserNameAndPassword(text, password, new Task.TaskErrorLoggingDelegate(base.WriteDebugInfoAndError)); } string text2 = base.Fields.IsModified("IncomingServer") ? base.IncomingServer : popSubscriptionProxy.IncomingServer; AggregationTaskUtils.ValidateIncomingServerLength(text2, new Task.TaskErrorLoggingDelegate(base.WriteDebugInfoAndError)); if (!base.ShouldSkipAccountValidation()) { bool leaveOnServer = base.Fields.IsModified("LeaveOnServer") ? this.LeaveOnServer : popSubscriptionProxy.LeaveOnServer; int port = base.Fields.IsModified("IncomingPort") ? base.IncomingPort : popSubscriptionProxy.IncomingPort; SecurityMechanism security = base.Fields.IsModified("IncomingSecurity") ? this.IncomingSecurity : popSubscriptionProxy.IncomingSecurity; LocalizedException exception; if (!Pop3AutoProvision.ValidatePopSettings(leaveOnServer, popSubscriptionProxy.AggregationType == AggregationType.Mirrored, text2, port, text, password, authenticationMechanism, security, popSubscriptionProxy.Subscription.UserLegacyDN, CommonLoggingHelper.SyncLogSession, out exception)) { base.WriteDebugInfoAndError(exception, (ErrorCategory)1003, dataObject); } } }
public async Task GetModuleOnBehalfOf() { // Setup ServiceIdentity results string parentEdgeId = "edge1"; string childEdgeId = "edge2"; string moduleId = "module1"; string deviceScope = "deviceScope1"; string parentScope = "parentScope1"; string generationId = "generation1"; var authentication = new ServiceAuthentication(new SymmetricKeyAuthentication(this.primaryKey, this.secondaryKey)); var resultDeviceIdentity = new ServiceIdentity(childEdgeId, null, deviceScope, new List <string>() { parentScope }, generationId, Enumerable.Empty <string>(), authentication, ServiceIdentityStatus.Enabled); var resultModuleIdentity = new ServiceIdentity(childEdgeId, moduleId, null, new List <string>() { deviceScope }, generationId, Enumerable.Empty <string>(), authentication, ServiceIdentityStatus.Enabled); var resultIdentities = new List <ServiceIdentity>() { resultDeviceIdentity, resultModuleIdentity }; var authChainMapping = new Dictionary <string, string>(); string targetId = childEdgeId + "/" + moduleId; authChainMapping.Add(targetId, $"{targetId};{childEdgeId};{parentEdgeId};edgeroot"); var controller = MakeController(childEdgeId, resultIdentities, authChainMapping); // Act controller.Request.Headers.Add(Constants.OriginEdgeHeaderKey, $"{childEdgeId}"); var request = new IdentityOnBehalfOfRequest(childEdgeId, moduleId, $"{childEdgeId};{parentEdgeId}"); await controller.GetDeviceAndModuleOnBehalfOfAsync(parentEdgeId, "$edgeHub", request); // Verify EdgeHub result types var expectedAuth = new AuthenticationMechanism() { SymmetricKey = new SymmetricKey() { PrimaryKey = this.primaryKey, SecondaryKey = this.secondaryKey } }; var expectedDeviceIdentities = new List <EdgeHubScopeDevice>() { new EdgeHubScopeDevice(childEdgeId, generationId, DeviceStatus.Enabled, expectedAuth, new DeviceCapabilities(), deviceScope, new List <string> { parentScope }) }; var expectedModuleIdentities = new List <EdgeHubScopeModule>() { new EdgeHubScopeModule(moduleId, childEdgeId, generationId, expectedAuth) }; var responseExpected = new EdgeHubScopeResultSuccess(expectedDeviceIdentities, expectedModuleIdentities); var responseExpectedJson = JsonConvert.SerializeObject(responseExpected); var responseActualBytes = GetResponseBodyBytes(controller); var responseActualJson = Encoding.UTF8.GetString(responseActualBytes); Assert.Equal((int)HttpStatusCode.OK, controller.HttpContext.Response.StatusCode); Assert.Equal(responseExpectedJson, responseActualJson); }
/// <summary> /// Convert twin to module /// </summary> /// <param name="auth"></param> /// <returns></returns> public static DeviceAuthenticationModel ToModel(this AuthenticationMechanism auth) { return(new DeviceAuthenticationModel { PrimaryKey = auth.SymmetricKey.PrimaryKey, SecondaryKey = auth.SymmetricKey.SecondaryKey }); }
static void ValidateAuthentication(AuthenticationMechanism authenticationMechanism, ServiceAuthentication serviceIdentityAuthentication) { Assert.NotNull(serviceIdentityAuthentication); switch (authenticationMechanism.Type) { case AuthenticationType.Sas: Assert.Equal(ServiceAuthenticationType.SymmetricKey, serviceIdentityAuthentication.Type); Assert.True(serviceIdentityAuthentication.SymmetricKey.HasValue); Assert.False(serviceIdentityAuthentication.X509Thumbprint.HasValue); Assert.Equal(authenticationMechanism.SymmetricKey.PrimaryKey, serviceIdentityAuthentication.SymmetricKey.OrDefault().PrimaryKey); Assert.Equal(authenticationMechanism.SymmetricKey.SecondaryKey, serviceIdentityAuthentication.SymmetricKey.OrDefault().SecondaryKey); break; case AuthenticationType.CertificateAuthority: Assert.Equal(ServiceAuthenticationType.CertificateAuthority, serviceIdentityAuthentication.Type); Assert.False(serviceIdentityAuthentication.X509Thumbprint.HasValue); Assert.False(serviceIdentityAuthentication.SymmetricKey.HasValue); break; case AuthenticationType.SelfSigned: Assert.Equal(ServiceAuthenticationType.CertificateThumbprint, serviceIdentityAuthentication.Type); Assert.True(serviceIdentityAuthentication.X509Thumbprint.HasValue); Assert.False(serviceIdentityAuthentication.SymmetricKey.HasValue); Assert.Equal(authenticationMechanism.X509Thumbprint.PrimaryThumbprint, serviceIdentityAuthentication.X509Thumbprint.OrDefault().PrimaryThumbprint); Assert.Equal(authenticationMechanism.X509Thumbprint.SecondaryThumbprint, serviceIdentityAuthentication.X509Thumbprint.OrDefault().SecondaryThumbprint); break; case AuthenticationType.None: Assert.Equal(ServiceAuthenticationType.None, serviceIdentityAuthentication.Type); Assert.False(serviceIdentityAuthentication.X509Thumbprint.HasValue); Assert.False(serviceIdentityAuthentication.SymmetricKey.HasValue); break; } }
private MonadConnectionInfo ConnectTenantWithDefaultCredential() { AuthenticationMechanism[] authMechanisms = new AuthenticationMechanism[] { AuthenticationMechanism.NegotiateWithImplicitCredential }; return(this.TryAuthenticationMechanisms(null, authMechanisms)); }
private MonadConnectionInfo ConnectOnPremiseWithDefaultCredential() { AuthenticationMechanism[] authMechanisms = new AuthenticationMechanism[] { AuthenticationMechanism.Kerberos }; return(this.TryAuthenticationMechanisms(null, authMechanisms)); }
private MonadConnectionInfo ConnectRemoteOnPremiseWithHttps(PSCredential cred) { AuthenticationMechanism[] authMechanisms = new AuthenticationMechanism[] { AuthenticationMechanism.Basic }; return(this.TryAuthenticationMechanisms(cred, authMechanisms)); }
private AuthenticationMechanism GetAuthMechanism() { var timeout = TimeSpan.FromSeconds(5); Log.Debug($"Determining the Auth Mechanism"); AuthenticationMechanism result = AuthenticationMechanism.Undefined; this.Driver.WaitUntil(d => { var pwdLocator = By.Name(PasswordInputName); var appAuthLocator = By.Id(AuthAppId); IWebElement element = null; int i = 0; while (element == null && i++ < 100) { this.Driver.DoWait(); var elementLocator = i % 2 == 0 ? pwdLocator : appAuthLocator; try { element = this.Driver.FindElement(elementLocator); var displayed = element?.Displayed; Log.Debug(() => $"{elementLocator} displayed: {displayed}"); } catch (StaleElementReferenceException) { Log.Debug(() => $"Element {elementLocator} is stale"); } catch (NoSuchElementException) { Log.Debug(() => $"Element {elementLocator} cannot be found"); } } if (element != null) { var name = element.GetAttribute("name"); var id = element.GetAttribute("id"); if (string.Equals(name, PasswordInputName, StringComparison.InvariantCultureIgnoreCase)) { result = AuthenticationMechanism.Password; } if (string.Equals(id, AuthAppId, StringComparison.InvariantCultureIgnoreCase)) { result = AuthenticationMechanism.AuthenticatorApp; } } Log.Info(() => $"Auth mechanism is {result}"); return(element != null); }, throwOnTimeout: false, timeout); return(result); }
public String RunPSScript(string scriptText) { String AD_Admin = GetParam("ADUsername", "Active Directory Administrator username"); String AD_Password = GetParam("ADPassword", "Active Directory Administrator password"); String ExchangeServer = GetParam("ExchangeServer", "Exchange Server Powershell URL"); var secure = new SecureString(); foreach (char c in AD_Password.ToCharArray()) { secure.AppendChar(c); } PSCredential credential = new PSCredential(AD_Admin, secure); int iRemotePort = 5985; string strShellURI = @"http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; string strAppName = @"/wsman"; AuthenticationMechanism auth = AuthenticationMechanism.Negotiate; WSManConnectionInfo ci = new WSManConnectionInfo( false, ExchangeServer, iRemotePort, strAppName, strShellURI, credential); ci.AuthenticationMechanism = auth; Runspace runspace = RunspaceFactory.CreateRunspace(ci); runspace.Open(); PowerShell psh = PowerShell.Create(); psh.AddCommand("Out-String"); psh.Commands.AddScript(scriptText); psh.Runspace = runspace; Collection <PSObject> results = psh.Invoke(); Collection <ErrorRecord> errors = psh.Streams.Error.ReadAll(); StringBuilder stringBuilder = new StringBuilder(); foreach (ErrorRecord obj in errors) { stringBuilder.AppendFormat("Script Error: {0} ", obj.Exception.Message.ToString()); } runspace.Close(); runspace.Dispose(); psh.Dispose(); return(stringBuilder.ToString()); }
public MachineManager(string ipAddress, int port, string username, SecureString password, AuthenticationMechanism authentication) { IpAddress = ipAddress; Port = port; Authentication = authentication; this._username = username; this._password = password; }
public EdgeHubScopeModule( string moduleId, string deviceId, string generationId, AuthenticationMechanism authentication) { this.Id = Preconditions.CheckNonWhiteSpace(moduleId, nameof(moduleId)); this.DeviceId = Preconditions.CheckNonWhiteSpace(deviceId, nameof(deviceId)); this.GenerationId = Preconditions.CheckNonWhiteSpace(generationId, nameof(generationId)); this.Authentication = Preconditions.CheckNotNull(authentication); }
public SessionEntry(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { SessionOptions = sessionOptions; _credential = credential; _certificateThumbprint = certificateThumbprint; _authenticationMechanism = authenticationMechanism; _useSsl = useSsl; _port = port; _psSessionOption = pssessionOption; Session = CimSession.Create(computerName, sessionOptions); }
private MonadConnectionInfo ConnectTenantWithExplicitCredential(PSCredential cred) { AuthenticationMechanism[] array = new AuthenticationMechanism[] { AuthenticationMechanism.Basic }; AuthenticationMechanism[] array2 = new AuthenticationMechanism[] { AuthenticationMechanism.Negotiate }; return(this.TryAuthenticationMechanisms(cred, cred.IsLiveId() ? array : array2)); }
private void DeserializeInvocationInfo(SerializationInfo info) { string str = info.GetString("InvocationInfo_Command"); string str1 = info.GetString("InvocationInfo_Name"); string str2 = info.GetString("InvocationInfo_ModuleName"); string str3 = info.GetString("InvocationInfo_AdapterTypeName"); Dictionary <string, object> strs = new Dictionary <string, object>(); string str4 = info.GetString("InvocationParam_ScriptBlock"); if (str4 != null) { strs.Add("ScriptBlock", ScriptBlock.Create(str4)); } string str5 = info.GetString("InvocationParam_FilePath"); if (!string.IsNullOrEmpty(str5)) { strs.Add("FilePath", str5); } str4 = info.GetString("InvocationParam_InitScript"); if (!string.IsNullOrEmpty(str4)) { strs.Add("InitializationScript", ScriptBlock.Create(str4)); } bool flag = info.GetBoolean("InvocationParam_RunAs32"); strs.Add("RunAs32", flag); AuthenticationMechanism value = (AuthenticationMechanism)info.GetValue("InvocationParam_Authentication", typeof(AuthenticationMechanism)); strs.Add("Authentication", value); object[] objArray = (object[])info.GetValue("InvocationParam_ArgList", typeof(object[])); if (objArray != null) { strs.Add("ArgumentList", objArray); } JobDefinition jobDefinition = new JobDefinition(null, str, str1); jobDefinition.ModuleName = str2; jobDefinition.JobSourceAdapterTypeName = str3; CommandParameterCollection commandParameterCollection = new CommandParameterCollection(); foreach (KeyValuePair <string, object> keyValuePair in strs) { CommandParameter commandParameter = new CommandParameter(keyValuePair.Key, keyValuePair.Value); commandParameterCollection.Add(commandParameter); } base.Definition = jobDefinition; base.Name = str1; base.Command = str; base.Parameters.Add(commandParameterCollection); }
public AuthenticationMechanism ToAzureModel() { AuthenticationMechanism auth = new AuthenticationMechanism(); switch (AuthenticationType) { case AuthenticationType.Sas: { auth.SymmetricKey = new SymmetricKey() { PrimaryKey = PrimaryKey, SecondaryKey = SecondaryKey }; auth.Type = Microsoft.Azure.Devices.AuthenticationType.Sas; break; } case AuthenticationType.SelfSigned: { auth.X509Thumbprint = new X509Thumbprint() { PrimaryThumbprint = PrimaryThumbprint, SecondaryThumbprint = SecondaryThumbprint }; auth.Type = Microsoft.Azure.Devices.AuthenticationType.SelfSigned; break; } case AuthenticationType.CertificateAuthority: { auth.X509Thumbprint = new X509Thumbprint() { PrimaryThumbprint = PrimaryThumbprint, SecondaryThumbprint = SecondaryThumbprint }; auth.Type = Microsoft.Azure.Devices.AuthenticationType.CertificateAuthority; break; } default: throw new ArgumentException("Not supported authentcation type"); } return(auth); }
internal static RemoteConnectionInfo BuildProxyWSManConnectionInfo(Uri connectionUri) { if (connectionUri == null) { throw new ArgumentNullException("connectionUri"); } PSCredential pscredential = null; AuthenticationMechanism authenticationMechanism = AuthenticationMechanism.NegotiateWithImplicitCredential; if (ExTraceGlobals.FaultInjectionTracer.IsTraceEnabled(TraceType.FaultInjection)) { ProxyHelper.FaultInjection_ProxySessionCredentialAndType(ref pscredential, ref authenticationMechanism); } return(new RemoteConnectionInfo(connectionUri, pscredential, ProxyHelper.ExchangeShellSchema, null, authenticationMechanism, true, 0)); }
public EdgeHubScopeDevice( string deviceId, string generationId, DeviceStatus status, AuthenticationMechanism authentication, DeviceCapabilities capabilities, string deviceScope, IEnumerable <string> parentScopes) { this.Id = Preconditions.CheckNonWhiteSpace(deviceId, nameof(deviceId)); this.GenerationId = Preconditions.CheckNonWhiteSpace(generationId, nameof(generationId)); this.Status = Preconditions.CheckNotNull(status); this.Authentication = Preconditions.CheckNotNull(authentication); this.Capabilities = Preconditions.CheckNotNull(capabilities); this.Scope = deviceScope; this.ParentScopes = parentScopes; }
internal static PasswordAuthenticationMechanism ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(AuthenticationMechanism psAuthenticationMechanism) { AuthenticationMechanism authenticationMechanism = psAuthenticationMechanism; switch (authenticationMechanism) { case AuthenticationMechanism.Default: { return(PasswordAuthenticationMechanism.Default); } case AuthenticationMechanism.Basic: { return(PasswordAuthenticationMechanism.Basic); } case AuthenticationMechanism.Negotiate: case AuthenticationMechanism.NegotiateWithImplicitCredential: { return(PasswordAuthenticationMechanism.Negotiate); } case AuthenticationMechanism.Credssp: { return(PasswordAuthenticationMechanism.CredSsp); } case AuthenticationMechanism.Digest: { return(PasswordAuthenticationMechanism.Digest); } case AuthenticationMechanism.Kerberos: { return(PasswordAuthenticationMechanism.Kerberos); } default: { return(PasswordAuthenticationMechanism.Default); } } }
/// <summary> /// Adds the provided device to the IoT hub with the provided security keys /// </summary> /// <param name="device"></param> /// <param name="securityKeys"></param> /// <returns></returns> public async Task<dynamic> AddDeviceAsync(dynamic device, SecurityKeys securityKeys) { Device iotHubDevice = new Device(DeviceSchemaHelper.GetDeviceID(device)); var authentication = new AuthenticationMechanism { SymmetricKey = new SymmetricKey { PrimaryKey = securityKeys.PrimaryKey, SecondaryKey = securityKeys.SecondaryKey } }; iotHubDevice.Authentication = authentication; await AzureRetryHelper.OperationWithBasicRetryAsync(async () => await _deviceManager.AddDeviceAsync(iotHubDevice)); return device; }
public static ServiceAuthentication ToServiceAuthentication(this AuthenticationMechanism authenticationMechanism) { Preconditions.CheckNotNull(authenticationMechanism, nameof(authenticationMechanism)); switch (authenticationMechanism.Type) { case AuthenticationType.CertificateAuthority: return(new ServiceAuthentication(ServiceAuthenticationType.CertificateAuthority)); case AuthenticationType.SelfSigned: return(new ServiceAuthentication( new X509ThumbprintAuthentication(authenticationMechanism.X509Thumbprint.PrimaryThumbprint, authenticationMechanism.X509Thumbprint.SecondaryThumbprint))); case AuthenticationType.Sas: return(new ServiceAuthentication( new SymmetricKeyAuthentication(authenticationMechanism.SymmetricKey.PrimaryKey, authenticationMechanism.SymmetricKey.SecondaryKey))); default: return(new ServiceAuthentication(ServiceAuthenticationType.None)); } }
/// <summary> /// Adds the provided device to the IoT hub with the provided security keys /// </summary> /// <param name="device"></param> /// <param name="securityKeys"></param> /// <returns></returns> public async Task<DeviceModel> AddDeviceAsync(DeviceModel device, SecurityKeys securityKeys) { var iotHubDevice = new Device(device.DeviceProperties.DeviceID); var authentication = new AuthenticationMechanism { SymmetricKey = new SymmetricKey { PrimaryKey = securityKeys.PrimaryKey, SecondaryKey = securityKeys.SecondaryKey } }; iotHubDevice.Authentication = authentication; await AzureRetryHelper.OperationWithBasicRetryAsync(async () => await this._deviceManager.AddDeviceAsync(iotHubDevice)); return device; }
/// <summary> /// Adds the provided device to the IoT hub with the provided security keys /// </summary> /// <param name="device"></param> /// <param name="securityKeys"></param> /// <returns></returns> public async Task <DeviceModel> AddDeviceAsync(DeviceModel device, SecurityKeys securityKeys) { var iotHubDevice = new Device(device.DeviceProperties.DeviceID); var authentication = new AuthenticationMechanism { SymmetricKey = new SymmetricKey { PrimaryKey = securityKeys.PrimaryKey, SecondaryKey = securityKeys.SecondaryKey } }; iotHubDevice.Authentication = authentication; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.AddDeviceAsync(iotHubDevice)); return(device); }
/// <summary> /// Adds the provided device to the IoT hub with the provided security keys /// </summary> /// <param name="device"></param> /// <param name="securityKeys"></param> /// <returns></returns> public async Task <dynamic> AddDeviceAsync(dynamic device, SecurityKeys securityKeys) { Azure.Devices.Device iotHubDevice = new Azure.Devices.Device(DeviceSchemaHelper.GetDeviceID(device)); var authentication = new AuthenticationMechanism { SymmetricKey = new SymmetricKey { PrimaryKey = securityKeys.PrimaryKey, SecondaryKey = securityKeys.SecondaryKey } }; iotHubDevice.Authentication = authentication; await AzureRetryHelper.OperationWithBasicRetryAsync <Azure.Devices.Device>(async() => await _deviceManager.AddDeviceAsync(iotHubDevice)); return(device); }
//public void ProcessResponsesTv(Collection<PSObject> oResults) //{ // TreeView oTreeView = this.tvResults; // TreeNode oNode = oTreeView.Nodes.Add("Results"); // oNode.Tag = null; // oTreeView.Nodes.Clear(); // TreeNode xNode = null; // foreach (PSObject PSresult in oResults) // { // foreach (PSPropertyInfo oInfo in PSresult.Properties) // { // xNode = new TreeNode(oInfo.Name + "[" + oInfo.TypeNameOfValue + "]"); // xNode.Tag = new TreeNodeTag(oInfo.Name, oInfo.TypeNameOfValue, oInfo.Value); // oNode.Nodes.Add(xNode); // xNode.Nodes.Add(""); // xNode = null; // } // } //} private void GetAuthenticationMechanism(string sAuthMethod, ref AuthenticationMechanism oAuthenticationMechanism, ref bool bSpecifyCredentials) { switch (cmboAuthentication.Text) { case "Basic": bSpecifyCredentials = true; oAuthenticationMechanism = AuthenticationMechanism.Basic; break; case "Credssp": bSpecifyCredentials = true; oAuthenticationMechanism = AuthenticationMechanism.Credssp; break; case "Default": bSpecifyCredentials = false; oAuthenticationMechanism = AuthenticationMechanism.Default; break; case "Digest": bSpecifyCredentials = true; oAuthenticationMechanism = AuthenticationMechanism.Digest; break; case "Kerberos": bSpecifyCredentials = false; oAuthenticationMechanism = AuthenticationMechanism.Kerberos; break; case "Negotiate": bSpecifyCredentials = true; oAuthenticationMechanism = AuthenticationMechanism.Negotiate; break; case "NegotiateWithImplicitCredential": bSpecifyCredentials = false; oAuthenticationMechanism = AuthenticationMechanism.NegotiateWithImplicitCredential; break; } }
public AuthenticationOptions WithMechanism(string value) { var tmp = value.ToUpper(); if (!ValidMechanism(tmp)) { throw new LeafConfigurationException($"{value} is not a supported authentication mechanism"); } switch (tmp) { case Saml2: Mechanism = AuthenticationMechanism.Saml2; break; default: Mechanism = AuthenticationMechanism.Unsecured; break; } return(this); }
/// <summary> /// Used to resolve authentication from the parameters chosen by the user. /// User has the following options: /// 1. AuthMechanism + Credential /// 2. CertificateThumbPrint /// /// All the above are mutually exclusive. /// </summary> /// <exception cref="InvalidOperationException"> /// If there is ambiguity as specified above. /// </exception> static internal void ValidateSpecifiedAuthentication(AuthenticationMechanism authentication, PSCredential credential, string certificateThumbprint) { if ((credential != null) && (certificateThumbprint != null)) { String message = FormatResourceMsgFromResourcetextS( "AmbiguosAuthentication", "CertificateThumbPrint", "credential"); throw new InvalidOperationException(message); } if ((authentication != AuthenticationMechanism.Default) && (authentication != AuthenticationMechanism.ClientCertificate) && (certificateThumbprint != null)) { String message = FormatResourceMsgFromResourcetextS( "AmbiguosAuthentication", "CertificateThumbPrint", authentication.ToString()); throw new InvalidOperationException(message); } }
static AuthenticationMechanism GetAuthenticationMechanism(ServiceAuthentication serviceAuth) { var authentication = new AuthenticationMechanism(); switch (serviceAuth.Type) { case ServiceAuthenticationType.SymmetricKey: authentication.Type = AuthenticationType.Sas; var sasKey = serviceAuth.SymmetricKey.Expect(() => new InvalidOperationException("SAS key shouldn't be empty when auth type is SymmetricKey")); authentication.SymmetricKey = new SymmetricKey() { PrimaryKey = sasKey.PrimaryKey, SecondaryKey = sasKey.SecondaryKey }; break; case ServiceAuthenticationType.CertificateThumbprint: authentication.Type = AuthenticationType.SelfSigned; var x509Thumbprint = serviceAuth.X509Thumbprint.Expect(() => new InvalidOperationException("X509 thumbprint shouldn't be empty when auth type is CertificateThumbPrint")); authentication.X509Thumbprint = new X509Thumbprint() { PrimaryThumbprint = x509Thumbprint.PrimaryThumbprint, SecondaryThumbprint = x509Thumbprint.SecondaryThumbprint }; break; case ServiceAuthenticationType.CertificateAuthority: authentication.Type = AuthenticationType.CertificateAuthority; break; case ServiceAuthenticationType.None: authentication.Type = AuthenticationType.None; break; default: throw new InvalidOperationException($"Unexpected ServiceAuthenticationType: {serviceAuth.Type}"); } return(authentication); }
/// <summary> /// This method firstly establishes a session to the remote target. /// Then executes the <paramref name="script"/>. /// When execution is done, the session is closed. /// </summary> /// <param name="script"> /// The powershell script to be executed inside PSSession. /// </param> /// <param name="cancelToken"> /// Long execution can be terminated by the cancelToken. /// This will also terminate the PSSession. /// </param> public void EnterSessionExecute(string script, CancellationToken cancelToken) { if (String.IsNullOrWhiteSpace(script)) { throw new ArgumentNullException(nameof(script)); } AuthenticationMechanism auth = AuthenticationMechanism.Default; WSManConnectionInfo connectionInfo = new WSManConnectionInfo( useSsl: true, computerName: _computerName, port: RemotePort, appName: AppName, shellUri: ShellUri, credential: _credential); connectionInfo.AuthenticationMechanism = auth; // GCE VM uses an GCP internal certificate, the root is not by default trusted. // We know we are connecting to GCP VM, it is safe to skip these certificate validation. connectionInfo.SkipCACheck = true; connectionInfo.SkipCNCheck = true; connectionInfo.SkipRevocationCheck = true; using (var runSpace = RunspaceFactory.CreateRunspace(connectionInfo)) { runSpace.Open(); Debug.WriteLine($"Connected to {_computerName} as {_credential.UserName}"); using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runSpace; powerShell.AddScript(script); WaitComplete(powerShell, cancelToken); } } }
private static int ConvertPSAuthToWSManAuth(AuthenticationMechanism psAuth) { switch (psAuth) { case AuthenticationMechanism.Default: return 1; case AuthenticationMechanism.Basic: return 8; case AuthenticationMechanism.Negotiate: return 4; case AuthenticationMechanism.Credssp: return 0x80; case AuthenticationMechanism.Digest: return 2; case AuthenticationMechanism.Kerberos: return 0x10; } return 1; }
private static int ConvertPSAuthToWSManAuth(AuthenticationMechanism psAuth) { switch (psAuth) { case AuthenticationMechanism.Default: return(1); case AuthenticationMechanism.Basic: return(8); case AuthenticationMechanism.Negotiate: return(4); case AuthenticationMechanism.Credssp: return(0x80); case AuthenticationMechanism.Digest: return(2); case AuthenticationMechanism.Kerberos: return(0x10); } return(1); }
public async void GetDeviceKeysAsync() { var deviceId = fixture.Create <string>(); var device = new Device(deviceId); var auth = new AuthenticationMechanism(); auth.SymmetricKey = new SymmetricKey(); auth.SymmetricKey.PrimaryKey = "1fLjiNCMZF37LmHnjZDyVQ =="; auth.SymmetricKey.SecondaryKey = "fbsIV6w7gfVUyoRIQFSVgw =="; device.Authentication = auth; deviceManagerMock.Setup(dm => dm.GetDeviceAsync(deviceId)) .ReturnsAsync(device); var keys = await iotHubRepository.GetDeviceKeysAsync(deviceId); Assert.NotNull(keys); deviceId = fixture.Create <string>(); deviceManagerMock.Setup(dm => dm.GetDeviceAsync(deviceId)) .ReturnsAsync(null); keys = await iotHubRepository.GetDeviceKeysAsync(deviceId); Assert.Null(keys); }
internal static List<WSManConnectionInfo> GetConnectionInfo(string[] PSComputerName, string[] PSConnectionUri, string PSCertificateThumbprint, string PSConfigurationName, bool? PSUseSsl, uint? PSPort, string PSApplicationName, PSCredential PSCredential, AuthenticationMechanism PSAuthentication, bool PSAllowRedirection, System.Management.Automation.Remoting.PSSessionOption options) { List<WSManConnectionInfo> connections = new List<WSManConnectionInfo>(); string[] machineList = null; bool connectByComputerName = false; // Connect by computername if ((! PSComputerName.IsNullOrEmpty()) && (PSConnectionUri.IsNullOrEmpty())) { machineList = PSComputerName; connectByComputerName = true; } else if ((PSComputerName.IsNullOrEmpty()) && (! PSConnectionUri.IsNullOrEmpty())) { machineList = PSConnectionUri; } else { throw new ArgumentException(Resources.CannotSupplyUriAndComputername); } // Go through each machine in the list an update its properties foreach (string machine in machineList) { if (!string.IsNullOrEmpty(machine)) { WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); if (PSPort.HasValue) { connectionInfo.Port = (int)PSPort.Value; } if (PSUseSsl.HasValue && (PSUseSsl.Value)) { connectionInfo.Scheme = WSManConnectionInfo.HttpsScheme; } if (!String.IsNullOrEmpty(PSConfigurationName)) { connectionInfo.ShellUri = PSConfigurationName; } if (!String.IsNullOrEmpty(PSApplicationName)) { connectionInfo.AppName = PSApplicationName; } if (connectByComputerName) { connectionInfo.ComputerName = machine; } else { connectionInfo.ConnectionUri = (Uri)LanguagePrimitives.ConvertTo(machine, typeof(Uri), System.Globalization.CultureInfo.InvariantCulture); } if (PSCredential != null) { connectionInfo.Credential = PSCredential; } if (!String.IsNullOrEmpty(PSCertificateThumbprint)) { connectionInfo.CertificateThumbprint = PSCertificateThumbprint; } if (PSAuthentication != AuthenticationMechanism.Default) { connectionInfo.AuthenticationMechanism = PSAuthentication; } connectionInfo.MaximumConnectionRedirectionCount = PSAllowRedirection ? DefaultMaximumConnectionRedirectionCount : 0; if (options != null) { connectionInfo.SetSessionOptions(options); } connections.Add(connectionInfo); } else { // add a null connection to account for "" or $null in PSComputerName parameter connections.Add(null); } } return connections; }
/// <summary> /// Get a CIM session for the target computer /// </summary> /// <param name="computerName"></param> /// <param name="credential"></param> /// <param name="certificateThumbprint"></param> /// <param name="authenticationMechanism"></param> /// <param name="sessionOptions"></param> /// <param name="useSsl"></param> /// <param name="port"></param> /// <param name="pssessionOption"></param> /// <returns></returns> internal CimSession GetSession(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(computerName), "ComputerName is null in GetSession. GetSession should not be called in this case."); lock (SyncRoot) { SessionEntry newSessionEntry; if (availableSessions.ContainsKey(computerName)) { List<SessionEntry> sel = availableSessions[computerName]; if (sel.Count > 0) { for (int i = 0; i < sel.Count; i++) { SessionEntry se = sel[i]; // No session options specified or the object matches exactly... if ((se.SessionOptions == null && sessionOptions == null) || CompareSessionOptions(se, sessionOptions, credential, certificateThumbprint, authenticationMechanism, useSsl, port, pssessionOption)) { // Up the number of references to this session object... se.AddReference(); return se.Session; } } } } // Allocate a new session entry for this computer newSessionEntry = new SessionEntry(computerName, credential, certificateThumbprint, authenticationMechanism, sessionOptions, useSsl, port, pssessionOption); newSessionEntry.IterationsRemaining = MaxIterations; newSessionEntry.AddReference(); if (! availableSessions.ContainsKey(computerName)) { availableSessions.Add(computerName, new List<SessionEntry>()); } availableSessions[computerName].Add(newSessionEntry); // Return the session object return newSessionEntry.Session; } }
internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string connectionString, string certificateThumbprint, bool usessl) { WSManHelper.ValidateSpecifiedAuthentication(authentication, credential, certificateThumbprint); int num = 0; if (authentication.ToString() != null) { if (authentication.Equals(AuthenticationMechanism.None)) { num = num | 0x8000; } if (authentication.Equals(AuthenticationMechanism.Basic)) { num = num | 0x40000 | 0x1000; } if (authentication.Equals(AuthenticationMechanism.Negotiate)) { num = num | 0x20000; } if (authentication.Equals(AuthenticationMechanism.Kerberos)) { num = num | 0x80000; } if (authentication.Equals(AuthenticationMechanism.Digest)) { num = num | 0x10000 | 0x1000; } if (authentication.Equals(AuthenticationMechanism.Credssp)) { num = num | 0x1000000 | 0x1000; } if (authentication.Equals(AuthenticationMechanism.ClientCertificate)) { num = num | 0x200000; } } IWSManConnectionOptionsEx2 userName = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); if (credential != null) { if (credential.UserName != null) { NetworkCredential networkCredential = credential.GetNetworkCredential(); if (!string.IsNullOrEmpty(networkCredential.Domain)) { userName.UserName = string.Concat(networkCredential.Domain, "\\", networkCredential.UserName); } else { if (authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { userName.UserName = networkCredential.UserName; } else { userName.UserName = string.Concat("\\", networkCredential.UserName); } } userName.Password = networkCredential.Password; if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { num = num | 0x1000; } } } if (certificateThumbprint != null) { userName.CertificateThumbprint = certificateThumbprint; num = num | 0x200000; } if (sessionoption == null) { num = num | 1; } else { if (sessionoption.ProxyAuthentication != 0) { int num1 = 0; int num2 = 0; if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyIEConfig)) { if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyAutoDetect)) { if (!sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyNoProxyServer)) { if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyWinHttpConfig)) { num1 = userName.ProxyWinHttpConfig(); } } else { num1 = userName.ProxyNoProxyServer(); } } else { num1 = userName.ProxyAutoDetect(); } } else { num1 = userName.ProxyIEConfig(); } if (!sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Basic)) { if (!sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Negotiate)) { if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Digest)) { num2 = userName.ProxyAuthenticationUseDigest(); } } else { num2 = userName.ProxyAuthenticationUseNegotiate(); } } else { num2 = userName.ProxyAuthenticationUseBasic(); } if (sessionoption.ProxyCredential == null) { userName.SetProxy((int)sessionoption.ProxyAccessType, (int)sessionoption.ProxyAuthentication, null, null); } else { try { userName.SetProxy(num1, num2, sessionoption.ProxyCredential.UserName, sessionoption.ProxyCredential.Password); } catch (Exception exception1) { Exception exception = exception1; this.AssertError(exception.Message, false, null); } } } if (sessionoption.SkipCACheck) { num = num | 0x2000; } if (sessionoption.SkipCNCheck) { num = num | 0x4000; } if (sessionoption.SPNPort > 0) { num = num | 0x400000; } if (!sessionoption.UseUtf16) { num = num | 1; } else { num = num | 0x800000; } if (!sessionoption.UseEncryption) { num = num | 0x100000; } if (sessionoption.SkipRevocationCheck) { num = num | 0x2000000; } } if (usessl) { num = num | 0x8000000; } IWSManSession operationTimeout = null; try { operationTimeout = (IWSManSession)wsmanObject.CreateSession(connectionString, num, userName); if (sessionoption != null && sessionoption.OperationTimeout > 0) { operationTimeout.Timeout = sessionoption.OperationTimeout; } } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.AssertError(cOMException.Message, false, null); } return operationTimeout; }
internal static List<WSManConnectionInfo> GetConnectionInfo(string[] PSComputerName, string[] PSConnectionUri, string PSCertificateThumbprint, string PSConfigurationName, bool? PSUseSsl, int? PSPort, string PSApplicationName, PSCredential PSCredential, AuthenticationMechanism PSAuthentication, bool PSAllowRedirection, PSSessionOption options) { int defaultMaximumConnectionRedirectionCount; List<WSManConnectionInfo> wSManConnectionInfos = new List<WSManConnectionInfo>(); string[] pSConnectionUri = null; bool flag = false; if (PSComputerName.IsNullOrEmpty() || !PSConnectionUri.IsNullOrEmpty()) { if (!PSComputerName.IsNullOrEmpty() || PSConnectionUri.IsNullOrEmpty()) { throw new ArgumentException(Resources.CannotSupplyUriAndComputername); } else { pSConnectionUri = PSConnectionUri; } } else { pSConnectionUri = PSComputerName; flag = true; } string[] strArrays = pSConnectionUri; for (int i = 0; i < (int)strArrays.Length; i++) { string str = strArrays[i]; if (string.IsNullOrEmpty(str)) { wSManConnectionInfos.Add(null); } else { WSManConnectionInfo wSManConnectionInfo = new WSManConnectionInfo(); if (PSPort.HasValue) { wSManConnectionInfo.Port = PSPort.Value; } if (PSUseSsl.HasValue && PSUseSsl.Value) { wSManConnectionInfo.Scheme = "https"; } if (!string.IsNullOrEmpty(PSConfigurationName)) { wSManConnectionInfo.ShellUri = PSConfigurationName; } if (!string.IsNullOrEmpty(PSApplicationName)) { wSManConnectionInfo.AppName = PSApplicationName; } if (!flag) { wSManConnectionInfo.ConnectionUri = (Uri)LanguagePrimitives.ConvertTo(str, typeof(Uri), CultureInfo.InvariantCulture); } else { wSManConnectionInfo.ComputerName = str; } if (PSCredential != null) { wSManConnectionInfo.Credential = PSCredential; } if (!string.IsNullOrEmpty(PSCertificateThumbprint)) { wSManConnectionInfo.CertificateThumbprint = PSCertificateThumbprint; } if (PSAuthentication != AuthenticationMechanism.Default) { wSManConnectionInfo.AuthenticationMechanism = PSAuthentication; } WSManConnectionInfo wSManConnectionInfo1 = wSManConnectionInfo; if (PSAllowRedirection) { defaultMaximumConnectionRedirectionCount = ActivityUtils.DefaultMaximumConnectionRedirectionCount; } else { defaultMaximumConnectionRedirectionCount = 0; } wSManConnectionInfo1.MaximumConnectionRedirectionCount = defaultMaximumConnectionRedirectionCount; if (options != null) { wSManConnectionInfo.SetSessionOptions(options); } wSManConnectionInfos.Add(wSManConnectionInfo); } } return wSManConnectionInfos; }
/// <summary> /// Used to resolve authentication from the parameters chosen by the user. /// User has the following options: /// 1. AuthMechanism + Credential /// 2. CertificateThumbPrint /// /// All the above are mutually exclusive. /// </summary> /// <exception cref="InvalidOperationException"> /// If there is ambiguity as specified above. /// </exception> internal static void ValidateSpecifiedAuthentication(PSCredential credential, string thumbprint, AuthenticationMechanism authentication) { if ((credential != null) && (thumbprint != null)) { String message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication, "CertificateThumbPrint", "Credential"); throw new InvalidOperationException(message); } if ((authentication != AuthenticationMechanism.Default) && (thumbprint != null)) { String message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication, "CertificateThumbPrint", authentication.ToString()); throw new InvalidOperationException(message); } if ((authentication == AuthenticationMechanism.NegotiateWithImplicitCredential) && (credential != null)) { string message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication, "Credential", authentication.ToString()); throw new InvalidOperationException(message); } }
private static bool CompareSessionOptions(CimConnectionManager.SessionEntry sessionEntry, CimSessionOptions options2, PSCredential credential2, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, bool useSsl, uint port, PSSessionOption pssessionOption) { TimeSpan timeout = sessionEntry.SessionOptions.Timeout; if (timeout.Equals(options2.Timeout)) { if (string.Equals(sessionEntry.SessionOptions.Culture.ToString(), options2.Culture.ToString(), StringComparison.OrdinalIgnoreCase)) { if (string.Equals(sessionEntry.SessionOptions.UICulture.ToString(), options2.UICulture.ToString(), StringComparison.OrdinalIgnoreCase)) { if (string.Equals(sessionEntry.CertificateThumbprint, certificateThumbprint, StringComparison.OrdinalIgnoreCase)) { if (sessionEntry.AuthenticationMechanism == authenticationMechanism) { if (WorkflowUtils.CompareCredential(sessionEntry.Credential, credential2)) { if (sessionEntry.UseSsl == useSsl) { if (sessionEntry.Port == port) { if (!(pssessionOption == null ^ sessionEntry.PSSessionOption == null)) { if (pssessionOption != null && sessionEntry.PSSessionOption != null) { if (sessionEntry.PSSessionOption.ProxyAccessType == pssessionOption.ProxyAccessType) { if (sessionEntry.PSSessionOption.ProxyAuthentication == pssessionOption.ProxyAuthentication) { if (WorkflowUtils.CompareCredential(sessionEntry.PSSessionOption.ProxyCredential, pssessionOption.ProxyCredential)) { if (sessionEntry.PSSessionOption.SkipCACheck == pssessionOption.SkipCACheck) { if (sessionEntry.PSSessionOption.SkipCNCheck == pssessionOption.SkipCNCheck) { if (sessionEntry.PSSessionOption.SkipRevocationCheck == pssessionOption.SkipRevocationCheck) { if (sessionEntry.PSSessionOption.NoEncryption == pssessionOption.NoEncryption) { if (sessionEntry.PSSessionOption.UseUTF16 != pssessionOption.UseUTF16) { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } return true; } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } }
internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string connectionString, string certificateThumbprint, bool usessl) { ValidateSpecifiedAuthentication(authentication, credential, certificateThumbprint); ////if authentication is given int sessionFlags = 0; if (authentication.ToString() != null) { if (authentication.Equals(AuthenticationMechanism.None)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNoAuthentication; } if (authentication.Equals(AuthenticationMechanism.Basic)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseBasic | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } if (authentication.Equals(AuthenticationMechanism.Negotiate)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseNegotiate; } if (authentication.Equals(AuthenticationMechanism.Kerberos)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseKerberos; } if (authentication.Equals(AuthenticationMechanism.Digest)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseDigest | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } if (authentication.Equals(AuthenticationMechanism.Credssp)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseCredSsp | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } if (authentication.Equals(AuthenticationMechanism.ClientCertificate)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate; } } IWSManConnectionOptionsEx2 connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); if (credential != null) { //connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); System.Net.NetworkCredential nwCredential = new System.Net.NetworkCredential(); if (credential.UserName != null) { nwCredential = credential.GetNetworkCredential(); if (String.IsNullOrEmpty(nwCredential.Domain)) { if ( authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic) ) { connObject.UserName = nwCredential.UserName; } else { // just wanted to not use null domain, empty is actually fine connObject.UserName = "******" + nwCredential.UserName; } } else { connObject.UserName = nwCredential.Domain + "\\" + nwCredential.UserName; } connObject.Password = nwCredential.Password; if (!authentication.Equals(AuthenticationMechanism.Credssp) || !authentication.Equals(AuthenticationMechanism.Digest) || authentication.Equals(AuthenticationMechanism.Basic)) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagCredUserNamePassword; } } } if (certificateThumbprint != null) { connObject.CertificateThumbprint = certificateThumbprint; sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate; } if (sessionoption != null) { if (sessionoption.ProxyAuthentication != 0) { int ProxyAccessflags = 0; int ProxyAuthenticationFlags = 0; if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyIEConfig)) { ProxyAccessflags = connObject.ProxyIEConfig(); } else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyAutoDetect)) { ProxyAccessflags = connObject.ProxyAutoDetect(); } else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyNoProxyServer)) { ProxyAccessflags = connObject.ProxyNoProxyServer(); } else if (sessionoption.ProxyAccessType.Equals(ProxyAccessType.ProxyWinHttpConfig)) { ProxyAccessflags = connObject.ProxyWinHttpConfig(); } if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Basic)) { ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseBasic(); } else if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Negotiate)) { ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseNegotiate(); } else if (sessionoption.ProxyAuthentication.Equals(ProxyAuthentication.Digest)) { ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseDigest(); } if (sessionoption.ProxyCredential != null) { try { connObject.SetProxy(ProxyAccessflags, ProxyAuthenticationFlags, sessionoption.ProxyCredential.UserName, sessionoption.ProxyCredential.Password); } catch (Exception ex) { AssertError(ex.Message, false, null); } } else { connObject.SetProxy((int)sessionoption.ProxyAccessType, (int)sessionoption.ProxyAuthentication, null, null); } } if (sessionoption.SkipCACheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipCACheck; } if (sessionoption.SkipCNCheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipCNCheck; } if (sessionoption.SPNPort > 0) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagEnableSpnServerPort; } if (sessionoption.UseUtf16) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf16; } else { //If UseUtf16 is false, then default Encoding is Utf8 sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf8; } if (!sessionoption.UseEncryption) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagNoEncryption; } if (sessionoption.SkipRevocationCheck) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagSkipRevocationCheck; } } else { //If SessionOption is null then, default Encoding is Utf8 sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUtf8; } if (usessl) { sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseSsl; } IWSManSession m_SessionObj = null; try { m_SessionObj = (IWSManSession)wsmanObject.CreateSession(connectionString, sessionFlags, connObject); if (sessionoption != null) { if (sessionoption.OperationTimeout > 0) { m_SessionObj.Timeout = sessionoption.OperationTimeout; } } } catch (COMException ex) { AssertError(ex.Message, false, null); } return m_SessionObj; }
public async Task GetDevicesAndModulesInTargetDeviceScope_RoundTripTest() { // Setup ServiceIdentity results string parentEdgeId = "edge1"; string childEdgeId = "edge2"; string deviceId = "device1"; string moduleId = "module1"; string deviceScope = "deviceScope1"; string parentScope = "parentScope1"; string generationId = "generation1"; string primaryKey = "t3LtII3CppvtVqycKp9bo043vCEgWbGBJAzXZNmoBXo="; string secondaryKey = "kT4ac4PpH5UY0vA1JpLQWOu2yG6qKoqwvzee3j1Z3bA="; var authentication = new ServiceAuthentication(new SymmetricKeyAuthentication(primaryKey, secondaryKey)); var resultDeviceIdentity = new ServiceIdentity(deviceId, null, deviceScope, new List <string>() { parentScope }, generationId, Enumerable.Empty <string>(), authentication, ServiceIdentityStatus.Enabled); var resultModuleIdentity = new ServiceIdentity(deviceId, moduleId, null, new List <string>() { deviceScope }, generationId, Enumerable.Empty <string>(), authentication, ServiceIdentityStatus.Enabled); var resultIdentities = new List <ServiceIdentity>() { resultDeviceIdentity, resultModuleIdentity }; var authChainMapping = new Dictionary <string, string>(); authChainMapping.Add(childEdgeId, "edge2;edge1;edgeroot"); var controller = MakeController(childEdgeId, resultIdentities, authChainMapping); // Act var request = new NestedScopeRequest(0, string.Empty, "edge2;edge1"); await controller.GetDevicesAndModulesInTargetDeviceScopeAsync(parentEdgeId, "$edgeHub", request); // Verify EdgeHub result types var expectedAuth = new AuthenticationMechanism() { SymmetricKey = new SymmetricKey() { PrimaryKey = primaryKey, SecondaryKey = secondaryKey } }; var expectedDeviceIdentities = new List <EdgeHubScopeDevice>() { new EdgeHubScopeDevice(deviceId, generationId, DeviceStatus.Enabled, expectedAuth, new DeviceCapabilities(), deviceScope, new List <string> { parentScope }) }; var expectedModuleIdentities = new List <EdgeHubScopeModule>() { new EdgeHubScopeModule(moduleId, deviceId, generationId, expectedAuth) }; var responseExpected = new EdgeHubScopeResultSuccess(expectedDeviceIdentities, expectedModuleIdentities); var responseExpectedJson = JsonConvert.SerializeObject(responseExpected); var responseActualBytes = GetResponseBodyBytes(controller); var responseActualJson = Encoding.UTF8.GetString(responseActualBytes); Assert.Equal((int)HttpStatusCode.OK, controller.HttpContext.Response.StatusCode); Assert.Equal(responseExpectedJson, responseActualJson); // Deserialize JSON back to SDK result types var scopeResult = JsonConvert.DeserializeObject <ScopeResult>(responseActualJson); // Convert to original ServiceIdentity type Assert.Equal(1, (int)scopeResult.Devices.Count()); Assert.Equal(1, (int)scopeResult.Modules.Count()); ServiceIdentity device = scopeResult.Devices.First().ToServiceIdentity(); ServiceIdentity module = scopeResult.Modules.First().ToServiceIdentity(); Assert.Equal(resultDeviceIdentity, device); Assert.Equal(resultModuleIdentity, module); }
public async void GetDeviceKeysAsync() { var deviceId = fixture.Create<string>(); var device = new Device(deviceId); var auth = new AuthenticationMechanism(); auth.SymmetricKey = new SymmetricKey(); auth.SymmetricKey.PrimaryKey = "1fLjiNCMZF37LmHnjZDyVQ =="; auth.SymmetricKey.SecondaryKey = "fbsIV6w7gfVUyoRIQFSVgw =="; device.Authentication = auth; deviceManagerMock.Setup(dm => dm.GetDeviceAsync(deviceId)) .ReturnsAsync(device); var keys = await iotHubRepository.GetDeviceKeysAsync(deviceId); Assert.NotNull(keys); deviceId = fixture.Create<string>(); deviceManagerMock.Setup(dm => dm.GetDeviceAsync(deviceId)) .ReturnsAsync(null); keys = await iotHubRepository.GetDeviceKeysAsync(deviceId); Assert.Null(keys); }
/// <summary> /// Creates an object with the information necessary to create a connection for a Runspace or RunspacePool. /// Note: computerName and connectionURI are mutually exclusive. If both are provided, the computerName parameter will be used. /// computerName and connectionURI need only be supplied for remote connections. If neither are provided a configuration for a /// local connection using all defaults will be created. /// </summary> /// <param name="computerName">[Optional] The hostname or FQDN of the computer to connect to. Defaults to null for a local connection.</param> /// <param name="connectionURI">[Optional] The URI to the PowerShell service to connect with. Defaults to DEFAULT_SHELL_URI.</param> /// <param name="shellURI">[Optional] The URI of the shell that is launched once the connection is made.</param> /// <param name="credential">[Optional] The PowerShell credentials to use when making the connection. Defaults to null which does not provide implicit credentials for the connection.</param> /// <param name="authMechanism">[Optional] The authentication mechanism employed when creating the connection. Defaults to null which uses the PowerShell default mechanism.</param> /// <param name="appName">[Optional] The application name used when making the PowerShell connection. Defaults to DEFAULT_APP_NAME which is the default PowerShell application name used for connections.</param> /// <param name="operationTimeoutInSec">[Optional] The time in seconds that a PowerShell connection will wait for an operation to complete before timing out. Defaults to DEFAULT_OPERATION_TIMEOUT_IN_SEC.</param> /// <param name="openTimeoutInSec">[Optional] The time in seconds that a PowerShell connection will wait for a connection to be established before timing out. Defaults to DEFAULT_OPEN_TIMEOUT_IN_SEC.</param> /// <param name="useSSL">[Optional] Whether to use SSL when creating the connection. Defaults to false.</param> /// <param name="port">[Optional] The port number to use when making the connection. Defaults to the PowerShell default port number appropriate to the SSL state of the connection.</param> /// <returns></returns> public static RunspaceConnectionInfo CreateRunspaceConnectionInfo(string computerName = null, string connectionURI = null, string shellURI = DEFAULT_SHELL_URI, PSCredential credential = null, AuthenticationMechanism authMechanism = AuthenticationMechanism.Default, string appName = DEFAULT_APP_NAME, int operationTimeoutInSec = DEFAULT_OPERATION_TIMEOUT_IN_SEC, int openTimeoutInSec = DEFAULT_OPEN_TIMEOUT_IN_SEC, bool useSSL = false, int port = 0) { WSManConnectionInfo info = null; // If invalid timeouts are supplied reset them to the defaults. if (operationTimeoutInSec <= 0) { operationTimeoutInSec = DEFAULT_OPERATION_TIMEOUT_IN_SEC; } if (openTimeoutInSec <= 0) { openTimeoutInSec = DEFAULT_OPEN_TIMEOUT_IN_SEC; } // Check whether we should use a default port. // Reset the connection to use the default port if invalid port numbers are supplied. if (port == 0 || port < 0) { // We need to initialize port with a default PowerShell port appropriate to it's SSL status. if (useSSL) { port = DEFAULT_PORT_NUMBER_SSL; } else { port = DEFAULT_PORT_NUMBER; } } // Determine whether to initialize the connection info object via computer name or connection URI. if (!string.IsNullOrWhiteSpace(computerName)) { // Use the computer name to initialize the connection info object. info = new WSManConnectionInfo(useSSL, computerName, port, appName, shellURI, credential, openTimeoutInSec); } else if (!string.IsNullOrWhiteSpace(connectionURI)) { // Use the connection URI to initialize the connection info object. info = new WSManConnectionInfo(new Uri(connectionURI), shellURI, credential); } else { // Create a connection information object using all defaults. info = new WSManConnectionInfo { // Set the timeout to use when opening the connection. OpenTimeout = openTimeoutInSec }; } // Configure the object to use the supplied authentication mechanism. info.AuthenticationMechanism = authMechanism; // Set the operation timeout. info.OperationTimeout = operationTimeoutInSec; // Return the configuration connection object. return info; }
internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, int port, string computername, string applicationname, bool usessl, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string certificateThumbprint) { IWSManEx wSManClass = (IWSManEx)(new WSManClass()); try { try { string str = this.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { string[] strArrays = new string[1]; object[] objArray = new object[4]; objArray[0] = ":"; objArray[1] = port; objArray[2] = "/"; objArray[3] = applicationname; strArrays[0] = string.Concat(objArray); string[] strArrays1 = str.Split(strArrays, StringSplitOptions.None); string[] strArrays2 = new string[1]; strArrays2[0] = "//"; string[] strArrays3 = strArrays1[0].Split(strArrays2, StringSplitOptions.None); computername = strArrays3[1].Trim(); } IWSManSession wSManSession = this.CreateSessionObject(wSManClass, authentication, sessionoption, credential, str, certificateThumbprint, usessl); wSManSession.Identify(0); string str1 = computername; if (str1 == null) { str1 = "localhost"; } this.AddtoDictionary(str1, wSManSession); } catch (IndexOutOfRangeException indexOutOfRangeException) { this.AssertError(this._resourceMgr.GetString("NotProperURI"), false, connectionuri); } catch (Exception exception1) { Exception exception = exception1; this.AssertError(exception.Message, false, computername); } } finally { if (!string.IsNullOrEmpty(wSManClass.Error)) { this.AssertError(wSManClass.Error, true, computername); } } }
/// <summary> /// Create an instance of the CIM activity implementation class /// </summary> /// <param name="activityImplementationContext"></param> /// <param name="computerName"></param> /// <param name="credential"></param> /// <param name="certificateThumbprint"></param> /// <param name="authenticationMechanism"></param> /// <param name="useSsl"></param> /// <param name="port"></param> /// <param name="sessionOption"></param> /// <param name="session"></param> /// <param name="cimSessionOptions"></param> /// <param name="moduleDefinition"></param> /// <param name="resourceUri"></param> 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) { throw new ArgumentNullException("activityImplementationContext"); } this.PowerShellInstance = activityImplementationContext.PowerShellInstance; ResourceUri = resourceUri; ComputerName = computerName; PSCredential = credential; PSCertificateThumbprint = certificateThumbprint; PSAuthentication = authenticationMechanism; PSUseSsl = useSsl; PSPort = port; PSSessionOption = sessionOption; Session = session; SessionOptions = cimSessionOptions; if (moduleDefinition != null) { // Creating a script block forces the string into the compiled script cache so we // don't need to reparse it at execution time. Locking the static _moduleDefinition is not // required since the operation is idempotent. _moduleScriptBlock = ScriptBlock.Create(moduleDefinition); _moduleDefinition = moduleDefinition; } }
internal static PasswordAuthenticationMechanism ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(AuthenticationMechanism psAuthenticationMechanism) { switch (psAuthenticationMechanism) { case AuthenticationMechanism.Basic: return PasswordAuthenticationMechanism.Basic; case AuthenticationMechanism.Negotiate: case AuthenticationMechanism.NegotiateWithImplicitCredential: return PasswordAuthenticationMechanism.Negotiate; case AuthenticationMechanism.Credssp: return PasswordAuthenticationMechanism.CredSsp; case AuthenticationMechanism.Digest: return PasswordAuthenticationMechanism.Digest; case AuthenticationMechanism.Kerberos: return PasswordAuthenticationMechanism.Kerberos; case AuthenticationMechanism.Default: default: return PasswordAuthenticationMechanism.Default; } }
private static int ConvertPSAuthToWSManAuth(AuthenticationMechanism psAuth) { int wsmanAuth; switch (psAuth) { case AuthenticationMechanism.Default: wsmanAuth = 0x1; break; case AuthenticationMechanism.Basic: wsmanAuth = 0x8; break; case AuthenticationMechanism.Digest: wsmanAuth = 0x2; break; case AuthenticationMechanism.Credssp: wsmanAuth = 0x80; break; case AuthenticationMechanism.Kerberos: wsmanAuth = 0x10; break; case AuthenticationMechanism.Negotiate: wsmanAuth = 0x4; break; default: wsmanAuth = 0x1; break; } return wsmanAuth; }
internal CimSession GetSession(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption) { CimSession session; lock (this.SyncRoot) { if (this.availableSessions.ContainsKey(computerName)) { List<CimConnectionManager.SessionEntry> item = this.availableSessions[computerName]; if (item.Count > 0) { int num = 0; while (num < item.Count) { CimConnectionManager.SessionEntry sessionEntry = item[num]; if ((sessionEntry.SessionOptions != null || sessionOptions != null) && !CimConnectionManager.CompareSessionOptions(sessionEntry, sessionOptions, credential, certificateThumbprint, authenticationMechanism, useSsl, port, pssessionOption)) { num++; } else { sessionEntry.AddReference(); session = sessionEntry.Session; return session; } } } } CimConnectionManager.SessionEntry sessionEntry1 = new CimConnectionManager.SessionEntry(computerName, credential, certificateThumbprint, authenticationMechanism, sessionOptions, useSsl, port, pssessionOption); sessionEntry1.IterationsRemaining = 6; sessionEntry1.AddReference(); if (!this.availableSessions.ContainsKey(computerName)) { this.availableSessions.Add(computerName, new List<CimConnectionManager.SessionEntry>()); } this.availableSessions[computerName].Add(sessionEntry1); session = sessionEntry1.Session; } return session; }
internal static PasswordAuthenticationMechanism ConvertPSAuthenticationMechanismToCimPasswordAuthenticationMechanism(AuthenticationMechanism psAuthenticationMechanism) { AuthenticationMechanism authenticationMechanism = psAuthenticationMechanism; switch (authenticationMechanism) { case AuthenticationMechanism.Default: { return PasswordAuthenticationMechanism.Default; } case AuthenticationMechanism.Basic: { return PasswordAuthenticationMechanism.Basic; } case AuthenticationMechanism.Negotiate: case AuthenticationMechanism.NegotiateWithImplicitCredential: { return PasswordAuthenticationMechanism.Negotiate; } case AuthenticationMechanism.Credssp: { return PasswordAuthenticationMechanism.CredSsp; } case AuthenticationMechanism.Digest: { return PasswordAuthenticationMechanism.Digest; } case AuthenticationMechanism.Kerberos: { return PasswordAuthenticationMechanism.Kerberos; } default: { return PasswordAuthenticationMechanism.Default; } } }
public WSManProviderNewItemComputerParameters() { this.authentication = AuthenticationMechanism.Default; this.applicationname = "wsman"; }
private static bool CompareSessionOptions(SessionEntry sessionEntry, CimSessionOptions options2, PSCredential credential2, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, bool useSsl, uint port, PSSessionOption pssessionOption) { if (!sessionEntry.SessionOptions.Timeout.Equals(options2.Timeout)) return false; if (!string.Equals(sessionEntry.SessionOptions.Culture.ToString(), options2.Culture.ToString(), StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(sessionEntry.SessionOptions.UICulture.ToString(), options2.UICulture.ToString(), StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(sessionEntry.CertificateThumbprint, certificateThumbprint, StringComparison.OrdinalIgnoreCase)) return false; if (sessionEntry.AuthenticationMechanism != authenticationMechanism) return false; if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.Credential, credential2)) return false; if (sessionEntry.UseSsl != useSsl) return false; if (sessionEntry.Port != port) return false; // check PSSessionOption if present if (pssessionOption == null ^ sessionEntry.PSSessionOption == null) { return false; } if (pssessionOption != null && sessionEntry.PSSessionOption != null) { if (sessionEntry.PSSessionOption.ProxyAccessType != pssessionOption.ProxyAccessType) return false; if (sessionEntry.PSSessionOption.ProxyAuthentication != pssessionOption.ProxyAuthentication) return false; if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.PSSessionOption.ProxyCredential, pssessionOption.ProxyCredential)) return false; if (sessionEntry.PSSessionOption.SkipCACheck != pssessionOption.SkipCACheck) return false; if (sessionEntry.PSSessionOption.SkipCNCheck != pssessionOption.SkipCNCheck) return false; if (sessionEntry.PSSessionOption.SkipRevocationCheck != pssessionOption.SkipRevocationCheck) return false; if (sessionEntry.PSSessionOption.NoEncryption != pssessionOption.NoEncryption) return false; if (sessionEntry.PSSessionOption.UseUTF16 != pssessionOption.UseUTF16) return false; } return true; }
/// <summary> /// This method is used by Connect-WsMan Cmdlet and New-Item of WsMan Provider to create connection to WsMan /// </summary> /// <param name="ParameterSetName"></param> /// <param name="connectionuri"></param> /// <param name="port"></param> /// <param name="computername"></param> /// <param name="applicationname"></param> /// <param name="usessl"></param> /// <param name="authentication"></param> /// <param name="sessionoption"></param> /// <param name="credential"></param> /// <param name="certificateThumbprint"></param> internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, int port, string computername, string applicationname, bool usessl, AuthenticationMechanism authentication, SessionOption sessionoption, PSCredential credential, string certificateThumbprint) { IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); try { string connectionStr = CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { //in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionStr.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); computername = constrsplit1[1].Trim(); } IWSManSession m_session = CreateSessionObject(m_wsmanObject, authentication, sessionoption, credential, connectionStr, certificateThumbprint, usessl); m_session.Identify(0); string key = computername; if (key == null) { key = "localhost"; } AddtoDictionary(key, m_session); } catch (IndexOutOfRangeException) { AssertError(_resourceMgr.GetString("NotProperURI"), false, connectionuri); } catch (Exception ex) { AssertError(ex.Message, false, computername); } finally { if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { AssertError(m_wsmanObject.Error, true, computername); } } }
internal static void ValidateSpecifiedAuthentication(AuthenticationMechanism authentication, PSCredential credential, string certificateThumbprint) { if (credential == null || certificateThumbprint == null) { if (authentication == AuthenticationMechanism.Default || authentication == AuthenticationMechanism.ClientCertificate || certificateThumbprint == null) { return; } else { object[] str = new object[2]; str[0] = "CertificateThumbPrint"; str[1] = authentication.ToString(); string str1 = WSManHelper.FormatResourceMsgFromResourcetextS("AmbiguosAuthentication", str); throw new InvalidOperationException(str1); } } else { object[] objArray = new object[2]; objArray[0] = "CertificateThumbPrint"; objArray[1] = "credential"; string str2 = WSManHelper.FormatResourceMsgFromResourcetextS("AmbiguosAuthentication", objArray); throw new InvalidOperationException(str2); } }
internal static bool CompareAuthentication(AuthenticationMechanism authentication1, AuthenticationMechanism authentication2) { return authentication1 == authentication2; }
public AuthenticatingWSManCommand() { this.authentication = AuthenticationMechanism.Default; }