Пример #1
0
 public Credential GetCredential()
 {
     if (!IsInvalid)
     {
         NativeCredential ncred = (NativeCredential)Marshal.PtrToStructure(handle,
                                                                           typeof(NativeCredential));
         Credential cred = new Credential
         {
             CredentialBlobSize = ncred.CredentialBlobSize,
             CredentialBlob     = Marshal.PtrToStringUni(ncred.CredentialBlob,
                                                         (int)ncred.CredentialBlobSize / 2),
             UserName    = Marshal.PtrToStringUni(ncred.UserName),
             TargetName  = Marshal.PtrToStringUni(ncred.TargetName),
             TargetAlias = Marshal.PtrToStringUni(ncred.TargetAlias),
             Type        = ncred.Type,
             Flags       = ncred.Flags,
             Persist     = ncred.Persist
         };
         return(cred);
     }
     else
     {
         throw new InvalidOperationException("Invalid CriticalHandle!");
     }
 }
Пример #2
0
                internal static NativeCredential GetNativeCredential(Credential cred)
                {
                    NativeCredential ncred = new NativeCredential();

                    ncred.AttributeCount     = 0;
                    ncred.AttributeCount     = 0;
                    ncred.Attributes         = IntPtr.Zero;
                    ncred.Comment            = IntPtr.Zero;
                    ncred.TargetAlias        = IntPtr.Zero;
                    ncred.Type               = cred.Type;
                    ncred.Persist            = (UInt32)cred.Persist;
                    ncred.CredentialBlobSize = (UInt32)cred.CredentialBlobSize;
                    ncred.TargetName         = Marshal.StringToCoTaskMemUni(cred.TargetName);
                    ncred.CredentialBlob     = Marshal.StringToCoTaskMemUni(cred.CredentialBlob);
                    ncred.UserName           = Marshal.StringToCoTaskMemUni(cred.UserName);
                    //                    var ncred = new NativeCredential
                    //                    {
                    //                        AttributeCount = 0,
                    //                        Attributes = IntPtr.Zero,
                    //                        Comment = IntPtr.Zero,
                    //                        TargetAlias = IntPtr.Zero,
                    //                        //Type = CRED_TYPE.DOMAIN_PASSWORD,
                    //                        Type = cred.Type,
                    //                        Persist = (UInt32)cred.Persist,
                    //                        CredentialBlobSize = (UInt32)cred.CredentialBlobSize,
                    //                        TargetName = Marshal.StringToCoTaskMemUni(cred.TargetName),
                    //                        CredentialBlob = Marshal.StringToCoTaskMemUni(cred.CredentialBlob),
                    //                        UserName = Marshal.StringToCoTaskMemUni(cred.UserName)
                    //                    };
                    return(ncred);
                }
