Search This Blog

Monday, June 10, 2013

Fedauth cookie issue in sharepoint 2010 -Forms Authentication



Please refer the  /*************Fed-Auth***************/ Logic in below code..


Issue Description
------------------------
You have SharePoint Site using SQL FBA claims authentication. You have enabled session cookie to not to store the cookie on the disk.
You have noticed that even though the user signs out of the site and close the browser, we can reuse the fedauth cookie captured from that session and browse back the same session.
You consider this as security issue and if the SharePoint site is on Internet anybody can hack the fedauth cookie and reuse the same for opening the SharePoint site.
 You would like to remove the fedauth cookie completely once the user sign out of the SharePoint site or close the browser so that any user cannot use the same fedauth for opening the SharePoint Site.
 You have used third party tool called backtrack 5 to edit the cookies and check the behaviour

Steps to Reproduce
------------------------
1. We configured the SharePoint site to use SQL FBA claims by following step by step http://blogs.msdn.com/b/kaevans/archive/2010/07/09/sql-server-provider-for-claims-based-authentication-in-sharepoint-2010.aspx
2. Then we downloaded and installed Fiddler. http://www.fiddler2.com/fiddler2/
3. We launched the Fiddler
4. We logged into the SharePoint site and using Fiddler captured the Fedauth cookie
5. Then we signed out of the SharePoint site and signed in again and found that a new fedauth cookie is assigned
6. Using Fiddler we tried to replay the previous default.aspx and we that the response was 200

Current Behaviour
----------------------
The fedauth cookie can be used to browse the SharePoint site even if the user sign out of the SharePoint site and close the browser

Expected Behaviour
--------------------------
User should not be able to reuse the fedauth cookie once the SharePoint site is signed out and browse is closed.

Analysis
-------------
The issue is not specific to SharePoint server product but is a generic issue about protecting a client from being compromised. Any server side fix that we make will not protect against the calls made from a compromised client because even if the SAML token replay can be prevented the compromised client can then replay the cookies issued by the server. The recommended solution is to use client protection tools or solutions to save clients from being compromised.

Workaround
-------------------

You have customized this workaround for your environment as follows,
Step1: Once employee authentication is successful, we are updating the flag/Token as Active in SQL level.
Step2: Post Authentication we are checking the flag/Token whether it is active or inactive.
Step3: When User Sign-out/Close the browser we are updating the same flag as Inactive.
Post Authentication Technique: we have added a web part on Master Pages, that web part will check the flag/Token whether user is navigating through Authentication or without Authentication.
If user is navigating without authentication that web part will redirect to Sign-out the page.



Post Authentication Technique: we have added a web part on Master Pages, that web part will check the flag/Token whether user is navigating through Authentication or without Authentication.
If user is navigating without authentication that web part will redirect to Sign-out the page.


<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Assembly Name="Microsoft.SharePoint.IdentityModel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
 <%@ Page Language="C#"  MasterPageFile="~/_layouts/Login.master"       %>
 <%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
   <%@ Import Namespace="Microsoft.SharePoint.IdentityModel" %>
   <%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>

 <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
  <%@ Import Namespace="Microsoft.SharePoint" %>
  <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ID="Content1" ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
    <SharePoint:EncodedLiteral runat="server" text="Syntelligence" EncodeMethod='HtmlEncode'/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server">
  <%--  <SharePoint:EncodedLiteral runat="server" text="<%$Resources:wss,login_pagetitle%>" EncodeMethod='HtmlEncode'/>--%>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderId="PlaceHolderSiteName" runat="server"/>
<asp:Content ID="Content4" ContentPlaceHolderId="PlaceHolderMain" runat="server">
 <div id="SslWarning" style="color:red;display:none">
 <SharePoint:EncodedLiteral runat="server"  EncodeMethod="HtmlEncode" Id="ClaimsFormsPageMessage" />
 </div>
