Ejemplo n.º 1
1
    static SqlCredential CreateCredential(String username)
    {
        // Prompt the user for a password and construct SqlCredential
        SecureString password = new SecureString();
        Console.WriteLine("Enter password for " + username + ": ");

        ConsoleKeyInfo nextKey = Console.ReadKey(true);

        while (nextKey.Key != ConsoleKey.Enter)
        {
            if (nextKey.Key == ConsoleKey.Backspace)
            {
                if (password.Length > 0)
                {
                    password.RemoveAt(password.Length - 1);
                    // erase the last * as well
                    Console.Write(nextKey.KeyChar);
                    Console.Write(" ");
                    Console.Write(nextKey.KeyChar);
                }
            }
            else
            {
                password.AppendChar(nextKey.KeyChar);
                Console.Write("*");
            }
            nextKey = Console.ReadKey(true);
        }

        Console.WriteLine();
        Console.WriteLine();
        password.MakeReadOnly();
        return new SqlCredential(username, password);
    }
Ejemplo n.º 2
0
        public string getTokenString(string user, SecureString password)
        {
            //credentials.Add ( new System.Uri ( uri ), "Basic", new NetworkCredential ( boxUser.Text, boxPw.SecurePassword) );
            //var url = Path.Combine ( URL, TOKEN );

            var client = new HttpClient();
            var content = new HttpRequestMessage(HttpMethod.Post, new Uri(URI, TOKEN));
            content.Headers()
            client.PostAsync(new Uri(URI, TOKEN),);

            var request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, TOKEN));
            request.ContentType = "text/json";
            request.Credentials = new NetworkCredential(user, password);
            request.Method = "POST";

            //var objStream = request.GetRequestStream ();
            //var writer = new StreamWriter ( objStream );

            //writer.Write ( "{\"comment\":\"ProtonetTool\"}" );
            //writer.Flush ();

            //writer.Close ();

            return ReadResponse(request);
        }
Ejemplo n.º 3
0
    /// <summary>
    /// Read a password from the console into a SecureString
    /// </summary>
    /// <returns>Password stored in a secure string</returns>
    public static SecureString GetPassword()
    {
        SecureString password = new SecureString();
        Console.WriteLine("Enter password: "******" ");
                    Console.Write(nextKey.KeyChar);
                }
            }
            else
            {
                password.AppendChar(nextKey.KeyChar);
                Console.Write("*");
            }
            nextKey = Console.ReadKey(true);
        }

        Console.WriteLine();

        // lock the password down
        password.MakeReadOnly();
        return password;
    }
    /// <summary>
    ///     A String extension method that converts the @this to a secure string.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>@this as a SecureString.</returns>
    public static SecureString ToSecureString(this string @this)
    {
        var secureString = new SecureString();
        foreach (Char c in @this)
            secureString.AppendChar(c);

        return secureString;
    }
Ejemplo n.º 5
0
 private static SecureString createSecureString(string s)
 {
     SecureString result = new SecureString();
     foreach(char ch in s)
     {
         result.AppendChar(ch);
     }
     return result;
 }
Ejemplo n.º 6
0
 public static SecureString ToSecureString(string input)
 {
     SecureString secure = new SecureString();
     foreach (char c in input)
     {
         secure.AppendChar(c);
     }
     secure.MakeReadOnly();
     return secure;
 }
Ejemplo n.º 7
0
 public static SecureString ReadPassword()
 {
     Console.Write("Password: ");
     SecureString secPass = new SecureString();
     ConsoleKeyInfo key = Console.ReadKey(true);
     while (key.KeyChar != '\r')
     {
         secPass.AppendChar(key.KeyChar);
         key = Console.ReadKey(true);
     }
     return secPass;
 }
Ejemplo n.º 8
0
        public X509Certificate(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
        {
            if (rawData == null || rawData.Length == 0)
                throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData));

            ValidateKeyStorageFlags(keyStorageFlags);

            using (var safePasswordHandle = new SafePasswordHandle(password))
            {
                Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, keyStorageFlags);
            }
        }
Ejemplo n.º 9
0
 public static string ToInsecureString(SecureString input)
 {
     string returnValue = string.Empty;
     IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
     try
     {
         returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
     }
     finally
     {
         System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
     }
     return returnValue;
 }
Ejemplo n.º 10
0
    public static SecureString ToSecureString(this IEnumerable<char> input)
    {
        if (input == null)
        {
            return null;
        }

        var secure = new SecureString();

        foreach (var c in input)
        {
            secure.AppendChar(c);
        }

        secure.MakeReadOnly();
        return secure;
    }
