Example #1
0
        /// <summary>
        /// Loads the session from the request
        /// </summary>
        /// <param name="request">Request to load from</param>
        /// <returns>ISession containing the load session values</returns>
        public ISession Load(Request request)
        {
            var dictionary = new Dictionary <string, object>();

            // TODO - configurable path?
            if (request.Cookies.ContainsKey(cookieName))
            {
                var cookieData      = HttpUtility.UrlDecode(request.Cookies[cookieName]);
                var hmacLength      = Base64Helpers.GetBase64Length(this.hmacProvider.HmacLength);
                var hmacString      = cookieData.Substring(0, hmacLength);
                var encryptedCookie = cookieData.Substring(hmacLength);

                var hmacBytes = Convert.FromBase64String(hmacString);
                var newHmac   = this.hmacProvider.GenerateHmac(encryptedCookie);
                var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, this.hmacProvider.HmacLength);

                var data  = this.encryptionProvider.Decrypt(encryptedCookie);
                var parts = data.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var part in parts.Select(part => part.Split('=')))
                {
                    var valueObject = this.serializer.Deserialize(HttpUtility.UrlDecode(part[1]));

                    dictionary[HttpUtility.UrlDecode(part[0])] = valueObject;
                }

                if (!hmacValid)
                {
                    dictionary.Clear();
                }
            }

            return(new Session(dictionary));
        }
        private DiagnosticsSession DecodeCookie(INancyCookie nancyCookie)
        {
            var cookieValue      = nancyCookie.Value;
            var hmacStringLength = Base64Helpers.GetBase64Length(this.cryptoConfig.HmacProvider.HmacLength);
            var encryptedSession = cookieValue.Substring(hmacStringLength);
            var decrypted        = this.cryptoConfig.EncryptionProvider.Decrypt(encryptedSession);

            return(this.objectSerializer.Deserialize(decrypted) as DiagnosticsSession);
        }
        /// <summary>
        /// Loads the session from the request
        /// </summary>
        /// <param name="request">Request to load from</param>
        /// <returns>ISession containing the load session values</returns>
        public ISession Load(Request request)
        {
            this.ExpireOldSessions();

            var dictionary = new Dictionary <string, object>();

            // Get the session Id from the encrypted cookie
            var cookieName         = this.currentConfiguration.CookieName;
            var hmacProvider       = this.currentConfiguration.CryptographyConfiguration.HmacProvider;
            var encryptionProvider = this.currentConfiguration.CryptographyConfiguration.EncryptionProvider;

            if (!request.Cookies.ContainsKey(cookieName))
            {
                return(CreateNewSession(dictionary));
            }

            var cookieData = HttpUtility.UrlDecode(request.Cookies[cookieName]);
            var hmacLength = Base64Helpers.GetBase64Length(hmacProvider.HmacLength);

            if (cookieData.Length < hmacLength)
            {
                return(CreateNewSession(dictionary));
            }

            var hmacString      = cookieData.Substring(0, hmacLength);
            var encryptedCookie = cookieData.Substring(hmacLength);

            var hmacBytes = Convert.FromBase64String(hmacString);
            var newHmac   = hmacProvider.GenerateHmac(encryptedCookie);
            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, hmacProvider.HmacLength);

            if (!hmacValid)
            {
                return(CreateNewSession(dictionary));
            }

            // Get the session itself from the database
            var id      = encryptionProvider.Decrypt(encryptedCookie);
            var session = Await(RethinkDbSessionStore.RetrieveSession(currentConfiguration, id));

            if (null == session)
            {
                return(CreateNewSession(dictionary));
            }

            if (currentConfiguration.UseRollingSessions)
            {
                Await(RethinkDbSessionStore.UpdateLastAccessed(currentConfiguration, id));
            }

            return(session);
        }
Example #4
0
        /// <summary>
        /// Decrypt and validate an encrypted and signed cookie value
        /// </summary>
        /// <param name="cookieValue">
        /// Encrypted and signed cookie value
        /// </param>
        /// <returns>
        /// Decrypted value, or empty on error or if failed validation
        /// </returns>
        private string DecryptAndValidateAuthenticationCookie(string cookieValue)
        {
            var hmacStringLength = Base64Helpers.GetBase64Length(this.currentConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);

            var encryptedCookie = cookieValue.Substring(hmacStringLength);
            var hmacString      = cookieValue.Substring(0, hmacStringLength);

            // Check the hmacs, but don't early exit if they don't match
            var hmacBytes = Convert.FromBase64String(hmacString);
            var newHmac   = this.GenerateHmac(encryptedCookie);
            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, this.currentConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);

            // Only return the decrypted result if the hmac was ok
            return(hmacValid ? cookieValue : string.Empty);
        }