<script runat="server" type="text/C#" language="C#" >
 
 
    void Page_Load(object sender, EventArgs e)
    {
        Response.Buffer = true;
        Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
        Response.Expires = -1500;
        Response.CacheControl = "no-cache";
        login.FindControl("UserName").Focus();
       // login.FindControl("UserName").Attributes.Add("autocomplete", "off");
        TextBox txt =(TextBox) login.FindControl("UserName");
        txt.AutoCompleteType = AutoCompleteType.Disabled;
           
        TextBox txtpwd = (TextBox)login.FindControl("Password");
        txtpwd.AutoCompleteType = AutoCompleteType.Disabled;
       // login.UserName.Focus();
        // Response.Write("suresh");
    }
    protected void lbForgotPassword_Click(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)login.FindControl("UserName");
        ////Response.Write(txt.Text.ToString());
        ////Response.End();

        if (txt.Text.Trim() != "")
        {
            if (chkValidUserId() == 0)
            {
                Session["Username"] = txt.Text.ToString();
                Response.Redirect("/_Layouts/ForgotPassword/Forgotpassword2.aspx");
            }
            else
            {
                string strScript1 = "<script language='javascript'>alert('ERR: Please Enter Valid User ID')</" + "script>";
                //this.ClientScript.RegisterClientScriptBlock(this.GetType(), "1", "strScript");
                Response.Write(strScript1);
            }
        }
        else
        {
            string strScript = "<script language='javascript'>alert('Info: Please Enter the User ID')</" + "script>";
            //this.ClientScript.RegisterClientScriptBlock(this.GetType(), "1", "strScript");
            Response.Write(strScript);

        }
    }
    protected int chkValidUserId()
    {
        TextBox txt = (TextBox)login.FindControl("UserName");
        string id = txt.Text.ToString();
        int result = 0;
        Match match = Regex.Match(id, "[^a-z0-9]", RegexOptions.IgnoreCase);
        while (match.Success)
        {
            string key = match.Value;
            //Console.Write(key);
            match = match.NextMatch();
            result = result + 1;
        }
        return result;

    }
    protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string strUser;
        string strLoginname = login.UserName.Trim();
        string strpwd = login.Password.Trim();
        try
        {
            if (login.UserName != null && login.UserName.Trim() != "")
            {
                //MembershipUser user = null;
                //user = Membership.GetUser(strLoginname, true);
                string strProvidername = ConfigurationManager.AppSettings["ProviderName"];
                MembershipProvider _provider = Membership.Providers[strProvidername.Trim()];
                strUser = strLoginname.Trim();
                MembershipUser user = _provider.GetUser(strUser, false);

                string strEmail = user.PasswordQuestion.Trim();
                Session["Username"] = strLoginname;
                if (user.IsLockedOut)
                {
                 
                    login.FailureText = "Your account has been locked";
                    //, Please contact the portal administrator
                }
                else if (strpwd.Length > 15)
                //if (strpwd.Length > 15)
                {
                    login.FailureText = "Maximum password length is 15 characters only.";
                }
                else if (_provider.ValidateUser(strLoginname, strpwd))
                {
                 
                    string strpwdquestion = user.PasswordQuestion.Trim();
                 
                    TimeSpan ts = DateTime.Now - user.LastPasswordChangedDate;
                    int bdays = 0;
                    bdays = 30 - ts.Days;
           if(user.Comment!=null && user.Comment!="")
           {
           string strComment=user.Comment.ToString();
           if(strComment=="1")
           {
                            Response.Redirect("UserPwdReset.aspx");
           }

           }
                    if (ts.Days >= 30)
                    {
                        Response.Redirect("Pwd.html");
                    }
                    //Added by kishore for spuser password reset after 90 days
                    if ((ts.Days > 90) && (strLoginname == "SPUser"))
                    {
                        Response.Redirect("Pwd.html");
                    }

                    if (strpwdquestion.ToLower() == "your company name?")
                    {
                        Session["pwd"] = strpwd;
                       // Response.Write("got it"); Response.End();
                        Response.Redirect("PwdQuesReset.aspx");


                    }

                    //CheckOnlineTest();
                   //"added by kishore"
                    bool status = false;
                    //

                    if (Context.Request.UrlReferrer.ToString().Contains("https://signin.syntel.in"))
                    {
                        //Response.Redirect("https://180.211.66.43/");
                        System.Uri obj = new Uri("https://syntelligence.syntelinc.com/");
                        status = SPClaimsUtility.AuthenticateFormsUser(obj, login.UserName.Trim(), login.Password.Trim());

                    }
                    else
                    {

                        try
                        {
                            status = SPClaimsUtility.AuthenticateFormsUser(Context.Request.UrlReferrer, login.UserName.Trim(), login.Password.Trim());
                        }
                        catch (Exception ex)
                        {
                            Response.Write(status);
                            Response.End();
                        }
                    }



                    if (status)
                    {
         
                        e.Authenticated = true;
                       
                        if (bdays > 0 && bdays < 5)
                        {

                            string strCon = ConfigurationManager.ConnectionStrings["Fbadb_sqlConnectionString"].ToString();
                            // Response.Write(ConfigurationManager.ConnectionStrings["Fbadb_sqlConnectionString"].ToString()); Response.End();
                            SqlConnection con = new SqlConnection(strCon);
                            SqlCommand cmd;

                            string stripadd = HttpContext.Current.Request.UserHostAddress;
                         

                            cmd = new SqlCommand();
                            con = new SqlConnection(strCon);

                            cmd.Connection = con;
                            con.Open();
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.CommandText = "aspnet_InsertToken";
                            SqlParameter[] sqlparams = new SqlParameter[3];

                            sqlparams[0] = new SqlParameter("@userid", System.Data.SqlDbType.VarChar, 50);
                            sqlparams[0].Value = strLoginname;
                            cmd.Parameters.Add(sqlparams[0]);

                            sqlparams[1] = new SqlParameter("@TIn", SqlDbType.DateTime);
                            sqlparams[1].Value = DateTime.Now;
                            cmd.Parameters.Add(sqlparams[1]);

                            sqlparams[2] = new SqlParameter("@IPADD", System.Data.SqlDbType.VarChar, 50);
                            sqlparams[2].Value = stripadd;
                            cmd.Parameters.Add(sqlparams[2]);

                            cmd.ExecuteNonQuery();
                       
                            if (!Context.Request.UrlReferrer.ToString().Contains("_layouts/login.aspx"))
                            {
                                Response.Redirect(Context.Request.UrlReferrer.ToString());
                               // Response.Redirect("http://arospdev01/Functions/ISandIT/Global Service Desk  Survey Feedback Analysis/IS and TSG -Survey consolidated-2013.pdf");
                                // Response.Redirect("https://syntelligence.syntelinc.com/Functions/ISandIT/Global%20Service%20Desk%20%20Survey%20Feedback%20Analysis/IS%20and%20TSG%20–Survey%20consolidated-2013.pdf");

                            }
                            if (Context.Request.UrlReferrer.ToString().Contains("Global Service Desk"))
                            {
                                //Response.Redirect("https://180.211.66.43/");
                                Response.Redirect("http://arospdev01/Functions/ISandIT/Global Service Desk  Survey Feedback Analysis/IS and TSG -Survey consolidated-2013.pdf");
                                // Response.Redirect("https://syntelligence.syntelinc.com/Functions/ISandIT/Global%20Service%20Desk%20%20Survey%20Feedback%20Analysis/IS%20and%20TSG%20–Survey%20consolidated-2013.pdf");

                            }
               if (Context.Request.UrlReferrer.ToString().Contains("SSO Survey Sample"))
                            {
                                Response.Redirect("http://arospdev01/Lists/SSO%20Survey%20Sample/NewForm.aspx");

                            }
         
                            if (Context.Request.UrlReferrer.ToString().Contains("Functions/Legal"))
                            {

                                Response.Redirect("/Functions/Legal/Pages/default.aspx");
                                //Response.Redirect("https://syntelligence.syntelinc.com/Functions/Legal/Pages/default.aspx");

                            }

                            //Added for Telebilling Main Page by Rama K. Sista CM#161134
                            if (Context.Request.UrlReferrer.ToString().ToLower().Contains("telebillinglmainpage.aspx"))
                            {
                             
                                Response.Redirect("http://arospdev01/_layouts/syntranet/TelebillinglMainPage.aspx");
                                //Response.Redirect("https://syntelligence.syntelinc.com/_layouts/syntranet/TelebillinglMainPage.aspx");

                            }                              
                            //end CM#161134

                            //Added for Travel Main Page by Sushanti
                            if (Context.Request.UrlReferrer.ToString().ToLower().Contains("travmainpage.aspx"))
                            {

                                //Response.Redirect("http://arospdev01/_layouts/Travel/Travmainpage.aspx");

                                Response.Redirect("https://syntelligence.syntelinc.com/_layouts/Travel/Travmainpage.aspx");
                            }
                            //Added for Travel Main Page by Sushanti
                             
                            else
                            {
                                Response.Redirect("pwd1.html?bd=" + bdays);
                            }
                        }
                        else
                        {
                            /*************************Fed-auth******************************************/


                            string strCon = ConfigurationManager.ConnectionStrings["Fbadb_sqlConnectionString"].ToString();

                            string stripadd = HttpContext.Current.Request.UserHostAddress;
                       
                            // Response.Write(ConfigurationManager.ConnectionStrings["Fbadb_sqlConnectionString"].ToString()); Response.End();
                            SqlConnection con = new SqlConnection(strCon);
                            SqlCommand cmd;

                            cmd = new SqlCommand();
                            con = new SqlConnection(strCon);

                            cmd.Connection = con;
                            con.Open();
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.CommandText = "aspnet_InsertToken";
                            SqlParameter[] sqlparams = new SqlParameter[3];

                            sqlparams[0] = new SqlParameter("@userid", System.Data.SqlDbType.VarChar, 50);
                            sqlparams[0].Value = strLoginname;
                            cmd.Parameters.Add(sqlparams[0]);

                            sqlparams[1] = new SqlParameter("@TIn", SqlDbType.DateTime);
                            sqlparams[1].Value = DateTime.Now;
                            cmd.Parameters.Add(sqlparams[1]);

                            sqlparams[2] = new SqlParameter("@IPADD", System.Data.SqlDbType.VarChar, 50);
                            sqlparams[2].Value = stripadd;
                            cmd.Parameters.Add(sqlparams[2]);

                            cmd.ExecuteNonQuery();
                         

                            /*************************Fed-auth*****************************************/
                            if (Context.Request.UrlReferrer.ToString().Contains("Global Service Desk"))
                            {
                                //Response.Redirect("https://180.211.66.43/");
                                Response.Redirect("http://arospdev01/Functions/ISandIT/Global Service Desk  Survey Feedback Analysis/IS and TSG -Survey consolidated-2013.pdf");
// Response.Redirect("https://syntelligence.syntelinc.com/Functions/ISandIT/Global%20Service%20Desk%20%20Survey%20Feedback%20Analysis/IS%20and%20TSG%20–Survey%20consolidated-2013.pdf");

                            }
               if (Context.Request.UrlReferrer.ToString().Contains("SSO Survey Sample"))
                            {
                                Response.Redirect("http://arospdev01/Lists/SSO%20Survey%20Sample/NewForm.aspx");

                            }
                            if (Context.Request.UrlReferrer.ToString().Contains("Functions/Legal"))
                            {
                                Response.Redirect("/Functions/Legal/Pages/default.aspx");

                                //Response.Redirect("https://syntelligence.syntelinc.com/Functions/Legal/Pages/default.aspx");

                            }
                            //Added for Telebilling Main Page by Rama K. Sista CM#161134
                            if (Context.Request.UrlReferrer.ToString().ToLower().Contains("telebillinglmainpage.aspx"))
                            {
               Response.Redirect("http://arospdev01/_layouts/syntranet/TelebillinglMainPage.aspx");
                                //Response.Redirect("https://syntelligence.syntelinc.com/_layouts/syntranet/TelebillinglMainPage.aspx");
                             
                            }
                            //End CM#161134

                            //Added for Travel Main Page by Sushanti
                            if (Context.Request.UrlReferrer.ToString().ToLower().Contains("travmainpage.aspx"))
                            {

                               // Response.Redirect("http://arospdev01/_layouts/Travel/Travmainpage.aspx");
                                Response.Redirect("https://syntelligence.syntelinc.com/_layouts/Travel/Travmainpage.aspx");

                            }
                            //Added for Travel Main Page by Sushanti
                             
                            else
                            {
                                Response.Redirect("/pages/default.aspx");
                            }
                         
                         
                        }

                    }

                    else
                    {

                        e.Authenticated = false;
                        login.FailureText = "Invalid login id or password";



                    }

                }
                else
                {
                    login.FailureText = "Invalid login id or password";
                 

                }
            }

            //bool status = false;
            ////

            //if (Context.Request.UrlReferrer.ToString().Contains("https://signin.syntel.in"))
            //{
            //    //Response.Redirect("https://180.211.66.43/");
            //    System.Uri obj = new Uri("https://syntelligence.syntelinc.com/");
            //    status = SPClaimsUtility.AuthenticateFormsUser(obj, login.UserName.Trim(), login.Password.Trim());

            //}
            //else
            //{

            //    try
            //    {
            //        status = SPClaimsUtility.AuthenticateFormsUser(Context.Request.UrlReferrer, login.UserName.Trim(), login.Password.Trim());
            //    }
            //    catch (Exception ex)
            //    {
            //        Response.Write(status);
            //        Response.End();
            //    }
            //}



            //if (status)
            //{

            //    e.Authenticated = true;
            //    Response.Redirect("/pages/default.aspx");

            //}

            //else
            //{

            //    e.Authenticated = false;
            //    //login.FailureText = "Invalid login id or password";
            //    login.FailureText = "Login failed";
                             

            //}
        }
        catch (Exception ex)
        {
            e.Authenticated = false;
            login.FailureText = "Invalid login id or password";
            //login.FailureText = ex.Message.ToString() ;
        }
     

         

    }
     
    </script>