Пример #3
0
        /// <summary>
        /// Query the credential cache, get the first one and return username.
        /// </summary>
        /// <returns>user name</returns>
        internal static string FetchDefaultUsername(string headNodeName)
        {
            //TODO: SF: headnodeName is a gateway string
            IntPtr ptr = IntPtr.Zero;

            try
            {
                int    count;
                string filter = string.Format(@"{0}\*", headNodeName);
                if (CredentialHelper.CredEnumerate(filter, 0, out count, out ptr))
                {
                    NativeCredential c      = (NativeCredential)Marshal.PtrToStructure(Marshal.ReadIntPtr(ptr), typeof(NativeCredential));
                    string           target = Marshal.PtrToStringUni(c.TargetName);
                    string[]         tmp    = target.Split(new char[] { '\\' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    return(tmp[1]);
                }
            }
            finally
            {
                if (ptr != IntPtr.Zero)
                {
                    CredFree(ptr);
                }
            }

            return(null);
        }
        public static Credential ToCredential(this NativeCredential nativeCredential)
        {
            Credential credential;

            try
            {
                credential = new Credential()
                {
                    Type        = nativeCredential.Type,
                    Flags       = nativeCredential.Flags,
                    Persist     = (CredPersist)nativeCredential.Persist,
                    UserName    = Marshal.PtrToStringUni(nativeCredential.UserName),
                    TargetName  = Marshal.PtrToStringUni(nativeCredential.TargetName),
                    TargetAlias = Marshal.PtrToStringUni(nativeCredential.TargetAlias),
                    Comment     = Marshal.PtrToStringUni(nativeCredential.Comment),
                    PaswordSize = nativeCredential.CredentialBlobSize,
                    LastWritten = nativeCredential.LastWritten.ToDateTime()
                };

                if (0 < nativeCredential.CredentialBlobSize)
                {
                    credential.Password = Marshal.PtrToStringUni(nativeCredential.CredentialBlob, (int)nativeCredential.CredentialBlobSize / 2);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("PSCredentialManager.Api.CredentialUtility.ConvertToCredential Unable to convert native credential to credential.", ex);
            }

            return(credential);
        }
Пример #5
0
            /// <summary>
            /// This method derives a NativeCredential instance from a given Credential instance.
            /// </summary>
            /// <param name="cred">The managed Credential counterpart containing data to be stored.</param>
            /// <returns>A NativeCredential instance that is derived from the given Credential
            /// instance.</returns>
            internal static NativeCredential GetNativeCredential(Credential cred)
            {
                var ncred = new NativeCredential();

                ncred.AttributeCount = 0;
                ncred.Attributes     = IntPtr.Zero;
                ncred.Comment        = IntPtr.Zero;
                ncred.TargetAlias    = IntPtr.Zero;
                ncred.Type           = CredTypes.CRED_TYPE_GENERIC;
                ncred.Persist        = (UInt32)cred.Persist;
                ncred.TargetName     = Marshal.StringToCoTaskMemUni(cred.TargetName);

                var encryptedPassword = EncryptPassword(cred.CredentialBlob);

                try
                {
                    ncred.CredentialBlob = Marshal.AllocHGlobal(encryptedPassword.Length);
                    Marshal.Copy(encryptedPassword, 0, ncred.CredentialBlob, encryptedPassword.Length);
                    ncred.CredentialBlobSize = (uint)encryptedPassword.Length;
                    ncred.Type = CredTypes.CRED_TYPE_GENERIC;
                }
                finally
                {
                    Marshal.FreeCoTaskMem(ncred.CredentialBlob);
                }

                ncred.UserName = Marshal.StringToCoTaskMemUni(cred.UserName);

                return(ncred);
            }
Пример #6
0
        public static NativeCredential ToNativeCredential(this Credential credential)
        {
            NativeCredential nativeCredential;

            try
            {
                nativeCredential = new NativeCredential()
                {
                    AttributeCount     = 0,
                    Attributes         = IntPtr.Zero,
                    Comment            = Marshal.StringToCoTaskMemUni(credential.Comment),
                    TargetAlias        = IntPtr.Zero,
                    Type               = credential.Type,
                    Persist            = (uint)credential.Persist,
                    CredentialBlobSize = credential.PaswordSize,
                    TargetName         = Marshal.StringToCoTaskMemUni(credential.TargetName),
                    CredentialBlob     = Marshal.StringToCoTaskMemUni(credential.Password),
                    UserName           = Marshal.StringToCoTaskMemUni(credential.UserName),
                    LastWritten        = credential.LastWritten.ToComFileTime()
                };
            }
            catch (Exception ex)
            {
                throw new Exception("PSCredentialManager.Api.CredentialUtility.ConvertToNativeCredential Unable to convert credential to native credential.", ex);
            }

            return(nativeCredential);
        }
Пример #7
0
        public void Store(string resource, PasswordCredential credential)
        {
            // Validations.
            byte[] byteArray = Encoding.Unicode.GetBytes(credential.Password);

            // Go ahead with what we have are stuff it into the CredMan structures.
            Credential cred = new Credential
            {
                TargetName         = resource,
                UserName           = credential.UserName,
                CredentialBlob     = credential.Password,
                CredentialBlobSize = (uint)byteArray.Length,
                AttributeCount     = 0,
                Attributes         = IntPtr.Zero,
                Comment            = null,
                TargetAlias        = null,
                Type    = CRED_TYPE.GENERIC,
                Persist = CRED_PERSIST.LOCAL_MACHINE
            };
            NativeCredential ncred = NativeCredential.GetNativeCredential(cred);

            // Write the info into the CredMan storage.
            bool written   = CredWrite(ref ncred, 0);
            int  lastError = Marshal.GetLastWin32Error();

            if (!written)
            {
                string message = "CredWrite failed with the error code " + lastError.ToString();
                throw new InvalidOperationException(message);
            }
        }
            internal Credential GetCredential()
            {
                if (!IsInvalid)
                {
                    // Get the Credential from the mem location
                    NativeCredential nativeCredential = (NativeCredential)Marshal.PtrToStructure(handle, typeof(NativeCredential));

                    // Create a managed Credential type and fill it with data from the native counterpart.
                    return(new Credential
                    {
                        CredentialBlobSize = nativeCredential.CredentialBlobSize,
                        CredentialBlob = Marshal.PtrToStringUni(nativeCredential.CredentialBlob, (int)nativeCredential.CredentialBlobSize / 2),
                        UserName = Marshal.PtrToStringUni(nativeCredential.UserName),
                        TargetName = Marshal.PtrToStringUni(nativeCredential.TargetName),
                        TargetAlias = Marshal.PtrToStringUni(nativeCredential.TargetAlias),
                        Type = nativeCredential.Type,
                        Flags = nativeCredential.Flags,
                        Persist = (CRED_PERSIST)nativeCredential.Persist
                    });
                }
                else
                {
                    throw new InvalidOperationException("Invalid CriticalHandle!");
                }
            }
Пример #9
0
            private Credential XlateNativeCred(IntPtr pCred)
            {
                NativeCredential ncred = (NativeCredential)Marshal.PtrToStructure(pCred, typeof(NativeCredential));
                Credential       cred  = new Credential();

                cred.Type    = ncred.Type;
                cred.Flags   = ncred.Flags;
                cred.Persist = (CRED_PERSIST)ncred.Persist;

                long LastWritten = ncred.LastWritten.dwHighDateTime;

                LastWritten      = (LastWritten << 32) + ncred.LastWritten.dwLowDateTime;
                cred.LastWritten = DateTime.FromFileTime(LastWritten);

                cred.UserName           = Marshal.PtrToStringUni(ncred.UserName);
                cred.TargetName         = Marshal.PtrToStringUni(ncred.TargetName);
                cred.TargetAlias        = Marshal.PtrToStringUni(ncred.TargetAlias);
                cred.Comment            = Marshal.PtrToStringUni(ncred.Comment);
                cred.CredentialBlobSize = ncred.CredentialBlobSize;
                if (0 < ncred.CredentialBlobSize)
                {
                    cred.CredentialBlob = Marshal.PtrToStringUni(ncred.CredentialBlob, (int)ncred.CredentialBlobSize / 2);
                }
                return(cred);
            }
Пример #10
0
            internal Credential GetCredential()
            {
                if (!IsInvalid)
                {
                    // Get the Credential from the mem location
                    NativeCredential ncred = (NativeCredential)Marshal.PtrToStructure(handle,
                                                                                      typeof(NativeCredential));

                    // Create a managed Credential type and fill it with data from the native counterpart.
                    Credential cred = new Credential();
                    cred.CredentialBlobSize = ncred.CredentialBlobSize;
                    cred.CredentialBlob     = Marshal.PtrToStringUni(ncred.CredentialBlob,
                                                                     (int)ncred.CredentialBlobSize / 2);
                    cred.UserName    = Marshal.PtrToStringUni(ncred.UserName);
                    cred.TargetName  = Marshal.PtrToStringUni(ncred.TargetName);
                    cred.TargetAlias = Marshal.PtrToStringUni(ncred.TargetAlias);
                    cred.Type        = ncred.Type;
                    cred.Flags       = ncred.Flags;
                    cred.Persist     = (Persistence)ncred.Persist;
                    return(cred);
                }
                else
                {
                    throw new InvalidOperationException("Invalid CriticalHandle!");
                }
            }
Пример #11
0
            /// <summary>
            /// 向添加计算机的凭据管理其中添加凭据
            /// </summary>
            /// <param name="key">internet地址或者网络地址</param>
            /// <param name="userName">用户名</param>
            /// <param name="secret">密码</param>
            /// <param name="type">密码类型</param>
            /// <param name="credPersist"></param>
            /// <returns></returns>
            public static int WriteCred(string key, string userName, string secret, CRED_TYPE type, CRED_PERSIST credPersist)
            {
                byte[] byteArray = Encoding.Unicode.GetBytes(secret);
                if (byteArray.Length > 512)
                {
                    throw new ArgumentOutOfRangeException("The secret message has exceeded 512 bytes.");
                }

                Credential cred = new Credential();

                cred.TargetName         = key;
                cred.CredentialBlob     = secret;
                cred.CredentialBlobSize = (UInt32)Encoding.Unicode.GetBytes(secret).Length;
                cred.AttributeCount     = 0;
                cred.Attributes         = IntPtr.Zero;
                cred.UserName           = userName;
                cred.Comment            = null;
                cred.TargetAlias        = null;
                cred.Type    = type;
                cred.Persist = credPersist;
                #region
                // var cred = new Credential
                //                {
                //                    TargetName = key,
                //                    CredentialBlob = secret,
                //                    CredentialBlobSize = (UInt32)Encoding.Unicode.GetBytes(secret).Length,
                //                    AttributeCount = 0,
                //                    Attributes = IntPtr.Zero,
                //                    UserName = userName,
                //                    Comment = null,
                //                    TargetAlias = null,
                //                    Type = type,
                //                    Persist = credPersist
                //                };
                #endregion
                NativeCredential ncred   = NativeCredential.GetNativeCredential(cred);
                bool             written = CredWrite(ref ncred, 0);
                int lastError            = Marshal.GetLastWin32Error();
                if (written)
                {
                    return(0);
                }

                string message = "";
                if (lastError == 1312)
                {
                    message = (string.Format(String.Format("Failed to save {0} with error code {{0}}.", key), lastError)
                               + "  This error typically occurrs on home editions of Windows XP and Vista.  Verify the version of Windows is Pro/Business or higher.");
                }
                else
                {
                    message = string.Format(String.Format("Failed to save {0} with error code {{0}}.", key), lastError);
                }
                return(1);
            }
Пример #12
0
        public void TestSerialize()
        {
            //Arrange
            var nativeCredential = new NativeCredential(userName, properties);

            // Act
            var result = nativeCredential.Serialize();

            //Assert
            Assert.AreEqual(serializedNativeCredential, result);
        }
Пример #13
0
        public void WriteCred(NativeCredential credential)
        {
            // Write the info into the CredMan storage.
            bool written   = Imports.CredWrite(ref credential, 0);
            int  lastError = Marshal.GetLastWin32Error();

            if (!written)
            {
                string message = $"CredWrite failed with the error code {lastError}.";
                throw new Exception(message);
            }
        }
Пример #14
0
        public void TestDeserialize()
        {
            //Arrange
            var nativeCredential = new NativeCredential();

            // Act
            var result = NativeCredential.Deserialize(serializedNativeCredential);

            //Assert
            Assert.AreEqual(userName, result.UserID);
            Assert.AreEqual(properties.Count, result.Properties.Count);
            Assert.AreEqual(properties[key], result.Properties[key]);
        }
Пример #15
0
        static private NativeCredential ConvertFrom(string credentialsName, NetworkCredential networkCredential)
        {
            var nativeCred = new NativeCredential()
            {
                TargetName         = credentialsName,
                UserName           = networkCredential.UserName,
                CredentialBlob     = Marshal.StringToCoTaskMemUni(networkCredential.Password),
                CredentialBlobSize = (UInt32)Encoding.Unicode.GetBytes(networkCredential.Password).Length,
                Type    = 1, //1 - GENERIC
                Persist = 2  //2 - LOCAL_MACHINE
            };

            return(nativeCred);
        }
            public static void WriteCredential(string credentialName, NetworkCredential credential)
            {
                var nativeCred = new NativeCredential
                {
                    TargetName         = credentialName,
                    UserName           = credential.UserName,
                    CredentialBlob     = Marshal.StringToCoTaskMemUni(credential.Password),
                    CredentialBlobSize = (uint)Encoding.Unicode.GetByteCount(credential.Password),
                    Type        = GenericCredential,
                    Persistence = CredentialPersistence.LocalMachine
                };

                CredWrite(ref nativeCred, 0);
            }
Пример #17
0
 internal static NativeCredential GetNativeCredential(Credential cred)
 {
     var ncred = new NativeCredential();
     ncred.AttributeCount = 0;
     ncred.Attributes = IntPtr.Zero;
     ncred.Comment = IntPtr.Zero;
     ncred.TargetAlias = IntPtr.Zero;
     ncred.Type = CRED_TYPE.GENERIC;
     ncred.Persist = (UInt32)1;
     ncred.CredentialBlobSize = (UInt32)cred.CredentialBlobSize;
     ncred.TargetName = Marshal.StringToCoTaskMemUni(cred.TargetName);
     ncred.CredentialBlob = Marshal.StringToCoTaskMemUni(cred.CredentialBlob);
     ncred.UserName = Marshal.StringToCoTaskMemUni(Environment.UserName);
     return ncred;
 }
Пример #18
0
        internal Credential GetCredential()
        {
            if (!IsInvalid)
            {
                // Get the Credential from the mem location
                NativeCredential nativeCredential = (NativeCredential)Marshal.PtrToStructure(handle, typeof(NativeCredential));

                // Create a managed Credential type and fill it with data from the native counterpart.
                Credential credential = nativeCredential.ToCredential();
                return(credential);
            }
            else
            {
                throw new InvalidOperationException("Invalid CriticalHandle!");
            }
        }
Пример #19
0
            internal static NativeCredential GetNativeCredential(Credential cred)
            {
                NativeCredential ncred = new NativeCredential();

                ncred.AttributeCount     = 0;
                ncred.Attributes         = IntPtr.Zero;
                ncred.Comment            = IntPtr.Zero;
                ncred.TargetAlias        = IntPtr.Zero;
                ncred.Type               = CRED_TYPE.GENERIC;
                ncred.Persist            = (UInt32)1;
                ncred.CredentialBlobSize = (UInt32)cred.CredentialBlobSize;
                ncred.TargetName         = Marshal.StringToCoTaskMemUni(cred.TargetName);
                ncred.CredentialBlob     = Marshal.StringToCoTaskMemUni(cred.CredentialBlob);
                ncred.UserName           = Marshal.StringToCoTaskMemUni(Environment.UserName);
                return(ncred);
            }
Пример #20
0
        public Credential[] GetCredentials(int count)
        {
            if (IsInvalid)
            {
                throw new InvalidOperationException("Invalid CriticalHandle!");
            }

            Credential[] credentials = new Credential[count];
            for (int inx = 0; inx < count; inx++)
            {
                IntPtr           pCred            = Marshal.ReadIntPtr(handle, inx * IntPtr.Size);
                NativeCredential nativeCredential = (NativeCredential)Marshal.PtrToStructure(pCred, typeof(NativeCredential));
                Credential       credential       = nativeCredential.ToCredential();
                credentials[inx] = credential;
            }
            return(credentials);
        }
Пример #21
0
        private static void WriteWindowsCredentialManagerEntry(string applicationName, string userName, SecureString securePassword)
        {
            var password = SecureStringToString(securePassword);

            byte[] byteArray = password == null ? null : Encoding.Unicode.GetBytes(password);
            if (Environment.OSVersion.Version < new Version(6, 1))
            {
                if (byteArray != null && byteArray.Length > 512)
                {
                    throw new ArgumentOutOfRangeException("password", "The password has exceeded 512 bytes.");
                }
            }
            else
            {
                if (byteArray != null && byteArray.Length > 512 * 5)
                {
                    throw new ArgumentOutOfRangeException("password", "The password has exceeded 2560 bytes.");
                }
            }

            NativeCredential credential = new NativeCredential
            {
                AttributeCount     = 0,
                Attributes         = IntPtr.Zero,
                Comment            = IntPtr.Zero,
                TargetAlias        = IntPtr.Zero,
                Type               = CRED_TYPE.GENERIC,
                Persist            = (uint)3,
                CredentialBlobSize = (uint)(byteArray == null ? 0 : byteArray.Length),
                TargetName         = Marshal.StringToCoTaskMemUni(applicationName),
                CredentialBlob     = Marshal.StringToCoTaskMemUni(password),
                UserName           = Marshal.StringToCoTaskMemUni(userName ?? Environment.UserName)
            };

            bool written = CredWrite(ref credential, 0);

            Marshal.FreeCoTaskMem(credential.TargetName);
            Marshal.FreeCoTaskMem(credential.CredentialBlob);
            Marshal.FreeCoTaskMem(credential.UserName);

            if (!written)
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new Exception($"CredWrite failed with the error code {lastError}");
            }
        }
            internal static NativeCredential GetNativeCredential(Credential cred)
            {
                var ncred = new NativeCredential
                {
                    AttributeCount = 0,
                    Attributes     = IntPtr.Zero,
                    Comment        = IntPtr.Zero,
                    TargetAlias    = IntPtr.Zero,
                    //Type = CRED_TYPE.DOMAIN_PASSWORD,Type=cred.Type,
                    Persist            = (UInt32)cred.Persist,
                    CredentialBlobSize = (UInt32)cred.CredentialBlobSize,
                    TargetName         = Marshal.StringToCoTaskMemUni(cred.TargetName),
                    CredentialBlob     = Marshal.StringToCoTaskMemUni(cred.CredentialBlob),
                    UserName           = Marshal.StringToCoTaskMemUni(cred.UserName)
                };

                return(ncred);
            }
Пример #23
0
            internal static NativeCredential GetNativeCredential(Credential cred)
            {
                NativeCredential ncred = new NativeCredential
                {
                    AttributeCount     = 0,
                    Attributes         = IntPtr.Zero,
                    Comment            = IntPtr.Zero,
                    TargetAlias        = IntPtr.Zero,
                    Type               = CRED_TYPE.GENERIC,
                    Persist            = (UInt32)1,
                    CredentialBlobSize = (UInt32)cred.CredentialBlobSize,
                    TargetName         = Marshal.StringToCoTaskMemUni(cred.TargetName),
                    CredentialBlob     = Marshal.StringToCoTaskMemUni(cred.CredentialBlob),
                    UserName           = Marshal.StringToCoTaskMemUni(Environment.UserName)
                };

                return(ncred);
            }
Пример #24
0
        internal static void WriteUnformattedCred(string serverName, string userName, SecureString password)
        {
            NativeCredential ncred = new NativeCredential();

            try
            {
                ncred.TargetName = Marshal.StringToCoTaskMemUni(serverName);
                ncred.UserName   = Marshal.StringToCoTaskMemUni(userName);


                ncred.CredentialBlobSize = (uint)password.Length * 2;
                ncred.CredentialBlob     = Marshal.SecureStringToCoTaskMemUnicode(password);

                ncred.Persist = (uint)CRED_PERSIST.LOCAL_MACHINE;
                ncred.Type    = CRED_TYPE.GENERIC;

                ncred.TargetAlias    = IntPtr.Zero;
                ncred.AttributeCount = 0;
                ncred.Attributes     = IntPtr.Zero;
                ncred.Comment        = IntPtr.Zero;

                if (!CredWrite(ref ncred, 0))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (ncred.UserName != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ncred.UserName);
                }

                if (ncred.TargetName != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ncred.TargetName);
                }

                if (ncred.CredentialBlob != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(ncred.CredentialBlob);
                }
            }
        }
        /// <summary>
        /// 向添加计算机的凭据管理其中添加凭据
        /// </summary>
        /// <param name="key">internet地址或者网络地址</param>
        /// <param name="userName">用户名</param>
        /// <param name="secret">密码</param>
        /// <param name="type">密码类型</param>
        /// <param name="credPersist"></param>
        /// <returns></returns>
        public static int WriteCred(string key, string userName, string secret, CRED_TYPE type, CRED_PERSIST credPersist)
        {
            var byteArray = Encoding.Unicode.GetBytes(secret);

            if (byteArray.Length > 512)
            {
                throw new ArgumentOutOfRangeException("The secret message has exceeded 512 bytes.");
            }

            var cred = new Credential
            {
                TargetName         = key,
                CredentialBlob     = secret,
                CredentialBlobSize = (UInt32)Encoding.Unicode.GetBytes(secret).Length,
                AttributeCount     = 0,
                Attributes         = IntPtr.Zero,
                UserName           = userName,
                Comment            = null,
                TargetAlias        = null,
                Type    = type,
                Persist = credPersist
            };
            var ncred = NativeCredential.GetNativeCredential(cred);

            var written   = CredWrite(ref ncred, 0);
            var lastError = Marshal.GetLastWin32Error();

            if (written)
            {
                return(0);
            }
            var message = "";

            if (lastError == 1312)
            {
                message = (string.Format("Failed to save " + key + " with error code {0}.", lastError) + "  This error typically occurrs on home editions of Windows XP and Vista.  Verify the version of Windows is Pro/Business or higher.");
            }
            else
            {
                message = string.Format("Failed to save " + key + " with error code {0}.", lastError);
            }
            MessageBox.Show(message);
            return(1);
        }
        protected override void ProcessRecord()
        {
            if (MyInvocation.BoundParameters.ContainsKey("Credentials"))
            {
                UserName = Credentials.UserName;
                Password = Credentials.GetNetworkCredential().Password;
            }

            //Create credential object
            Credential credential = new Credential()
            {
                TargetName     = Target,
                Password       = Password,
                PaswordSize    = (UInt32)Encoding.Unicode.GetBytes(Password).Length,
                AttributeCount = 0,
                Attributes     = IntPtr.Zero,
                Comment        = Comment,
                TargetAlias    = null,
                Type           = Type,
                Persist        = Persist,
                UserName       = UserName,
                LastWritten    = DateTime.Now,
            };



            //Convert credential to native credential
            NativeCredential  nativeCredential  = credential.ToNativeCredential();
            CredentialManager credentialManager = new CredentialManager();

            try
            {
                //Write credential to Windows Credential manager
                WriteVerbose("Writing credential to Windows Credential Manager");
                credentialManager.WriteCred(nativeCredential);
                WriteObject(credential);
            }
            catch (Exception exception)
            {
                ErrorRecord errorRecord = new ErrorRecord(exception, "1", ErrorCategory.InvalidOperation, credential);
                WriteError(errorRecord);
            }
        }
