public object CheckSsoCertificate()
        {
            CheckSsoPermissions();

            var log = LogManager.GetLogger(typeof(SettingsApi));

            try
            {
                var settings = SsoSettings.Load();

                if (!string.IsNullOrEmpty(settings.ClientPassword))
                {
                    settings.ClientPassword = InstanceCrypto.Decrypt(settings.ClientPassword);
                }

                return(new
                {
                    success = true,
                    exist = GetCertificate(settings.ClientCertificateFileName, settings.ClientPassword, log) != null
                });
            }
            catch (Exception exception)
            {
                log.Error(exception);

                return(new
                {
                    success = false,
                    message = exception.Message
                });
            }
        }
        private string GetPassword(object passwordBytesObject)
        {
            string password = string.Empty;

            try
            {
                if (passwordBytesObject != null)
                {
                    object[] passwordBytesObjects = (object[])passwordBytesObject;
                    byte[]   passwordBytes        = new byte[passwordBytesObjects.Length];
                    for (int i = 0; i < passwordBytesObjects.Length; i++)
                    {
                        passwordBytes[i] = Convert.ToByte(passwordBytesObjects[i]);
                    }
                    if (passwordBytes.Length != 0)
                    {
                        password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(passwordBytes));
                    }
                }
            }
            catch (Exception ex)
            {
                password = string.Empty;
                log.ErrorFormat("Can't decrypt password {0}, {1}", ex.ToString(), ex.StackTrace);
            }
            return(password);
        }
Beispiel #3
0
        private List <DirectoryEntry> Search(string rootDistinguishedName, string filter, SearchScope scope,
                                             LDAPSupportSettings settings)
        {
            var type = AuthenticationTypes.ReadonlyServer | AuthenticationTypes.Secure;

            if (settings.PortNumber == Constants.SSL_LDAP_PORT)
            {
                type |= AuthenticationTypes.SecureSocketsLayer;
            }

            string password;

            try
            {
                password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(settings.PasswordBytes));
            }
            catch (Exception)
            {
                password = string.Empty;
            }

            var de = settings.Authentication
                                    ? CreateDirectoryEntry(rootDistinguishedName, settings.Login, password, type)
                                    : CreateDirectoryEntry(rootDistinguishedName);

            return(de != null?Search(de, filter, scope) : null);
        }
        public override LDAPObject GetDomain(LDAPSupportSettings settings)
        {
            try
            {
                string password;
                var    type = AuthenticationTypes.ReadonlyServer | AuthenticationTypes.Secure;
                try
                {
                    password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(settings.PasswordBytes));
                }
                catch (Exception)
                {
                    password = string.Empty;
                }

                if (settings.PortNumber == Constants.SSL_LDAP_PORT)
                {
                    type |= AuthenticationTypes.SecureSocketsLayer;
                }

                var entry = settings.Authentication
                                ? new DirectoryEntry(settings.Server + ":" + settings.PortNumber, settings.Login, password,
                                                     type)
                                : new DirectoryEntry(settings.Server + ":" + settings.PortNumber);

                return(LDAPObjectFactory.CreateObject(entry));
            }
            catch (Exception e)
            {
                Log.WarnFormat("Can't get current domain. May be current user has not needed permissions. {0}", e);
                return(null);
            }
        }
Beispiel #5
0
        public static int GetLoginEventIdFromCookie(string cookie)
        {
            int loginEventId = 0;

            if (string.IsNullOrEmpty(cookie))
            {
                return(loginEventId);
            }

            try
            {
                cookie = (HttpUtility.UrlDecode(cookie) ?? "").Replace(' ', '+');
                var s = InstanceCrypto.Decrypt(cookie).Split('$');
                if (8 < s.Length)
                {
                    loginEventId = !string.IsNullOrEmpty(s[8]) ? int.Parse(s[8]) : 0;
                }
            }
            catch (Exception err)
            {
                LogManager.GetLogger("ASC.Core").ErrorFormat("Failed to get login event ID from cookie: cookie {0}, loginEvent {1}: {2}",
                                                             cookie, loginEventId, err);
            }
            return(loginEventId);
        }
