Example #1
0
        public byte[] GetXmlBytes(IDataProtection dataProtection)
        {
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();

            xmlWriterSettings.Indent   = true;
            xmlWriterSettings.Encoding = Encoding.UTF8;
            MemoryStream memoryStream = new MemoryStream();
            XmlWriter    xmlWriter    = XmlWriter.Create(memoryStream, xmlWriterSettings);

            using (xmlWriter)
            {
                xmlWriter.WriteStartElement("DataSourceDefinition", "http://schemas.microsoft.com/sqlserver/reporting/2006/03/reportdatasource");
                xmlWriter.WriteElementString("Extension", Extension);
                xmlWriter.WriteElementString("ConnectString", GetConnectionString(dataProtection));
                xmlWriter.WriteElementString("CredentialRetrieval", CredentialsRetrieval.ToString());
                if (CredentialsRetrieval == CredentialsRetrievalOption.Prompt || CredentialsRetrieval == CredentialsRetrievalOption.Store)
                {
                    xmlWriter.WriteElementString("WindowsCredentials", WindowsCredentials.ToString());
                }
                if (CredentialsRetrieval == CredentialsRetrievalOption.Prompt)
                {
                    xmlWriter.WriteElementString("Prompt", string.IsNullOrEmpty(Prompt) ? "" : Prompt);
                }
                if (CredentialsRetrieval == CredentialsRetrievalOption.Store)
                {
                    xmlWriter.WriteElementString("ImpersonateUser", ImpersonateUser.ToString());
                }
                xmlWriter.WriteElementString("Enabled", Enabled.ToString());
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();
                return(memoryStream.ToArray());
            }
        }
 protected void OnValidateCredentials(object source, ServerValidateEventArgs args)
 {
     try
     {
         var service     = new WebServiceAPI();
         var credentials = new WindowsCredentials()
         {
             WinUserName = txtUserName.Text,
             UserName    = txtUserName.Text,
             Password    = txtPassword.Text,
             WinDomain   = txtDomain.Text,
             Domain      = txtDomain.Text
         };
         args.IsValid = service.IsCredentialsValid(credentials);
         if (args.IsValid)
         {
             SecureStoreManager.SetExtentrixWindowsCredentials(LogLocation, SPContext.Current.Web.CurrentUser, credentials);
             SecureStoreManager.SetCredentialsLiveTime(CredentialLiveTime);
             Credentials = credentials;
         }
     }
     catch (Exception ex)
     {
         Logger.Default.Error(LogLocation, "User - " + Page.Request.LogonUserIdentity.Name + " ; Error = " + ex.Message, ex);
         AppMultiView.ActiveViewIndex = 5;
     }
 }
Example #3
0
        public async Task LogIn()
        {
            try
            {
                _duringOperation = true;
                NotifyOfPropertyChange(() => CanLogIn);
                LoginInfoMessage = "Łączenie..";
                AuthenticatedUser user = await _apiHelper.Authenticate(UserName, Password);

                LoginInfoMessage = "";

                await _apiHelper.GetLoggedUserData(user.Access_Token);

                if (RemeberMe)
                {
                    WindowsCredentials.SaveLoginPassword(UserName, Password);
                }
                else
                {
                    WindowsCredentials.DeleteLoginPassword();
                }

                await _eventAggregator.PublishOnUIThreadAsync(new LogOnEvent(reloadNeeded : true), new CancellationToken());

                _duringOperation = false;
                NotifyOfPropertyChange(() => CanLogIn);
            }
            catch (Exception ex)
            {
                _logger.Error("Got exception", ex);
                LoginInfoMessage = ex.Message;
                _duringOperation = false;
                NotifyOfPropertyChange(() => CanLogIn);
            }
        }