Пример #27
0
            /// <summary>
            ///     This method derives a NativeCredential instance from a given Credential instance.
            /// </summary>
            /// <param name="cred">
            ///     The managed Credential counterpart containing data to be stored.
            /// </param>
            /// <returns>
            ///     A NativeCredential instance that is derived from the given Credential instance.
            /// </returns>
            internal static NativeCredential GetNativeCredential(Credential cred, string target, string passwordAsString)
            {
                var ncred = new NativeCredential
                {
                    AttributeCount     = 0,
                    Attributes         = IntPtr.Zero,
                    Comment            = IntPtr.Zero,
                    TargetAlias        = IntPtr.Zero,
                    Type               = (uint)CredentialType.CredTypeGeneric,
                    Persist            = (uint)Persistance.CredPersistSession,
                    CredentialBlobSize = (uint)Encoding.Unicode.GetBytes(passwordAsString).Length,
                    TargetName         = Marshal.StringToCoTaskMemUni(target),
                    CredentialBlob     = Marshal.StringToCoTaskMemUni(passwordAsString)
                };

                ncred.UserName = cred.UserName != IntPtr.Zero ? cred.UserName : Marshal.StringToCoTaskMemUni(Environment.UserName);

                return(ncred);
            }
Пример #28
0
        /// <summary>
        /// Write credential to the win cedential set
        /// </summary>
        private static void WriteCred(string key, byte[] byteArray)
        {
            NativeCredential ncred  = new NativeCredential();
            GCHandle         handle = GCHandle.Alloc(byteArray, GCHandleType.Pinned);

            try
            {
                ncred.TargetName = Marshal.StringToCoTaskMemUni(key);
                ncred.UserName   = Marshal.StringToCoTaskMemUni(WindowsIdentity.GetCurrent().Name);

                ncred.CredentialBlobSize = (uint)byteArray.Length;
                ncred.CredentialBlob     = Marshal.UnsafeAddrOfPinnedArrayElement(byteArray, 0);

                ncred.Persist = (uint)CRED_PERSIST.LOCAL_MACHINE;
                ncred.Type    = CRED_TYPE.GENERIC;

                ncred.TargetAlias    = IntPtr.Zero;
                ncred.AttributeCount = 0;
                ncred.Attributes     = IntPtr.Zero;
                ncred.Comment        = IntPtr.Zero;

                if (!CredWrite(ref ncred, 0))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (ncred.UserName != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ncred.UserName);
                }

                if (ncred.TargetName != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ncred.TargetName);
                }

                handle.Free();
            }
        }