<div align="center">
<script language="javascript"> history.forward(-1)


function validate()
{

   var id = document.getElementById('ctl00_PlaceHolderMain_login_UserName')

   if (id.value == '')
   {
       alert('Kindly Enter User ID')
       return false;
   }
   else
   {
        //alert(id.value);
       //window.open('/_layouts/ForgetPwd.aspx?userid='+id.value,'_self');
       if(chkUserId()==0)
   {
              window.open('/_Layouts/ForgotPassword/Forgotpassword2.aspx?userid='+id.value,'_self');
            }
   else
   {
        alert("Please enter valid userid");
        return false;
   }
           
   }
   
}
    function chkUserId()
    {
        var id = document.getElementById('ctl00_PlaceHolderMain_login_UserName').value;
        var result=0;
        for(var j=0; j<id.length; j++)
   {
     var alphaa = id.charAt(j);
     var hh = alphaa.charCodeAt(0);
     if((hh > 47 && hh<58) || (hh > 64 && hh<91) || (hh > 96 && hh<123))
     {
         
     }
     else
     {
       result=result+1;
     }
  }
     return result;
   
    }
function opensecQues()
{
   var id = document.getElementById('ctl00_PlaceHolderMain_login_UserName');
        if (id.value == '')
   {
       alert('Kindly Enter User ID')
       return false;
   }
   else
   {
   
       window.open('/_Layouts/ForgotPassword/SecurityQuestion.aspx?userid='+id.value,'_self');
 
   }
}