Example #4
0
        /// <summary>
        /// Get credentials for updating datasource
        /// </summary>
        /// <param name="credentialType">Type of credential selected by user</param>
        /// <param name="credentialsArray">Credentials entered by the user</param>
        /// <returns>Credentials for updating the datasource</returns>
        public CredentialsBase GetCredentials(string credentialType, string[] credentialsArray)
        {
            CredentialsBase credentials;

            // Capture credentials based on credential type selected by the user
            switch (credentialType)
            {
            case Constants.KeyCredentials:
                credentials = new KeyCredentials(key: credentialsArray[0]);
                break;

            case Constants.BasicCredentials:
                credentials = new BasicCredentials(username: credentialsArray[0], password: credentialsArray[1]);
                break;

            case Constants.OAuth2Credentials:
                credentials = new OAuth2Credentials(accessToken: credentialsArray[0]);
                break;

            case Constants.WindowsCredentials:
                credentials = new WindowsCredentials(username: credentialsArray[0], password: credentialsArray[1]);
                break;

            default:
                Console.Error.WriteLine(Constants.InvalidCredType);
                throw new Exception(Constants.InvalidCredType);
            }

            return(credentials);
        }
Example #5
0
        private SecurityCredentials WindowsSecurityCredentialsBuilder()
        {
            var windowsCredentials = new WindowsCredentials();

            windowsCredentials.RemoteSpn = this.ConfigSection.GetSetting <string>(RemoteSecurityPrincipalName, null);
            return(windowsCredentials);
        }
Example #6
0
 /// <inheritdoc/>
 protected override NetworkCredential Prompt(string target, WindowsCredentialsFlags flags)
 {
     if (flags.HasFlag(WindowsCredentialsFlags.IncorrectPassword))
     {
         Log.Error(string.Format(Resources.InvalidCredentials, target));
     }
     return(WindowsCredentials.PromptCli(target, flags));
 }
