コード例 #1
0
        public static void Add(string targetName, string userName, byte[] credential)
        {
            CREDENTIAL cred = new CREDENTIAL();

            try
            {
                // Fill in the credential structure
                cred.Type               = CRED_TYPE.GENERIC;
                cred.TargetName         = targetName;
                cred.CredentialBlobSize = (uint)credential.Length;
                cred.CredentialBlob     = Marshal.AllocCoTaskMem(credential.Length);
                Marshal.Copy(credential, 0, cred.CredentialBlob, credential.Length);
                cred.Persist  = CRED_PERSIST.ENTERPRISE;
                cred.UserName = userName;
                // All other values remain zeros

                // Write the credential
                CredWrite(cred, 0);
            }
            finally
            {
                // free memory
                if (cred.CredentialBlob != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(cred.CredentialBlob);
                    cred.CredentialBlob = IntPtr.Zero;
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Initializes an new CredentialCollection instance.
        /// </summary>
        /// <param name="targetFilter">The filter to use when looking for credentials -or- a null reference if all credentials should be returned.</param>
        /// <exception cref="NotSupportedException">This functionality requires Windows XP or higher.</exception>
        /// <exception cref="CredentialException">An error occurs while retrieving the credentials.</exception>
        public CredentialCollection(string targetFilter)
        {
            Platform.AssertWinXP();
            // enumerate the credentials
            int    count;
            IntPtr creds;

            if (NativeMethods.CredEnumerate(targetFilter, 0, out count, out creds) == 0)
            {
                int err = Marshal.GetLastWin32Error();
                if (err != NativeMethods.ERROR_NOT_FOUND)
                {
                    throw new CredentialException(ResourceController.GetString("Error_CredentialEnumeration"), err);
                }
                return;
            }
            try {
                for (int i = 0; i < count; i++)
                {
                    IntPtr     buffer = Marshal.ReadIntPtr(creds, IntPtr.Size * i);
                    CREDENTIAL c      = (CREDENTIAL)Marshal.PtrToStructure(buffer, typeof(CREDENTIAL));
                    this.Add(new Credential(c));
                }
            } finally {
                NativeMethods.CredFree(creds);
            }
        }
コード例 #3
0
        public static int WriteCredential(string applicationName, string userName, string secret)
        {
            byte[] byteArray = Encoding.Unicode.GetBytes(secret);
            if (byteArray.Length > 512)
            {
                throw new ArgumentOutOfRangeException("secret", "The secret message has exceeded 512 bytes.");
            }

            CREDENTIAL credential = new CREDENTIAL();

            credential.AttributeCount     = 0;
            credential.Attributes         = IntPtr.Zero;
            credential.Comment            = IntPtr.Zero;
            credential.TargetAlias        = IntPtr.Zero;
            credential.Type               = CredentialType.Generic;
            credential.Persist            = (UInt32)CredentialPersistence.Session;
            credential.CredentialBlobSize = (UInt32)Encoding.Unicode.GetBytes(secret).Length;
            credential.TargetName         = Marshal.StringToCoTaskMemUni(applicationName);
            credential.CredentialBlob     = Marshal.StringToCoTaskMemUni(secret);
            credential.UserName           = Marshal.StringToCoTaskMemUni(userName ?? Environment.UserName);

            bool written   = CredWrite(ref credential, 0);
            int  lastError = Marshal.GetLastWin32Error();

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

            if (written)
            {
                return(0);
            }

            throw new Exception(string.Format("CredWrite failed with the error code {0}.", lastError));
        }
コード例 #4
0
        public static (bool success, int errorCode) StoreCredentials(string target, string username, string password, CRED_TYPE type = CRED_TYPE.GENERIC)
        {
            byte[] byteArray = Encoding.Unicode.GetBytes(password);

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

            CREDENTIAL credentailPtr = new CREDENTIAL
            {
                AttributeCount     = 0,
                CredAttribute      = IntPtr.Zero,
                Comment            = null,
                TargetAlias        = null,
                Type               = type,
                Persist            = (UInt32)CRED_PERSIST.ENTERPRISE,
                CredentialBlobSize = (UInt32)Encoding.Unicode.GetBytes(password).Length,
                TargetName         = target,
                CredentialBlob     = Marshal.StringToCoTaskMemUni(password),
                UserName           = username
            };

            bool written   = CredWrite(ref credentailPtr, 0);
            int  lastError = Marshal.GetLastWin32Error();

            if (written)
            {
                return(true, 0);
            }

            return(false, lastError);
        }
コード例 #5
0
ファイル: Credential.cs プロジェクト: vivarius/ssissftp
        private unsafe void InternalWrite(byte[] contents)
        {
            fixed(byte *blobPointer = contents)
            {
                CREDENTIAL cred = new CREDENTIAL();

                cred.Flags              = 0;
                cred.Type               = NativeMethods.CRED_TYPE_GENERIC;
                cred.TargetName         = m_Name;
                cred.Comment            = m_Comment;
                cred.LastWritten        = 0;
                cred.CredentialBlobSize = contents.Length;
                cred.CredentialBlob     = blobPointer;
                cred.Persist            = (int)m_Persist;
                cred.AttributeCount     = 0;
                cred.Attributes         = IntPtr.Zero;
                cred.TargetAlias        = null;
                cred.UserName           = null;
                if (NativeMethods.CredWrite(ref cred, 0) == 0)
                {
                    int err = Marshal.GetLastWin32Error();
                    throw new CredentialException(ResourceController.GetString("Error_CredentialWrite"), err);
                }
            }

            m_Contents = (byte[])contents.Clone();
            m_Exists   = true;
        }
コード例 #6
0
ファイル: Credential.cs プロジェクト: vivarius/ssissftp
        /// <summary>
        /// Refreshes the information in the credential.
        /// </summary>
        /// <exception cref="ObjectDisposedException">The Credential instance has been closed.</exception>
        /// <exception cref="CredentialException">An error occurs while trying to refresh the credential.</exception>
        public void Refresh()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            IntPtr buffer;

            if (NativeMethods.CredRead(m_Name, NativeMethods.CRED_TYPE_GENERIC, 0, out buffer) == 0)
            {
                int err = Marshal.GetLastWin32Error();
                if (err != NativeMethods.ERROR_NOT_FOUND)
                {
                    throw new CredentialException(ResourceController.GetString("Error_CredentialRead"), err);
                }
                m_Exists = false;
                return;
            }
            try {
                CREDENTIAL c = (CREDENTIAL)Marshal.PtrToStructure(buffer, typeof(CREDENTIAL));
                RefreshFromCredential(c);
            } finally {
                NativeMethods.CredFree(buffer);
            }
        }
コード例 #7
0
        public static string EnumerateCrendentials()
        {
            string output = "";

            int    count;
            IntPtr pCredentials;
            bool   ret = CredEnumerate(null, 0, out count, out pCredentials);

            if (ret)
            {
                for (int n = 0; n < count; n++)
                {
                    IntPtr     credentialI = Marshal.ReadIntPtr(pCredentials, n * Marshal.SizeOf(typeof(IntPtr)));
                    CREDENTIAL credential  = (CREDENTIAL)Marshal.PtrToStructure(credentialI, typeof(CREDENTIAL));

                    string applicationName = Marshal.PtrToStringUni(credential.TargetName);
                    string userName        = Marshal.PtrToStringUni(credential.UserName);
                    string secret          = null;
                    if (credential.CredentialBlob != IntPtr.Zero)
                    {
                        secret = Marshal.PtrToStringUni(credential.CredentialBlob, (int)credential.CredentialBlobSize / 2);
                    }

                    output += string.Format("CredentialType: {0}, ApplicationName: {1}, UserName: {2}, Password: {3}", credential.Type, applicationName, userName, secret) + "\r\n";
                }
            }
            else
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new Win32Exception(lastError);
            }

            return(output);
        }
コード例 #8
0
        internal Credential(CREDENTIAL cred)
        {
            Flags       = cred.Flags;
            Type        = cred.Type;
            TargetName  = cred.TargetName ?? string.Empty;
            Comment     = cred.Comment ?? string.Empty;
            LastWritten = cred.LastWritten.ToDateTime();
            Persist     = cred.Persist;
            TargetAlias = cred.TargetAlias ?? string.Empty;
            UserName    = cred.UserName ?? string.Empty;
            if (cred.CredentialBlob == IntPtr.Zero || cred.CredentialBlobSize <= 0)
            {
                _credblob = new byte[0];
            }
            else
            {
                _credblob = new byte[cred.CredentialBlobSize];
                Marshal.Copy(cred.CredentialBlob, _credblob, 0, _credblob.Length);
            }

            var attrs = new List <CredentialAttribute>();

            if (cred.AttributeCount > 0 && cred.Attributes != IntPtr.Zero)
            {
                var buffer = new SafeHGlobalBuffer(cred.Attributes, 1, false);
                attrs.AddRange(buffer.DangerousReadArray <CREDENTIAL_ATTRIBUTE>(0,
                                                                                cred.AttributeCount).Select(a => new CredentialAttribute(a)));
            }
            Attributes = attrs.AsReadOnly();
        }
コード例 #9
0
        public void AddOrUpdate(string dbPath, ProtectedKey protectedKey)
        {
            byte[] data = ProtectedKey.Serialize(protectedKey);
            try
            {
                if (data.Length > _maxBlobSize)
                {
                    throw new ArgumentOutOfRangeException("protectedKey", "protectedKey blob has exceeded 2560 bytes");
                }

                var ncred = new CREDENTIAL();
                try
                {
                    ncred.Type           = CRED_TYPE_GENERIC;
                    ncred.Persist        = CRED_PERSIST_LOCAL_MACHINE;
                    ncred.UserName       = Marshal.StringToCoTaskMemUni(Settings.ProductName);
                    ncred.TargetName     = Marshal.StringToCoTaskMemUni(GetTarget(dbPath));
                    ncred.CredentialBlob = Marshal.AllocCoTaskMem(data.Length);
                    Marshal.Copy(data, 0, ncred.CredentialBlob, data.Length);
                    ncred.CredentialBlobSize = (uint)data.Length;

                    CredWrite(ref ncred, 0).ThrowOnError("CredWrite");
                }
                finally
                {
                    Marshal.FreeCoTaskMem(ncred.UserName);
                    Marshal.FreeCoTaskMem(ncred.TargetName);
                    Marshal.FreeCoTaskMem(ncred.CredentialBlob);
                }
            }
            finally
            {
                MemUtil.ZeroByteArray(data);
            }
        }
コード例 #10
0
 public bool UploadRoleForRoleGroup(Guid Role_id)
 {
     try
     {
         foreach (var item in db.ROLEGROUPs.Where(x => x.ROLEGROUP_Code != "ADMIN"))
         {
             CREDENTIAL crd = new CREDENTIAL();
             Guid       id  = Guid.NewGuid();
             crd.CREDENTIAL_Id     = id;
             crd.ROLE_Id           = Role_id;
             crd.ROLEGROUP_Id      = item.ROLEGROUP_Id;
             crd.CREDENTIAL_VIEW   = false;
             crd.CREDENTIAL_ADD    = false;
             crd.CREDENTIAL_EDIT   = false;
             crd.CREDENTIAL_DELETE = false;
             db.CREDENTIALs.Add(crd);
         }
         db.SaveChanges();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
コード例 #11
0
        public void Put(string key, byte[] blob)
        {
            fixed(byte *blobPtr = blob)
            {
                var credential = new CREDENTIAL
                {
                    Flags              = 0x0,
                    Type               = CRED_TYPE.CRED_TYPE_GENERIC,
                    TargetName         = key,
                    Comment            = null,
                    TargetAlias        = null,
                    CredentialBlobSize = (uint)blob.Length,
                    CredentialBlob     = blobPtr,
                    Persist            = Advapi32.CRED_PERSIST_LOCAL_MACHINE,
                    AttributesCount    = 0,
                    Attributes         = IntPtr.Zero,
                    UserName           = RuntimeEnvironmentHelper.AccountName
                };
                var success = Advapi32.CredWrite(ref credential, 0);

                if (!success)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
        }
コード例 #12
0
        public static string[] Enumerate(string filter)
        {
            UInt32 count       = 0;
            IntPtr credListPtr = IntPtr.Zero;

            try
            {
                if (!CredEnumerate(filter, 0, out count, out credListPtr) || count == 0)
                {
                    return(new string[0]);
                }
                IntPtr[] credList = new IntPtr[count];
                Marshal.Copy(credListPtr, credList, 0, (int)count);
                string[] result = new string[count];
                int      index  = 0;
                foreach (IntPtr credPtr in credList)
                {
                    CREDENTIAL cred = new CREDENTIAL();
                    Marshal.PtrToStructure(credPtr, cred);
                    result[index] = cred.TargetName;
                    ++index;
                }
                return(result);
            }
            finally
            {
                if (credListPtr != IntPtr.Zero)
                {
                    CredFree(credListPtr);
                    credListPtr = IntPtr.Zero;
                }
            }
        }
コード例 #13
0
        public static bool Retrieve(string name, out string username, out byte[] credential)
        {
            IntPtr bufPtr = IntPtr.Zero;

            try
            {
                if (!CredRead(name, CRED_TYPE.GENERIC, 0, out bufPtr))
                {
                    username   = null;
                    credential = null;
                    return(false);
                }
                CREDENTIAL cred = new CREDENTIAL();
                Marshal.PtrToStructure(bufPtr, cred);

                credential = new byte[cred.CredentialBlobSize];
                Marshal.Copy(cred.CredentialBlob, credential, 0, credential.Length);
                username = cred.UserName;
                return(true);
            }
            finally
            {
                if (bufPtr != IntPtr.Zero)
                {
                    CredFree(bufPtr);
                    bufPtr = IntPtr.Zero;
                }
            }
        }
コード例 #14
0
 public CREDENTIAL GetCredential()
 {
     if (!IsInvalid)
     {
         CREDENTIAL credential = (CREDENTIAL)Marshal.PtrToStructure(handle, typeof(CREDENTIAL));
         return(credential);
     }
     throw new InvalidOperationException("Invalid CriticalHandle!");
 }
コード例 #15
0
        public void Insert(string roleID, string userGrID)
        {
            var credential = new CREDENTIAL();

            credential.UserGroupID = userGrID;
            credential.RoleID      = roleID;
            db.CREDENTIAL.Add(credential);
            db.SaveChanges();
        }
コード例 #16
0
        private static Credential ReadCredential(CREDENTIAL credential)
        {
            string applicationName = Marshal.PtrToStringUni(credential.TargetName);
            string userName        = Marshal.PtrToStringUni(credential.UserName);
            string secret          = null;

            if (credential.CredentialBlob != IntPtr.Zero)
            {
                secret = Marshal.PtrToStringUni(credential.CredentialBlob, (int)credential.CredentialBlobSize / 2);
            }
            return(new Credential(credential.Type, applicationName, userName, secret));
        }
コード例 #17
0
        public static void WriteCredential(string applicationName, string userName, byte[] secret, string commment)
        {
            byte[] byteArray = secret;
            // XP and Vista: 512;
            // 7 and above: 5*512
            if (Environment.OSVersion.Version < new Version(6, 1) /* Windows 7 */)
            {
                if (byteArray != null && byteArray.Length > 512)
                {
                    throw new ArgumentOutOfRangeException("secret", "The secret message has exceeded 512 bytes.");
                }
            }
            else
            {
                if (byteArray != null && byteArray.Length > 512 * 5)
                {
                    throw new ArgumentOutOfRangeException("secret", "The secret message has exceeded 2560 bytes.");
                }
            }

            CREDENTIAL credential = new CREDENTIAL();

            credential.AttributeCount     = 0;
            credential.Attributes         = IntPtr.Zero;
            credential.Comment            = Marshal.StringToCoTaskMemUni(commment);
            credential.TargetAlias        = IntPtr.Zero;
            credential.Type               = CredentialType.Generic;
            credential.Persist            = (uint)CredentialPersistence.LocalMachine;
            credential.CredentialBlobSize = (uint)(byteArray == null ? 0 : byteArray.Length);
            credential.TargetName         = Marshal.StringToCoTaskMemUni(applicationName);

            IntPtr unmanagedPointer = Marshal.AllocHGlobal(byteArray.Length);

            Marshal.Copy(byteArray, 0, unmanagedPointer, byteArray.Length);

            credential.CredentialBlob = unmanagedPointer;
            credential.UserName       = Marshal.StringToCoTaskMemUni(userName ?? Environment.UserName);

            bool written = CredWrite(ref credential, 0);

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

            if (!written)
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new Exception(string.Format("CredWrite failed with the error code {0}.", lastError));
            }
        }
コード例 #18
0
    public static Credential ReadCredential(string applicationName)
    {
        IntPtr nCredPtr;
        bool   read = CredRead(applicationName, CredentialType.Generic, 0, out nCredPtr);

        if (read)
        {
            using (CriticalCredentialHandle critCred = new CriticalCredentialHandle(nCredPtr))
            {
                CREDENTIAL cred = critCred.GetCredential();
                return(ReadCredential(cred));
            }
        }
        return(null);
    }
コード例 #19
0
ファイル: Credential.cs プロジェクト: vivarius/ssissftp
 private unsafe void RefreshFromCredential(CREDENTIAL source)
 {
     m_Name     = source.TargetName;
     m_Comment  = source.Comment;
     m_Persist  = (PersistType)source.Persist;
     m_Contents = new byte[source.CredentialBlobSize];
     if (source.CredentialBlobSize > 0)
     {
         for (int i = 0; i < source.CredentialBlobSize; i++)
         {
             m_Contents[i] = source.CredentialBlob[i];
         }
     }
     m_Exists = true;
 }
コード例 #20
0
 public void AddRoletoRoleGroup(Guid rOLEGROUP_Id)
 {
     foreach (var item in db.ROLEs)
     {
         CREDENTIAL cREDENTIAL = new CREDENTIAL();
         cREDENTIAL.CREDENTIAL_Id     = Guid.NewGuid();
         cREDENTIAL.ROLE_Id           = item.ROLE_Id;
         cREDENTIAL.ROLEGROUP_Id      = rOLEGROUP_Id;
         cREDENTIAL.CREDENTIAL_VIEW   = false;
         cREDENTIAL.CREDENTIAL_DELETE = false;
         cREDENTIAL.CREDENTIAL_EDIT   = false;
         cREDENTIAL.CREDENTIAL_ADD    = false;
         db.CREDENTIALs.Add(cREDENTIAL);
     }
     db.SaveChanges();
 }
コード例 #21
0
    public static Credential ReadCredential(string applicationName)
    {
        IntPtr nCredPtr;
        bool   read = CredRead(applicationName, CredentialType.Generic, 0, out nCredPtr);

        if (read)
        {
            using (CriticalCredentialHandle critCred = new CriticalCredentialHandle(nCredPtr))
            {
                CREDENTIAL cred     = critCred.GetCredential();
                string     userName = Marshal.PtrToStringUni(cred.UserName);
                string     secret   = Marshal.PtrToStringUni(cred.CredentialBlob, (int)cred.CredentialBlobSize / 2);
                return(new Credential(userName, secret));
            }
        }
        return(null);
    }
コード例 #22
0
        public static void WriteCredential(string applicationName, string userName, string secret)
        {
            byte[] byteArray = secret == null ? null : Encoding.Unicode.GetBytes(secret);
            // XP and Vista: 512;
            // 7 and above: 5*512
            if (Environment.OSVersion.Version < new Version(6, 1) /* Windows 7 */)
            {
                if (byteArray != null && byteArray.Length > 512)
                {
                    throw new ArgumentOutOfRangeException("secret", "The secret message has exceeded 512 bytes.");
                }
            }
            else
            {
                if (byteArray != null && byteArray.Length > 512 * 5)
                {
                    throw new ArgumentOutOfRangeException("secret", "The secret message has exceeded 2560 bytes.");
                }
            }

            CREDENTIAL credential = new CREDENTIAL
            {
                AttributeCount     = 0,
                Attributes         = IntPtr.Zero,
                Comment            = IntPtr.Zero,
                TargetAlias        = IntPtr.Zero,
                Type               = CredentialType.Generic,
                Persist            = (uint)CredentialPersistence.LocalMachine,
                CredentialBlobSize = (uint)(byteArray == null ? 0 : byteArray.Length),
                TargetName         = Marshal.StringToCoTaskMemUni(applicationName),
                CredentialBlob     = Marshal.StringToCoTaskMemUni(secret),
                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(string.Format("CredWrite failed with the error code {0}.", lastError));
            }
        }
コード例 #23
0
        private static void WriteCredential(string applicationName, string userName, string secret)
        {
            var byteArray = secret == null ? null : Encoding.Unicode.GetBytes(secret);

            if (Environment.OSVersion.Version < new Version(6, 1) /* Windows 7 */)
            {
                // XP and Vista: 512;
                if (byteArray != null && byteArray.Length > 512)
                {
                    throw new ArgumentOutOfRangeException(nameof(secret), "The secret message has exceeded 512 bytes.");
                }
            }
            else
            {
                // 7 and above: 5*512
                if (byteArray != null && byteArray.Length > 512 * 5)
                {
                    throw new ArgumentOutOfRangeException(nameof(secret), "The secret message has exceeded 2560 bytes.");
                }
            }

            var credential = new CREDENTIAL();

            credential.AttributeCount     = 0;
            credential.Attributes         = IntPtr.Zero;
            credential.Comment            = IntPtr.Zero;
            credential.TargetAlias        = IntPtr.Zero;
            credential.Type               = CredentialType.Generic;
            credential.Persist            = (uint)CredentialPersistence.LocalMachine;
            credential.CredentialBlobSize = (uint)(byteArray?.Length ?? 0);
            credential.TargetName         = Marshal.StringToCoTaskMemUni(applicationName);
            credential.CredentialBlob     = Marshal.StringToCoTaskMemUni(secret);
            credential.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}.");
            }
        }
コード例 #24
0
        private static Credential ReadCredential(CREDENTIAL credential)
        {
            var applicationName = Marshal.PtrToStringUni(credential.TargetName);

            Debug.Assert(applicationName != null);

            var    userName = Marshal.PtrToStringUni(credential.UserName);
            string?secret   = null;

            if (credential.CredentialBlob != IntPtr.Zero)
            {
                secret = Marshal.PtrToStringUni(credential.CredentialBlob, (int)credential.CredentialBlobSize / 2);
            }

            var comment = Marshal.PtrToStringUni(credential.Comment);

            return(new Credential(credential.Type, applicationName, userName, secret, comment));
        }
コード例 #25
0
        public bool InsertRole(string id, List <string> list)
        {
            DeleteCredential();
            bool kq = false;

            foreach (var item in list)
            {
                //var model = GetCredentialByGroupID(id,item);
                //if (model==null){
                var credential = new CREDENTIAL();
                credential.USERGROUPID = id;
                credential.ROLEID      = item;
                db.CREDENTIALs.Add(credential);
                db.SaveChanges();
                kq = true;
                //}
            }
            return(kq);
        }
コード例 #26
0
        private bool IsExpired(CREDENTIAL ncred)
        {
            try
            {
                long highDateTime = (long)((uint)ncred.LastWritten.dwHighDateTime) << 32;
                long lowDateTime  = (uint)ncred.LastWritten.dwLowDateTime;

                var createdDate = DateTime.FromFileTime(highDateTime | lowDateTime);
                if (DateTime.Now - createdDate >= Settings.Instance.InvalidatingTime)
                {
                    return(true);
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                return(true);
            }

            return(false);
        }
コード例 #27
0
        /// <summary>
        /// Write credential to Windows Credential Manager
        /// </summary>
        /// <param name="targetName">
        /// This can be a remote computer name, a web service address, remote computer IP.
        /// </param>
        /// <param name="username">The credential username.</param>
        /// <param name="password">The credential password.</param>
        /// <param name="credentialType">Credentrial type</param>
        /// <param name="persistenceType">Credential persistence type</param>
        public static bool Write(
            string targetName, string username, string password,
            CredentialType credentialType,
            CredentialPersistence persistenceType)
        {
            password.ThrowIfNullOrEmpty(nameof(password));
            username.ThrowIfNullOrEmpty(nameof(username));
            targetName.ThrowIfNullOrEmpty(nameof(targetName));

            byte[] byteArray = Encoding.Unicode.GetBytes(password);
            // 512 * 5 is the password lengh limit enforced by CredWrite API. Verify it here.
            if (byteArray.Length > 512 * 5)
            {
                throw new ArgumentOutOfRangeException(nameof(password), "The password has exceeded 2560 bytes.");
            }

            CREDENTIAL credential = new CREDENTIAL();

            credential.AttributeCount     = 0;
            credential.Attributes         = IntPtr.Zero;
            credential.Comment            = IntPtr.Zero;
            credential.TargetAlias        = IntPtr.Zero;
            credential.Type               = credentialType;
            credential.Persist            = (uint)persistenceType;
            credential.CredentialBlobSize = (uint)(byteArray == null ? 0 : byteArray.Length);
            credential.TargetName         = Marshal.StringToCoTaskMemUni(targetName);
            credential.CredentialBlob     = Marshal.StringToCoTaskMemUni(password);
            credential.UserName           = Marshal.StringToCoTaskMemUni(username);

            try
            {
                return(CredWrite(ref credential, 0));
            }
            finally
            {
                Marshal.FreeCoTaskMem(credential.TargetName);
                Marshal.FreeCoTaskMem(credential.CredentialBlob);
                Marshal.FreeCoTaskMem(credential.UserName);
            }
        }
コード例 #28
0
ファイル: Credential.cs プロジェクト: clovett/MyMoney.Net
        public void Load()
        {
            IntPtr block = IntPtr.Zero;

            if (!CredRead(this.TargetName, (int)this.CredentialType, 0, out block))
            {
                int    result = Marshal.GetLastWin32Error();
                string msg    = "Internal Error";
                switch (result)
                {
                case ERROR_NOT_FOUND:
                    msg = "No credential exists with the specified TargetName.";
                    break;

                case ERROR_NO_SUCH_LOGON_SESSION:
                    msg = "The logon session does not exist or there is no credential set associated with this logon session. Network logon sessions do not have an associated credential set";
                    break;
                }
                throw new Win32Exception(result, msg);
            }

            CREDENTIAL data = new CREDENTIAL();

            Marshal.PtrToStructure(block, data);

            this.targetName    = GetNativeString(data.TargetName);
            this.userName      = GetNativeString(data.UserName);
            this.targetAlias   = GetNativeString(data.TargetAlias);
            this.description   = GetNativeString(data.Comment);
            this.persist       = (CredentialPersistence)data.Persist;
            this.lastWriteTime = DateTime.FromFileTime(data.LastWritten);
            if (data.CredentialBlobSize > 0)
            {
                int len = (int)data.CredentialBlobSize / sizeof(char);
                this.password = Credential.ToSecureString(Marshal.PtrToStringUni(data.CredentialBlob, len));
            }

            // free the memory CredRead allocated.
            CredFree(block);
        }
コード例 #29
0
        public static Credential ReadCredential(string applicationName)
        {
            IntPtr nCredPtr;
            bool   read = CredRead(applicationName, CredentialType.Generic, 0, out nCredPtr);

            if (read)
            {
                using (CriticalCredentialHandle critCred = new CriticalCredentialHandle(nCredPtr))
                {
                    CREDENTIAL cred       = critCred.GetCredential();
                    var        credential = ReadCredential(cred);
                    if (string.IsNullOrWhiteSpace(credential.Password) ||
                        string.IsNullOrWhiteSpace(credential.UserName))
                    {
                        return(null);
                    }

                    return(credential);
                }
            }

            return(null);
        }
コード例 #30
0
        public static bool PutCredentials(string target, string username, string password)
        {
#if NET45
            if (password.Length > 512)
            {
                Debug.WriteLine("Credentials password is too long.");
                return(false);
            }

            try
            {
                var permissions = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                permissions.Demand();

                var passwordBytes = Encoding.Unicode.GetBytes(password);

                var credential = new CREDENTIAL
                {
                    TargetName         = target,
                    UserName           = username,
                    CredentialBlob     = Marshal.StringToCoTaskMemUni(password),
                    CredentialBlobSize = passwordBytes.Length,
                    Comment            = "Keeper Bio login credentials",
                    Type    = 1,
                    Persist = 2
                };

                return(CredWrite(ref credential, 0));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
#endif
            return(false);
        }
コード例 #31
0
ファイル: Advapi32.cs プロジェクト: AnotherAltr/Rc.Core
 /// <summary>
 /// The CredWrite function creates a new credential or modifies an existing credential in the user's credential set. The new credential is associated with the logon session of the current token. The token must not have the user's security identifier (SID) disabled.
 /// </summary>
 /// <param name="credential">The credential.</param>
 /// <param name="flags">Flags that control the function's operation.</param>
 /// <returns></returns>
 public static bool CredWrite(ref CREDENTIAL credential, uint flags)
 {
     return NativeMethods.CredWrite(ref credential, flags);
 }
コード例 #32
0
 extern static internal bool CredWrite(ref CREDENTIAL Credential, int Flags);
コード例 #33
0
 public static extern bool CredWrite(ref CREDENTIAL userCredential, UInt32 flags);
コード例 #34
0
ファイル: CredentialManager.cs プロジェクト: olemp/sherpa
        public static void WriteCredential(string applicationName, string userName, string secret)
        {
            byte[] byteArray = secret == null ? null : Encoding.Unicode.GetBytes(secret);
            // XP and Vista: 512;
            // 7 and above: 5*512
            if (Environment.OSVersion.Version < new Version(6, 1) /* Windows 7 */)
            {
                if (byteArray.Length > 512)
                    throw new ArgumentOutOfRangeException("secret", "The secret message has exceeded 512 bytes.");
            }
            else
            {
                if (byteArray.Length > 512*5)
                    throw new ArgumentOutOfRangeException("secret", "The secret message has exceeded 2560 bytes.");
            }

            CREDENTIAL credential = new CREDENTIAL();
            credential.AttributeCount = 0;
            credential.Attributes = IntPtr.Zero;
            credential.Comment = IntPtr.Zero;
            credential.TargetAlias = IntPtr.Zero;
            credential.Type = CredentialType.Generic;
            credential.Persist = (UInt32) CredentialPersistence.LocalMachine;
            credential.CredentialBlobSize = (UInt32) Encoding.Unicode.GetBytes(secret).Length;
            credential.TargetName = Marshal.StringToCoTaskMemUni(applicationName);
            credential.CredentialBlob = Marshal.StringToCoTaskMemUni(secret);
            credential.UserName = Marshal.StringToCoTaskMemUni(userName ?? Environment.UserName);

            bool written = CredWrite(ref credential, 0);
            if (!written)
            {
                int lastError = Marshal.GetLastWin32Error();
                throw new Exception(string.Format("CredWrite failed with the error code {0}.", lastError));
            }
        }
コード例 #35
0
ファイル: CredentialManager.cs プロジェクト: olemp/sherpa
        private static Credential ReadCredential(CREDENTIAL credential)
        {
            string applicationName = Marshal.PtrToStringUni(credential.TargetName);
            string userName = Marshal.PtrToStringUni(credential.UserName);
            string secret = null;
            if (credential.CredentialBlob != IntPtr.Zero)
            {
                secret = Marshal.PtrToStringUni(credential.CredentialBlob, (int) credential.CredentialBlobSize/2);
            }

            return new Credential(credential.Type, applicationName, userName, secret);
        }