/// <summary> /// /// </summary> /// <param name="member"></param> /// <param name="autoCreate"></param> /// <param name="enableAutologin"></param> /// <param name="admin"></param> public string SessionBegin(long userId, bool autoCreate, bool enableAutologin, bool twoFactor, DnsRecord record, Uri urlreferer) { string cookieName = "hailToTheChef"; /*XmlSerializer xs; StringWriter stw;*/ string protocol = "http://"; if (core.Settings.UseSecureCookies) { protocol = "https://"; } string rootSessionId = string.Empty; if (record != null) { rootSessionId = core.Session.SessionId; } sessionData = null; sessionId = null; string currentDomain = core.Hyperlink.CurrentDomain; if (record != null) { currentDomain = record.Domain; } if (!String.IsNullOrEmpty(IsBotUserAgent(Request.UserAgent))) { signInState = SessionSignInState.Bot; core.Hyperlink.SidUrls = false; return sessionId; } if (record == null) { if (Request.Cookies[cookieName + "_sid"] != null || Request.Cookies[cookieName + "_data"] != null) { if (Request.Cookies[cookieName + "_sid"] != null) { sessionId = Request.Cookies[cookieName + "_sid"].Value; } if (Request.Cookies[cookieName + "_data"] != null) { /*xs = new XmlSerializer(typeof(SessionCookie)); StringReader sr = new StringReader(HttpUtility.UrlDecode(Request.Cookies[cookieName + "_data"].Value));*/ try { sessionData = new SessionCookie(HttpUtility.UrlDecode(Request.Cookies[cookieName + "_data"].Value)); //(SessionCookie)xs.Deserialize(sr); } catch { sessionData = new SessionCookie(); } } else { sessionData = new SessionCookie(); } if (string.IsNullOrEmpty(sessionId)) { sessionId = (string)Request.QueryString["sid"]; } sessionMethod = SessionMethods.Cookie; } else { sessionData = new SessionCookie(); if (Request.QueryString["sid"] != null) { sessionId = (string)Request.QueryString["sid"]; } sessionMethod = SessionMethods.Get; } } else { sessionData = new SessionCookie(); } if (!string.IsNullOrEmpty(sessionId)) { if (!IsValidSid(sessionId)) { sessionId = ""; } } if (record != null) { sessionMethod = SessionMethods.Get; } // // First off attempt to join with the autologin value if we have one // If not, just use the user_id value // loggedInMember = null; if (userId != 0) { //if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '' && $user_id) if (!string.IsNullOrEmpty(sessionData.autoLoginId) && userId > 0) { SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info); query.AddJoin(JoinTypes.Inner, "session_keys", "user_id", "user_id"); query.AddCondition("user_keys.user_id", userId); query.AddCondition("user_active", true); query.AddCondition("key_id", SessionState.SessionMd5(sessionData.autoLoginId)); System.Data.Common.DbDataReader userReader = db.ReaderQuery(query); if (userReader.HasRows) { userReader.Read(); loggedInMember = new User(core, userReader, UserLoadOptions.Info); userReader.Close(); userReader.Dispose(); enableAutologin = isLoggedIn = true; if (loggedInMember.UserInfo.TwoFactorAuthVerified && twoFactor) { signInState = SessionSignInState.TwoFactorValidated; } else { signInState = SessionSignInState.SignedIn; } } else { userReader.Close(); userReader.Dispose(); core.Template.Parse("REDIRECT_URI", "/"); if (record == null) { Response.Cookies.Clear(); HttpCookie sessionDataCookie = new HttpCookie(cookieName + "_data"); //sessionDataCookie.Domain = core.Hyperlink.CurrentDomain; sessionDataCookie.Path = "/"; sessionDataCookie.Value = ""; sessionDataCookie.Expires = DateTime.MinValue; sessionDataCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain; sessionDataCookie.HttpOnly = true; Response.Cookies.Add(sessionDataCookie); HttpCookie sessionSidCookie = new HttpCookie(cookieName + "_sid"); //sessionSidCookie.Domain = core.Hyperlink.CurrentDomain; sessionSidCookie.Path = "/"; sessionSidCookie.Value = ""; sessionSidCookie.Expires = DateTime.MinValue; sessionDataCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain; sessionSidCookie.HttpOnly = true; Response.Cookies.Add(sessionSidCookie); if (Request.Cookies[cookieName + "_sid"] == null && signInState != SessionSignInState.Bot) { core.Hyperlink.SidUrls = true; } } //core.Display.ShowMessage("Error", "Error starting session"); /*Response.Write("Error starting session"); if (db != null) { db.CloseConnection(); } Response.End(); return null;*/ /* Let's try just signing out rather than showing an error message */ userId = 0; } } else if (!autoCreate) { sessionData.autoLoginId = ""; sessionData.userId = userId; if (userId > 0) { SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info); query.AddCondition("user_active", true); query.AddCondition("user_keys.user_id", userId); System.Data.Common.DbDataReader userSessionReader = db.ReaderQuery(query); if (userSessionReader.HasRows) { userSessionReader.Read(); loggedInMember = new User(core, userSessionReader, UserLoadOptions.Info); userSessionReader.Close(); userSessionReader.Dispose(); isLoggedIn = true; //signInState = SessionSignInState.SignedIn; if (loggedInMember.UserInfo.TwoFactorAuthVerified && twoFactor) { signInState = SessionSignInState.TwoFactorValidated; } else { signInState = SessionSignInState.SignedIn; } } else { userSessionReader.Close(); userSessionReader.Dispose(); // TODO: activation //core.Display.ShowMessage("Inactive account", "You have attempted to use an inactive account. If you have just registered, check for an e-mail with an activation link at the e-mail address you provided."); Response.Write("You have attempted to use an inactive account. If you have just registered, check for an e-mail with an activation link at the e-mail address you provided."); //Display.ShowMessage(this, "Error", "Error starting session"); //Response.Write("fail 1"); if (db != null) { db.CloseConnection(); } Response.End(); } } } } // // At this point either loggedInMember should be populated or // one of the below is true // * Key didn't match one in the DB // * User does not exist // * User is inactive // if (loggedInMember == null) { if (sessionData == null) { sessionData = new SessionCookie(); } sessionData.autoLoginId = ""; sessionData.userId = userId = 0; enableAutologin = isLoggedIn = false; signInState = SessionSignInState.SignedOut; if (userId > 0) { SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info); query.AddCondition("user_keys.user_id", userId); System.Data.Common.DbDataReader userReader = db.ReaderQuery(query); if (userReader.HasRows) { userReader.Read(); loggedInMember = new User(core, userReader, UserLoadOptions.Info); } userReader.Close(); userReader.Dispose(); } } // INFO: phpBB2 performs a ban check, we don't have those facilities so let's skip // // Create or update the session // long changedRows = 0; if (record == null) { changedRows = db.UpdateQuery(string.Format("UPDATE user_sessions SET session_time_ut = UNIX_TIMESTAMP(), user_id = {0}, session_signed_in = {1} WHERE session_string = '{3}' AND session_ip = '{2}';", userId, (byte)signInState, ipAddress.ToString(), sessionId)); // , session_http_referer = '' } if (changedRows == 0) { // This should force new sessions on external domains to re-auth rather than logout if (core.Hyperlink.CurrentDomain != Hyperlink.Domain) { string referer = string.Empty; if (HttpContext.Current.Request.UrlReferrer != null) { referer = HttpContext.Current.Request.UrlReferrer.ToString(); } HttpContext.Current.Response.Redirect(protocol + Hyperlink.Domain + string.Format("/session.aspx?domain={0}&path={1}&urlreferer={2}", HttpContext.Current.Request.Url.Host, core.PagePath.TrimStart(new char[] { '/' }), referer)); return string.Empty; } else { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] randomNumber = new byte[16]; rng.GetBytes(randomNumber); //Random rand = new Random((int)(DateTime.Now.Ticks & 0xFFFF)); //rand.NextDouble().ToString() string rand = HexRNG(randomNumber); sessionId = SessionState.SessionMd5(rand + "bsseed" + DateTime.Now.Ticks.ToString() + ipAddress.ToString()).ToLower(); if (record == null) { rootSessionId = sessionId; } string referer = string.Empty; if (urlreferer != null) { referer = urlreferer.ToString(); } db.UpdateQuery(string.Format("INSERT INTO user_sessions (session_string, session_time_ut, session_start_ut, session_signed_in, session_ip, user_id, session_root_string, session_domain, session_http_referer) VALUES ('{0}', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), {1}, '{2}', {3}, '{4}', '{5}', '{6}')", sessionId, (byte)signInState, ipAddress.ToString(), userId, Mysql.Escape(rootSessionId), Mysql.Escape(currentDomain), Mysql.Escape(referer))); } } if (record == null) { // 1 in 100 chance of deleting stale sessions // Move delete stale session code outside to allow guest sessions to clear stale sessions on low use websites Random rand = new Random(); if (rand.NextDouble() * 100 < 1) { db.UpdateQuery(string.Format("DELETE FROM user_sessions WHERE session_time_ut + {0} < UNIX_TIMESTAMP()", SessionState.SESSION_EXPIRES)); } if (userId != 0) { long ts = UnixTime.UnixTimeStamp() - loggedInMember.UserInfo.LastVisitDateRaw; if (ts >= 60) { db.UpdateQuery(string.Format("UPDATE user_info SET user_last_visit_ut = UNIX_TIMESTAMP() where user_id = {0}", loggedInMember.UserId)); } if (enableAutologin) { string autoLoginKey = SessionState.SessionMd5(rand.NextDouble().ToString() + "zzseed").Substring(4, 16) + SessionState.SessionMd5(rand.NextDouble().ToString() + "zzseed").Substring(4, 16); if (!string.IsNullOrEmpty(sessionData.autoLoginId)) { db.UpdateQuery(string.Format("UPDATE session_keys SET key_last_ip = '{0}', key_id = '{1}', key_last_visit_ut = UNIX_TIMESTAMP() WHERE key_id = '{2}'", ipAddress.ToString(), SessionState.SessionMd5(autoLoginKey), SessionState.SessionMd5(sessionData.autoLoginId))); } else { db.UpdateQuery(string.Format("INSERT INTO session_keys (key_id, user_id, key_last_ip, key_last_visit_ut, key_browser_string) VALUES ('{0}', {1}, '{2}', UNIX_TIMESTAMP(), '{3}')", SessionState.SessionMd5(autoLoginKey), userId, ipAddress.ToString(), Mysql.Escape(Request.UserAgent))); } sessionData.autoLoginId = autoLoginKey; autoLoginKey = ""; } else { sessionData.autoLoginId = ""; } } } core.Hyperlink.Sid = sessionId; if (record == null) { Response.Cookies.Clear(); /*xs = new XmlSerializer(typeof(SessionCookie)); StringBuilder sb = new StringBuilder(); stw = new StringWriter(sb); xs.Serialize(stw, sessionData); stw.Flush(); stw.Close();*/ HttpCookie newSessionDataCookie = new HttpCookie(cookieName + "_data"); //newSessionDataCookie.Domain = core.Hyperlink.CurrentDomain; // DO NOT DO THIS, exposes cookie to sub domains newSessionDataCookie.Path = "/"; newSessionDataCookie.Value = sessionData.ToString().Replace("\r", "").Replace("\n", ""); newSessionDataCookie.Expires = DateTime.Now.AddYears(1); newSessionDataCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain; newSessionDataCookie.HttpOnly = true; Response.Cookies.Add(newSessionDataCookie); HttpCookie newSessionSidCookie = new HttpCookie(cookieName + "_sid"); //newSessionSidCookie.Domain = core.Hyperlink.CurrentDomain; // DO NOT DO THIS, exposes cookie to sub domains newSessionSidCookie.Path = "/"; newSessionSidCookie.Value = sessionId; newSessionSidCookie.Expires = DateTime.MinValue; newSessionSidCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain; newSessionSidCookie.HttpOnly = true; Response.Cookies.Add(newSessionSidCookie); if (Request.Cookies[cookieName + "_sid"] == null && signInState != SessionSignInState.Bot) { core.Hyperlink.SidUrls = true; } } return sessionId; }
public void SessionPagestart(string userIp) { #if DEBUG Stopwatch timeTimer = new Stopwatch(); timeTimer.Start(); #endif long nowUt = UnixTime.UnixTimeStamp(); #if DEBUG timeTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.b in {0} -->\r\n", timeTimer.ElapsedTicks / 10000000.0)); #endif string cookieName = "hailToTheChef"; /*XmlSerializer xs; StringWriter stw;*/ string protocol = "http://"; if (core.Settings.UseSecureCookies) { protocol = "https://"; } sessionData = null; sessionId = null; #if DEBUG Stopwatch botTimer = new Stopwatch(); botTimer.Start(); #endif if (!String.IsNullOrEmpty(IsBotUserAgent(Request.UserAgent))) { signInState = SessionSignInState.Bot; core.Hyperlink.SidUrls = false; return; } #if DEBUG botTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.c in {0} -->\r\n", botTimer.ElapsedTicks / 10000000.0)); #endif #if DEBUG Stopwatch cookieTimer = new Stopwatch(); cookieTimer.Start(); #endif HttpCookie sidCookie = Request.Cookies[cookieName + "_sid"]; HttpCookie dataCookie = Request.Cookies[cookieName + "_data"]; if (sidCookie != null || dataCookie != null) { if (sidCookie != null) { sessionId = sidCookie.Value; } if (dataCookie != null) { /*xs = new XmlSerializer(typeof(SessionCookie)); StringReader sr = new StringReader(HttpUtility.UrlDecode(Request.Cookies[cookieName + "_data"].Value));*/ try { sessionData = new SessionCookie(HttpUtility.UrlDecode(dataCookie.Value)); //(SessionCookie)xs.Deserialize(sr); } catch { sessionData = new SessionCookie(); } } else { sessionData = new SessionCookie(); } if (string.IsNullOrEmpty(sessionId)) { sessionId = (string)Request.QueryString["sid"]; } if ((Hyperlink.Domain != core.Hyperlink.CurrentDomain) && (sessionId != (string)Request.QueryString["sid"]) && (!string.IsNullOrEmpty((string)Request.QueryString["sid"]))) { sessionData = new SessionCookie(); sessionId = (string)Request.QueryString["sid"]; } if ((core.Hyperlink.CurrentDomain != Hyperlink.Domain) && string.IsNullOrEmpty(sessionId)) { string referer = string.Empty; if (HttpContext.Current.Request.UrlReferrer != null) { referer = HttpContext.Current.Request.UrlReferrer.ToString(); } HttpContext.Current.Response.Redirect(protocol + Hyperlink.Domain + string.Format("/session.aspx?domain={0}&path={1}&urlreferer={2}", HttpContext.Current.Request.Url.Host, core.PagePath.TrimStart(new char[] { '/' }), referer)); //return; } sessionMethod = SessionMethods.Cookie; } else { sessionData = new SessionCookie(); if (Request.QueryString["sid"] != null) { sessionId = (string)Request.QueryString["sid"]; } sessionMethod = SessionMethods.Get; if ((core.Hyperlink.CurrentDomain != Hyperlink.Domain) && string.IsNullOrEmpty(sessionId)) { string referer = string.Empty; if (HttpContext.Current.Request.UrlReferrer != null) { referer = HttpContext.Current.Request.UrlReferrer.ToString(); } HttpContext.Current.Response.Redirect(protocol + Hyperlink.Domain + string.Format("/session.aspx?domain={0}&path={1}&urlreferer={2}", HttpContext.Current.Request.Url.Host, core.PagePath.TrimStart(new char[] { '/' }), referer)); //return; } } #if DEBUG cookieTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.d in {0} -->\r\n", cookieTimer.ElapsedTicks / 10000000.0)); #endif #if DEBUG Stopwatch sidTimer = new Stopwatch(); sidTimer.Start(); #endif if (!string.IsNullOrEmpty(sessionId)) { if (!IsValidSid(sessionId)) { sessionId = ""; } } #if DEBUG sidTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.e in {0} -->\r\n", sidTimer.ElapsedTicks / 10000000.0)); #endif if (!string.IsNullOrEmpty(sessionId)) { // // session_id exists so go ahead and attempt to grab all // data in preparation // SelectQuery query = User.GetSelectQueryStub(core, UserLoadOptions.Info); query.AddFields("session_ip", "session_time_ut", "session_signed_in"); query.AddJoin(JoinTypes.Inner, new DataField(typeof(User), "user_id"), new DataField("user_sessions", "user_id")); query.AddCondition("session_string", sessionId); System.Data.Common.DbDataReader userSessionReader = db.ReaderQuery(query); // // Did the session exist in the DB? // if (userSessionReader.HasRows) { userSessionReader.Read(); //DataRow userSessionRow = userSessionTable.Rows[0]; loggedInMember = new User(core, userSessionReader, UserLoadOptions.Info); sbyte sessionSignedIn = (sbyte)userSessionReader["session_signed_in"]; long sessionTimeUt = (long)userSessionReader["session_time_ut"]; string sessionIp = (string)userSessionReader["session_ip"]; userSessionReader.Close(); userSessionReader.Dispose(); core.Hyperlink.Sid = sessionId; if (loggedInMember.UserId != 0) { isLoggedIn = true; if (loggedInMember.UserInfo.TwoFactorAuthVerified) { signInState = (SessionSignInState)sessionSignedIn; } else { signInState = SessionSignInState.SignedIn; } } // // Do not check IP assuming equivalence, if IPv4 we'll check only first 24 // bits ... I've been told (by vHiker) this should alleviate problems with // load balanced et al proxies while retaining some reliance on IP security. // // we will use complete matches in BoxSocial if (sessionIp == userIp) { // // Only update session DB a minute or so after last update // if (nowUt - sessionTimeUt >= 60) { long changedRows = db.UpdateQuery(string.Format("UPDATE user_sessions SET session_time_ut = UNIX_TIMESTAMP(), session_http_referer = '' WHERE session_string = '{0}';", sessionId)); if (SignedIn) { long ts = UnixTime.UnixTimeStamp() - loggedInMember.UserInfo.LastVisitDateRaw; if (ts >= 60) { db.UpdateQuery(string.Format("UPDATE user_info SET user_last_visit_ut = UNIX_TIMESTAMP() where user_id = {0}", loggedInMember.UserId)); Random rand = new Random(); // 1 in 10 chance of deleting stale sessions if (rand.NextDouble() * 10 < 1) { db.UpdateQuery(string.Format("DELETE FROM user_sessions WHERE session_time_ut + {0} < UNIX_TIMESTAMP()", SessionState.SESSION_EXPIRES)); } } } SessionClean(sessionId); } #if DEBUG Stopwatch cookie2Timer = new Stopwatch(); cookie2Timer.Start(); #endif Response.Cookies.Clear(); /*xs = new XmlSerializer(typeof(SessionCookie)); StringBuilder sb = new StringBuilder(); stw = new StringWriter(sb); xs.Serialize(stw, sessionData); stw.Flush(); stw.Close();*/ HttpCookie newSessionDataCookie = new HttpCookie(cookieName + "_data"); newSessionDataCookie.Value = sessionData.ToString().Replace("\r", "").Replace("\n", ""); newSessionDataCookie.Path = "/"; newSessionDataCookie.Expires = DateTime.Now.AddYears(1); newSessionDataCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain; newSessionDataCookie.HttpOnly = true; Response.Cookies.Add(newSessionDataCookie); HttpCookie newSessionSidCookie = new HttpCookie(cookieName + "_sid"); newSessionSidCookie.Path = "/"; newSessionSidCookie.Value = sessionId; newSessionSidCookie.Expires = DateTime.MinValue; newSessionSidCookie.Secure = core.Settings.UseSecureCookies && core.Hyperlink.CurrentDomain == Hyperlink.Domain; newSessionSidCookie.HttpOnly = true; Response.Cookies.Add(newSessionSidCookie); // Add the session_key to the userdata array if it is set if (Request.Cookies[cookieName + "_sid"] == null && signInState != SessionSignInState.Bot) { core.Hyperlink.SidUrls = true; } #if DEBUG cookie2Timer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.f in {0} -->\r\n", cookie2Timer.ElapsedTicks / 10000000.0)); #endif return; } } else { userSessionReader.Close(); userSessionReader.Dispose(); //Display.ShowMessage(this, "Error", "Error starting session"); //Response.Write("fail 3"); //Response.End(); } } // // If we reach here then no (valid) session exists. So we'll create a new one, // using the cookie user_id if available to pull basic user prefs. // long userId = (sessionData != null && sessionData.userId > 0) ? sessionData.userId : 0; // If the current domain is not the root domain, and the session is empty if ((core.Hyperlink.CurrentDomain != Hyperlink.Domain) && userId > 0 /*&& string.IsNullOrEmpty(sessionId)*/) { if ((core.Hyperlink.CurrentDomain != Hyperlink.Domain) && string.IsNullOrEmpty(sessionId)) { string referer = string.Empty; if (HttpContext.Current.Request.UrlReferrer != null) { referer = HttpContext.Current.Request.UrlReferrer.ToString(); } HttpContext.Current.Response.Redirect(protocol + Hyperlink.Domain + string.Format("/session.aspx?domain={0}&path={1}&urlreferer={2}", HttpContext.Current.Request.Url.Host, core.PagePath.TrimStart(new char[] { '/' }), referer)); //return; } } else { #if DEBUG Stopwatch httpTimer = new Stopwatch(); httpTimer.Start(); #endif SessionBegin(userId, true); #if DEBUG httpTimer.Stop(); HttpContext.Current.Response.Write(string.Format("<!-- section A.1.a in {0} -->\r\n", httpTimer.ElapsedTicks / 10000000.0)); #endif } }