private void InnerBind( string protocolSequence, string networkAddress, string endpoint, AccountCredential transportCredential, ClientSecurityContext securityContext) { if (RpceClientTransport != null) { throw new InvalidOperationException("SRVS has already been bind"); } RpceClientTransport = new RpceClientTransport(); try { RpceClientTransport.Bind( protocolSequence, networkAddress, endpoint, transportCredential, SrvsUtility.SRVS_INTERFACE_UUID, SrvsUtility.SRVS_INTERFACE_MAJOR_VERSION, SrvsUtility.SRVS_INTERFACE_MINOR_VERSION, securityContext, AuthenticationLevel, true, RpceTimeout); } catch { RpceClientTransport = null; throw; } }
private KerberosTicket GetTGTCachedToken(AccountCredential inputCredential, string inputServerPrincipleName) { cacheLock.EnterReadLock(); KerberosTicket cachedTGTToken = null; CacheTokenKey findedKey = null; foreach (var kvp in TGTTokenCache) { int address = this.credential.GetHashCode(); if (kvp.Key.CredentialAddress.Equals(inputCredential) && kvp.Key.ServerPrincipleName.Equals(inputServerPrincipleName)) { findedKey = kvp.Key; break; } } if (findedKey != null) { cachedTGTToken = TGTTokenCache[findedKey]; //TODO: Remove from cache if token expired } cacheLock.ExitReadLock(); return(cachedTGTToken); }
public KerberosClientSecurityContext(AccountCredential clientCredential, string serviceName, ClientSecurityContextAttribute contextAttributes) { if (clientCredential.DomainName == null) { throw new ArgumentNullException(nameof(clientCredential.DomainName)); } if (clientCredential.AccountName == null) { throw new ArgumentNullException(nameof(clientCredential.AccountName)); } if (clientCredential.Password == null) { throw new ArgumentNullException(nameof(clientCredential.Password)); } if (serviceName == null) { throw new ArgumentNullException(nameof(serviceName)); } this.contextAttribute = contextAttributes; client = new KileClient(clientCredential.DomainName, clientCredential.AccountName, clientCredential.Password, KileAccountType.User); this.serverName = serviceName; domain = clientCredential.DomainName; userLogonName = clientCredential.AccountName; client.Connect(clientCredential.DomainName, ConstValue.KDC_PORT, KileConnectionType.TCP); InitContextSize(); }
/// <summary> /// The two client connects to the two IP addresses of scaleout file server /// Negotiate, SessionSetup, TreeConnect /// </summary> private Smb2FunctionalClient InitializeClient(IPAddress ip, out uint treeId) { Smb2FunctionalClient client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, this.Site); client.ConnectToServerOverTCP(ip); client.Negotiate( Smb2Utility.GetDialects(DialectRevision.Smb21), testConfig.IsSMB1NegotiateEnabled); //client.SessionSetup( // testConfig.DefaultSecurityPackage, // //testConfig.ScaleOutFileServerName, // testConfig.AccountCredential, // testConfig.UseServerGssToken); AccountCredential accountCredential = false ? TestConfig.NonAdminAccountCredential : TestConfig.AccountCredential; client.SessionSetup(TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, accountCredential, false); //client.TreeConnect(Smb2Utility.GetUncPath(testConfig.ScaleOutFileServerName, testConfig.CAShareName), out treeId); //uint treeId_t; string sharePath = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare); client.TreeConnect(sharePath, out treeId); return(client); }
/// <summary> /// Bind SWN to the RPC server. /// </summary> /// <param name="serverName">SWN server name to bind</param> /// <param name="bindCred">Credential to bind SWN server</param> /// <param name="secContext">Security provider for RPC</param> /// <param name="timeout">Timeout for bind and requests</param> /// <param name="authLevel">RPCE authentication level</param> /// <returns>Return true if success, or false for fail</returns> ///<exception cref="ArgumentNullException"> /// Thrown when serverName is null or empty. /// </exception> public bool SwnBind( string serverName, AccountCredential bindCred, ClientSecurityContext secContext, RpceAuthenticationLevel authLevel, TimeSpan timeout) { if (string.IsNullOrEmpty(serverName)) { throw new ArgumentNullException("serverName"); } //Query endpoint on SWN server ushort[] endpoints = SwnUtility.QueryEndpoints(serverName); bool retVal = RpcBind( RpceUtility.RPC_OVER_TCPIP_PROTOCOL_SEQUENCE, serverName, endpoints[0].ToString(), bindCred, secContext, authLevel, timeout); rpceTimeout = timeout; return(retVal); }
/// <summary> /// Create or delete a file or directory with a given name. /// </summary> /// <param name="client">the functional client used to create</param> /// <param name="isDirectory">true for file and false for directory</param> /// <param name="isDeleteFlagSet">true for delete flag set</param> /// <param name="isNonAdmin">true for non admin account credential</param> /// <param name="fileNametype">the file name type: ValidFileName, SymbolicLinkInMiddle, SymbolicLinkAtLast, InvalidSymbolicLink</param> /// <param name="isValidAccessMask">true for valid access mask, which should contain DELETE or GENERIC_ALL</param> private void OperateFileOrDirectory(Smb2FunctionalClient client, bool isDirectory, bool isDeleteFlagSet, bool isNonAdmin, FileNameType fileNameType, bool isValidAccessMask) { CreateOptions_Values createOption; CreateDisposition_Values createDisposition; if (isDirectory) { createOption = CreateOptions_Values.FILE_DIRECTORY_FILE; } else { createOption = CreateOptions_Values.FILE_NON_DIRECTORY_FILE; } BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start the client by sending the following requests: NEGOTIATE; SESSION_SETUP; TREE_CONNECT."); client.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled); AccountCredential accountCredential = isNonAdmin ? TestConfig.NonAdminAccountCredential : TestConfig.AccountCredential; client.SessionSetup(TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, accountCredential, false); uint treeId; client.TreeConnect(sharePath, out treeId); FILEID fileId; Smb2CreateContextResponse[] createContextResponse; AccessMask accessMask = AccessMask.GENERIC_READ | AccessMask.GENERIC_WRITE | AccessMask.DELETE; accessMask = isValidAccessMask ? accessMask : AccessMask.GENERIC_READ | AccessMask.GENERIC_WRITE; // The delete flag is set in the following situations: 1. Delete an existed file; 2. Test CreateOptions_Values.FILE_DELETE_ON_CLOSE combined with DesiredAccess createOption = isDeleteFlagSet ? (createOption | CreateOptions_Values.FILE_DELETE_ON_CLOSE) : createOption; // The createDisposition is set to FILE_OPEN if the file already existed; else, if it's the first time to create a file, this field should be set to FILE_CREATE createDisposition = (fileNameType == FileNameType.ExistedValidFileName) ? CreateDisposition_Values.FILE_OPEN : CreateDisposition_Values.FILE_CREATE; fileName = GetFileName(isDirectory, fileNameType); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client sends CREATE request with create option: {0} and create disposition: {1}", createOption, createDisposition); uint status = client.Create( treeId, fileName, createOption, out fileId, out createContextResponse, accessMask: accessMask, createDisposition: createDisposition, checker: (header, response) => { CheckCreateResponse(isNonAdmin, createOption, accessMask, header, response, fileNameType); }); AddTestFileName(sharePath, fileName); if (status == Smb2Status.STATUS_SUCCESS) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the client by sending the following requests: CLOSE; TREE_DISCONNECT; LOG_OFF."); client.Close(treeId, fileId); } client.TreeDisconnect(treeId); client.LogOff(); }
/// <summary> /// Constructor /// </summary> /// <param name="account">Client account credential.</param> /// <param name="target">Target name.</param> public NlmpClientSecurityConfig( AccountCredential account, string target) : base(SecurityPackageType.Ntlm) { this.clientCredential = account; this.targetName = target; }
public static ClientSecurityContext CreateClientSecurityContext( string serverName, AccountCredential credential, ClientSecurityContextAttribute contextAttribute ) { return(CreateClientSecurityContext(serverName, credential, KerberosAccountType.User, credential.DomainName, 88, TransportType.TCP, contextAttribute)); }
/// <inheritdoc/> public async Task ProcessNotificationEntities(string applicationName, IList <EmailNotificationItemEntity> notificationEntities) { var traceprops = new Dictionary <string, string>(); traceprops[AIConstants.Application] = applicationName; traceprops[AIConstants.MeetingNotificationCount] = notificationEntities?.Count.ToString(CultureInfo.InvariantCulture); this.logger.TraceInformation($"Started {nameof(this.ProcessNotificationEntities)} method of {nameof(SMTPNotificationProvider)}.", traceprops); if (notificationEntities is null || notificationEntities.Count == 0) { throw new ArgumentNullException(nameof(notificationEntities), "notificationEntities are null."); } var client = new SmtpClient(this.smtpSetting.SmtpUrl, this.smtpSetting.SmtpPort); AccountCredential selectedAccountCreds = this.emailAccountManager.FetchAccountToBeUsedForApplication(applicationName, this.applicationAccounts); client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(selectedAccountCreds.AccountName, selectedAccountCreds.PrimaryPassword, this.smtpSetting.SmtpDomain); client.EnableSsl = true; var applicationFromAddress = this.applicationAccounts.Find(a => a.ApplicationName == applicationName).FromOverride; foreach (var item in notificationEntities) { item.From = applicationFromAddress; item.TryCount++; item.ErrorMessage = string.Empty; // Reset the error message on next retry. try { var sendForReal = this.mailSettings.Find(a => a.ApplicationName == applicationName).SendForReal; var toOverride = this.mailSettings.Find(a => a.ApplicationName == applicationName).ToOverride; MessageBody body = await this.emailManager.GetNotificationMessageBodyAsync(applicationName, item).ConfigureAwait(false); MailMessage message = item.ToSmtpMailMessage(body); if (!sendForReal) { message.To.Add(string.Join(",", toOverride.Split(Common.ApplicationConstants.SplitCharacter, System.StringSplitOptions.RemoveEmptyEntries).ToList())); message.CC.Clear(); message.Bcc.Clear(); message.ReplyToList.Clear(); } await client.SendMailAsync(message).ConfigureAwait(false); item.Status = NotificationItemStatus.Sent; } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { this.logger.WriteCustomEvent($"{AIConstants.CustomEventMailSendFailed} for notificationId: {item.NotificationId} "); item.Status = NotificationItemStatus.Failed; item.ErrorMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } } this.logger.TraceInformation($"Finished {nameof(this.ProcessNotificationEntities)} method of {nameof(SMTPNotificationProvider)}.", traceprops); }
/// <summary> /// Constructor /// </summary> /// <param name="account">Client account credential.</param> /// <param name="target">SPN of the service to which the client wishes to authenticate.</param> /// <param name="securityAttributes">Security Attributes.</param> public NlmpClientSecurityConfig( AccountCredential account, string target, ClientSecurityContextAttribute securityAttributes) : base(SecurityPackageType.Ntlm) { this.clientCredential = account; this.targetName = target; this.SecurityAttributes = securityAttributes; }
protected bool TryReadFile(Smb2FunctionalClient client, AccountCredential user, string sharePath, string fileName) { bool accessSucceed = true; BaseTestSite.Log.Add(LogEntryKind.Debug, "Client sends NEGOTIATE message."); client.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled); BaseTestSite.Log.Add(LogEntryKind.Debug, "Client sends SESSION_SETUP message using account: {0}@{1}.", user.AccountName, user.DomainName); client.SessionSetup(TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, user, false); uint treeId; BaseTestSite.Log.Add(LogEntryKind.Debug, "Client sends TREE_CONNECT message to access share: {0}.", sharePath); client.TreeConnect(sharePath, out treeId); FILEID fileId; Smb2CreateContextResponse[] createContexResponse; BaseTestSite.Log.Add(LogEntryKind.Debug, "Client sends CREATE request."); uint status = client.Create( treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileId, out createContexResponse, accessMask: AccessMask.FILE_READ_DATA | AccessMask.FILE_READ_ATTRIBUTES, createDisposition: CreateDisposition_Values.FILE_OPEN, checker: (header, response) => { if (header.Status == Smb2Status.STATUS_SUCCESS) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Successfully opened the file with Access Mask: FILE_READ_DATA | FILE_READ_ATTRIBUTES."); accessSucceed = true; } else if (header.Status == Smb2Status.STATUS_ACCESS_DENIED) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Fail to open the file with Access Mask: FILE_READ_DATA | FILE_READ_ATTRIBUTES."); accessSucceed = false; } else { BaseTestSite.Assert.Fail("Unexpected error code in CREATE response: {0}", Smb2Status.GetStatusCode(header.Status)); } }); if (status == Smb2Status.STATUS_SUCCESS) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Tear down the client by sending the following requests: CLOSE; TREE_DISCONNECT; LOG_OFF."); client.Close(treeId, fileId); } client.TreeDisconnect(treeId); client.LogOff(); return(accessSucceed); }
/// <summary> /// Performs CredSSP authentication. /// </summary> /// <exception cref="IOException">Raised when attempting to read from/write to the remote connection which /// has been closed</exception> /// <exception cref="EndOfStreamException">Raised when the username or password doesn't match or authentication /// fails</exception> public void Authenticate() { // Authenticated already, do nothing if (isAuthenticated) { return; } credential = new AccountCredential(domain, userName, password); byte[] receivedBuffer = new byte[MaxBufferSize]; int bytesReceived = 0; // Dispose the context as it may be timed out if (context != null) { context.Dispose(); } context = new SspiClientSecurityContext( SecurityPackageType.CredSsp, credential, serverPrincipal, attribute, SecurityTargetDataRepresentation.SecurityNativeDrep); context.Initialize(null); // Get first token byte[] token = context.Token; // SSL handshake while (context.NeedContinueProcessing) { // Send handshake request clientStream.Write(token, 0, token.Length); // Get handshake resopnse bytesReceived = clientStream.Read(receivedBuffer, 0, receivedBuffer.Length); // The remote connection has been closed if (bytesReceived == 0) { throw new EndOfStreamException("Authentication failed: remote connection has been closed."); } byte[] inToken = new byte[bytesReceived]; Array.Copy(receivedBuffer, inToken, bytesReceived); // Get next token from response context.Initialize(inToken); token = context.Token; } // Send the last token, handshake over, CredSSP is established // Note if there're errors during authentication, an SSPIException will be raised // and isAuthentication will not be true. clientStream.Write(token, 0, token.Length); isAuthenticated = true; }
public void ReEstablishResilientOpenRequest(ModelUser user) { reconnectClient = new Smb2FunctionalClient(testConfig.Timeout, testConfig, this.Site); AccountCredential account = testConfig.AccountCredential; if (user == ModelUser.DefaultUser) { account = testConfig.AccountCredential; } else if (user == ModelUser.DiffUser) { account = testConfig.NonAdminAccountCredential; } // Connect to Share ConnectToShare( Site, testConfig, reconnectClient, new DialectRevision[] { dialect }, clientGuid, account, out dialect, out treeId); // Reconnect to the Open Smb2CreateContextResponse[] createContextResponse; testConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_RECONNECT); uint status = reconnectClient.Create( treeId, fileName, CreateOptions_Values.NONE, out fileId, out createContextResponse, createContexts: new Smb2CreateContextRequest[] { new Smb2CreateDurableHandleReconnect() { Data = fileId } }, checker: (header, response) => { // do nothing, skip the exception } ); ReEstablishResilientOpenResponse((ModelSmb2Status)status); }
/// <summary> /// Constructor /// </summary> /// <param name="clientCredential">Client account credential.</param> /// <param name="serverPrincipal">Server principal.</param> /// <param name="contextAttributes">Client security context attributes.</param> /// <param name="targetDataRep">The data representation, such as byte ordering, on the target.</param> public SspiClientSecurityConfig( AccountCredential clientCredential, string serverPrincipal, ClientSecurityContextAttribute contextAttributes, SecurityTargetDataRepresentation targetDataRep) : base(SecurityPackageType.Unknown) { this.clientCredential = clientCredential; this.serverPrincipal = serverPrincipal; this.securityAttributes = contextAttributes; this.targetDataRep = targetDataRep; }
/// <summary> /// Constructor. /// </summary> /// <param name="account">Account credential.</param> /// <param name="logonName">Logon name.</param> /// <param name="serviceName">Service name.</param> /// <param name="kdcIpAddress">KDC IP address</param> /// <param name="attributes">Client security attributes.</param> /// <param name="connectionType">Connection type.</param> public KerberosClientSecurityConfig( AccountCredential account, string serviceName, ClientSecurityContextAttribute attributes) : base(SecurityPackageType.Kerberos) { this.clientCredential = account; this.logonName = account.AccountName; this.serviceName = serviceName; this.kdcIpAddress = account.DomainName.ParseIPAddress(); this.securityAttributes = attributes; this.transportType = TransportType.TCP; }
/// <summary> /// Constructor /// </summary> /// <param name="packageType">Specifies the name of the security package with which these credentials will be used /// </param> /// <param name="serverCredential">The credential of server, if null, use default user account.</param> /// <param name="serverPrincipal">Server principal name</param> /// <param name="contextAttributes">Bit flags that specify the attributes required by the server to establish /// the context</param> /// <param name="targetDataRep">The data representation, such as byte ordering, on the target. This parameter /// can be either SECURITY_NATIVE_DREP or SECURITY_NETWORK_DREP.</param> public SspiServerSecurityContext( SecurityPackageType packageType, AccountCredential serverCredential, string serverPrincipal, ServerSecurityContextAttribute contextAttributes, SecurityTargetDataRepresentation targetDataRep) { this.packageType = packageType; this.serverPrincipalName = serverPrincipal; this.securityContextAttributes = contextAttributes; this.targetDataRepresentaion = targetDataRep; this.AcquireCredentialsHandle(serverCredential); }
/// <summary> /// FetchAccountToBeUsedForApplication. /// </summary> /// <param name="applicationName">applicationName.</param> /// <param name="applicationAccounts">applicationAccounts.</param> /// <returns> Tuple(AuthenticationHeaderValue, AccountCredential).</returns> public AccountCredential FetchAccountToBeUsedForApplication(string applicationName, List <ApplicationAccounts> applicationAccounts) { AccountCredential selectedAccountCredential = null; var accountsOfApplication = applicationAccounts?.Find(a => a.ApplicationName == applicationName)?.Accounts?.FindAll(acc => acc.IsEnabled); if (accountsOfApplication != null && accountsOfApplication.Count > 0) { this.selectedIndex = this.selectedIndex > accountsOfApplication.Count - 1 ? 0 : this.selectedIndex; int indexOfAccountToBeUsedRR = this.selectedIndex; selectedAccountCredential = accountsOfApplication[indexOfAccountToBeUsedRR]; } return(selectedAccountCredential); }
/// <summary> /// Generate a new NlmpClient Security Context /// </summary> /// <param name="domain" cref="KerberosClientCredential">Login user Credential</param> /// <param name="accountType">The type of the logon account. User or Computer</param> /// <param name="kdcAddress">The IP address of the KDC.</param> /// <param name="kdcPort">The port of the KDC.</param> /// <param name="transportType">Whether the transport is TCP or UDP transport.</param> /// <returns></returns> public static ClientSecurityContext CreateClientSecurityContext( string serverName, AccountCredential credential, KerberosAccountType accountType, IPAddress kdcAddress, int kdcPort, TransportType transportType, ClientSecurityContextAttribute contextAttribute, KerberosConstValue.OidPkt oidPkt = KerberosConstValue.OidPkt.KerberosToken, string salt = null ) { return(new KerberosClientSecurityContext(serverName, credential, accountType, kdcAddress, kdcPort, transportType, contextAttribute, oidPkt, salt)); }
/// <summary> /// Constructor /// </summary> /// <param name="flags">Negotiation flags.</param> /// <param name="clientCredential">Client account credential.</param> /// <param name="isDomainJoined">Joined in a domain or not</param> /// <param name="netbiosDomainName">Netbios domain name.</param> /// <param name="netbiosMachineName">Netbios machine name.</param> public NlmpServerSecurityConfig( NegotiateTypes flags, NlmpClientCredential clientCredential, bool isDomainJoined, string netbiosDomainName, string netbiosMachineName) : base(SecurityPackageType.Ntlm) { this.negotiateflags = flags; this.clientCredential = clientCredential; this.isDomainJoined = isDomainJoined; this.netbiosDomainName = netbiosDomainName; this.netbiosMachineName = netbiosMachineName; this.targetName = clientCredential.TargetName; }
/// <inheritdoc/> public async Task ProcessNotificationEntities(string applicationName, IList <EmailNotificationItemEntity> notificationEntities) { if (notificationEntities is null || notificationEntities.Count == 0) { throw new ArgumentNullException(nameof(notificationEntities), "notificationEntities are null."); } var traceProps = new Dictionary <string, string>(); traceProps[AIConstants.Application] = applicationName; traceProps[AIConstants.EmailNotificationCount] = notificationEntities.Count.ToString(CultureInfo.InvariantCulture); this.logger.TraceInformation($"Started {nameof(this.ProcessNotificationEntities)} method of {nameof(MSGraphNotificationProvider)}.", traceProps); var applicationFromAddress = this.applicationAccounts.Find(a => a.ApplicationName == applicationName).FromOverride; AccountCredential selectedAccountCreds = this.emailAccountManager.FetchAccountToBeUsedForApplication(applicationName, this.applicationAccounts); AuthenticationHeaderValue authenticationHeaderValue = await this.tokenHelper.GetAuthenticationHeaderValueForSelectedAccount(selectedAccountCreds).ConfigureAwait(false); Tuple <AuthenticationHeaderValue, AccountCredential> selectedAccount = new Tuple <AuthenticationHeaderValue, AccountCredential>(authenticationHeaderValue, selectedAccountCreds); this.logger.TraceVerbose($"applicationFromAddress: {applicationFromAddress}", traceProps); // Override the From address of notifications based on application configuration notificationEntities.ToList().ForEach(nie => nie.From = applicationFromAddress); if (authenticationHeaderValue == null) { foreach (var item in notificationEntities) { item.Status = NotificationItemStatus.Failed; item.ErrorMessage = $"Could not retrieve authentication token with selected account:{selectedAccount.Item2?.AccountName} for the application:{applicationName}."; } } else { string emailAccountUsed = selectedAccount.Item2.AccountName; if (this.mSGraphSetting.EnableBatching) { await this.ProcessEntitiesInBatch(applicationName, notificationEntities, selectedAccount).ConfigureAwait(false); } else { await this.ProcessEntitiesIndividually(applicationName, notificationEntities, selectedAccount).ConfigureAwait(false); } } this.logger.TraceInformation($"Finished {nameof(this.ProcessNotificationEntities)} method of {nameof(MSGraphNotificationProvider)}.", traceProps); }
/// <inheritdoc/> public async Task <string> GetAccessTokenForSelectedAccount(AccountCredential selectedAccountCredential) { var traceProps = new Dictionary <string, string>(); if (selectedAccountCredential == null) { throw new ArgumentNullException(nameof(selectedAccountCredential)); } traceProps[AIConstants.EmailAccount] = selectedAccountCredential.AccountName; this.logger.TraceInformation($"Started {nameof(this.GetAccessTokenForSelectedAccount)} method of {nameof(TokenHelper)}.", traceProps); string authority = this.userTokenSetting.Authority; string clientId = this.userTokenSetting.ClientId; string userEmail = selectedAccountCredential?.AccountName; string userPassword = System.Web.HttpUtility.UrlEncode(selectedAccountCredential.PrimaryPassword); var token = string.Empty; using (HttpClient client = new HttpClient()) { var tokenEndpoint = $"{authority}"; var accept = ApplicationConstants.JsonMIMEType; client.DefaultRequestHeaders.Add("Accept", accept); string postBody = $"resource={clientId}&client_id={clientId}&grant_type=password&username={userEmail}&password={userPassword}&scope=openid"; using (var response = await client.PostAsync(tokenEndpoint, new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded")).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) { var jsonresult = JObject.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); token = (string)jsonresult["access_token"]; } else { var errorResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false); traceProps["Message"] = errorResponse; this.logger.TraceInformation($"An error occurred while fetching token for {selectedAccountCredential.AccountName}. Details: {errorResponse}", traceProps); this.logger.WriteCustomEvent("Unable to get Access Token", traceProps); token = null; } } } this.logger.TraceInformation($"Finished {nameof(this.GetAccessTokenForSelectedAccount)} method of {nameof(TokenHelper)}.", traceProps); return(token); }
/// <summary> /// Constructor. /// </summary> /// <param name="account">Account credential.</param> /// <param name="logonName">Logon name.</param> /// <param name="serviceName">Service name.</param> /// <param name="kdcIpAddress">KDC IP address</param> /// <param name="attributes">Client security attributes.</param> /// <param name="connectionType">Connection type.</param> public KerberosClientSecurityConfig( AccountCredential account, string logonName, string serviceName, IPAddress kdcIpAddress, ClientSecurityContextAttribute attributes, TransportType transportType) : base(SecurityPackageType.Kerberos) { this.clientCredential = account; this.logonName = logonName; this.serviceName = serviceName; this.kdcIpAddress = kdcIpAddress; this.securityAttributes = attributes; this.transportType = transportType; }
/// <summary> /// Connect and bind to a RPCE remote host. /// </summary> /// <param name="protocolSequence"> /// A protocol sequence.<para/> /// Support ncacn_ip_tcp and ncacn_np only. /// </param> /// <param name="networkAddress"> /// A network address of RPCE remote host. /// </param> /// <param name="endpoint"> /// An endpoint that its format and content /// are associated with the protocol sequence. /// </param> /// <param name="transportCredential"> /// If connect by SMB/SMB2, it's the security credential /// used by underlayer transport (SMB/SMB2). /// If connect by TCP, this parameter is ignored. /// </param> /// <param name="interfaceId"> /// A Guid of interface_id that is binding to. /// </param> /// <param name="interfaceMajorVersion"> /// interface_major_ver that is binding to. /// </param> /// <param name="interfaceMinorVersion"> /// interface_minor_ver that is binding to. /// </param> /// <param name="securityContext"> /// A security provider. If setting to null, indicate the default authentication type NTLM is selected. /// </param> /// <param name="authenticationLevel"> /// An authentication level. /// </param> /// <param name="supportsHeaderSign"> /// Indicates whether client supports header sign or not. /// </param> /// <param name="timeout"> /// Timeout period. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when protSeq, networkAddr or endpoint is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server. /// </exception> public virtual void Bind( string protocolSequence, string networkAddress, string endpoint, AccountCredential transportCredential, Guid interfaceId, ushort interfaceMajorVersion, ushort interfaceMinorVersion, ClientSecurityContext securityContext, RpceAuthenticationLevel authenticationLevel, bool supportsHeaderSign, TimeSpan timeout) { Bind(protocolSequence, networkAddress, endpoint, transportCredential, interfaceId, interfaceMajorVersion, interfaceMinorVersion, securityContext, securityContext, authenticationLevel, supportsHeaderSign, timeout); }
/// <summary> /// Constructor /// </summary> /// <param name="logger">Enable the log</param> /// <param name="contentServerName">The ContentServer name</param> /// <param name="hostedCacheServerName">The HostedCacheServer name</param> /// <param name="accountCredential">Account credential</param> /// <param name="securityPackageType">security package: NTLM, Negotiate, kerbrose</param> public BranchCacheDetector(Logger logger, string contentServerName, string hostedCacheServerName, AccountCredential accountCredential, SecurityPackageType securityPackageType = SecurityPackageType.Negotiate) { ContentServerName = contentServerName; HostedCacheServerName = hostedCacheServerName; Credential = accountCredential; SecurityPackageType = securityPackageType; logWriter = logger; logWriter.AddLog(LogLevel.Information, string.Format("ContentServerName: {0}", ContentServerName)); logWriter.AddLog(LogLevel.Information, string.Format("HostedCacheServerName: {0}", HostedCacheServerName)); logWriter.AddLog(LogLevel.Information, string.Format("DomainName: {0}", Credential.DomainName)); logWriter.AddLog(LogLevel.Information, string.Format("UserName: {0}", Credential.AccountName)); logWriter.AddLog(LogLevel.Information, string.Format("UserPassword: {0}", Credential.Password)); logWriter.AddLog(LogLevel.Information, string.Format("SecurityPackageType: {0}", SecurityPackageType.ToString())); logWriter.AddLineToLog(LogLevel.Information); }
/// <summary> /// Set up an RPC session with a specific server. /// </summary> /// <param name="serverName">Server computer name</param> /// <param name="credential">User account used to setup this session</param> /// <param name="securityContext">Security context of session</param> public void Bind( string serverName, AccountCredential credential, ClientSecurityContext securityContext) { if (string.IsNullOrEmpty(serverName)) { throw new ArgumentNullException("serverName"); } InnerBind( RpceUtility.RPC_OVER_NAMED_PIPE_PROTOCOL_SEQUENCE, serverName, SrvsUtility.SRVS_NAMED_PIPE, credential, securityContext); }
public KerberosClientSecurityContext(AccountCredential clientCredential, string logonName, string serviceName, IPAddress kdcIpAddress, ClientSecurityContextAttribute contextAttributes, KileConnectionType transportType) { if (clientCredential.DomainName == null) { throw new ArgumentNullException(nameof(clientCredential.DomainName)); } if (clientCredential.AccountName == null) { throw new ArgumentNullException(nameof(clientCredential.AccountName)); } if (clientCredential.Password == null) { throw new ArgumentNullException(nameof(clientCredential.Password)); } if (kdcIpAddress == null) { throw new ArgumentNullException(nameof(kdcIpAddress)); } if (logonName == null) { throw new ArgumentNullException(nameof(logonName)); } if (serviceName == null) { throw new ArgumentNullException(nameof(serviceName)); } client = new KileClient(clientCredential.DomainName, clientCredential.AccountName, clientCredential.Password, KileAccountType.User); service = serviceName; domain = clientCredential.DomainName; userLogonName = logonName; contextAttribute = contextAttributes; client.Connect(kdcIpAddress.ToString(), ConstValue.KDC_PORT, transportType); contextSizes = new SecurityPackageContextSizes(); contextSizes.MaxTokenSize = ConstValue.MAX_TOKEN_SIZE; contextSizes.MaxSignatureSize = ConstValue.MAX_SIGNATURE_SIZE; contextSizes.BlockSize = ConstValue.BLOCK_SIZE; contextSizes.SecurityTrailerSize = ConstValue.SECURITY_TRAILER_SIZE; }
public FSDetector (Logger logger, string targetSUT, AccountCredential accountCredential, SecurityPackageType securityPackageType) { sutName = targetSUT; Credential = accountCredential; SecurityPackageType = securityPackageType; logWriter = logger; logWriter.AddLog(LogLevel.Information, string.Format("SutName: {0}", sutName)); logWriter.AddLog(LogLevel.Information, string.Format("DomainName: {0}", Credential.DomainName)); logWriter.AddLog(LogLevel.Information, string.Format("UserName: {0}", Credential.AccountName)); logWriter.AddLog(LogLevel.Information, string.Format("UserPassword: {0}", Credential.Password)); logWriter.AddLog(LogLevel.Information, string.Format("SecurityPackageType: {0}", SecurityPackageType.ToString())); logWriter.AddLineToLog(LogLevel.Information); }
/// <summary> /// Create a KerberosClientSecurityContext instance. /// </summary> /// <param name="domain" cref="KerberosClientCredential">Login user Credential</param> /// <param name="accountType">The type of the logon account. User or Computer</param> /// <param name="kdcAddress">The IP address of the KDC.</param> /// <param name="kdcPort">The port of the KDC.</param> /// <param name="transportType">Whether the transport is TCP or UDP transport.</param> /// <exception cref="System.ArgumentNullException">Thrown when the input parameter is null.</exception> public KerberosClientSecurityContext( string serverName, AccountCredential credential, KerberosAccountType accountType, IPAddress kdcAddress, int kdcPort, TransportType transportType, ClientSecurityContextAttribute contextAttribute, KerberosConstValue.OidPkt oidPkt = KerberosConstValue.OidPkt.KerberosToken, string salt = null ) { this.credential = credential; this.serverName = serverName; this.contextAttribute = contextAttribute; this.client = new KerberosClient(this.credential.DomainName, this.credential.AccountName, this.credential.Password, accountType, kdcAddress, kdcPort, transportType, oidPkt, salt); this.UpdateDefaultSettings(); }
private static void ConnectToShare( ITestSite testSite, SMB2ModelTestConfig testConfig, Smb2FunctionalClient client, DialectRevision[] dialects, Guid clientGuid, AccountCredential account, out DialectRevision responseDialect, out uint treeId) { client.ConnectToServer(testConfig.UnderlyingTransport, testConfig.SutComputerName, testConfig.SutIPAddress); // Negotiate NEGOTIATE_Response?negotiateResponse = null; client.Negotiate( dialects, testConfig.IsSMB1NegotiateEnabled, clientGuid: clientGuid, checker: (header, response) => { testSite.Assert.AreEqual( Smb2Status.STATUS_SUCCESS, header.Status, "{0} should succeed", header.Command); negotiateResponse = response; }); responseDialect = negotiateResponse.Value.DialectRevision; // SMB2 SESSION SETUP client.SessionSetup( testConfig.DefaultSecurityPackage, testConfig.SutComputerName, account, testConfig.UseServerGssToken); // SMB2 Tree Connect client.TreeConnect( Smb2Utility.GetUncPath(testConfig.SutComputerName, testConfig.BasicFileShare), out treeId); }
/// <summary> /// Initialize RpceServerContext. /// </summary> /// <param name="protocolSequence">The RPC protocol sequence strings.</param> /// <param name="endpoint">The endpoint of server.</param> /// <param name="namedPipeTransportCredential">Credential for namepiped transport.</param> internal RpceServerContext( String protocolSequence, String endpoint, AccountCredential namedPipeTransportCredential) { this.protocolSequence = protocolSequence; this.endpoint = endpoint; this.namedPipeTransportCredential = namedPipeTransportCredential; this.sessions = new Dictionary <string, RpceServerSessionContext>(); this.tempSessions = new Dictionary <string, RpceServerSessionContext>(); //set default value this.maxReceiveFragmentSize = RpceUtility.DEFAULT_MAX_RECEIVE_FRAGMENT_SIZE; this.maxTransmitFragmentSize = RpceUtility.DEFAULT_MAX_TRANSMIT_FRAGMENT_SIZE; this.rpcVersionMajor = 5; this.rpcVersionMinor = 1; this.ndrVersion = RpceNdrVersion.NDR; }