/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a WSS token. IssuedIdentityToken wssToken = args.NewIdentity as IssuedIdentityToken; if (wssToken != null) { SecurityToken samlToken = ParseAndVerifySamlToken(wssToken.DecryptedTokenData); args.Identity = new UserIdentity(samlToken); Utils.Trace("SAML Token Accepted: {0}", args.Identity.DisplayName); return; } // check for a user name token. UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { VerifyPassword(userNameToken.UserName, userNameToken.DecryptedPassword); args.Identity = new UserIdentity(userNameToken); Utils.Trace("UserName Token Accepted: {0}", args.Identity.DisplayName); return; } // check for x509 user token. X509IdentityToken x509Token = args.NewIdentity as X509IdentityToken; if (userNameToken != null) { VerifyCertificate(x509Token.Certificate); args.Identity = new UserIdentity(x509Token); Utils.Trace("X509 Token Accepted: {0}", args.Identity.DisplayName); return; } }
/// <summary> /// Displays the dialog. /// </summary> public UserIdentity ShowDialog(IUserIdentity identity, string caption) { if (!String.IsNullOrEmpty(caption)) { this.Text = caption; } if (identity != null) { UserNameIdentityToken token = identity.GetIdentityToken() as UserNameIdentityToken; if (token != null) { UserNameTB.Text = token.UserName; PasswordTB.Text = token.DecryptedPassword; } } if (ShowDialog() != DialogResult.OK) { return(null); } return(new UserIdentity(UserNameTB.Text, PasswordTB.Text)); }
/// <summary> /// Displays the dialog. /// </summary> public bool ShowDialog(UserNameIdentityToken token) { if (token != null) { UserNameCB.Text = token.UserName; if (token.Password != null && token.Password.Length > 0) { PasswordTB.Text = new UTF8Encoding().GetString(token.Password); } } if (ShowDialog() != DialogResult.OK) { return false; } token.UserName = UserNameCB.Text; if (!String.IsNullOrEmpty(PasswordTB.Text)) { token.Password = new UTF8Encoding().GetBytes(PasswordTB.Text); } else { token.Password = null; } return true; }
/// <summary> /// Check whether it is an acceptable session. /// </summary> /// <param name="session">The session.</param> /// <param name="args">IdentityToken.</param> void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { switch (args.UserTokenPolicy.TokenType) { case UserTokenType.UserName: UserNameIdentityToken token = args.NewIdentity as UserNameIdentityToken; if (!m_userNameValidator.Validate(token)) { // Bad user access denied. // construct translation object with default text. TranslationInfo info = new TranslationInfo( "InvalidUserInformation", "en-US", "Specified user information are not valid. UserName='******'.", token.UserName); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "InvalidUserInformation", "http://opcfoundation.org", new LocalizedText(info))); } break; default: break; } }
/// <summary> /// Displays the dialog. /// </summary> public bool ShowDialog(UserNameIdentityToken token) { if (token != null) { UserNameCB.SelectedItem = token.UserName; if (token.Password != null && token.Password.Length > 0) { PasswordTB.Password = new UTF8Encoding().GetString(token.Password); } } Popup myPopup = new Popup(); myPopup.Child = this; myPopup.IsOpen = true; token.UserName = UserNameCB.SelectedItem.ToString(); if (!String.IsNullOrEmpty(PasswordTB.Password)) { token.Password = new UTF8Encoding().GetBytes(PasswordTB.Password); } else { token.Password = null; } return(true); }
/// <summary> /// Save UserNameIdentityToken. /// </summary> private static void SaveUserName(string applicationName, UserNameIdentityToken userNameToken) { try { string relativePath = Utils.Format("%CommonApplicationData%\\OPC Foundation\\Accounts\\{0}\\{1}.xml", applicationName, userNameToken.UserName); string absolutePath = Utils.GetAbsoluteFilePath(relativePath, false, false, true); // oops - nothing found. if (absolutePath == null) { absolutePath = Utils.GetAbsoluteFilePath(relativePath, true, false, true); } UserNameIdentityToken outputToken = new UserNameIdentityToken() { UserName = userNameToken.UserName, Password = EncryptPassword(userNameToken.Password), EncryptionAlgorithm = "Triple DES", }; // open the file. FileStream ostrm = File.Open(absolutePath, FileMode.Create, FileAccess.ReadWrite); using (XmlTextWriter writer = new XmlTextWriter(ostrm, System.Text.Encoding.UTF8)) { DataContractSerializer serializer = new DataContractSerializer(typeof(UserNameIdentityToken)); serializer.WriteObject(writer, outputToken); } } catch (Exception e) { Utils.Trace(e, "Unexpected error saving user configuration for COM Wrapper with UserName={0}.", userNameToken.UserName); } }
/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a WSS token. IssuedIdentityToken wssToken = args.NewIdentity as IssuedIdentityToken; // check for a user name token. UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { args.Identity = VerifyPassword(userNameToken); Logger.Information($"UserName Token Accepted: {args.Identity.DisplayName}"); return; } // check for x509 user token. X509IdentityToken x509Token = args.NewIdentity as X509IdentityToken; if (x509Token != null) { VerifyCertificate(x509Token.Certificate); args.Identity = new UserIdentity(x509Token); Logger.Information($"X509 Token Accepted: {args.Identity.DisplayName}"); return; } }
/// <summary> /// Displays the dialog. /// </summary> public bool ShowDialog(UserNameIdentityToken token) { if (token != null) { UserNameCB.Text = token.UserName; if (token.Password != null && token.Password.Length > 0) { PasswordTB.Text = new UTF8Encoding().GetString(token.Password); } } if (ShowDialog() != DialogResult.OK) { return(false); } token.UserName = UserNameCB.Text; if (!String.IsNullOrEmpty(PasswordTB.Text)) { token.Password = new UTF8Encoding().GetBytes(PasswordTB.Text); } else { token.Password = null; } return(true); }
private void ListView_MouseClick(object sender, MouseEventArgs e) { if (e == null || e.Button != MouseButtons.Right) { return; } // Get current item. m_SelectedItem = UserNameListView.GetItemAt(e.X, e.Y); if (m_SelectedItem != null) { UserNameIdentityToken userNameToken = m_SelectedItem.Tag as UserNameIdentityToken; if (userNameToken != null) { // Set current item. m_SelectedTolken = userNameToken; } ContextMenuVisible_NoCreate(); } else { ContextMenuVisible_Create(); } }
public UserIdentity ShowDialog(IWin32Window owner, string caption, UserIdentity identity) { if (!String.IsNullOrEmpty(caption)) { InstructuctionsLabel.Text = caption; InstructuctionsLabel.Visible = true; } UserNameTextBox.Text = null; PasswordTextBox.Text = null; if (identity != null) { UserNameIdentityToken token = identity.GetIdentityToken() as UserNameIdentityToken; if (token != null) { UserNameTextBox.Text = token.UserName; PasswordTextBox.Text = token.DecryptedPassword; } } if (base.ShowDialog(owner) != DialogResult.OK) { return(null); } return(new UserIdentity(UserNameTextBox.Text.Trim(), PasswordTextBox.Text.Trim())); }
private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { UserNameIdentityToken userNameIdentityToken = args.NewIdentity as UserNameIdentityToken; if (userNameIdentityToken != null) { args.Identity = VerifyPassword(userNameIdentityToken); args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_AuthenticatedUser); if (args.Identity is SystemConfigurationIdentity) { args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_ConfigureAdmin); args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_SecurityAdmin); } return; } X509IdentityToken x509IdentityToken = args.NewIdentity as X509IdentityToken; if (x509IdentityToken != null) { VerifyUserTokenCertificate(x509IdentityToken.Certificate); args.Identity = new UserIdentity(x509IdentityToken); Utils.Trace("X509 Token Accepted: {0}", args.Identity.DisplayName); args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_AuthenticatedUser); return; } args.Identity = new UserIdentity(); args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_Anonymous); }
private void AddUser(string name, string password) { UserNameIdentityToken user = new UserNameIdentityToken(); user.UserName = name; user.DecryptedPassword = password; // m_server.CurrentInstance }
/// <summary> /// Load UserNameIdentityToken. /// </summary> /// <returns>UserNameIdentityToken list.</returns> public static Dictionary <string, UserNameIdentityToken> LoadUserName(string applicationName) { Dictionary <string, UserNameIdentityToken> resultTokens = new Dictionary <string, UserNameIdentityToken>(); try { string relativePath = Utils.Format("%CommonApplicationData%\\OPC Foundation\\Accounts\\{0}", applicationName); string absolutePath = Utils.GetAbsoluteDirectoryPath(relativePath, false, false, false); if (string.IsNullOrEmpty(absolutePath)) { return(resultTokens); } foreach (string filePath in Directory.GetFiles(absolutePath)) { // oops - nothing found. if (filePath == null) { continue; } // open the file. using (FileStream istrm = File.Open(filePath, FileMode.Open, FileAccess.Read)) { using (XmlTextReader reader = new XmlTextReader(istrm)) { DataContractSerializer serializer = new DataContractSerializer(typeof(UserNameIdentityToken)); UserNameIdentityToken userNameToken = (UserNameIdentityToken)serializer.ReadObject(reader, false); if (userNameToken.UserName == null || userNameToken.Password == null) { // The configuration file has problem. Utils.Trace("Unexpected error saving user configuration for COM Wrapper."); continue; } if (resultTokens.ContainsKey(userNameToken.UserName)) { // When I already exist, I ignore it. Utils.Trace("When I already exist, I ignore it. UserName={0}", userNameToken.UserName); continue; } userNameToken.Password = DecryptPassword(userNameToken.Password); userNameToken.DecryptedPassword = new UTF8Encoding().GetString(userNameToken.Password); resultTokens.Add(userNameToken.UserName, userNameToken); } } } } catch (Exception e) { Utils.Trace(e, "Unexpected error saving user configuration for COM Wrapper."); } return(resultTokens); }
/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a user name token. UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { args.Identity = VerifyPassword(userNameToken); return; } }
/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a user name token UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { if (VerifyPassword(userNameToken)) { switch (userNameToken.UserName) { // Server configuration administrator, manages the GDS server security case "sysadmin": { args.Identity = new SystemConfigurationIdentity(new UserIdentity(userNameToken)); Utils.Trace("SystemConfigurationAdmin Token Accepted: {0}", args.Identity.DisplayName); return; } // GDS administrator case "appadmin": { args.Identity = new RoleBasedIdentity(new UserIdentity(userNameToken), GdsRole.ApplicationAdmin); Utils.Trace("ApplicationAdmin Token Accepted: {0}", args.Identity.DisplayName); return; } // GDS user case "appuser": { args.Identity = new RoleBasedIdentity(new UserIdentity(userNameToken), GdsRole.ApplicationUser); Utils.Trace("ApplicationUser Token Accepted: {0}", args.Identity.DisplayName); return; } } } } // check for x509 user token. X509IdentityToken x509Token = args.NewIdentity as X509IdentityToken; if (x509Token != null) { GdsRole role = GdsRole.ApplicationUser; VerifyUserTokenCertificate(x509Token.Certificate); // todo: is cert listed in admin list? then // role = GdsRole.ApplicationAdmin; Utils.Trace("X509 Token Accepted: {0} as {1}", args.Identity.DisplayName, role.ToString()); args.Identity = new RoleBasedIdentity(new UserIdentity(x509Token), role); return; } }
/// <summary> /// Validates the password for a username token. /// </summary> private IUserIdentity VerifyPassword(UserNameIdentityToken userNameToken) { try { string userName = userNameToken.UserName; string password = userNameToken.DecryptedPassword; if (string.IsNullOrEmpty(userName)) { // an empty username is not accepted. throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, "Security token is not a valid username token. An empty username is not accepted."); } if (string.IsNullOrEmpty(password)) { // an empty password is not accepted. throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Security token is not a valid username token. An empty password is not accepted."); } switch (userName) { // User with permission to configure server case "sysadmin" when password == "demo": return(new SystemConfigurationIdentity(new UserIdentity(userNameToken))); // standard users for CTT verification case "user1" when password == "password": case "user2" when password == "password1": return(new UserIdentity(userNameToken)); default: { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "InvalidPassword", "en-US", "Invalid username or password.", userName); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "InvalidPassword", LoadServerProperties().ProductUri, new LocalizedText(info))); } } } catch (Exception e) { Utils.Trace($"Session Manager Impersonate Exception:\r\n{e.StackTrace}"); } return(null); }
/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a user name token. UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { args.Identity = VerifyPassword(userNameToken); Utils.LogInfo(Utils.TraceMasks.Security, "Username Token Accepted: {0}", args.Identity?.DisplayName); // set AuthenticatedUser role for accepted user/password authentication args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_AuthenticatedUser); if (args.Identity is SystemConfigurationIdentity) { // set ConfigureAdmin role for user with permission to configure server args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_ConfigureAdmin); args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_SecurityAdmin); } return; } // check for x509 user token. X509IdentityToken x509Token = args.NewIdentity as X509IdentityToken; if (x509Token != null) { VerifyUserTokenCertificate(x509Token.Certificate); args.Identity = new UserIdentity(x509Token); Utils.LogInfo(Utils.TraceMasks.Security, "X509 Token Accepted: {0}", args.Identity?.DisplayName); // set AuthenticatedUser role for accepted certificate authentication args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_AuthenticatedUser); return; } // check for anonymous token. if (args.NewIdentity is AnonymousIdentityToken || args.NewIdentity == null) { // allow anonymous authentication and set Anonymous role for this authentication args.Identity = new UserIdentity(); args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_Anonymous); return; } // unsuported identity token type. throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, "Not supported user token type: {0}.", args.NewIdentity); }
/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a user name token. UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { VerifyPassword(userNameToken.UserName, userNameToken.DecryptedPassword); args.Identity = new UserIdentity(userNameToken); Utils.Trace("UserName Token Accepted: {0}", args.Identity.DisplayName); } }
/// <summary> /// Called when a client tries to change its user identity. /// 当客户端尝试更改其用户身份时调用 /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a user name token. // 检查用户名令牌 UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { VerifyPassword(userNameToken.UserName, userNameToken.DecryptedPassword); args.Identity = new UserIdentity(userNameToken); return; } }
/// <summary> /// Add a User. /// </summary> /// <param name="applicationName">The Application Name.</param> /// <param name="userName">The UserName.</param> /// <param name="password">The Password.</param> public void Add(string applicationName, string userName, string password) { lock (m_lock) { UserNameIdentityToken newUserNameToken = new UserNameIdentityToken() { UserName = userName, DecryptedPassword = password, }; newUserNameToken.Password = new UTF8Encoding().GetBytes(newUserNameToken.DecryptedPassword); m_UserNameIdentityTokens.Add(newUserNameToken.UserName, newUserNameToken); SaveUserName(applicationName, newUserNameToken); } }
/// <summary> /// Add a User. /// </summary> /// <param name="applicationName">The Application Name.</param> /// <param name="userName">The UserName.</param> /// <param name="password">The Password.</param> public void Add(string applicationName, string userName, string password) { lock (m_lock) { UserNameIdentityToken newUserNameToken = new UserNameIdentityToken() { UserName = userName, DecryptedPassword = password, }; newUserNameToken.Password = new UTF8Encoding().GetBytes(newUserNameToken.DecryptedPassword); m_UserNameIdentityTokens.Add(newUserNameToken.UserName, newUserNameToken); SaveUserName(applicationName, newUserNameToken); } }
/// <summary> /// Validates the password for a username token. /// </summary> private IUserIdentity VerifyPassword(UserNameIdentityToken userNameToken) { var userName = userNameToken.UserName; var password = userNameToken.DecryptedPassword; if (String.IsNullOrEmpty(userName)) { // an empty username is not accepted. throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, "Security token is not a valid username token. An empty username is not accepted."); } if (String.IsNullOrEmpty(password)) { // an empty password is not accepted. throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Security token is not a valid username token. An empty password is not accepted."); } // User with permission to configure server if (userName == "sysadmin" && password == "demo") { return(new SystemConfigurationIdentity(new UserIdentity(userNameToken))); } // standard users for CTT verification if (!((userName == "user1" && password == "password") || (userName == "user2" && password == "password1"))) { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "InvalidPassword", "en-US", "Invalid username or password.", userName); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "InvalidPassword", LoadServerProperties().ProductUri, new LocalizedText(info))); } return(new UserIdentity(userNameToken)); }
/// <summary> /// Sets the current user identity. /// </summary> public void SetUserIdentity(IUserIdentity identity) { string methodName = "IOPCSecurityPrivate.Logon"; try { IOPCSecurityPrivate server = BeginComCall <IOPCSecurityPrivate>(methodName, true); if (server != null) { int bAvailable = 0; server.IsAvailablePriv(out bAvailable); if (bAvailable != 0) { bool logoff = true; if (identity != null && identity.TokenType == UserTokenType.UserName) { UserNameIdentityToken identityToken = identity.GetIdentityToken() as UserNameIdentityToken; if (identityToken != null) { server.Logon(identityToken.UserName, identityToken.Password.ToString()); logoff = false; } } if (logoff) { server.Logoff(); } } } } catch (Exception e) { ComCallError(methodName, e); } finally { EndComCall(methodName); } }
/// <summary> /// Validates the password for a username token. /// </summary> private IUserIdentity VerifyPassword(UserNameIdentityToken userNameToken) { string username = userNameToken.UserName; string password = userNameToken.DecryptedPassword; string msg; if (string.IsNullOrEmpty(username)) { msg = Locale.IsRussian ? "Пустое имя пользователя не допускается" : "Empty username is not allowed"; log.WriteError(msg); throw new ServiceResultException(StatusCodes.BadIdentityTokenInvalid, msg); } if (string.IsNullOrEmpty(password)) { msg = Locale.IsRussian ? "Пустой пароль не допускается" : "Empty password is not allowed"; log.WriteError(msg); throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected, msg); } // user with permission to configure server //if (userName == "admin" && password == "scada") // return new SystemConfigurationIdentity(new UserIdentity(userNameToken)); // standard user if (username == options.Username && password == options.Password) { log.WriteAction(Locale.IsRussian ? "Пользователь '{0}' принят" : "User '{0}' accepted", username); return(new UserIdentity(userNameToken)); } msg = string.Format(Locale.IsRussian ? "Неверное имя пользователя или пароль для '{0}'" : "Invalid username or password for '{0}'", username); log.WriteError(msg); throw new ServiceResultException(new ServiceResult(StatusCodes.BadUserAccessDenied, "InvalidPassword", LoadServerProperties().ProductUri, new LocalizedText(msg))); }
/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a user name token. UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { args.Identity = VerifyPassword(userNameToken); return; } // check for x509 user token. X509IdentityToken x509Token = args.NewIdentity as X509IdentityToken; if (x509Token != null) { VerifyUserTokenCertificate(x509Token.Certificate); args.Identity = new UserIdentity(x509Token); Utils.Trace("X509 Token Accepted: {0}", args.Identity.DisplayName); return; } }
/// <summary> /// Updates the local displayed in the control. /// </summary> private void UpdateUserIdentity(Session session) { UserNameTB.Text = null; PasswordTB.Text = null; // get the current identity. IUserIdentity identity = session.Identity; if (identity != null && identity.TokenType == UserTokenType.UserName) { UserNameIdentityToken token = identity.GetIdentityToken() as UserNameIdentityToken; if (token != null) { UserNameTB.Text = token.UserName; PasswordTB.Text = token.DecryptedPassword; } } }
/// <summary> /// Called when a client tries to change its user identity. /// </summary> private void SessionManager_ImpersonateUser(Session session, ImpersonateEventArgs args) { // check for a user name token. UserNameIdentityToken userNameToken = args.NewIdentity as UserNameIdentityToken; if (userNameToken != null) { args.Identity = VerifyPassword(userNameToken); // set AuthenticatedUser role for accepted user/password authentication args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_AuthenticatedUser); if (args.Identity is SystemConfigurationIdentity) { // set ConfigureAdmin role for user with permission to configure server args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_ConfigureAdmin); args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_SecurityAdmin); } return; } // check for x509 user token. X509IdentityToken x509Token = args.NewIdentity as X509IdentityToken; if (x509Token != null) { VerifyUserTokenCertificate(x509Token.Certificate); args.Identity = new UserIdentity(x509Token); Utils.Trace("X509 Token Accepted: {0}", args.Identity.DisplayName); // set AuthenticatedUser role for accepted certificate authentication args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_AuthenticatedUser); return; } // allow anonymous authentication and set Anonymous role for this authentication args.Identity = new UserIdentity(); args.Identity.GrantedRoleIds.Add(ObjectIds.WellKnownRole_Anonymous); }
/// <summary> /// Validates the password for a username token. /// </summary> private IUserIdentity VerifyPassword(UserNameIdentityToken userNameToken) { var userName = userNameToken.UserName; var password = userNameToken.DecryptedPassword; if (string.IsNullOrEmpty(userName)) { // an empty username is not accepted. throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, "Security token is not a valid username token. An empty username is not accepted."); } if (string.IsNullOrEmpty(password)) { // an empty password is not accepted. throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Security token is not a valid username token. An empty password is not accepted."); } // verify operator and administrator users if (!((userName == "operator" && password == "password1") || (userName == "administrator" && password == "password2"))) { // construct translation object with default text. var info = new TranslationInfo( "InvalidPassword", "en-US", "Invalid username or password.", userName); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "InvalidPassword", LoadServerProperties().ProductUri, new LocalizedText(info))); } return(new UserIdentity(userNameToken)); }
private IUserIdentity VerifyPassword(UserNameIdentityToken userNameIdentityToken) { var userName = userNameIdentityToken.UserName; var password = userNameIdentityToken.DecryptedPassword; if (String.IsNullOrEmpty(userName)) { // 用户名不可空 throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, "Security token is not a valid username token. An empty username is not accepted."); } if (String.IsNullOrEmpty(password)) // 密码不可空 { throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Security token is not a valid username token. An empty password is not accepted."); } if (userName == "sysadmin" && password == "demo") { return(new SystemConfigurationIdentity(new UserIdentity(userNameIdentityToken))); } if (!((userName == "user1" && password == "password") || (userName == "user2" && password == "password1"))) { TranslationInfo info = new TranslationInfo( "InvalidPassword", "en-US", "Invalid username or password.", userName); throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "InvalidPassword", LoadServerProperties().ProductUri, new LocalizedText(info))); } return(new UserIdentity(userNameIdentityToken)); }
/// <summary> /// This method is called at the being of the thread that processes a request. /// </summary> protected override OperationContext ValidateRequest(RequestHeader requestHeader, RequestType requestType) { OperationContext context = base.ValidateRequest(requestHeader, requestType); if (requestType == RequestType.Write) { // reject all writes if no user provided. if (context.UserIdentity.TokenType == UserTokenType.Anonymous) { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "NoWriteAllowed", "en-US", "Must provide a valid user before calling write."); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "NoWriteAllowed", Opc.Ua.Gds.Namespaces.OpcUaGds, new LocalizedText(info))); } UserIdentityToken securityToken = context.UserIdentity.GetIdentityToken(); // check for a user name token. UserNameIdentityToken userNameToken = securityToken as UserNameIdentityToken; if (userNameToken != null) { lock (m_lock) { m_contexts.Add(context.RequestId, new ImpersonationContext()); } } } return(context); }
private async void UserIdentityBTN_Click(object sender, RoutedEventArgs e) { try { UserTokenItem currentItem = new UserTokenItem(UserTokenType.Anonymous); if (UserTokenTypeCB.SelectedIndex != -1) { currentItem = (UserTokenItem)UserTokenTypeCB.SelectedItem; } UserIdentityToken identity = null; m_userIdentities.TryGetValue(currentItem.ToString(), out identity); switch (currentItem.Policy.TokenType) { case UserTokenType.UserName: { UserNameIdentityToken userNameToken = identity as UserNameIdentityToken; if (userNameToken == null) { userNameToken = new UserNameIdentityToken(); } if (new UsernameTokenDlg().ShowDialog(userNameToken)) { userNameToken.PolicyId = currentItem.Policy.PolicyId; m_userIdentities[currentItem.ToString()] = userNameToken; UserIdentityTB.Text = userNameToken.UserName; } break; } default: { MessageDlg dialog = new MessageDlg("User token type not supported at this time."); await dialog.ShowAsync(); break; } } } catch (Exception exception) { GuiUtils.HandleException(String.Empty, GuiUtils.CallerName(), exception); } }
protected override async Task OnOpenAsync(CancellationToken token) { await base.OnOpenAsync(token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); // if SessionId is provided then we skip the CreateSessionRequest and go directly to (re)ActivateSession. // requires from previous Session: SessionId, AuthenticationToken, RemoteNonce if (this.SessionId == null) { var localNonce = this.RemoteEndpoint.SecurityMode != MessageSecurityMode.None ? this.GetNextNonce() : null; var localCertificateBlob = this.RemoteEndpoint.SecurityMode != MessageSecurityMode.None ? this.LocalCertificate.RawData : null; var createSessionRequest = new CreateSessionRequest { RequestHeader = new RequestHeader { TimeoutHint = this.TimeoutHint, ReturnDiagnostics = this.DiagnosticsHint, Timestamp = DateTime.UtcNow }, ClientDescription = this.LocalDescription, EndpointUrl = this.RemoteEndpoint.EndpointUrl, SessionName = this.LocalDescription.ApplicationName, ClientNonce = localNonce, ClientCertificate = localCertificateBlob, RequestedSessionTimeout = this.SessionTimeout, MaxResponseMessageSize = this.RemoteMaxMessageSize }; var createSessionResponse = (CreateSessionResponse)await this.RequestAsync(createSessionRequest).ConfigureAwait(false); this.SessionId = createSessionResponse.SessionId; this.AuthenticationToken = createSessionResponse.AuthenticationToken; this.RemoteNonce = createSessionResponse.ServerNonce; // verify the server's certificate is the same as the certificate from the selected endpoint. if (this.RemoteEndpoint.ServerCertificate != null && !this.RemoteEndpoint.ServerCertificate.SequenceEqual(createSessionResponse.ServerCertificate)) { throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Server did not return the same certificate used to create the channel."); } // verify the server's signature. switch (this.RemoteEndpoint.SecurityPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: case SecurityPolicyUris.Basic256: byte[] dataToVerify = Concat(localCertificateBlob, localNonce); if (!this.RemotePublicKey.VerifyData(dataToVerify, createSessionResponse.ServerSignature.Signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)) { throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid, "Server did not provide a correct signature for the nonce data provided by the client."); } break; case SecurityPolicyUris.Basic256Sha256: byte[] dataToVerify256 = Concat(localCertificateBlob, localNonce); if (!this.RemotePublicKey.VerifyData(dataToVerify256, createSessionResponse.ServerSignature.Signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) { throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid, "Server did not provide a correct signature for the nonce data provided by the client."); } break; default: break; } } // create client signature SignatureData clientSignature = null; switch (this.RemoteEndpoint.SecurityPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: case SecurityPolicyUris.Basic256: byte[] dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce); clientSignature = new SignatureData { Signature = this.LocalPrivateKey.SignData(dataToSign, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1), Algorithm = RsaSha1Signature, }; break; case SecurityPolicyUris.Basic256Sha256: byte[] dataToSign256 = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce); clientSignature = new SignatureData { Signature = this.LocalPrivateKey.SignData(dataToSign256, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1), Algorithm = RsaSha256Signature, }; break; default: clientSignature = new SignatureData(); break; } // supported UserIdentityToken types are AnonymousIdentityToken, UserNameIdentityToken, IssuedIdentityToken, X509IdentityToken UserIdentityToken identityToken = null; SignatureData tokenSignature = null; // if UserIdentity type is IssuedIdentity if (this.UserIdentity is IssuedIdentity) { var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.IssuedToken); if (tokenPolicy == null) { throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected); } var issuedIdentity = (IssuedIdentity)this.UserIdentity; byte[] plainText = Concat(issuedIdentity.TokenData, this.RemoteNonce); var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri; RSA asymRemoteEncryptionKey; switch (secPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: asymRemoteEncryptionKey = this.RemoteCertificate.GetRSAPublicKey(); identityToken = new IssuedIdentityToken { TokenData = asymRemoteEncryptionKey.EncryptTokenData(plainText, secPolicyUri), EncryptionAlgorithm = RsaV15KeyWrap, PolicyId = tokenPolicy.PolicyId }; break; case SecurityPolicyUris.Basic256: case SecurityPolicyUris.Basic256Sha256: asymRemoteEncryptionKey = this.RemoteCertificate.GetRSAPublicKey(); identityToken = new IssuedIdentityToken { TokenData = asymRemoteEncryptionKey.EncryptTokenData(plainText, secPolicyUri), EncryptionAlgorithm = RsaOaepKeyWrap, PolicyId = tokenPolicy.PolicyId }; break; default: identityToken = new IssuedIdentityToken { TokenData = issuedIdentity.TokenData, EncryptionAlgorithm = null, PolicyId = tokenPolicy.PolicyId }; break; } tokenSignature = new SignatureData(); } // if UserIdentity type is X509Identity else if (this.UserIdentity is X509Identity) { var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.Certificate); if (tokenPolicy == null) { throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected); } var x509Identity = (X509Identity)this.UserIdentity; identityToken = new X509IdentityToken { CertificateData = x509Identity.Certificate?.RawData, PolicyId = tokenPolicy.PolicyId }; var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri; switch (secPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: case SecurityPolicyUris.Basic256: var asymSigningKey = x509Identity.Certificate?.GetRSAPrivateKey(); if (asymSigningKey != null) { byte[] dataToSign = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce); tokenSignature = new SignatureData { Signature = asymSigningKey.SignData(dataToSign, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1), Algorithm = RsaSha1Signature, }; break; } tokenSignature = new SignatureData(); break; case SecurityPolicyUris.Basic256Sha256: var asymSigningKey256 = x509Identity.Certificate?.GetRSAPrivateKey(); if (asymSigningKey256 != null) { byte[] dataToSign256 = Concat(this.RemoteEndpoint.ServerCertificate, this.RemoteNonce); tokenSignature = new SignatureData { Signature = asymSigningKey256.SignData(dataToSign256, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1), Algorithm = RsaSha256Signature, }; break; } tokenSignature = new SignatureData(); break; default: tokenSignature = new SignatureData(); break; } } // if UserIdentity type is UserNameIdentity else if (this.UserIdentity is UserNameIdentity) { var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.UserName); if (tokenPolicy == null) { throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected); } var userNameIdentity = (UserNameIdentity)this.UserIdentity; byte[] plainText = Concat(System.Text.Encoding.UTF8.GetBytes(userNameIdentity.Password), this.RemoteNonce); var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri; RSA asymRemoteEncryptionKey; switch (secPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: asymRemoteEncryptionKey = this.RemoteCertificate.GetRSAPublicKey(); identityToken = new UserNameIdentityToken { UserName = userNameIdentity.UserName, Password = asymRemoteEncryptionKey.EncryptTokenData(plainText, secPolicyUri), EncryptionAlgorithm = RsaV15KeyWrap, PolicyId = tokenPolicy.PolicyId }; break; case SecurityPolicyUris.Basic256: case SecurityPolicyUris.Basic256Sha256: asymRemoteEncryptionKey = this.RemoteCertificate.GetRSAPublicKey(); identityToken = new UserNameIdentityToken { UserName = userNameIdentity.UserName, Password = asymRemoteEncryptionKey.EncryptTokenData(plainText, secPolicyUri), EncryptionAlgorithm = RsaOaepKeyWrap, PolicyId = tokenPolicy.PolicyId }; break; default: identityToken = new UserNameIdentityToken { UserName = userNameIdentity.UserName, Password = System.Text.Encoding.UTF8.GetBytes(userNameIdentity.Password), EncryptionAlgorithm = null, PolicyId = tokenPolicy.PolicyId }; break; } tokenSignature = new SignatureData(); } // if UserIdentity type is AnonymousIdentity or null else { var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.Anonymous); if (tokenPolicy == null) { throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected); } identityToken = new AnonymousIdentityToken { PolicyId = tokenPolicy.PolicyId }; tokenSignature = new SignatureData(); } var activateSessionRequest = new ActivateSessionRequest { RequestHeader = new RequestHeader { TimeoutHint = this.TimeoutHint, ReturnDiagnostics = this.DiagnosticsHint, Timestamp = DateTime.UtcNow }, ClientSignature = clientSignature, LocaleIds = new[] { CultureInfo.CurrentUICulture.TwoLetterISOLanguageName }, UserIdentityToken = identityToken, UserTokenSignature = tokenSignature }; var activateSessionResponse = (ActivateSessionResponse)await this.RequestAsync(activateSessionRequest).ConfigureAwait(false); this.RemoteNonce = activateSessionResponse.ServerNonce; await this.FetchNamespaceTablesAsync().ConfigureAwait(false); }
/// <summary> /// Connects to the UA server identfied by the CLSID. /// </summary> /// <param name="clsid">The CLSID.</param> /// <returns>The UA server.</returns> private Session Connect(Guid clsid) { // load the endpoint information. ConfiguredEndpoint endpoint = m_endpoint = LoadConfiguredEndpoint(clsid); if (endpoint == null) { throw new ServiceResultException(StatusCodes.BadConfigurationError); } // update security information. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(BindingFactory.Default); // check if halted while waiting for a response. if (!m_running) { throw new ServiceResultException(StatusCodes.BadServerHalted); } } // look up the client certificate. X509Certificate2 clientCertificate = m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true); // create a message context to use with the channel. ServiceMessageContext messageContext = m_configuration.CreateMessageContext(); // create the channel. ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, clientCertificate, messageContext); // create the session. Session session = new Session(channel, m_configuration, endpoint, clientCertificate); // create a session name that is useful for debugging. string sessionName = Utils.Format("COM Client ({0})", System.Net.Dns.GetHostName()); // open the session. Opc.Ua.UserIdentity identity = null; if (endpoint.UserIdentity != null) { // need to decode password. UserNameIdentityToken userNameToken = endpoint.UserIdentity as UserNameIdentityToken; if (userNameToken != null) { UserNameIdentityToken copy = new UserNameIdentityToken(); copy.PolicyId = userNameToken.PolicyId; copy.DecryptedPassword = new UTF8Encoding().GetString(userNameToken.Password); copy.UserName = userNameToken.UserName; copy.EncryptionAlgorithm = userNameToken.EncryptionAlgorithm; identity = new Opc.Ua.UserIdentity(copy); } // create the identity object. else { identity = new Opc.Ua.UserIdentity(endpoint.UserIdentity); } } session.Open(sessionName, identity); // return the new session. return(session); }
private bool VerifyPassword(UserNameIdentityToken userNameToken) { // TODO: check username/password permissions return(userNameToken.DecryptedPassword == "demo"); }
/// <summary> /// Validates a User. /// </summary> /// <param name="token">UserNameIdentityToken.</param> /// <returns>True if the list contains a valid item.</returns> public bool Validate(UserNameIdentityToken token) { return Validate(token.UserName, token.DecryptedPassword); }
/// <summary> /// Connects to the UA server identfied by the CLSID. /// </summary> /// <param name="clsid">The CLSID.</param> /// <returns>The UA server.</returns> private Session Connect(Guid clsid) { // load the endpoint information. ConfiguredEndpoint endpoint = m_endpoint = LoadConfiguredEndpoint(clsid); if (endpoint == null) { throw new ServiceResultException(StatusCodes.BadConfigurationError); } // update security information. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(BindingFactory.Default); // check if halted while waiting for a response. if (!m_running) { throw new ServiceResultException(StatusCodes.BadServerHalted); } } // look up the client certificate. X509Certificate2 clientCertificate = m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true); // create a message context to use with the channel. ServiceMessageContext messageContext = m_configuration.CreateMessageContext(); // create the channel. ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, clientCertificate, messageContext); // create the session. Session session = new Session(channel, m_configuration, endpoint, clientCertificate); // create a session name that is useful for debugging. string sessionName = Utils.Format("COM Client ({0})", System.Net.Dns.GetHostName()); // open the session. Opc.Ua.UserIdentity identity = null; if (endpoint.UserIdentity != null) { // need to decode password. UserNameIdentityToken userNameToken = endpoint.UserIdentity as UserNameIdentityToken; if (userNameToken != null) { UserNameIdentityToken copy = new UserNameIdentityToken(); copy.PolicyId = userNameToken.PolicyId; copy.DecryptedPassword = new UTF8Encoding().GetString(userNameToken.Password); copy.UserName = userNameToken.UserName; copy.EncryptionAlgorithm = userNameToken.EncryptionAlgorithm; identity = new Opc.Ua.UserIdentity(copy); } // create the identity object. else { identity = new Opc.Ua.UserIdentity(endpoint.UserIdentity); } } session.Open(sessionName, identity); // return the new session. return session; }
/// <summary> /// Save UserNameIdentityToken. /// </summary> private static void SaveUserName(string applicationName, UserNameIdentityToken userNameToken) { try { string relativePath = Utils.Format("%CommonApplicationData%\\OPC Foundation\\Accounts\\{0}\\{1}.xml", applicationName, userNameToken.UserName); string absolutePath = Utils.GetAbsoluteFilePath(relativePath, false, false, true); // oops - nothing found. if (absolutePath == null) { absolutePath = Utils.GetAbsoluteFilePath(relativePath, true, false, true); } UserNameIdentityToken outputToken = new UserNameIdentityToken() { UserName = userNameToken.UserName, Password = EncryptPassword(userNameToken.Password), EncryptionAlgorithm = "Triple DES", }; // open the file. FileStream ostrm = File.Open(absolutePath, FileMode.Create, FileAccess.ReadWrite); using (XmlTextWriter writer = new XmlTextWriter(ostrm, System.Text.Encoding.UTF8)) { DataContractSerializer serializer = new DataContractSerializer(typeof(UserNameIdentityToken)); serializer.WriteObject(writer, outputToken); } } catch (Exception e) { Utils.Trace(e, "Unexpected error saving user configuration for COM Wrapper with UserName={0}.", userNameToken.UserName); } }