Beispiel #6
0
        public static List <LDAPObject> Search(string root, Criteria criteria, LDAPSupportSettings settings)
        {
            var    type = AuthenticationTypes.ReadonlyServer | AuthenticationTypes.Secure;
            string password;

            try
            {
                password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(settings.PasswordBytes));
            }
            catch (Exception)
            {
                password = string.Empty;
            }
            if (settings.PortNumber == Constants.SSL_LDAP_PORT)
            {
                type |= AuthenticationTypes.SecureSocketsLayer;
            }
            var entry = settings.Authentication ? new DirectoryEntry(root, settings.Login, password, type) : new DirectoryEntry(root);

            try
            {
                object nativeObject = entry.NativeObject;
            }
            catch (Exception e)
            {
                _log.ErrorFormat("Error authenticating user. Current user has not access to read this directory: {0}. {1}", root, e);
                return(null);
            }
            return(SearchInternal(root, criteria != null ? criteria.ToString() : null, SearchScope.Subtree, settings));
        }
        public void ProcessRequest(HttpContext context)
        {
            var d = context.Request.QueryString["d"];

            if (string.IsNullOrEmpty(d))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            var param = HttpUtility.UrlDecode(InstanceCrypto.Decrypt(d)).Split('|');

            if (param.Length != 3)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            context.Response.Clear();
            context.Response.ContentType = "text/javascript";
            context.Response.Charset     = "utf-8";

            var etag = d.GetHashCode().ToString();

            context.Response.Cache.SetETag(etag);
            if (string.Equals(context.Request.Headers["If-None-Match"], etag))
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotModified;
            }
            else
            {
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.Write(JavaScriptResourceSerialize(Type.GetType(param[0], true), param[1], CultureInfo.GetCultureInfo(param[2])));
            }
        }
Beispiel #8
0
        public static bool DecryptCookie(string cookie, out int tenant, out Guid userid, out string login, out string password, out int indexTenant, out DateTime expire, out int indexUser)
        {
            tenant      = Tenant.DEFAULT_TENANT;
            userid      = Guid.Empty;
            login       = null;
            password    = null;
            indexTenant = 0;
            expire      = DateTime.MaxValue;
            indexUser   = 0;

            if (string.IsNullOrEmpty(cookie))
            {
                return(false);
            }

            try
            {
                cookie = (HttpUtility.UrlDecode(cookie) ?? "").Replace(' ', '+');
                var s = InstanceCrypto.Decrypt(cookie).Split('$');

                if (0 < s.Length)
                {
                    login = s[0];
                }
                if (1 < s.Length)
                {
                    tenant = int.Parse(s[1]);
                }
                if (2 < s.Length)
                {
                    password = s[2];
                }
                if (4 < s.Length)
                {
                    userid = new Guid(s[4]);
                }
                if (5 < s.Length)
                {
                    indexTenant = int.Parse(s[5]);
                }
                if (6 < s.Length)
                {
                    expire = DateTime.ParseExact(s[6], DateTimeFormat, CultureInfo.InvariantCulture);
                }
                if (7 < s.Length)
                {
                    indexUser = int.Parse(s[7]);
                }

                return(true);
            }
            catch (Exception err)
            {
                LogManager.GetLogger("ASC.Core").ErrorFormat("Authenticate error: cookie {0}, tenant {1}, userid {2}, login {3}, pass {4}, indexTenant {5}, expire {6}: {7}",
                                                             cookie, tenant, userid, login, password, indexTenant, expire.ToString(DateTimeFormat), err);
            }
            return(false);
        }
 public Guid AuthKey(InstanceCrypto instanceCrypto)
 {
     if (!_authKey.HasValue)
     {
         _authKey = !string.IsNullOrEmpty(_request.Query["userid"])
                         ? new Guid(instanceCrypto.Decrypt(_request.Query["userid"]))
                         : Guid.Empty;
     }
     return(_authKey.Value);
 }