Ejemplo n.º 11
0
    private static void VerifyString(SecureString ss, string exString)
    {
        IntPtr uniStr = IntPtr.Zero;
        try
        {
            uniStr = SecureStringMarshal.SecureStringToCoTaskMemUnicode(ss);
            string acString = Marshal.PtrToStringUni(uniStr);

            Assert.Equal(exString.Length, acString.Length);
            Assert.Equal(exString, acString);
        }
        finally
        {
            if (uniStr != IntPtr.Zero)
                SecureStringMarshal.ZeroFreeCoTaskMemUnicode(uniStr);
        }
    }
Ejemplo n.º 12
0
    private static SecureString CreateSecureString(string exValue)
    {
        SecureString ss = null;

        if (string.IsNullOrEmpty(exValue))
            ss = new SecureString();
        else
        {
            unsafe
            {
                fixed (char* mychars = exValue.ToCharArray())
                    ss = new SecureString(mychars, exValue.Length);
            }
        }

        Assert.NotNull(ss);
        return ss;
    }
Ejemplo n.º 13
0
        public static SecureString FindKeePassPassword(
            PwDatabase database,
            bool caseSensitive = false,
            string username = null,
            string url = null,
            string title = null,
            string notes = null)
        {
            var entries =  FindKeePassEntries(database, caseSensitive, true, username, url, title, notes);
            if (entries == null)
                return null;

            foreach(var entry in entries)
            {
                var secureString = new SecureString();
                var value = entry.Strings.ReadSafe("Password");
                foreach (var c in value)
                    secureString.AppendChar(c);

                return secureString;
            }

            return null;
        }
 /// <summary>
 /// Create session to device, or throw exceptions if not successful
 /// </summary>
 /// <param name="uri">The URI specified by the operator when adding the device</param>
 /// <param name="userName">The user name specified</param>
 /// <param name="password">The password specified</param>
 /// <returns>Container representing a device</returns>
 protected override Container CreateContainer(Uri uri, string userName, SecureString password, ICollection <HardwareSetting> hardwareSettings)
 {
     return(new BeiaDeviceDriver_HumContainer(this));
 }
Ejemplo n.º 15
0
 public static bool SetUpClientCert(byte[] rawData, SecureString password)
 {
     return(SetUpClientCert(new X509Certificate2(rawData, password)));
 }
Ejemplo n.º 16
0
 public X509Certificate2(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
 {
     Import(fileName, password, keyStorageFlags);
 }
Ejemplo n.º 17
0
 public static bool SetUpClientCert(string fileName, SecureString password)
 {
     return(SetUpClientCert(new X509Certificate2(fileName, password)));
 }
Ejemplo n.º 18
0
		public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) 
		{
			byte[] rawData = File.ReadAllBytes (fileName);
			Import (rawData, (string)null, keyStorageFlags);
		}
Ejemplo n.º 19
0
 public static UserWallet Open(WalletIndexer indexer, string path, SecureString password)
 {
     return(new UserWallet(indexer, path, password.ToAesKey(), false));
 }
Ejemplo n.º 20
0
 public static UserWallet Create(WalletIndexer indexer, string path, SecureString password)
 {
     return(new UserWallet(indexer, path, password.ToAesKey(), true));
 }
