防止注入式攻击

来源:互联网 发布:mac系统ps 编辑:程序博客网 时间:2024/04/30 13:57

网站的后台就想是自家的后花园,如果谁都能进的话,那你的家不就成了公园.没有一点的安全行可言,现在有很多的网站后台都存在着安全隐患.

     注入式攻击是指利用设计上的漏洞,在目标服务器上运行sql命令以及进行其他方式的攻击,动态生成sql命令是没有对用户输入的数据进行验证,这是注入式攻击得逞的主要原因.

    例如: 如果用户的查询语句是 select * from tbadmin where name='"+loginname+"' and pwd='"+loginpwd+"',那么,如果用户名为1'or'1'='1,则查询语句就变成:select * from admin where tbadmin='1 or '1'='1' and pwd='"+loginpwd+"'   经系统核对无误,从而进入程序管理页面,就可以为所欲为了.所以在用户登陆时,一定要进行检查.特别是一些特殊字符,比如单引号,双引号,分号,逗号,冒号,连接号等一些危险字符进行转换或是过滤.

需要过滤的字符串有:

 /// <summary>
    /// 避免危险字符
    /// 作者:谢良超
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string Inputstring(string str)
    {
       
        str = str.Replace("'", "''");
        str = str.Replace("*", "");
        str = str.Replace("&", "&amp;");
        str = str.Replace("<", "&lt;");
        str = str.Replace(">", "&gt");
        str = str.Replace("/n", "<br/>");
        str = str.Replace("/r/n", "<br/>");
        str = str.Replace("?", "");
        str = str.Replace("select", "");
        str = str.Replace("insert", "");
        str = str.Replace("update", "");
        str = str.Replace("delete", "");
        str = str.Replace("create", "");
        str = str.Replace("drop", "");
        str = str.Replace("delcare", "");
        return str.Trim();
    }

      这还不是最有效的方法,最有效的方法是通过以下方法,可以通过参数把非法字符过滤掉:

 /// <summary>
    /// 防止注入式攻击
    /// 作者:谢良超
    /// </summary>
    /// <param name="loginname"></param>
    /// <param name="loginpwd"></param>
    /// <returns></returns>
    public int checkLogin(string loginName, string loginPwd)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["strcon"]);
        SqlCommand myCommand = new SqlCommand("select count(*) from tbuser where name=@loginName and pwd=@loginPwd", con);
        myCommand.Parameters.Add(new SqlParameter("@loginName", SqlDbType.NVarChar, 20));
        myCommand.Parameters["@loginName"].Value = loginName;
        myCommand.Parameters.Add(new SqlParameter("@loginPwd", SqlDbType.NVarChar, 20));
        myCommand.Parameters["@loginPwd"].Value = loginPwd;
        myCommand.Connection.Open();
        int i = (int)myCommand.ExecuteScalar();
        myCommand.Connection.Close();
        return i;
    }

以上方法是我自己摸索出来的不一定管用,如有不到之处望大家谅解,也希望大家能提出更好的方法,吾将不胜感激!

原创粉丝点击