How to Use WebClient to simulate CSRF-controlled website login

Source: Internet
Author: User

Generally, we use the WebRequest class to POST data to the server. However, in many cases, the corresponding server has been verified to see if you are logged in or not from the same domain, these are all simple. We can change their attributes to fool the server. But what should we do if the server implements CSRF control?

If you are not familiar with CSRF, you can ask why G is. Here is a brief introduction. In general, CSRF places a hidden field in a single table page. Then, when the form is submitted, the server verifies whether the NAVEVALUE in the POST contains the field and verifies its value if it contains the field.

The problem arises. In this case, how can we write the data that we POST to the server? Although we can check HTML to find out what this NAME is and what its VALUE is, however, this VALUE usually changes every time it is refreshed. Well, how can we get it during POST?

The common WebRequest methods on the Internet are definitely not good, because they all use this class to first obtain a Stream, and write the data we want to POST to the server in this Stream, however, we do not know the value of CSRF at this time. POST must have encountered an error in the past. In theory, we need to GET it once first, and then parse the obtained HTML to GET the CSRF value, but then we will go to WebRequest. when Creat intends to go to POST, it is equivalent to re-accessing it again, and its CSRF value has changed. It seems that this cannot be done.

Fortunately, we still have webclients that can be used. WebClient allows us to keep an instance, while WebRequest is only created through static methods and cannot be used by changing URLs, this may also be the purpose of Microsoft's new HttpClient in NET4 to unify the HTTP access interface.

Now, what we need to do is inherit WebClient and rewrite the corresponding method. The Code is as follows:

 

public class CookieAwareWebClient : WebClient    {        public string Method;        public CookieContainer CookieContainer { get; set; }        public Uri Uri { get; set; }        public CookieAwareWebClient()            : this(new CookieContainer())        {        }        public CookieAwareWebClient(CookieContainer cookies)        {            this.CookieContainer = cookies;            this.Encoding = Encoding.UTF8;        }        protected override WebRequest GetWebRequest(Uri address)        {            WebRequest request = base.GetWebRequest(address);            if (request is HttpWebRequest)            {                (request as HttpWebRequest).CookieContainer = this.CookieContainer;                (request as HttpWebRequest).ServicePoint.Expect100Continue = false;                (request as HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.5 Safari/537.36";                (request as HttpWebRequest).Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";                (request as HttpWebRequest).Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8,en;q=0.6,nl;q=0.4,zh-TW;q=0.2");                (request as HttpWebRequest).Referer = "some url";                (request as HttpWebRequest).KeepAlive = true;                (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;                if (Method == "POST")                {                    (request as HttpWebRequest).ContentType = "application/x-www-form-urlencoded";                }            }            HttpWebRequest httpRequest = (HttpWebRequest)request;            httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;            return httpRequest;        }        protected override WebResponse GetWebResponse(WebRequest request)        {            WebResponse response = base.GetWebResponse(request);            String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];            if (setCookieHeader != null)            {                //do something if needed to parse out the cookie.                try                {                    if (setCookieHeader != null)                    {                        Cookie cookie = new Cookie();                         cookie.Domain = request.RequestUri.Host;                        this.CookieContainer.Add(cookie);                    }                }                catch (Exception)                {                }            }            return response;        }    }



We can see that the most important thing is to make good use of the CookieContainer class. The next step is how to use it. We need to first access the login page, get the HTML and then replace the regular expression, get the csrf value, and then POST it to the corresponding server.

 

var cookieJar = new CookieContainer();            CookieAwareWebClient client = new CookieAwareWebClient(cookieJar);            // the website sets some cookie that is needed for login, and as well the 'lt' is always different            string response = client.DownloadString("url for get");            string regx = "<input type=\"hidden\" id=\"lt\" name=\"lt\" value=\"(?<PID>\\S+?)\" />";            // parse the 'lt' and cookie is auto handled by the cookieContainer            string token = Regex.Match(response, regx).Groups[1].Value;            string urlforlogin = "url for login";            string postData =                string.Format("username={0}&password={1}&lt={2}", "user", "pass", token);            client.Method = "POST";                        response = client.UploadString("url for login", postData);            client.Method = "GET";


Now we can end it. In the later stage, we will change different URLs to DownloadString, also known as crawlers. Next we can perform different data analysis based on different services.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.