Cross-site Request forgery csrf/xsrf< II: Application >

Source: Internet
Author: User
Tags csrf attack

There are two main types of <java examples of defense methods >

1. Check the Referer field

There is a referer field in the HTTP header that indicates which address the request originated from. When processing sensitive data requests, typically, the Referer Word field and the requested address are located under the same domain name. For example, the Referer field address should be the address of the Web page where the transfer button is located, and should also be under www.examplebank.com. In the case of a request from a csrf attack, the Referer field will be the address that contains the malicious URL, not under Www.examplebank.com, when the server can identify malicious access.

This approach is simple and low-effort, requiring only one step verification at the critical access point.

  * * * But this approach also has its limitations because it relies entirely on the browser to send the correct referer field. Although the HTTP protocol explicitly stipulates the contents of this field, it does not guarantee the specific implementation of the visiting browser, nor does it guarantee that the browser does not have a security vulnerability affecting this field. And there is also the possibility of attackers attacking certain browsers and tampering with their referer fields.

Check the Referer field as follows:

@Override Public voidDoFilter (ServletRequest servletrequest, Servletresponse servletresponse, Filterchain filterchain) throwsIOException, servletexception {httpservletrequest httpreq=(httpservletrequest) ServletRequest; HttpServletResponse Httpresp=(HttpServletResponse) servletresponse; String Path=Httpreq.getcontextpath (); String BasePath= Servletrequest.getscheme () + "://" +Servletrequest.getservername ()+ ":" + servletrequest.getserverport () + path + "/"; //anti-CSRF: HTTP header settings Referer filteringString referer = Httpreq.getheader ("Referer");//REFRESH        if(Referer! =NULL&& Referer.indexof (BasePath) < 0) {//***             //to determine that access is unsafeString Ctxpath =Httpreq.getcontextpath (); Httpresp.sendredirect (Ctxpath+ "/common/gonosecurity.do"); return;    } filterchain.dofilter (ServletRequest, HTTPRESP); }

2. Add a checksum token

Because the nature of CSRF is that attackers deceive users into accessing their own set of addresses, if a request for access to sensitive data is required to require the user's browser to provide a cookie that is not in existence and the attacker cannot forge the data as a checksum, the attacker can no longer perform a csrf attack. This data is usually a data item in the form. The server generates and attaches it to the form, and its content is a pseudo-random number. When the client submits the request through the form, the pseudo-random number is also submitted for verification. Normal access, the client browser can correctly get and return this pseudo-chaos, and through the csrf of deception attacks, the attacker can not know beforehand the value of this pseudo-chaotic number, the server side will be because the value of the checksum token is empty or error, rejected the suspicious request.

Token validation rules:

A. A token field is generated when the account is logged in and the token is passed into the session;

B. When the front-end sends the request, uses the session object in the JSP to obtain the token, and uploads it to the backstage;

C. Whether the token parameters in the filter request and the token parameters in the session are consistent;

D. If it is the same, then pass through; inconsistency jumps to the unsafe page.

The code is as follows:

A. A token field is generated when the account is logged in and the token is passed into the session;

    Private voidMainlogindirect (HttpServletRequest request,map<string, object>Respmap, Integer islogin, Regaccout account) {        //Salt EncryptionRegsalt rs=Regaccoutservice.getregsaltbyaccname (Account.getacc_name ()); if(rs==NULL) {respmap.put (Const.ajax_service_message,"Invalid user! "); }Else{String password=Account.getpassword (); String Password1=request.getparameter ("Password"); String ISVIP=request.getparameter ("Isvip"); String Salt=Rs.getsalt (); if(Cryptoutils.verify (password, password1, salt)) {//Password is correctSessionutil.setattribute (Const.session_csrftoken,srmstringutil.getuuid ());//***Create tokens, anti-CSRFRespmap.put ("PW",true); }Else{//The password is not correctRespmap.put (const.ajax_service_message, "password is wrong! Please re-enter.) "); Respmap.put ("PW",false); }        }    }

B. When the front-end sends the request, uses the session object in the JSP to obtain the token, and uploads it to the backstage;

functionAsyncajaxmethod (URL,PARAMS,ISASYNC,FN) {Params.csrftoken= "${sessionscope.csrftoken}"; // *** Get token $.ajax here ({type:"POST", Async:isasync, Url:getwebroot ()+URL, DataType:' JSON ', Data:params,//* * * beforesend:function () {               $("Body"). Append ("<div id= ' spin_wrap ' ></div>"); $("#spin_wrap"). AddClass ("Spin_mask")); Spinner.spin (document.getElementById ("Spin_wrap")); }, Success:function(Result) {//turn off loding effectsSpinner.spin (); $("Body #spin_wrap"). Remove (); if(result.success==false){                    //artificially thrown exception, but requires setting Success=false                    if(result.ajaxerrorcode==999){                        if(Hasremainloginpop ()) {//have popup login boxremindlogin_flag=true; }                        if(!Remindlogin_flag) {Window.wxc.xcConfirm ("Login timeout, please log in again", Window.wxc.xcConfirm.typeEnum.confirm, {onClose:function(){//Timeout, the login box pops upWindow.pluglogin ();                        }                            }); }                    }Else if(result.ajaxerrorcode==970) {Go_redirect ("Error/nosecurity.htm"); }Else if(result.ajaxerrorcode==980) {Go_redirect ("Error/bekick.html"); }Else if(result.ajaxerrorcode==300)                    {                        varOption ={title: "Hint", Btn:parseint ("0001", 2)};                    Window.wxc.xcConfirm (Result.message, window.wxc.xcconfirm.typeenum.custom,option); }                    Else                    {                        //300: Request parameter ExceptionWindow.wxc.xcConfirm ("The operation failed, please try again later", Window.wxc.xcConfirm.typeEnum.error); }                                        }Else{//default Success==true                    if(result.ajaxerrorcode==200){                        if(fn!=NULL&&typeof(fn) = = "function") {fn (result); }                    }Else{window.wxc.xcConfirm (' Sorry, the return flag is wrong, please try again later or contact the Administrator ', Window.wxc.xcConfirm.typeEnum.error); }                }           },           //jump to this point when the exception is not capturedErrorfunction(XMLHttpRequest, Textstatus, Errorthrown) {//turn off loding effectsSpinner.spin (); $("Body #spin_wrap"). Remove (); if(xmlhttprequest.status==404) {Go_redirect ("Error/404.html"); }Else if(xmlhttprequest.status==500) {Go_redirect ("Error/500.html"); }Else{window.wxc.xcConfirm (' Sorry, program exception not caught, please try again later or contact the Administrator ', Window.wxc.xcConfirm.typeEnum.error);    }           }        }); returnRemindlogin_flag;}

C. Whether the token parameters in the filter request and the token parameters in the session are consistent;

D. If it is the same, then pass through; inconsistency jumps to the unsafe page.

if(Taruri.endswith (". Do") &&!iswithouturi (Taruri) && httpreq.getcontenttype ()! =NULL) {String ContentType=Httpreq.getcontenttype (); String Post_csrftoken= ""; if(ContentType! =NULL&& contenttype.contains ("Multipart/form-data") {multiparthttpservletrequest multireq=Multipartresolver.resolvemultipart (httpreq); Post_csrftoken=Multireq.getparameter (Const.session_csrftoken); Req=Multireq; }Else{Post_csrftoken=Httpreq.getparameter (Const.session_csrftoken); }                                //CSRF Defense: Deciding whether to take tokensString csrftoken=(String) Sessionutil.getattribute (Const.session_csrftoken); if(post_csrftoken==NULL|| !csrftoken.equals (Post_csrftoken)) {//* * * to determine token correctness //to determine that access is unsafeHttpresp.sendredirect (ctxpath+ "/common/gonosecurity.do"); return; }                            }

Cross-site Request forgery csrf/xsrf< II: Application >

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.