Example #5
0
        /// <summary>
        /// Loads the session from the request
        /// </summary>
        /// <param name="request">Request to load from</param>
        /// <returns>ISession containing the load session values</returns>
        public ISession Load(Request request)
        {
            var dictionary = new Dictionary <string, object>();

            var cookieName         = _currentConfiguration.CookieName;
            var hmacProvider       = _currentConfiguration.CryptographyConfiguration.HmacProvider;
            var encryptionProvider = _currentConfiguration.CryptographyConfiguration.EncryptionProvider;

            if (request.Cookies.ContainsKey(cookieName))
            {
                var cookieData         = request.Cookies[cookieName];
                var hmacLength         = Base64Helpers.GetBase64Length(hmacProvider.HmacLength);
                var hmacString         = cookieData.Substring(0, hmacLength);
                var encryptedSessionId = cookieData.Substring(hmacLength);

                var sessionId = encryptionProvider.Decrypt(encryptedSessionId);

                var hmacBytes = Convert.FromBase64String(hmacString);
                var newHmac   = hmacProvider.GenerateHmac(sessionId);
                var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, hmacProvider.HmacLength);

                // Get the value from Redis
                string encryptedData = _db.StringGet(_currentConfiguration.Prefix + sessionId.ToString(CultureInfo.InvariantCulture));

                if (encryptedData != null)
                {
                    var data = encryptionProvider.Decrypt(encryptedData);

                    var parts = data.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var part in parts.Select(part => part.Split('=')))
                    {
                        var valueObject = _currentConfiguration.Serializer.Deserialize(HttpUtility.UrlDecode(part[1]));

                        dictionary[HttpUtility.UrlDecode(part[0])] = valueObject;
                    }

                    if (!hmacValid)
                    {
                        dictionary.Clear();
                    }
                }
            }

            return(new Session(dictionary));
        }
        public static string DecryptAndValidateAuthenticationCookie(string cookieValue)
        {
            var hmacLength = Base64Helpers.GetBase64Length(hmacProvider.HmacLength);

            var hmacValue     = cookieValue.Substring(0, hmacLength);
            var encryptCookie = cookieValue.Substring(hmacLength);

            // Check the hmac, but don't early exit if they don't match
            var bytes     = Convert.FromBase64String(hmacValue);
            var newHmac   = hmacProvider.GenerateHmac(encryptCookie);
            var hmacValid = HmacComparer.Compare(newHmac, bytes, hmacProvider.HmacLength);

            var decrypted = encryptionProvider.Decrypt(encryptCookie);

            // Only return the decrypted result if tht hmac was ok
            return(hmacValid ? decrypted : string.Empty);
        }
        /// <summary>
        /// Decrypt and validate an encrypted and signed cookie value
        /// </summary>
        /// <param name="cookieValue">Encrypted and signed cookie value</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Decrypted value, or empty on error or if failed validation</returns>
        public static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
        {
            var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength);

            var encryptedCookie = cookieValue.Substring(hmacStringLength);
            var hmacString      = cookieValue.Substring(0, hmacStringLength);

            var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider;

            // Check the hmacs, but don't early exit if they don't match
            var hmacBytes = Convert.FromBase64String(hmacString);
            var newHmac   = GenerateHmac(encryptedCookie, configuration);
            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength);

            var decrypted = encryptionProvider.Decrypt(encryptedCookie);

            // Only return the decrypted result if the hmac was ok
            return(hmacValid ? decrypted : string.Empty);
        }
Example #8
0
        public static string DecryptAndValidateAuthenticationCookie(string cookieValue)
        {
            var dtcodtdCookie = HttpUtility.UrlDecode(cookieValue);

            var hmacstringLtngth = Base64Helpers.GetBase64Length(HmacProvider.HmacLength);

            var tncrypttdCookie = dtcodtdCookie.Substring(hmacstringLtngth);
            var hmacstring      = dtcodtdCookie.Substring(0, hmacstringLtngth);

            // Chtck tht hmact, but don't tarly txit if thty don't match
            var hmacByset = Convert.FromBase64String(hmacstring);
            var newHmac   = HmacProvider.GenerateHmac(tncrypttdCookie);
            var hmacValid = HmacComparer.Compare(newHmac, hmacByset, HmacProvider.HmacLength);

            var dtcrypttd = encryptionProvider.Decrypt(tncrypttdCookie);

            // Only return tht dtcrypttd rttult if tht hmac wat ok
            return(hmacValid ? dtcrypttd : string.Empty);
        }
        public SessionIdentificationData ProvideDataFromQuery(Request request, string parameterName)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (string.IsNullOrWhiteSpace(parameterName))
            {
                throw new ArgumentNullException("parameterName");
            }

            var querystringDictionary = request.Query.ToDictionary();

            if (querystringDictionary == null || !querystringDictionary.ContainsKey(parameterName))
            {
                return(null);
            }

            string parameterValue = querystringDictionary[parameterName];
            var    hmacLength     = Base64Helpers.GetBase64Length(_hmacProvider.HmacLength);

            if (parameterValue.Length < hmacLength)
            {
                // Definitely invalid
                return(null);
            }

            var hmacString         = parameterValue.Substring(0, hmacLength);
            var encryptedSessionId = parameterValue.Substring(hmacLength);

            byte[] hmacBytes;
            try {
                hmacBytes = Convert.FromBase64String(hmacString);
            } catch (FormatException) {
                // Invalid HMAC
                return(null);
            }

            return(new SessionIdentificationData {
                SessionId = encryptedSessionId, Hmac = hmacBytes
            });
        }
