"Original" C # General Rights Management-Program security checks, which you must consider in place

Source: Internet
Author: User
Tags servervariables

Access to universal permissions has been a year, and now it has been very skilled to share some of the good development ideas under common rights management.

Security vulnerabilities for a small project, may not be a special attention, for a large project, this is particularly important to pay attention to, especially in the development of the project is to be vigilant, below I listed some of the project development need to pay attention to the security

    1. The check of the page text box, what type of content each text box fills is must use regular expression to enforce the restriction, cannot enter useless information casually, this is the first step
    2. For the C/s program, we can directly use regular expression to limit, for B/S page program, we also need to JS authentication and background code verification, because the browser can prohibit JS, so that JS does not work, so we take the way is two steps away, JS verification, need to back-end data must also be strictly verified To prevent malicious data from entering the database, it is important to keep a good door.
    3. Interface call security, through the post and get call interface, know the server's external IP can be directly called, so try to use the intranet, this is a great security risk.
    4. Prevent SQL injection, especially non-numeric text boxes, users can directly fill in the UPDATE statement, you have to check, you can also limit the text box character length to control, a lot of programmers always forget this, the length of the string and the database table fields through the calculation, not too long or too short.

      software development, Use up to two HTML elements is input text box and button label, when the user through the keyboard, mouse action text box to enter the text content, click Submit we need the first step to verify the data.

    • b/s text box

      common regular expressions

      through a number of page security inspection tools to detect, here first listed our development used in the Security Check tool AppScan Source, some of its use tips, here also give a link, appscan use share     

    • c/s text box

    • interface Security

When our interface through the external network call is very insecure, others know the URL can be very easy to call, because the company SMS interface is now my responsibility, every day in the call to send SMS interface, a lot of clients to mobilize, the resulting text messages have tens of thousands, if the hacker knows, That this is the message of the bomber, so for the sake of security in the interface to do a bit of processing, through the intranet IP call interface, the network IP stop using, look at the code

1             //gets the requested URL address2             varIpAddress = DotNet.Business.Utilities.GetIPAddress (true);3             //must be an intranet IP request to call the interface, do security checks, do not meet the requirements, direct return4             if(!Iphelper.islocalip (ipAddress))5             {6result = (int) Messagestatus.iperror;7                 returnresult; 8}

The code is not particularly many, just a few lines of code, so that you can achieve the security requirements, the client call must fill in the domain name or IP request address of the intranet, so that the program can pass the check, we look at the method to obtain the IP address, the parameter true is to represent whether your server is enabled proxy mode, General server if not through the Nginx proxy, you can not fill out, if the server is a proxy must fill in true, so that you can get to the requesting client's real IP address.

1         /// <summary>2         ///get client IP address3         /// </summary>4         /// <param name= "Transparent" >whether the agent is used</param>5         /// <returns>IP Address</returns>6          Public Static stringGetipaddress (BOOLtransparent =false)7         {8             stringIP =string. Empty;9             if(System.Web.HttpContext.Current! =NULL)Ten             { One                 if(Transparent) A                 { -                     if(httpcontext.current.request.servervariables["http_x_forwarded_for"] !=NULL) -                     { theIP = httpcontext.current.request.servervariables["http_x_forwarded_for"]. ToString (); -                     } -                 } -                 if(string. Isnullorwhitespace (IP)) +                 { -                     if(httpcontext.current.request.servervariables["Http_via"] !=NULL) +                     { AIP = httpcontext.current.request.servervariables["http_x_forwarded_for"]. ToString (); at                     } -                     Else -                     { -IP = httpcontext.current.request.servervariables["REMOTE_ADDR"]. ToString (); -                     } -                 } in             } -             returnIP; to}

Next we look at the method to check whether the local IP address, the intranet address is generally 192.168 and so on the beginning of the IP is the server's intranet address, so we determine the beginning can be obtained whether the result of the intranet IP.

1         /// <summary>2         ///Check if it is an intranet IP3         /// </summary>4         /// <param name= "ipAddress" ></param>5         /// <returns></returns>6          Public Static BOOLIslocalip (stringipAddress)7         {8             BOOLresult =false;9             if(!string. IsNullOrEmpty (ipAddress))Ten             { One                 if(Ipaddress.startswith ("192.168.")  A|| Ipaddress.startswith ("172.") -|| Ipaddress.startswith (".")) -                 { theresult =true; -                 } -             } -             returnresult; +}
    • SQL Security

For the front-end request of the ordinary text box, must be done before warehousing to prevent SQL statement check, in the Common Rights Management code, we generally use strong type of entity for database deletion and modification, do not apply the way of splicing SQL statements Database operations, I have been very disgusted splicing SQL and then submit database execution, Although this is very good at debugging time to find the SQL statement of the error, but from a rigorous perspective of the program is not correct, object-oriented tells us to use more entities, more use of strong type. Also splicing SQL statements are generally just into the work of the rookie like to do things, so the development must be more use of ORM Rapid Development Framework (I personally recommend the common Rights Management ORM Development Framework), compatible with multiple databases, can be flexible to switch, execute fast, UI layer does not splice SQL statements, parameterized query, Multi-table query, paging.

for SQL injection vulnerabilities, refer to the SQL injection Vulnerability, We must do a security check for the parameter values we submit to the background.