Ejemplo n.º 21
0
        /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
        private void GoodB2G2()
        {
            string data;

            if (PrivateReturnsTrue())
            {
                data = ""; /* Initialize data */
                /* Read data from a database */
                {
                    try
                    {
                        /* setup the connection */
                        using (SqlConnection connection = IO.GetDBConnection())
                        {
                            connection.Open();
                            /* prepare and execute a (hardcoded) query */
                            using (SqlCommand command = new SqlCommand(null, connection))
                            {
                                command.CommandText = "select name from users where id=0";
                                command.Prepare();
                                using (SqlDataReader dr = command.ExecuteReader())
                                {
                                    /* POTENTIAL FLAW: Read data from a database query SqlDataReader */
                                    data = dr.GetString(1);
                                }
                            }
                        }
                    }
                    catch (SqlException exceptSql)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error with SQL statement");
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (PrivateReturnsTrue())
            {
                /* FIX: Hash data before storing in registry */
                {
                    string salt = "ThisIsMySalt";
                    using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                    {
                        byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                        byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                        data = IO.ToHex(hashedCredsAsBytes);
                    }
                }
                using (SecureString secureData = new SecureString())
                {
                    for (int i = 0; i < data.Length; i++)
                    {
                        secureData.AppendChar(data[i]);
                    }
                    RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                    key.CreateSubKey("CWEparent");
                    key = key.OpenSubKey("CWEparent", true);
                    key.CreateSubKey("TestingCWE");
                    key = key.OpenSubKey("TestingCWE", true);
                    key.SetValue("CWE", secureData);
                }
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"Webhook was triggered!");

            try
            {
                var jsonContent = await req.Content.ReadAsStringAsync();

                log.Info(jsonContent);
                dynamic data = JsonConvert.DeserializeObject(jsonContent);

                // TODO: Rather than using web application settings, we should be using the Azure Key Vault for
                // credentials

                var connectionString  = WebUtility.UrlDecode(WebUtility.UrlDecode(data.SpoSiteName.ToString()));
                var documentSetUrl    = string.Empty;
                var applicationFolder = data.ApplicationFolder.ToString();
                var permitFolderName  = data.PermitFolder.ToString();

                using (ClientContext clientContext = new ClientContext(connectionString))
                {
                    var dummy = new TaxonomyItem(clientContext, null);

                    var username = ConfigurationManager.ConnectionStrings["UserName"].ConnectionString;
                    var password = ConfigurationManager.ConnectionStrings["Password"].ConnectionString;

                    var securePassword = new SecureString();
                    foreach (char p in password)
                    {
                        securePassword.AppendChar(p);
                    }

                    var credentials = new SharePointOnlineCredentials(username, securePassword);
                    clientContext.Credentials = credentials;

                    log.Info("Got client context and set credentials");
                    log.Info(string.Format("ListName is {0}", data.ListName.ToString()));

                    var list                 = clientContext.Web.Lists.GetByTitle(data.ListName.ToString());
                    var rootFolder           = list.RootFolder;
                    var permitFolderUrl      = String.Format("{0}/{1}", data.ListName.ToString(), permitFolderName);
                    var applicationFolderUrl = String.Format("{0}/{1}", permitFolderUrl, applicationFolder);

                    // Get the Permit folder content type
                    var ctPermit = GetByName(list.ContentTypes, data.PermitContentType.ToString());
                    log.Info(string.Format("Permit Content Type Id is {0}", ctPermit.Id.StringValue));

                    // Create permit sub folder inside list root folder if it doesn't exist
                    var permitFolder = CreateSubFolderIfDoesntExist(clientContext, permitFolderName, rootFolder, ctPermit, data.PermitFolder.ToString(), log, data.ListName.ToString());
                    log.Info(string.Format("Folder is {0}", permitFolder.Name));



                    // Get the Application document set content type
                    var ctApplication = GetByName(list.ContentTypes, data.ApplicationContentType.ToString());
                    log.Info(string.Format("Applicaction Content Type Id is {0}", ctApplication.Id.StringValue));

                    // Create the Document Set
                    Folder f;

                    try
                    {
                        var ds = DocumentSet.Create(clientContext, permitFolder, applicationFolder, ctApplication.Id);
                        clientContext.ExecuteQuery();
                        documentSetUrl = ds.Value;
                        log.Info(string.Format("Document Set Id is {0}", documentSetUrl));
                    }
                    catch (ServerException ex) when(ex.Message.StartsWith("A document, folder or document set with the name") && ex.Message.EndsWith("already exists."))
                    {
                        documentSetUrl = "Document set exists already";
                        log.Info(string.Format("Handling {0} - {1}", ex.Source, ex.Message));
                    }

                    // Create Complince folder
                    try
                    {
                        log.Info("try to create Compliance folder...");
                        var complinceFolder = DocumentSet.Create(clientContext, permitFolder, "Compliance", ctPermit.Id);
                        clientContext.ExecuteQuery();
                        log.Info("Compliance folder created");
                    }
                    catch (ServerException ex) when(ex.Message.StartsWith("A document, folder or document set with the name") && ex.Message.EndsWith("already exists."))
                    {
                        documentSetUrl = "Document set exists already";
                        log.Info(string.Format("Handling {0} - {1}", ex.Source, ex.Message));
                    }
                }

                return(req.CreateResponse(HttpStatusCode.OK, "{ \"DocumentSetUrl\" : \"" + documentSetUrl + "\" }"));
            }
            catch (Exception ex)
            {
                log.Info(string.Format("{0} Exception {1}", ex.Source, ex.ToString()));
                return(req.CreateResponse(HttpStatusCode.InternalServerError, "Critial error creating SharePoint DocumentSet: " + ex.Message));
            }
        }
Ejemplo n.º 23
0
        static void Test()
        {
            string pkcs11LibraryPath = null;
            var    logFilePath       = @"d:\pkcs11-logger-x64.log";
            string loggerLibraryPath;

            if (Net.Pkcs11Interop.Common.Platform.Uses64BitRuntime)
            {
                pkcs11LibraryPath = @"acos5evopkcs11.dll";
                loggerLibraryPath = @"pkcs11-logger-x64.dll";
            }
            else
            {
                pkcs11LibraryPath = @"acos5evopkcs11.dll";
                loggerLibraryPath = @"pkcs11-logger-x86.dll";
            }

            System.Environment.SetEnvironmentVariable("PKCS11_LOGGER_LIBRARY_PATH", pkcs11LibraryPath);
            System.Environment.SetEnvironmentVariable("PKCS11_LOGGER_LOG_FILE_PATH", logFilePath);
            System.Environment.SetEnvironmentVariable("PKCS11_LOGGER_FLAGS", "64");


            Pkcs11InteropFactories factories = new Pkcs11InteropFactories();

            using (IPkcs11Library pkcs11Library =
                       factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, loggerLibraryPath, AppType.MultiThreaded))
            {
                // Do something interesting
                ISlot slot = GetUsableSlot(pkcs11Library);

                // Open RW session
                using (ISession session = slot.OpenSession(SessionType.ReadWrite))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, _pin);


                    var ss = new SecureString();
                    for (var i = 0; i < pass.Length; i++)
                    {
                        ss.AppendChar(pass[i]);
                    }

                    var certBytes         = File.ReadAllBytes("localhost.pfx");
                    X509Certificate2 cert = new X509Certificate2(certBytes, ss, X509KeyStorageFlags.Exportable);
                    var bCert             = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert);
                    var encodedCert       = bCert.GetEncoded();

                    var privateKeyParams = cert.GetRSAPrivateKey().ExportParameters(true);

                    var unencryptedPrivateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                        new RsaPrivateCrtKeyParameters(
                            new BigInteger(1, privateKeyParams.Modulus),
                            new BigInteger(1, privateKeyParams.Exponent),
                            new BigInteger(1, privateKeyParams.D),
                            new BigInteger(1, privateKeyParams.P),
                            new BigInteger(1, privateKeyParams.Q),
                            new BigInteger(1, privateKeyParams.DP),
                            new BigInteger(1, privateKeyParams.DQ),
                            new BigInteger(1, privateKeyParams.InverseQ))).GetEncoded();

                    IObjectHandle tempKey = GenerateKey(session);
                    byte[]        iv      = session.GenerateRandom(8);

                    var result    = new MemoryStream();
                    var mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_DES3_CBC_PAD, iv);
                    session.Encrypt(mechanism, tempKey, new MemoryStream(unencryptedPrivateKey), result);
                    var encryptedPrivateKey = result.ToArray();

                    WriteCert(session, encodedCert, cert, bCert);

                    session.Logout();
                }
            }
        }