Example #7
0
        public async Task Run(TestContext context)
        {
            var url = this.Url;
            var db  = this.Database;

            var remoteConn = context.Connection as IRemoteConnection;

            if (string.IsNullOrEmpty(url) && remoteConn != null)
            {
                url = remoteConn.Url.ToString();
            }
            if (string.IsNullOrEmpty(db))
            {
                db = context.Connection.Database;
            }

            var prefs = new ConnectionPreferences();

            prefs.Headers.UserAgent = "InnovatorAdmin UnitTest";
            var conn = await Factory.GetConnection(url, prefs, true).ToTask();

            ICredentials cred;

            switch (this.Type)
            {
            case CredentialType.Anonymous:
                cred = new AnonymousCredentials(db);
                break;

            case CredentialType.Windows:
                cred = new WindowsCredentials(db);
                break;

            default:
                if (_password.IsNullOrEmpty())
                {
                    cred = context.CredentialStore.OfType <ExplicitCredentials>()
                           .FirstOrDefault(c => string.Equals(c.Database, db) && string.Equals(c.Username, this.UserName));
                }
                else
                {
                    cred = new ExplicitCredentials(db, this.UserName, _password);
                }
                break;
            }

            if (cred == null)
            {
                throw new InvalidOperationException("Could not create credentials for this login type");
            }
            await conn.Login(cred, true).ToTask();

            context.PushConnection(conn);
        }
        public static Credentials GetExtentrixWindowsCredentials(Page page, LogLocationEnum LogLocation, SPUser user)
        {
            WindowsCredentials extentrixCredentials = null;

            SecureStoreCredentialCollection ssCreds = null;
            SPServiceContext context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);

            SecureStoreServiceProxy ssp = new SecureStoreServiceProxy();
            ISecureStore            iss = ssp.GetSecureStore(context);

            try
            {
                ssCreds = iss.GetCredentials(Constants.TargetAppID);

                if (ssCreds != null && ssCreds.Count() > 0)
                {
                    extentrixCredentials = new WindowsCredentials();
                    IList <TargetApplicationField> applicationFields = GetTargetApplicationFields(Constants.TargetAppID);

                    foreach (TargetApplicationField taf in applicationFields)
                    {
                        switch (taf.Name)
                        {
                        case "Windows User Name":
                            extentrixCredentials.UserName =
                                ReadSecureString(ssCreds[applicationFields.IndexOf(taf)].Credential);
                            break;

                        case "Windows Password":
                            extentrixCredentials.Password =
                                ReadSecureString(ssCreds[applicationFields.IndexOf(taf)].Credential);
                            break;

                        case "Domain":
                            extentrixCredentials.Domain =
                                ReadSecureString(ssCreds[applicationFields.IndexOf(taf)].Credential);
                            break;
                        }
                    }
                }
            }
            catch (SecureStoreServiceCredentialsNotFoundException ex)
            {
                Logger.Default.Error(LogLocation, ex.Message, ex);
            }
            catch (Exception ex)
            {
                Logger.Default.Info(LogLocation, "SecureStore: Exception getting Windows Credentials");
                Logger.Default.Error(LogLocation, ex.Message, ex);
            }

            return(extentrixCredentials);
        }
        public void Cloud_WindowsCredentialsTest()
        {
            CredentialsBase credentials       = new WindowsCredentials("user", "pass");
            var             credentialDetails = new CredentialDetails(credentials, PrivacyLevel.Organizational, EncryptedConnection.Encrypted);

            Assert.IsNotNull(credentialDetails);
            Assert.AreEqual("{\"credentialData\":[{\"name\":\"username\",\"value\":\"user\"},{\"name\":\"password\",\"value\":\"pass\"}]}", credentialDetails.Credentials);
            Assert.AreEqual(CredentialType.Windows, credentialDetails.CredentialType);
            Assert.AreEqual(EncryptedConnection.Encrypted, credentialDetails.EncryptedConnection);
            Assert.AreEqual(EncryptionAlgorithm.None, credentialDetails.EncryptionAlgorithm);
            Assert.AreEqual(PrivacyLevel.Organizational, credentialDetails.PrivacyLevel);
            Assert.AreEqual(false, credentialDetails.UseCallerAADIdentity);
        }
        public void OnPrem_WindowsCredentialsTest()
        {
            CredentialsBase credentials          = new WindowsCredentials("user", "pass");
            var             credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey);

            var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.Organizational, EncryptedConnection.Encrypted, credentialsEncryptor);

            Assert.IsNotNull(credentialDetails);
            Assert.IsNotNull(credentialDetails.Credentials);
            Assert.AreEqual(CredentialType.Windows, credentialDetails.CredentialType);
            Assert.AreEqual(EncryptedConnection.Encrypted, credentialDetails.EncryptedConnection);
            Assert.AreEqual(EncryptionAlgorithm.RSAOAEP, credentialDetails.EncryptionAlgorithm);
            Assert.AreEqual(PrivacyLevel.Organizational, credentialDetails.PrivacyLevel);
            Assert.AreEqual(false, credentialDetails.UseCallerAADIdentity);
        }
Example #11
0
 private void LoadCredentials()
 {
     try
     {
         var cred = WindowsCredentials.LoadLoginPassword();
         if (cred.UserName?.Length > 0 && cred.Password?.Length > 0)
         {
             UserName  = cred.UserName;
             Password  = cred.Password;
             RemeberMe = true;
         }
     }
     catch (Exception ex)
     {
         _logger.Error("Got exception", ex);
     }
 }
        /// <inheritdoc/>
        public override NetworkCredential GetCredential(Uri uri, string authType)
        {
            #region Sanity checks
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            #endregion

            string target = uri.ToStringRfc();

            if (!Interactive && !WindowsCredentials.IsCredentialStored(target))
            {
                return(null);
            }

            var flags = WindowsCredentialsFlags.GenericCredentials | WindowsCredentialsFlags.ExcludeCertificates | WindowsCredentialsFlags.ShowSaveCheckBox;
            if (WasReportedInvalid(uri))
            {
                flags |= WindowsCredentialsFlags.IncorrectPassword | WindowsCredentialsFlags.AlwaysShowUI;
            }

            return(Prompt(target, flags));
        }