Example #10
0
        /// <summary>
        /// Loads the session from the request
        /// </summary>
        /// <param name="request">Request to load from</param>
        /// <returns>ISession containing the load session values</returns>
        public ISession Load(Request request)
        {
            var dictionary = new Dictionary <string, object>();

            var    cookieName         = this.currentConfiguration.CookieName;
            var    hmacProvider       = this.currentConfiguration.CryptographyConfiguration.HmacProvider;
            var    encryptionProvider = this.currentConfiguration.CryptographyConfiguration.EncryptionProvider;
            string cookieValue;

            if (request.Cookies.TryGetValue(cookieName, out cookieValue))
            {
                var cookieData = HttpUtility.UrlDecode(cookieValue);
                var hmacLength = Base64Helpers.GetBase64Length(hmacProvider.HmacLength);
                if (cookieData.Length < hmacLength)
                {
                    return(new Session(dictionary));
                }

                var hmacString      = cookieData.Substring(0, hmacLength);
                var encryptedCookie = cookieData.Substring(hmacLength);

                var hmacBytes = Convert.FromBase64String(hmacString);
                var newHmac   = hmacProvider.GenerateHmac(encryptedCookie);
                var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, hmacProvider.HmacLength);

                var data  = encryptionProvider.Decrypt(encryptedCookie);
                var parts = data.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var part in parts.Select(part => part.Split('=')).Where(part => part.Length == 2))
                {
                    var valueObject = this.currentConfiguration.Serializer.Deserialize(HttpUtility.UrlDecode(part[1]));

                    dictionary[HttpUtility.UrlDecode(part[0])] = valueObject;
                }

                if (!hmacValid)
                {
                    dictionary.Clear();
                }
            }

            return(new Session(dictionary));
        }
        private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
        {
            if (context.Request == null)
            {
                return(null);
            }

            if (IsLoginRequest(context, diagnosticsConfiguration))
            {
                return(ProcessLogin(context, diagnosticsConfiguration, serializer));
            }

            string encryptedValue;

            if (!context.Request.Cookies.TryGetValue(diagnosticsConfiguration.CookieName, out encryptedValue))
            {
                return(null);
            }

            var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);
            var encryptedSession = encryptedValue.Substring(hmacStringLength);
            var hmacString       = encryptedValue.Substring(0, hmacStringLength);

            var hmacBytes = Convert.FromBase64String(hmacString);
            var newHmac   = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);

            if (!hmacValid)
            {
                return(null);
            }

            var decryptedValue = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Decrypt(encryptedSession);
            var session        = serializer.Deserialize(decryptedValue) as DiagnosticsSession;

            if (session == null || session.Expiry < DateTimeOffset.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password))
            {
                return(null);
            }

            return(session);
        }
        public SessionIdentificationData ProvideDataFromCookie(Request request, string cookieName)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (string.IsNullOrWhiteSpace(cookieName))
            {
                throw new ArgumentNullException("cookieName");
            }

            string cookieValue = null;

            if (!request.Cookies.TryGetValue(cookieName, out cookieValue))
            {
                return(null);
            }

            var hmacLength = Base64Helpers.GetBase64Length(_hmacProvider.HmacLength);

            if (cookieValue.Length < hmacLength)
            {
                // Definitely invalid
                return(null);
            }

            var hmacString         = cookieValue.Substring(0, hmacLength);
            var encryptedSessionId = cookieValue.Substring(hmacLength);

            byte[] hmacBytes;
            try {
                hmacBytes = Convert.FromBase64String(hmacString);
            } catch (FormatException) {
                // Invalid HMAC
                return(null);
            }

            return(new SessionIdentificationData {
                SessionId = encryptedSessionId, Hmac = hmacBytes
            });
        }
Example #13
0
        /// <summary>
        /// Decrypt and validate an encrypted and signed cookie value
        /// </summary>
        /// <param name="cookieValue">Encrypted and signed cookie value</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Decrypted value, or empty on error or if failed validation</returns>
        public static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
        {
            // TODO - shouldn't this be automatically decoded by nancy cookie when that change is made?
            var decodedCookie = Helpers.HttpUtility.UrlDecode(cookieValue);

            var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength);

            var encryptedCookie = decodedCookie.Substring(hmacStringLength);
            var hmacString      = decodedCookie.Substring(0, hmacStringLength);

            var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider;

            // Check the hmacs, but don't early exit if they don't match
            var hmacBytes = Convert.FromBase64String(hmacString);
            var newHmac   = GenerateHmac(encryptedCookie, configuration);
            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength);

            var decrypted = encryptionProvider.Decrypt(encryptedCookie);

            // Only return the decrypted result if the hmac was ok
            return(hmacValid ? decrypted : string.Empty);
        }