Beispiel #10
0
 public string GetEncryptedCode(InstanceCrypto InstanceCrypto, Signature Signature)
 {
     try
     {
         return(InstanceCrypto.Decrypt(Code));
     }
     catch
     {
         //support old scheme stored in the DB
         return(Signature.Read <string>(Code));
     }
 }
Beispiel #11
0
        protected string GetPassword(byte[] passwordBytes)
        {
            string password;

            try
            {
                password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(passwordBytes));
            }
            catch
            {
                password = string.Empty;
            }
            return(password);
        }
        private string GetPassword(byte[] passwordBytes)
        {
            string password;

            try
            {
                password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(passwordBytes));
            }
            catch (Exception)
            {
                password = string.Empty;
            }
            return(password);
        }
        public string GetKeys(Guid userId)
        {
            var linker  = Snapshot.Get("webstudio");
            var profile = linker.GetLinkedProfiles(userId.ToString(), ProviderConstants.Encryption).FirstOrDefault();

            if (profile == null)
            {
                return(null);
            }

            var keys = InstanceCrypto.Decrypt(profile.Name);

            return(keys);
        }
Beispiel #14
0
        public List <LDAPObject> Search(string root, Criteria criteria, string userFilter, LDAPSupportSettings settings)
        {
            var    type = AuthenticationTypes.ReadonlyServer | AuthenticationTypes.Secure;
            string password;

            try
            {
                password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(settings.PasswordBytes));
            }
            catch (Exception)
            {
                password = string.Empty;
            }

            if (settings.PortNumber == Constants.SSL_LDAP_PORT)
            {
                type |= AuthenticationTypes.SecureSocketsLayer;
            }

            var entry = settings.Authentication
                            ? new DirectoryEntry(root, settings.Login, password, type)
                            : new DirectoryEntry(root);

            try
            {
                // ReSharper disable UnusedVariable
                var nativeObject = entry.NativeObject;
                // ReSharper restore UnusedVariable
            }
            catch (Exception e)
            {
                _log.ErrorFormat(
                    "Error authenticating user. Current user has not access to read this directory: {0}. {1}", root, e);
                return(new List <LDAPObject>(0));
            }

            if (!string.IsNullOrEmpty(userFilter) && !userFilter.StartsWith("(") && !userFilter.EndsWith(")"))
            {
                userFilter = "(" + userFilter + ")";
            }

            return(SearchInternal(root, criteria != null ? "(&" + criteria + userFilter + ")" : userFilter,
                                  SearchScope.Subtree, settings));
        }
        public object GetSsoCertificateKey()
        {
            CheckSsoPermissions();

            var log = LogManager.GetLogger(typeof(SettingsApi));

            try
            {
                var settings = SsoSettings.Load();

                if (string.IsNullOrEmpty(settings.ClientCertificateFileName))
                {
                    throw new Exception("Certificate is not found");
                }

                if (!string.IsNullOrEmpty(settings.ClientPassword))
                {
                    settings.ClientPassword = InstanceCrypto.Decrypt(settings.ClientPassword);
                }

                var base64ExportCertificate = FillBase64ExportCertificate(settings, log);

                if (string.IsNullOrEmpty(base64ExportCertificate))
                {
                    throw new Exception("Certificate is unaccessable");
                }

                return(new
                {
                    success = true,
                    publicKey = base64ExportCertificate
                });
            }
            catch (Exception exception)
            {
                log.Error(exception);

                return(new
                {
                    success = false,
                    message = exception.Message
                });
            }
        }
        public static string GetPassword(byte[] passwordBytes)
        {
            if (passwordBytes == null || passwordBytes.Length == 0)
            {
                return(string.Empty);
            }

            string password;

            try
            {
                password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(passwordBytes));
            }
            catch (Exception)
            {
                password = string.Empty;
            }
            return(password);
        }
        public static bool DecryptCookie(string cookie, out int tenant, out Guid userid, out string login, out string password)
        {
            tenant   = Tenant.DEFAULT_TENANT;
            userid   = Guid.Empty;
            login    = null;
            password = null;

            if (string.IsNullOrEmpty(cookie))
            {
                return(false);
            }

            try
            {
                cookie = HttpUtility.UrlDecode(cookie).Replace(' ', '+');
                var s = InstanceCrypto.Decrypt(cookie).Split('$');

                if (0 < s.Length)
                {
                    login = s[0];
                }
                if (1 < s.Length)
                {
                    tenant = int.Parse(s[1]);
                }
                if (2 < s.Length)
                {
                    password = s[2];
                }
                if (4 < s.Length)
                {
                    userid = new Guid(s[4]);
                }
                return(true);
            }
            catch (Exception err)
            {
                LogManager.GetLogger("ASC.Core").ErrorFormat("Authenticate error: cookie {0}, tenant {1}, userid {2}, login {3}, pass {4}: {5}",
                                                             cookie, tenant, userid, login, password, err);
            }
            return(false);
        }
        public static EncryptionSettings Deserialize(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(new EncryptionSettings());
            }

            var parts = value.Split(new[] { '#' }, StringSplitOptions.None);

            var password    = string.IsNullOrEmpty(parts[0]) ? string.Empty : InstanceCrypto.Decrypt(parts[0]);
            var status      = int.Parse(parts[1]);
            var notifyUsers = bool.Parse(parts[2]);

            return(new EncryptionSettings
            {
                Password = password,
                Status = (EncryprtionStatus)status,
                NotifyUsers = notifyUsers
            });
        }
        public static string GetKeys(Guid userId)
        {
            var linker  = new AccountLinker("webstudio");
            var profile = linker.GetLinkedProfiles(userId.ToString(), ProviderConstants.Encryption).FirstOrDefault();

            if (profile == null)
            {
                return(null);
            }

            try
            {
                var keys = InstanceCrypto.Decrypt(profile.Name);
                return(keys);
            }
            catch (Exception ex)
            {
                var message = string.Format("Can not decrypt {0} keys for {1}", ProviderConstants.Encryption, userId);
                LogManager.GetLogger("ASC").Error(message, ex);
                return(null);
            }
        }