Example #13
0
        public bool IsCredentialsValid(WindowsCredentials credentials)
        {
            bool res = false;

            foreach (Farm farm in farms)
            {
                WSConstants.CTX_XML    = farm.Url;
                WSConstants.CTXXMLPort = farm.Port;
                try
                {
                    res = WebService.DisconnectSessions(0, null, credentials, new String[] { "all" }, new String[] { "all" });
                }
                catch (Exception e)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("Extentrix", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, e.Message, e.StackTrace);
                    //do nothing
                }
                if (res)
                {
                    return(res);
                }
            }
            return(res);
        }
        public static void SetExtentrixWindowsCredentials(LogLocationEnum LogLocation, SPUser user, WindowsCredentials extentrixCredentials)
        {
            try
            {
                IList <TargetApplicationField> applicationFields = GetTargetApplicationFields(Constants.TargetAppID);
                IList <ISecureStoreCredential> creds             = new List <ISecureStoreCredential>(applicationFields.Count);

                using (SecureStoreCredentialCollection credentials = new SecureStoreCredentialCollection(creds))
                {
                    foreach (TargetApplicationField taf in applicationFields)
                    {
                        switch (taf.Name)
                        {
                        case "Windows User Name":
                            creds.Add(new SecureStoreCredential(MakeSecureString(extentrixCredentials.UserName),
                                                                SecureStoreCredentialType.WindowsUserName));
                            break;

                        case "Windows Password":
                            creds.Add(new SecureStoreCredential(MakeSecureString(extentrixCredentials.Password),
                                                                SecureStoreCredentialType.WindowsPassword));
                            break;

                        case "Domain":
                            creds.Add(new SecureStoreCredential(MakeSecureString(extentrixCredentials.Domain)
                                                                , SecureStoreCredentialType.Generic));
                            break;
                        }
                    }

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                SPServiceContext context    = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
                                SecureStoreServiceProxy ssp = new SecureStoreServiceProxy();
                                ISecureStore iss            = ssp.GetSecureStore(context);

                                iss.SetUserCredentials(Constants.TargetAppID, GetSSClaim(user), credentials);
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Logger.Default.Info(LogLocation, "SecureStore: Exception setting windows credentials");
                Logger.Default.Error(LogLocation, ex.Message, ex);
            }
        }
Example #15
0
 /// <inheritdoc/>
 protected override NetworkCredential Prompt(string target, WindowsCredentialsFlags flags)
 => WindowsCredentials.PromptDialog(target, flags);
Example #16
0
 /// <summary>
 /// 删除域用户凭据
 /// </summary>
 /// <param name="target"></param>
 /// <param name="flags"></param>
 /// <returns></returns>
 public bool DeleteCredential(string target, int flags)
 {
     return(WindowsCredentials.DeleteCred(target, flags));
 }
Example #17
0
 /// <summary>
 /// 添加域用户凭据
 /// </summary>
 /// <param name="key"></param>
 /// <param name="username"></param>
 /// <param name="secret"></param>
 /// <param name="Message"></param>
 /// <returns></returns>
 public int WriteCredential(string key, string username, string secret, out string Message)
 {
     return(WindowsCredentials.AddCred(key, username, secret, out Message));
 }
Example #18
0
        public int ExecuteHealthCheck(CalamariVariableDictionary variables)
        {
            if (!ServiceFabricHelper.IsServiceFabricSdkKeyInRegistry())
            {
                throw new Exception("Could not find the Azure Service Fabric SDK on this server. This SDK is required before running health checks on Service Fabric targets.");
            }

            var connectionEndpoint   = variables.Get(SpecialVariables.Action.ServiceFabric.ConnectionEndpoint);
            var securityMode         = (AzureServiceFabricSecurityMode)Enum.Parse(typeof(AzureServiceFabricSecurityMode), variables.Get(SpecialVariables.Action.ServiceFabric.SecurityMode));
            var serverCertThumbprint = variables.Get(SpecialVariables.Action.ServiceFabric.ServerCertThumbprint);

            var clientCertVariable = variables.Get(SpecialVariables.Action.ServiceFabric.ClientCertVariable);

            var certificateStoreLocation = variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreLocation);

            if (string.IsNullOrWhiteSpace(certificateStoreLocation))
            {
                certificateStoreLocation = StoreLocation.LocalMachine.ToString();
            }

            var certificateStoreName = variables.Get(SpecialVariables.Action.ServiceFabric.CertificateStoreName);

            if (string.IsNullOrWhiteSpace(certificateStoreName))
            {
                certificateStoreName = "My";
            }

            var aadUserCredentialUsername = variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialUsername);
            var aadUserCredentialPassword = variables.Get(SpecialVariables.Action.ServiceFabric.AadUserCredentialPassword);

            log.Verbose($"Checking connectivity to Service Fabric cluster '{connectionEndpoint}' with security-mode '{securityMode}'");
            FabricClient fabricClient = null;

            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (securityMode)
            {
            case AzureServiceFabricSecurityMode.SecureClientCertificate:
            {
                log.Info("Connecting with Secure Client Certificate");

                var clientCertThumbprint = variables.Get(clientCertVariable + ".Thumbprint");
                var commonName           = variables.Get(clientCertVariable + ".SubjectCommonName");

                certificateStore.GetOrAdd(variables, clientCertVariable, certificateStoreName, certificateStoreLocation);

                var xc = GetCredentials(clientCertThumbprint, certificateStoreLocation, certificateStoreName, serverCertThumbprint, commonName);
                try
                {
                    fabricClient = new FabricClient(xc, connectionEndpoint);
                }
                catch (Exception ex)
                {
                    // SF throw weird exception messages if you don't have the certificate installed.
                    if (ex.InnerException != null && ex.InnerException.Message.Contains("0x80071C57"))
                    {
                        throw new Exception($"Service Fabric was unable to to find certificate with thumbprint '{clientCertThumbprint}' in Cert:\\{certificateStoreLocation}\\{certificateStoreName}. Please make sure you have installed the certificate on the Octopus Server before attempting to use/reference it in a Service Fabric Cluster target.");
                    }
                    throw;
                }
                break;
            }

            case AzureServiceFabricSecurityMode.SecureAzureAD:
            {
                log.Info("Connecting with Secure Azure Active Directory");
                var claimsCredentials = new ClaimsCredentials();
                claimsCredentials.ServerThumbprints.Add(serverCertThumbprint);
                // ReSharper disable once UseObjectOrCollectionInitializer
                fabricClient = new FabricClient(claimsCredentials, connectionEndpoint);
                fabricClient.ClaimsRetrieval += (o, e) =>
                {
                    try
                    {
                        return(GetAccessToken(e.AzureActiveDirectoryMetadata, aadUserCredentialUsername, aadUserCredentialPassword));
                    }
                    catch (Exception ex)
                    {
                        log.Error($"Connect failed: {ex.PrettyPrint()}");
                        return("BAD_TOKEN");        //TODO: mark.siedle - You cannot return null or an empty value here or the Azure lib spazzes out trying to call a lib that doesn't exist "System.Fabric.AzureActiveDirectory.Client"  :(
                    }
                };
                break;
            }

            case AzureServiceFabricSecurityMode.SecureAD:
            {
                log.Info("Connecting with Secure Azure Active Directory");
                log.Verbose("Using the service account of the octopus service as windows credentials");
                var windowsCredentials = new WindowsCredentials();
                fabricClient = new FabricClient(windowsCredentials, connectionEndpoint);
                break;
            }

            default:
            {
                log.Info("Connecting unsecurely");
                fabricClient = new FabricClient(connectionEndpoint);
                break;
            }
            }

            if (fabricClient == null)
            {
                throw new Exception("Unable to create Service Fabric client.");
            }

            try
            {
                fabricClient.ClusterManager.GetClusterManifestAsync().GetAwaiter().GetResult();
                log.Verbose("Successfully received a response from the Service Fabric client");
            }
            finally
            {
                fabricClient.Dispose();
            }

            return(0);
        }