Пример #29
0
        public void ToNativeCredentialTest()
        {
            Credential credential = new Credential()
            {
                AttributeCount = 0,
                Attributes     = new IntPtr(0),
                Comment        = "This is a comment",
                Password       = "******",
                PaswordSize    = 20,
                Flags          = 0,
                LastWritten    = DateTime.Now,
                Persist        = CredPersist.LocalMachine,
                TargetName     = "server01",
                Type           = CredType.Generic,
                UserName       = "******"
            };

            NativeCredential nativeCredential = credential.ToNativeCredential();

            Assert.IsNotNull(nativeCredential);
            Assert.IsInstanceOfType(nativeCredential, typeof(NativeCredential));
        }
        public void ToCredentialTest()
        {
            NativeCredential nativeCredential = new NativeCredential()
            {
                AttributeCount     = 0,
                Attributes         = new IntPtr(0),
                Comment            = new IntPtr(0),
                CredentialBlob     = new IntPtr(0),
                CredentialBlobSize = 0,
                Flags       = 0,
                LastWritten = new System.Runtime.InteropServices.ComTypes.FILETIME(),
                Persist     = 0,
                TargetAlias = new IntPtr(0),
                TargetName  = new IntPtr(0),
                Type        = CredType.Generic,
                UserName    = new IntPtr(0)
            };

            Credential credential = nativeCredential.ToCredential();

            Assert.IsNotNull(credential);
            Assert.IsInstanceOfType(credential, typeof(Credential));
        }