Ejemplo n.º 24
0
 /// <summary>Initializes a new instance of the <see cref="SafeCoTaskMemString"/> class.</summary>
 /// <param name="s">The string value.</param>
 /// <param name="charSet">The character set.</param>
 public SafeCoTaskMemString(SecureString s, CharSet charSet = CharSet.Unicode) : this(StringHelper.AllocSecureString(s, charSet), charSet)
 {
     Capacity = s == null ? 0 : StringHelper.GetCharSize(charSet) * (s.Length + 1);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Prompt for credentials.
        /// </summary>
        /// <param name="caption">Caption for the message.</param>
        /// <param name="message">Message to be displayed.</param>
        /// <param name="userName">Name of the user whose credentials are to be prompted for. If set to null or empty string, the function will prompt for user name first.</param>
        /// <param name="confirmPassword">Prompts user to re-enter the password for confirmation.</param>
        /// <param name="targetName">Name of the target for which credentials are being collected.</param>
        /// <param name="allowedCredentialTypes">What type of credentials can be supplied by the user.</param>
        /// <param name="options">Options that control the credential gathering UI behavior.</param>
        /// <returns>PSCredential object, or null if input was cancelled (or if reading from stdin and stdin at EOF).</returns>
        public override PSCredential PromptForCredential(
            string caption,
            string message,
            string userName,
            bool confirmPassword,
            string targetName,
            PSCredentialTypes allowedCredentialTypes,
            PSCredentialUIOptions options)
        {
            PSCredential cred                  = null;
            SecureString password              = null;
            SecureString reenterPassword       = null;
            string       userPrompt            = null;
            string       passwordPrompt        = null;
            string       confirmPasswordPrompt = null;
            string       passwordMismatch      = null;

            if (!string.IsNullOrEmpty(caption))
            {
                // Should be a skin lookup
                WriteLineToConsole();
                WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption));
            }

            if (!string.IsNullOrEmpty(message))
            {
                WriteLineToConsole(WrapToCurrentWindowWidth(message));
            }

            if (string.IsNullOrEmpty(userName))
            {
                userPrompt = ConsoleHostUserInterfaceSecurityResources.PromptForCredential_User;

                // need to prompt for user name first
                do
                {
                    WriteToConsole(userPrompt, true);
                    userName = ReadLine();
                    if (userName == null)
                    {
                        return(null);
                    }
                }while (userName.Length == 0);
            }

            passwordPrompt = StringUtil.Format(ConsoleHostUserInterfaceSecurityResources.PromptForCredential_Password, userName);

            // now, prompt for the password
            do
            {
                WriteToConsole(passwordPrompt, true);
                password = ReadLineAsSecureString();
                if (password == null)
                {
                    return(null);
                }
            }while (password.Length == 0);

            if (confirmPassword)
            {
                confirmPasswordPrompt = StringUtil.Format(ConsoleHostUserInterfaceSecurityResources.PromptForCredential_ReenterPassword, userName);
                passwordMismatch      = StringUtil.Format(ConsoleHostUserInterfaceSecurityResources.PromptForCredential_PasswordMismatch);

                // now, prompt to re-enter the password.
                WriteToConsole(confirmPasswordPrompt, true);
                reenterPassword = ReadLineAsSecureString();
                if (reenterPassword == null)
                {
                    return(null);
                }

                if (!SecureStringEquals(password, reenterPassword))
                {
                    WriteToConsole(ConsoleColor.Red, ConsoleColor.Black, passwordMismatch, false);
                    return(null);
                }
            }

            WriteLineToConsole();
            cred = new PSCredential(userName, password);
            return(cred);
        }