</script>
<div align="center">
        <table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
            <tr>
                <td colspan="3" height="4">
            </td>
            </tr>
            <tr>
                <td width="5"  height="4">
            </td>
           
 <td width="554">
                <img src="/_layouts/IMAGES/Lock.jpg">
                </td>
                <td width="400" valign="top" >
             
              <center>  <div  style="BACKGROUND: url(/_layouts/IMAGES/articleTopLogin.gif) no-repeat; WIDTH: 405px; height:205px">
                    <asp:Login ID="login"  FailureText="<%$ Resources:wss,login_pageFailureText %>" TitleText="Sign In" TitleTextStyle-Font-Underline=true TitleTextStyle-ForeColor=#003366 TextBoxStyle-Font-Names="Verdana" TitleTextStyle-Font-Bold="true" TextBoxStyle-Font-Size="18px" TitleTextStyle-Height="50"
                        UserNameLabelText="User Id:" RememberMeSet=true    PasswordLabelText="Password:" OnAuthenticate="Login_Authenticate"
                        TitleTextStyle-Width="300px"  CheckBoxStyle-CssClass="ih-Checkox" CheckBoxStyle-ForeColor="#003366"  DisplayRememberMe=false runat="server"
                         LabelStyle-CssClass="LabelRightLog">
                        <InstructionTextStyle Font-Italic="True" ForeColor="Black"  />
                        <TextBoxStyle  Font-Size="X-Small" Width="150" />
                        <LoginButtonStyle  BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px"
                            Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" Width="50px" CssClass="loginButton"  />
                    </asp:Login>
                           
           <%--                  