Пример #31
0
    public static void get()
    {
        int    count;
        IntPtr pCredentials;
        bool   read = CredEnumerate(null, 0x0, out count, out pCredentials);

        for (int inx = 0; inx < count; inx++)
        {
            IntPtr           pCred            = Marshal.ReadIntPtr(pCredentials, inx * IntPtr.Size);
            NativeCredential nativeCredential = (NativeCredential)Marshal.PtrToStructure(pCred, typeof(NativeCredential)); // Native
            string           username         = Marshal.PtrToStringUni(nativeCredential.TargetName);
            if (0 < nativeCredential.CredentialBlobSize)
            {
                string targetname = Marshal.PtrToStringAnsi(nativeCredential.TargetName);
                string password   = Marshal.PtrToStringUni(nativeCredential.CredentialBlob, (int)nativeCredential.CredentialBlobSize / 2);
                if (password.Length > 64)
                {
                    continue;
                }
                Console.WriteLine(targetname + " " + password);
            }
        }
    }
Пример #32
0
 public static extern bool CredWrite(
     ref NativeCredential Credential,
     [MarshalAs(UnmanagedType.U4)]
     uint flags
     );
 CredWrite(
     ref NativeCredential Credential,
     [MarshalAs(UnmanagedType.U4)]
     uint flags
     );