Ejemplo n.º 26
0
		public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
		{
			Import (rawData, password, keyStorageFlags);
		}
Ejemplo n.º 27
0
		public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
		{
			Import (fileName, password, keyStorageFlags);
		}
Ejemplo n.º 28
0
 public X509Certificate2(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
 {
     Import(rawData, password, keyStorageFlags);
 }
Ejemplo n.º 29
0
 public override void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
 {
     byte[] rawData = File.ReadAllBytes(fileName);
     Import(rawData, (string)null, keyStorageFlags);
 }
Ejemplo n.º 30
0
 public X509Certificate2(byte[] rawData, SecureString password)
 {
     Import(rawData, password, X509KeyStorageFlags.DefaultKeySet);
 }
Ejemplo n.º 31
0
 public override void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
 {
     Import(rawData, (string)null, keyStorageFlags);
 }
		public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
			: base (rawData, password, keyStorageFlags) 
		{
			_cert = new MX.X509Certificate (base.GetRawCertData ());
		}
Ejemplo n.º 33
0
 public X509Certificate2(string fileName, SecureString password)
 {
     Import(fileName, password, X509KeyStorageFlags.DefaultKeySet);
 }
Ejemplo n.º 34
0
		public virtual byte[] Export (X509ContentType contentType, SecureString password)
		{
			byte[] pwd = (password == null) ? null : password.GetBuffer ();
			return Export (contentType, pwd);
		}
        // copy constructor
        internal CspParameters (CspParameters parameters) {
            ProviderType = parameters.ProviderType;
            ProviderName = parameters.ProviderName;
            KeyContainerName = parameters.KeyContainerName;
            KeyNumber = parameters.KeyNumber;
            Flags = parameters.Flags;
#if FEATURE_MACL            
            m_cryptoKeySecurity = parameters.m_cryptoKeySecurity;
#endif // FEATURE_MACL
#if FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS
            m_keyPassword = parameters.m_keyPassword;
            m_parentWindowHandle = parameters.m_parentWindowHandle;
#endif // FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS
        }
 public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) => s != null ? s.MarshalToString(globalAlloc: false, unicode: false) : IntPtr.Zero;