<div style="vertical-align:middle" >
<a id="A1" href="ForgetPwd.aspx"  style="color: red; font-size:9pt">
Forgot Password?</a></div>--%>
<center>
                         <%--<div style="vertical-align:middle;"  ><a id="A1" href="javascript:void()" onclick="return validate();"   style="color: red; font-size:9pt">Forgot Password?</a></div>--%>
                         <div style="vertical-align:middle;"><asp:LinkButton id="lbForgotPassword" Text="Forgot Password?" OnClick="lbForgotPassword_Click"  runat="server" style="color: red; font-size:9pt"/></div>
                         </center>
                         <table>
                           <tr><td style="font-size:8pt; font-weight:normal; text-align:left">&#8226; Please note 3 incorrect attemps will lock your account.</td></tr>
                             <tr><td style="font-size:8pt; font-weight:normal; text-align:left">&#8226; Please use Forgot password link to get a new password.</td></tr>
<tr><td style="font-size:8pt; font-weight:normal; text-align:left">&#8226; Please use Single Signon (SSO) to manage your passwords.</td></tr>
                            </table>
</div></center>

<div  style="BACKGROUND: url(/_layouts/IMAGES/articleLoginbot.gif) no-repeat; WIDTH: 405px;"></div>
                </td>
            </tr>
             <tr>
                <td colspan="3" height="1">
            </td>
           
            </tr>

        </table>
    </div>

<script>
    function openwnd()
    {
   // window.open('/_Layouts/ForgetPwd.aspx','_new');
    window.open('/_Layouts/ForgotPassword/Forgotpasswrod1.aspx','_new');
    }
    </script>
</asp:Content>


No comments:

Post a Comment