/// <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)); }
public void Given_valid_session_parameter_then_returns_expected_result() { var actual = _sessionIdentificationDataProvider.ProvideDataFromQuery(_validRequest, _parameterName); Assert.Equal(_expectedResult.SessionId, actual.SessionId); Assert.True(HmacComparer.Compare(actual.Hmac, _expectedResult.Hmac, _hmacProvider.HmacLength)); }
public void Should_validate(string input1, string input2, bool expected) { var hmac1 = provider.GenerateHmac(input1); var hmac2 = provider.GenerateHmac(input2); var result = HmacComparer.Compare(hmac1, hmac2, provider.HmacLength); result.ShouldEqual(expected); }
public void Should_return_true_if_both_correct_length_and_equal() { var hmac1 = new byte[] { 1, 2, 3, 4 }; var hmac2 = new byte[] { 1, 2, 3, 4 }; var result = HmacComparer.Compare(hmac1, hmac2, 4); result.ShouldBeTrue(); }
public void Should_return_false_if_not_equal() { var hmac1 = new byte[] { 1, 2, 3, 4 }; var hmac2 = new byte[] { 1, 2, 3, 5 }; var result = HmacComparer.Compare(hmac1, hmac2, 4); result.ShouldBeFalse(); }
public void Should_return_false_if_second_length_wrong() { var hmac1 = new byte[] { 1, 2, 3, 0 }; var hmac2 = new byte[] { 1, 2, 3 }; var result = HmacComparer.Compare(hmac1, hmac2, 4); result.ShouldBeFalse(); }
/// <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); }
/// <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); }
public bool IsValidHmac(SessionIdentificationData sessionIdentificationData) { if (sessionIdentificationData == null) { throw new ArgumentNullException("sessionIdentificationData"); } if (sessionIdentificationData.Hmac == null) { return(false); } var incomingBytes = sessionIdentificationData.Hmac; var expectedHmac = _hmacProvider.GenerateHmac(sessionIdentificationData.SessionId); return(HmacComparer.Compare(expectedHmac, incomingBytes, _hmacProvider.HmacLength)); }
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> /// 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 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); }
/// <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); }
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); }
/// <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)); }
/// <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); }
public void Given_session_id_is_new_then_manipulates_response() { const string encryptedSessionId = "ABC_sessionid_xyz"; var hmacBytes = new byte[] { 1, 2, 3 }; A.CallTo(() => _fakeEncryptionProvider.Encrypt(_validSessionId.Value.ToString())).Returns(encryptedSessionId); A.CallTo(() => _fakeHmacProvider.GenerateHmac(encryptedSessionId)).Returns(hmacBytes); A.CallTo(() => _fakeHmacProvider.HmacLength).Returns(hmacBytes.Length); _byQueryStringParamIdentificationMethod.SaveSessionId(_validSessionId, _context); A.CallTo( () => _fakeResponseManipulatorForSession.ModifyResponseToRedirectToSessionAwareUrl( _context, A <SessionIdentificationData> .That.Matches(sid => sid.SessionId == encryptedSessionId && HmacComparer.Compare(sid.Hmac, hmacBytes, _fakeHmacProvider.HmacLength)), _parameterName)).MustHaveHappened(); }
public void Adds_expected_cookie_to_response_containing_data_from_encryptionprovider_and_hmacprovider_and_returns_null() { const string encryptedSessionId = "ABC_sessionid_xyz"; var hmacBytes = new byte[] { 1, 2, 3 }; var hmacString = Convert.ToBase64String(hmacBytes); var expectedCookieData = string.Format("{0}{1}", encryptedSessionId, hmacString); A.CallTo(() => _fakeEncryptionProvider.Encrypt(_validSessionId.Value.ToString())).Returns(encryptedSessionId); A.CallTo(() => _fakeHmacProvider.GenerateHmac(encryptedSessionId)).Returns(hmacBytes); A.CallTo(() => _fakeHmacProvider.HmacLength).Returns(hmacBytes.Length); A.CallTo( () => _fakeCookieFactory.CreateCookie( _cookieName, null, null, A <SessionIdentificationData> .That.Matches(cookieData => cookieData.SessionId == encryptedSessionId && HmacComparer.Compare(cookieData.Hmac, hmacBytes, _fakeHmacProvider.HmacLength)))) .Returns(new NancyCookie("cookiefortest", expectedCookieData)); _bySessionIdCookieIdentificationMethod.SaveSessionId(_validSessionId, _context); var addedCookie = _context.Response.Cookies.FirstOrDefault(cookie => cookie.Value == expectedCookieData); Assert.NotNull(addedCookie); }