Beispiel #20
0
        public static bool DecryptCookie(string cookie, out int tenant, out Guid userid, out string login, out string password)
        {
            tenant   = Tenant.DEFAULT_TENANT;
            userid   = Guid.Empty;
            login    = null;
            password = null;

            if (string.IsNullOrEmpty(cookie))
            {
                return(false);
            }

            try
            {
                cookie = HttpUtility.UrlDecode(cookie).Replace(' ', '+');
                var s = InstanceCrypto.Decrypt(cookie).Split('$');

                if (0 < s.Length)
                {
                    login = s[0];
                }
                if (1 < s.Length)
                {
                    tenant = int.Parse(s[1]);
                }
                if (2 < s.Length)
                {
                    password = s[2];
                }
                if (4 < s.Length)
                {
                    userid = new Guid(s[4]);
                }
                return(true);
            }
            catch { }
            return(false);
        }
Beispiel #21
0
        public static bool DecryptCookie(string cookie, out int tenant, out Guid userid, out string login, out string password)
        {
            tenant   = Tenant.DEFAULT_TENANT;
            userid   = Guid.Empty;
            login    = null;
            password = null;

            try
            {
                var s    = InstanceCrypto.Decrypt(cookie).Split('$');
                var salt = 3 < s.Length ? s[3] : null;
                if (salt != null && salt != GetUserDepenencySalt())
                {
                    return(false);
                }

                if (0 < s.Length)
                {
                    login = s[0];
                }
                if (1 < s.Length)
                {
                    tenant = int.Parse(s[1]);
                }
                if (2 < s.Length)
                {
                    password = s[2];
                }
                if (4 < s.Length)
                {
                    userid = new Guid(s[4]);
                }
                return(true);
            }
            catch { }
            return(false);
        }
Beispiel #22
0
 private static string DecryptPassword(string password)
 {
     return(string.IsNullOrEmpty(password) ? string.Empty : InstanceCrypto.Decrypt(password));
 }
