字符串注入攻击

                //查询编号和名称(必须一致才能获取)

                Console.Write("请输入编号");
                string ids = Console.ReadLine();
                Console.Write("请输入名称");
                string name = Console.ReadLine();


                string str = "server=.;database=mydb;user=sa;pwd=123";
                SqlConnection conn = new SqlConnection(str);

                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "select * from fruit where    name='"+name+"' and ids='"+ids+"'";//字符串拼接容易被攻击

                conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    Console.Write(dr["ids"].ToString() + "    ");
                    Console.Write(dr["name"].ToString() + "    ");
                    Console.Write(dr["price"].ToString() + "    ");
                    Console.Write(dr["source"].ToString() + "    ");
                    Console.Write(dr["stack"].ToString() + "    ");
                    Console.WriteLine(dr["image"].ToString());

                }

                conn.Close();
                //解决方案
Console.Write("请输入编号"); string ids = Console.ReadLine(); Console.Write("请输入名称"); string name = Console.ReadLine(); string str = "server=.;database=mydb;user=sa;pwd=123"; SqlConnection conn = new SqlConnection(str); SqlCommand cmd = conn.CreateCommand(); //字符串注入攻击 ‘空格or 1=1 -- //避免攻击 占位符赋值 //cmd.CommandText = "select * from fruit where ids=@ids and name=@name"; //cmd.Parameters.Clear(); //cmd.Parameters.Add("@ids", ids); //cmd.Parameters.Add("@name", name); //parameters集合 使其作为整体放进去,而不是拼接 conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Console.Write(dr["ids"].ToString() + " "); Console.Write(dr["name"].ToString() + " "); Console.Write(dr["price"].ToString() + " "); Console.Write(dr["source"].ToString() + " "); Console.Write(dr["stack"].ToString() + " "); Console.WriteLine(dr["image"].ToString()); } conn.Close();

 

解决前

解决后

posted @ 2016-03-31 16:37  苍穹丶  阅读(704)  评论(0编辑  收藏  举报