Ejemplo n.º 37
0
        public IAccessToken Authenticate(
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenant,
            SecureString password,
            string promptBehavior,
            Action <string> promptAction,
            IAzureTokenCache tokenCache,
            string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            IAccessToken token;
            var          cache = tokenCache as TokenCache;

            if (cache == null)
            {
                cache = TokenCache.DefaultShared;
            }

            Task <IAccessToken> authToken;

            if (Builder.Authenticator.TryAuthenticate(account, environment, tenant, password, promptBehavior, Task.FromResult(promptAction), tokenCache, resourceId, out authToken))
            {
                return(authToken.ConfigureAwait(false).GetAwaiter().GetResult());
            }

            var configuration = GetAdalConfiguration(environment, tenant, resourceId, cache);

            TracingAdapter.Information(
                Resources.AdalAuthConfigurationTrace,
                configuration.AdDomain,
                configuration.AdEndpoint,
                configuration.ClientId,
                configuration.ClientRedirectUri,
                configuration.ResourceClientUri,
                configuration.ValidateAuthority);
            if (account != null && account.Type == AzureAccount.AccountType.ManagedService)
            {
                token = GetManagedServiceToken(account, environment, tenant, resourceId);
            }
            else if (account != null && environment != null &&
                     account.Type == AzureAccount.AccountType.AccessToken)
            {
                var rawToken = new RawAccessToken
                {
                    TenantId  = tenant,
                    UserId    = account.Id,
                    LoginType = AzureAccount.AccountType.AccessToken
                };

                if ((string.Equals(resourceId, environment.AzureKeyVaultServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                     string.Equals(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                    account.IsPropertySet(AzureAccount.Property.KeyVaultAccessToken))
                {
                    rawToken.AccessToken = account.GetProperty(AzureAccount.Property.KeyVaultAccessToken);
                }
                else if ((string.Equals(resourceId, environment.GraphEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                          string.Equals(AzureEnvironment.Endpoint.GraphEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                         account.IsPropertySet(AzureAccount.Property.GraphAccessToken))
                {
                    rawToken.AccessToken = account.GetProperty(AzureAccount.Property.GraphAccessToken);
                }
                else if ((string.Equals(resourceId, environment.ActiveDirectoryServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) ||
                          string.Equals(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) &&
                         account.IsPropertySet(AzureAccount.Property.AccessToken))
                {
                    rawToken.AccessToken = account.GetAccessToken();
                }
                else
                {
                    throw new InvalidOperationException(string.Format(Resources.AccessTokenResourceNotFound, resourceId));
                }

                token = rawToken;
            }
            else if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
            {
                var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint);
                token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type);
            }
            else
            {
                token = TokenProvider.GetAccessToken(configuration, promptBehavior, promptAction, account.Id, password, account.Type);
            }

            account.Id = token.UserId;
            return(token);
        }
Ejemplo n.º 38
0
 public bool IsCredentialValid(string username, SecureString password)
 {
     return(XdContext.Credentials.Any(x => x.Username == username && x.Password == password));
 }
Ejemplo n.º 39
0
        public string GetAadAuthenticatedToken(AsAzureContext asAzureContext, SecureString password, PromptBehavior promptBehavior, string clientId, string resourceUri, Uri resourceRedirectUri)
        {
            var authUriBuilder = new UriBuilder((string)asAzureContext.Environment.Endpoints[AsAzureEnvironment.AsRolloutEndpoints.AdAuthorityBaseUrl]);

            authUriBuilder.Path = string.IsNullOrEmpty(asAzureContext.Account.Tenant)
                ? "common"
                : asAzureContext.Account.Tenant;

            var authenticationContext = new AuthenticationContext(
                authUriBuilder.ToString(),
                AsAzureClientSession.TokenCache);

            AuthenticationResult result = null;
            string accountType          = string.IsNullOrEmpty(asAzureContext.Account.Type) ? AsAzureAccount.AccountType.User : asAzureContext.Account.Type;

            if (password == null && accountType == AsAzureAccount.AccountType.User)
            {
                if (asAzureContext.Account.Id != null)
                {
                    result = authenticationContext.AcquireToken(
                        resourceUri,
                        clientId,
                        resourceRedirectUri,
                        promptBehavior,
                        new UserIdentifier(asAzureContext.Account.Id, UserIdentifierType.OptionalDisplayableId));
                }
                else
                {
                    result = authenticationContext.AcquireToken(
                        resourceUri,
                        clientId,
                        resourceRedirectUri,
                        promptBehavior);
                }

                asAzureContext.Account.Id       = result.UserInfo.DisplayableId;
                asAzureContext.Account.Tenant   = result.TenantId;
                asAzureContext.Account.UniqueId = result.UserInfo.UniqueId;
            }
            else
            {
                if (accountType == AsAzureAccount.AccountType.User)
                {
                    UserCredential userCredential = new UserCredential(asAzureContext.Account.Id, password);
                    result = authenticationContext.AcquireToken(resourceUri, clientId, userCredential);

                    asAzureContext.Account.Id       = result.UserInfo.DisplayableId;
                    asAzureContext.Account.Tenant   = result.TenantId;
                    asAzureContext.Account.UniqueId = result.UserInfo.UniqueId;
                }
                else if (accountType == AsAzureAccount.AccountType.ServicePrincipal)
                {
                    if (string.IsNullOrEmpty(asAzureContext.Account.CertificateThumbprint))
                    {
                        ClientCredential credential = new ClientCredential(asAzureContext.Account.Id, password);
                        result = authenticationContext.AcquireToken(resourceUri, credential);
                    }
                    else
                    {
                        DiskDataStore dataStore   = new DiskDataStore();
                        var           certificate = dataStore.GetCertificate(asAzureContext.Account.CertificateThumbprint);
                        if (certificate == null)
                        {
                            throw new ArgumentException(string.Format(Resources.CertificateNotFoundInStore, asAzureContext.Account.CertificateThumbprint));
                        }

                        result = authenticationContext.AcquireToken(resourceUri, new ClientAssertionCertificate(asAzureContext.Account.Id, certificate));
                    }
                }
            }

            return(result.AccessToken);
        }
Ejemplo n.º 40
0
 public void StorePassword(SecureString pass)
 {
     _password = pass;
 }
		public X509Certificate2 (byte[] rawData, SecureString password) : base (rawData, password) 
		{
			_cert = new MX.X509Certificate (base.GetRawCertData ());
		}
Ejemplo n.º 42
0
        public string Encrypt(string text, SecureString pass = null)
        {
            var password = pass ?? GetPassword();

            return(FileSecurity.Encrypt(text, password));
        }
		public X509Certificate2 (string fileName, SecureString password) 
		{
			_cert = new MX.X509Certificate (base.GetRawCertData ());
		}
Ejemplo n.º 44
0
 private static bool ValidatePassword(SecureString password)
 {
     return((password != null) && (password.Length >= 5));
 }
Ejemplo n.º 45
0
		public virtual void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
		{
			byte[] rawData = Load (fileName);
			Import (rawData, (string)null, keyStorageFlags);
		}
Ejemplo n.º 46
0
 private static bool ValidatePasswordConfirmation(SecureString password, SecureString passwordConfirmation)
 {
     return(SecureStringExtensions.AreEqual(password, passwordConfirmation));
 }
 public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) => s != null ? s.MarshalToString(globalAlloc: true, unicode: true) : IntPtr.Zero;
Ejemplo n.º 48
0
 public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain)
 {
     throw new PlatformNotSupportedException(SR.ProcessStartWithPasswordAndDomainNotSupported);
 }
Ejemplo n.º 49
0
 public static ISshKey GetSshKey(this EntrySettings settings,
     ProtectedStringDictionary strings, ProtectedBinaryDictionary binaries,
     SprContext sprContext)
 {
     if (!settings.AllowUseOfSshKey) {
     return null;
       }
       KeyFormatter.GetPassphraseCallback getPassphraseCallback =
     delegate(string comment)
     {
       var securePassphrase = new SecureString();
     var passphrase = SprEngine.Compile(strings.ReadSafe(
                   PwDefs.PasswordField), sprContext);
       foreach (var c in passphrase) {
     securePassphrase.AppendChar(c);
       }
       return securePassphrase;
     };
       Func<Stream> getPrivateKeyStream;
       Func<Stream> getPublicKeyStream = null;
       switch (settings.Location.SelectedType) {
     case EntrySettings.LocationType.Attachment:
       if (string.IsNullOrWhiteSpace(settings.Location.AttachmentName)) {
     throw new NoAttachmentException();
       }
       var privateKeyData = binaries.Get(settings.Location.AttachmentName);
       var publicKeyData = binaries.Get(settings.Location.AttachmentName + ".pub");
       getPrivateKeyStream = () => new MemoryStream(privateKeyData.ReadData());
       if (publicKeyData != null)
     getPublicKeyStream = () => new MemoryStream(publicKeyData.ReadData());
       return GetSshKey(getPrivateKeyStream, getPublicKeyStream,
                    settings.Location.AttachmentName, getPassphraseCallback);
     case EntrySettings.LocationType.File:
       getPrivateKeyStream = () => File.OpenRead(settings.Location.FileName);
       var publicKeyFile = settings.Location.FileName + ".pub";
       if (File.Exists(publicKeyFile))
     getPublicKeyStream = () => File.OpenRead(publicKeyFile);
       return GetSshKey(getPrivateKeyStream, getPublicKeyStream,
                    settings.Location.AttachmentName, getPassphraseCallback);
     default:
       return null;
       }
 }
Ejemplo n.º 50
0
 internal CollectionHash(string workspaceId, SecureString sharedKey)
 {
     _WorkspaceId = workspaceId;
     _Algorithm   = new HMACSHA256(Convert.FromBase64String(new NetworkCredential(string.Empty, sharedKey).Password));
 }
 public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s);
Ejemplo n.º 52
0
 /// <summary>
 /// Constructs an AmazonSimpleNotificationServiceClient with AWS Access Key ID, AWS Secret Key and an
 /// AmazonSimpleNotificationService Configuration object
 /// </summary>
 /// <param name="awsAccessKeyId">AWS Access Key ID</param>
 /// <param name="awsSecretAccessKey">AWS Secret Access Key as a SecureString</param>
 /// <param name="region">The region to connect to.</param>
 public AmazonSimpleNotificationServiceClient(string awsAccessKeyId, SecureString awsSecretAccessKey, RegionEndpoint region)
     : this(new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey), new AmazonSimpleNotificationServiceConfig() { RegionEndpoint = region }, true) { }
Ejemplo n.º 53
0
		public X509Certificate2 (string fileName, SecureString password)
		{
			Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
		}
Ejemplo n.º 54
0
        private bool OnExportKeyCommand(string[] args)
        {
            if (Program.Wallet == null)
            {
                Console.WriteLine("You have to open the wallet first.");
                return(true);
            }
            if (args.Length < 2 || args.Length > 4)
            {
                Console.WriteLine("error");
                return(true);
            }
            UInt160 scriptHash = null;
            string  path       = null;

            if (args.Length == 3)
            {
                try
                {
                    scriptHash = Wallet.ToScriptHash(args[2]);
                }
                catch (FormatException)
                {
                    path = args[2];
                }
            }
            else if (args.Length == 4)
            {
                scriptHash = Wallet.ToScriptHash(args[2]);
                path       = args[3];
            }
            using (SecureString password = ReadSecureString("password"))
            {
                if (password.Length == 0)
                {
                    Console.WriteLine("cancelled");
                    return(true);
                }
                if (!Program.Wallet.VerifyPassword(password))
                {
                    Console.WriteLine("Incorrect password");
                    return(true);
                }
            }
            IEnumerable <KeyPair> keys;

            if (scriptHash == null)
            {
                keys = Program.Wallet.GetKeys();
            }
            else
            {
                keys = new[] { Program.Wallet.GetKeyByScriptHash(scriptHash) }
            };
            if (path == null)
            {
                foreach (KeyPair key in keys)
                {
                    Console.WriteLine(key.Export());
                }
            }
            else
            {
                File.WriteAllLines(path, keys.Select(p => p.Export()));
            }
            return(true);
        }
Ejemplo n.º 55
0
		public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
		{
			Import (rawData, (string) null, keyStorageFlags);
		}
Ejemplo n.º 56
0
        private bool OnSendCommand(string[] args)
        {
            if (args.Length < 4 || args.Length > 5)
            {
                Console.WriteLine("error");
                return(true);
            }
            if (Program.Wallet == null)
            {
                Console.WriteLine("You have to open the wallet first.");
                return(true);
            }
            using (SecureString password = ReadSecureString("password"))
            {
                if (password.Length == 0)
                {
                    Console.WriteLine("cancelled");
                    return(true);
                }
                if (!Program.Wallet.VerifyPassword(password))
                {
                    Console.WriteLine("Incorrect password");
                    return(true);
                }
            }
            UInt256 assetId;

            switch (args[1].ToLower())
            {
            case "neo":
            case "ans":
                assetId = Blockchain.SystemShare.Hash;
                break;

            case "gas":
            case "anc":
                assetId = Blockchain.SystemCoin.Hash;
                break;

            default:
                assetId = UInt256.Parse(args[1]);
                break;
            }
            UInt160             scriptHash = Wallet.ToScriptHash(args[2]);
            bool                isSendAll  = string.Equals(args[3], "all", StringComparison.OrdinalIgnoreCase);
            ContractTransaction tx;

            if (isSendAll)
            {
                Coin[] coins = Program.Wallet.FindUnspentCoins().Where(p => p.Output.AssetId.Equals(assetId)).ToArray();
                tx = new ContractTransaction
                {
                    Attributes = new TransactionAttribute[0],
                    Inputs     = coins.Select(p => p.Reference).ToArray(),
                    Outputs    = new[]
                    {
                        new TransactionOutput
                        {
                            AssetId    = assetId,
                            Value      = coins.Sum(p => p.Output.Value),
                            ScriptHash = scriptHash
                        }
                    }
                };
            }
            else
            {
                if (!Fixed8.TryParse(args[3], out Fixed8 amount))
                {
                    Console.WriteLine("Incorrect Amount Format");
                    return(true);
                }
                if (amount.GetData() % (long)Math.Pow(10, 8 - Blockchain.Default.GetAssetState(assetId).Precision) != 0)
                {
                    Console.WriteLine("Incorrect Amount Precision");
                    return(true);
                }
                Fixed8 fee = args.Length >= 5 ? Fixed8.Parse(args[4]) : Fixed8.Zero;
                tx = Program.Wallet.MakeTransaction(new ContractTransaction
                {
                    Outputs = new[]
                    {
                        new TransactionOutput
                        {
                            AssetId    = assetId,
                            Value      = amount,
                            ScriptHash = scriptHash
                        }
                    }
                }, fee: fee);
                if (tx == null)
                {
                    Console.WriteLine("Insufficient funds");
                    return(true);
                }
            }
            SignatureContext context = new SignatureContext(tx);

            Program.Wallet.Sign(context);
            if (context.Completed)
            {
                tx.Scripts = context.GetScripts();
                Program.Wallet.SaveTransaction(tx);
                LocalNode.Relay(tx);
                Console.WriteLine($"TXID: {tx.Hash}");
            }
            else
            {
                Console.WriteLine("SignatureContext:");
                Console.WriteLine(context.ToString());
            }
            return(true);
        }
Ejemplo n.º 57
0
		public X509Certificate2 (byte[] rawData, SecureString password)
		{
			Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
		}
Ejemplo n.º 58
0
 public Task <KeyValuePair <bool, string> > GenerateToken(string login, SecureString password)
 {
     return(Task.Run(() => new KeyValuePair <bool, string>(true, null)));
 }
Ejemplo n.º 59
0
		public CspParameters (int providerType, string providerName, string keyContainerName, 
			CryptoKeySecurity cryptoKeySecurity, SecureString keyPassword)
			: this (providerType, providerName, keyContainerName)
		{
			if (cryptoKeySecurity != null)
				CryptoKeySecurity = cryptoKeySecurity;
			_password = keyPassword;
		}
Ejemplo n.º 60
0
 public Result StoreKey(PrivateKey key, SecureString password)
 {
     return(StoreKey(key.Address, key.KeyBytes, password));
 }