1         #regionpublic static string Sqlsafe (string value) checks the security of the parameter2         /// <summary>3         ///Check the security of the parameters4         /// </summary>5         /// <param name= "value" >Parameters</param>6         /// <returns>Safety Parameters</returns>7          Public Static stringSqlsafe (stringvalue)8         {9Value = value. Replace ("'",""'");Ten             //value = value. Replace ("%", "'%"); One             returnvalue; A         } -         #endregion

Take a look at the full page request case code, which is a small summary of common rights Management security

        #region public ActionResult List (Pager Pager, String begindate, String endDate, String Oldrecordkey, String newval UE) Get the modification record///<summary>///Get the modification record///</summary>//<param name= "pager" > minutes Page entities </param>///<param Name= "Begindate" > Start date </param>//<param name= "endDate" > End Date & lt;/param>//<param name= "Oldrecordkey" > Original key value, usually a number </param>//<param name= "NewValue" New value modified </param>///<returns></returns> public actionresult List (Pager Pager, string begin            Date, String endDate, String Oldrecordkey, String newvalue) {var dt1 = DateTime.Now; var dbhelper = Dbhelperfactory.gethelper (Basesysteminfo.businessdbtype, basesysteminfo.businessdbconnectionstring)            ;            var paramaterlist = new list<keyvaluepair<string, object>> (); var listwhere = new list<string> ();//Query condition StriNG conditions = null; Change the date range if (!string. IsNullOrEmpty (begindate) &&!string. IsNullOrEmpty (endDate)) {Listwhere.add (string. Format ("{0} between To_date ({1}, ' Yyyy-mm-dd hh24:mi:ss ') and To_date ({2}, ' Yyyy-mm-dd hh24:mi:ss ')", zto_                Modifyentity.fieldcreate_date, Dbhelper.getparameter ("BeginTime"), Dbhelper.getparameter ("EndTime")); Paramaterlist.add (New keyvaluepair<string, object> ("BeginTime", Dblogic.sqlsafe (Convert.todatetime ( Begindate + "00:00:00").                ToString (Basesysteminfo.datetimeformat))); Paramaterlist.add (New keyvaluepair<string, object> ("EndTime", Dblogic.sqlsafe (Convert.todatetime (endDate + " 23:59:59 ").            ToString (Basesysteminfo.datetimeformat))); }//Primary key value if (!string. IsNullOrEmpty (Oldrecordkey)) {Listwhere.add (string. Format ("{0} = {1}", Zto_modifyentity.fieldrecored_key_old, Dbhelper.getparameter (zto_modifyentity.fi(Eldrecored_key_old))); Paramaterlist.add (New keyvaluepair<string, object> (Dbhelper.getparameter (Zto_modifyentity.fieldrecored_key            _old), Dblogic.sqlsafe (Oldrecordkey)); }//Modified new value if (!string. IsNullOrEmpty (NewValue)) {Listwhere.add (string.                Format ("{0} = {1}", Zto_modifyentity.fieldvalue_new, Dbhelper.getparameter (zto_modifyentity.fieldvalue_new))); Paramaterlist.add (New keyvaluepair<string, object> (Dbhelper.getparameter (zto_modifyentity.fieldvalue_new),            Dblogic.sqlsafe (NewValue)); }//Not super admin or high-privileged users can only see their own if (! Hasrole ()) {Listwhere.add (string. Format ("{0} = {1}", zto_modifyentity.fieldcreate_man_id, Dbhelper.getparameter (zto_modifyentity.fieldcreate_man_id                ))); Paramaterlist.add (New keyvaluepair<string, object> (Dbhelper.getparameter (zto_modifyentity.fieldcreate_man_            (ID), userinfo.id));      }      Get sort field var SortField = request["Sort"]; if (string.            IsNullOrEmpty (SortField)) {SortField = zto_modifyentity.fieldcreate_date;            } SortField + = ("" + request["direction"]);            int totalrows; if (Listwhere.count > 0) {conditions + = string.                Join ("and", listwhere);//Build query Condition}//Return column name var backfieldlist = new[] { String. Format ("{0}| |" -' | | {1})                 {0} ", Zto_modifyentity.fieldtable_code,zto_modifyentity.fieldtable_name), Zto_modifyentity.fieldcreate_date, Zto_modifyentity.fieldrecored_key_old, Zto_modifyentity.fieldcoloum_code, ZT O_modifyentity.fieldcoloum_name, Zto_modifyentity.fieldvalue_old, Zto_modifyentity.fieldvalu            E_new, Zto_modifyentity.fieldcreate_man}; var dt = Dblogic.getdatatablebYpage (DBHelper, out Totalrows, Zto_modifyentity.tablename, String.            Join (",", backfieldlist), Pager.pageno, pager.pagesize, conditions, paramaterlist, SortField);            Hashtable HT = BUILDHT (dt, totalrows, DT1);        Return Json (HT, jsonrequestbehavior.allowget); } #endregion

A good ORM framework can help us deal with some simple interfaces in our work, saving time and saving lives.

is looking at my blog This children's shoes, I see you imposing, there is a faint of the king's Breath, there will be a future! Next to the word "recommended", you can conveniently point it, action quasi, I do not accept a penny, you also good to come back to me!

"Original" C # General Rights Management-Program security checks, which you must consider in place

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.