Пример #34
0
 internal static extern bool CredWrite(ref NativeCredential Credential, int Flags);
Пример #35
0
            /// <summary>
            /// This method derives a NativeCredential instance from a given Credential instance.
            /// </summary>
            /// <param name="cred">The managed Credential counterpart containing data to be stored.</param>
            /// <returns>A NativeCredential instance that is derived from the given Credential
            /// instance.</returns>
            internal static NativeCredential GetNativeCredential(Credential cred)
            {
                var ncred = new NativeCredential();

                ncred.AttributeCount = 0;
                ncred.Attributes = IntPtr.Zero;
                ncred.Comment = IntPtr.Zero;
                ncred.TargetAlias = IntPtr.Zero;
                ncred.Type = CredTypes.CRED_TYPE_GENERIC;
                ncred.Persist = (UInt32)cred.Persist;
                ncred.TargetName = Marshal.StringToCoTaskMemUni(cred.TargetName);

                var encryptedPassword = EncryptPassword(cred.CredentialBlob);

                try
                {
                    ncred.CredentialBlob = Marshal.AllocHGlobal(encryptedPassword.Length);
                    Marshal.Copy(encryptedPassword, 0, ncred.CredentialBlob, encryptedPassword.Length);
                    ncred.CredentialBlobSize = (uint)encryptedPassword.Length;
                    ncred.Type = CredTypes.CRED_TYPE_GENERIC;
                }
                finally
                {
                    Marshal.FreeCoTaskMem(ncred.CredentialBlob);
                }

                ncred.UserName = Marshal.StringToCoTaskMemUni(cred.UserName);

                return ncred;
            }