Example #19
0
        static void Main(string[] args)
        {
            #region Windows Credentials
            SecureString securepassword    = new SecureString();
            string       plaintextpassword = "******";
            foreach (char c in plaintextpassword)
            {
                securepassword.AppendChar(c);
            }
            IMachineCredentials mcwin = new WindowsCredentials()
            {
                Domain   = string.Empty,
                Username = "******",
                Password = securepassword
            };
            #endregion

            #region UNIX Credentials
            securepassword    = new SecureString();
            plaintextpassword = "******";
            foreach (char c in plaintextpassword)
            {
                securepassword.AppendChar(c);
            }
            IMachineCredentials mcunix = new UNIXCredentials
            {
                Username = "******",
                Password = securepassword
            };
            #endregion

            #region Network Device Credentials
            securepassword    = new SecureString();
            plaintextpassword = "******";
            foreach (char c in plaintextpassword)
            {
                securepassword.AppendChar(c);
            }
            SecureString ensecurepassword    = new SecureString();
            string       enplaintextpassword = "******";
            foreach (char c in enplaintextpassword)
            {
                ensecurepassword.AppendChar(c);
            }
            IMachineCredentials mcnwdev = new NetworkDeviceCredentials
            {
                Username   = "******",
                Password   = securepassword,
                ENPassword = ensecurepassword
            };
            #endregion

            List <Scripts> scrlst = new List <Scripts>();
            scrlst.Add(
                new Scripts()
            {
                Script     = ScriptType.POWERSHELL,
                ScriptName = "IISVersion",
                ScriptText = "(Get-ItemProperty -Path HKLM:\\SOFTWARE\\Microsoft\\InetStp).versionString"
            }
                );
            scrlst.Add(
                new Scripts()
            {
                Script     = ScriptType.BASH,
                ScriptName = "PERLVERSION",
                ScriptText = "perl --version"
            }
                );

            LocalPremise localPremise = new LocalPremise
            {
                WindowsCredentials       = mcwin,
                UNIXCredentials          = mcunix,
                NetworkDeviceCredentials = mcnwdev,
                ScriptList = scrlst
            };
            localPremise.Scan("10.10.5.40/29");
            while (!localPremise.IsComplete)
            {
                Thread.Sleep(10000);
            }
            List <MachineInfo> minfos = localPremise.ServerFound;
            foreach (MachineInfo mi in minfos)
            {
                Console.WriteLine("IPAddress: " + mi.IPAddress);
                Console.WriteLine("ispingable: " + mi.IsPingable);
                Console.WriteLine("OSType: " + mi.OSType);
                if (!string.IsNullOrEmpty(mi.OSVersion))
                {
                    Console.WriteLine("OSVersion: " + mi.OSVersion.Trim());
                }
                if (!string.IsNullOrEmpty(mi.Hostname))
                {
                    Console.WriteLine("Hostname: " + mi.Hostname.Trim());
                }
                foreach (KeyValuePair <string, uint> entry in mi.OpenedPorts)
                {
                    Console.WriteLine(entry.Key + " : " + entry.Value);
                }
                foreach (KeyValuePair <string, string> entry in mi.ScriptOutput)
                {
                    Console.WriteLine(entry.Key + " : " + entry.Value);
                }
                Console.WriteLine(Environment.NewLine);
            }
        }
Example #20
0
 public bool IsValidWindowsCredentials(WindowsCredentials windowsCredentials, ref string errorMsg, string farmName)
 {
     WSConstants.CTX_XML    = farms[farmName].Url;
     WSConstants.CTXXMLPort = farms[farmName].Port;
     return(WebService.IsValidWindowsCredentials(windowsCredentials, ref errorMsg));
 }