Beispiel #23
0
        public static byte CheckSettings(LDAPSupportSettings settings, LDAPUserImporter importer)
        {
            if (!settings.EnableLdapAuthentication)
            {
                return(OPERATION_OK);
            }
            string password;

            try
            {
                password = new UnicodeEncoding().GetString(InstanceCrypto.Decrypt(settings.PasswordBytes));
            }
            catch
            {
                password = string.Empty;
            }
            try
            {
                if (settings.Authentication)
                {
                    CheckCredentials(settings.Login, password, settings.Server, settings.PortNumber);
                }
                if (!CheckServerAndPort(settings.Server, settings.PortNumber,
                                        settings.Authentication, settings.Login, password))
                {
                    return(WRONG_SERVER_OR_PORT);
                }
            }
            catch (DirectoryServicesCOMException)
            {
                return(CREDENTIALS_NOT_VALID);
            }
            catch (COMException)
            {
                return(WRONG_SERVER_OR_PORT);
            }

            if (!CheckUserDN(settings.UserDN, settings.Server, settings.PortNumber,
                             settings.Authentication, settings.Login, password))
            {
                return(WRONG_USER_DN);
            }
            try
            {
                importer.AllDomainUsers = GetUsersByAttributes(settings);
            }
            catch (ArgumentException)
            {
                _log.ErrorFormat("Incorrect filter. userFilter = {0}", settings.UserFilter);
                return(INCORRECT_LDAP_FILTER);
            }
            if (importer.AllDomainUsers == null || importer.AllDomainUsers.Count == 0)
            {
                _log.ErrorFormat("Any user is not found. userDN = {0}", settings.UserDN);
                return(USERS_NOT_FOUND);
            }
            if (!CheckLoginAttribute(importer.AllDomainUsers[0], settings.LoginAttribute))
            {
                return(WRONG_LOGIN_ATTRIBUTE);
            }
            if (settings.GroupMembership)
            {
                if (!CheckGroupDNAndGroupName(settings.GroupDN, settings.GroupName, settings.Server,
                                              settings.PortNumber, settings.Authentication, settings.Login, password))
                {
                    return(WRONG_GROUP_DN_OR_GROUP_NAME);
                }

                importer.DomainGroups = GetGroupsByParameter(settings);
                if (importer.DomainGroups == null || importer.DomainGroups.Count == 0)
                {
                    return(GROUPS_NOT_FOUND);
                }

                if (!CheckGroupAttribute(importer.DomainGroups[0], settings.GroupAttribute))
                {
                    return(WRONG_GROUP_ATTRIBUTE);
                }
                if (!CheckUserAttribute(importer.AllDomainUsers[0], settings.UserAttribute))
                {
                    return(WRONG_USER_ATTRIBUTE);
                }
            }
            return(OPERATION_OK);
        }
Beispiel #24
0
 private static OAuth20Token DecryptToken(string token)
 {
     return(string.IsNullOrEmpty(token) ? null : FromJson(InstanceCrypto.Decrypt(token)));
 }
Beispiel #25
0
        internal void FromTransport(string transportstring)
        {
            var serialized = Encoding.UTF8.GetString(InstanceCrypto.Decrypt(HttpServerUtility.UrlTokenDecode(transportstring)));

            FromSerializedString(serialized);
        }
Beispiel #26
0
 public string CreateHash2(string s)
 {
     return(!string.IsNullOrEmpty(s) ? "S|" + Crypto.GetV(instanceCrypto.Decrypt(s), 1, true) : s);
 }
 private string DecryptPassword(string password)
 {
     return(InstanceCrypto.Decrypt(password));
 }
Beispiel #28
0
        internal void FromTransport(string transportstring)
        {
            var serialized = Encoding.UTF8.GetString(InstanceCrypto.Decrypt(WebEncoders.Base64UrlDecode(transportstring)));

            FromSerializedString(serialized);
        }
Beispiel #29
0
 public static string DecryptPassword(string password)
 {
     return(InstanceCrypto.Decrypt(password));
 }