如何保护Ajax链接请求? [英] How to secure Ajax link requests?

查看:53
本文介绍了如何保护Ajax链接请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象下一个场景:用户想要注册到网页并填写表格.在他填写表单时,jQuery会通过正则表达式进行检查,如果字段有效,等等. ..

以电子邮件作为用户注册后将使用的主键,需要使用

首先清空身体,然后导航回我们想要的任何位置.但是,javascript/jquery将整个内容捕获为字符串,然后我只提取了[和]之间的字符串.该令牌仅可用于下一个请求,因此每个AJAX请求都将具有其唯一的令牌.在第二次请求中,刚刚使用的令牌被删除.

获得令牌后,将其作为参数附加到我请求的任何链接上,如下所示:

ajaxRequestObjet = $.ajax({
    url: "http://localhost:8084/mywebsite.com/servlet", //<-- local tomcat server
    method: "POST",
    data: "type=AJAX&page=some-article&token=fmf5p81m6e56n4va3nkfu2ns8n"
});

此方法对手动检查网站并尝试使用链接的人有效,但是自动执行此操作的java/php/IIS服务器又如何呢?

为此要求标题!像这样:

boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With")); 

只有在存在XMLHttpRequest的情况下,它才会为真.

最后一件事要牢记.确保'Access-Control-Allow-Origin' header is NOT present in your app以确保服务器中未包含任何javascript都不会获取服务器资源.如果此标头不存在,chrome将返回此标头:

XMLHttpRequest cannot load http://localhost:8084/mywebsite.com/servlet. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

Java服务器位于tomcat中,我对此测试使用了另一个apache,这是apache中存在的小html,它给出了上面的错误:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

    <script>
    ajaxRequestObjet = $.ajax({
        url: "http://localhost:8084/mywebsite.com/servlet",
        method: "POST",
        data: "type=AJAX&page=Token"
    });

    ajaxRequestObjet.done(function (msg) { 
        alert(msg);
    });

    </script>

</head>
<body>
</body>
</html>

解决方案

虽然您无法100%控制它...但是有一些选择..

尝试使用与验证码脚本相同的方法.

基本上在用户加载表单/页面时..您在其PHP会话中生成一个随机字符串/id并将其存储..当他们发送ajax请求时,让您的ajax检查还附加字符串/id并要求它在允许执行检查之前,否则返回标头500或其他内容.

使用这种会话方法,您可以设置允许的支票限制(例如5),并且一旦用户尝试了5次以上的支票,就要求他们重新加载页面或执行人工支票(例如Captcha).然后重置其计数.甚至允许在1小时内/每个IP或其他内容总共说30个.

还可以使用智能事件在完成Ajax检查时触发,例如,更改字段/选项卡或按下按钮时.或者在检测到有效电子邮件时,但是说.com.au将触发两次.

基本上,即使有人嗅探您的JS文件并尝试自动执行电子邮件检查器,也是如此.这将要求他们找到一种方法来附加您生成的字符串/id,并限制其执行的请求数量.

除此之外,您还可以轻松完成更多工作..但是还有其他一些想法.

其中大多数都可以使用PHP会话/cookie解决.例如,如果他们检查并找到3个电子邮件地址..然后再次将其设置为限制,并强迫他们要求手动提交内容或其他内容.

看看上面的建议对您有何帮助,任何问题都可以随时提出.但是周末可能要花一两天才能回复我.还要研究Captcha脚本如何为它们提供足够的源代码.

时间延迟只会看起来很糟糕/使您的网站显示缓慢/使用户等待响应的错误.

您需要限制每个会话/ip地址的查找量.否则,总有一种方法可以通过这些检查..基本上,一旦它们达到限制..强制用户/ip/会话等待几分钟/小时,然后使用验证码脚本对其进行验证,以使其无法编写脚本...

JavaScript安全性/隐藏源代码

虽然您不能真正做到这一点,但是您可以做一些事情,使用带有JS标头的PHP页面生成JS..因此<script src='myjscode.php'></script>,这使PHP可以检查有效的会话.

多次检查/在这种情况下(如果可能)

取决于您的方法,这是供用户检查他们是否已经拥有帐户的吗?如果是这样..您可以将电子邮件支票与他们的姓名/国家/地区/年龄/出生日期等结合使用...因此,他们需要选择两个或三个正确的匹配值,然后才能从ajax调用中获取支票/响应?

也许不是您的情况,但只是想将其也添加进来.

Imagine the next scenario: a user wants to register to a webpage and fills a form. While he is filling the form, jQuery keeps checking through a regular expression if fields are valid, etc...

Taking the email as the primary key which the user will use after registering to login, the email field needs to be checked with Ajax to let the user know if that email is registered or not. I want to check it with Ajax to avoid sending the full form and emptying it, refreshing page, etc...

So, when the user has ended filling the email field, the Ajax request is sent to the server, something like the next link:

example.com/check.php?email=abcdefg@gmail.com

When check.php receives the email, it asks the database if it exists or not and returns a message like: User already exists if user exists or null if user does not exist.

The question is: if someone digs through my .js and finds out links similar to that, they could use that link to send a large number of requests to find out if those random emails exist. This could lead to heavy use of the database or in the worst cases even crashing and private information leaks.

Someone could do a huge for loop to check emails like:

//Getting the response of the next links
example.com/check.php?email=aaaaaaa@gmail.com // Returns null
example.com/check.php?email=aaaaaab@gmail.com // Returns null
example.com/check.php?email=aaaaaac@gmail.com // Returns null
example.com/check.php?email=aaaaaad@gmail.com // Returns User already exists

------------------------------------------------------------------------------------------------------------------------------------

Since i last accepted the answer, i kept investigating this and found the solution to avoid this behaviour. The following code is for JAVA but the logic can be applied to any other server-side language.

Before doing ANY ajax request to the server, I request a token to the server. This token looks like this fmf5p81m6e56n4va3nkfu2ns8n it is made by a simple method, it can, however, be more complex, but this is good to go.

public String getToken() throws UnsupportedEncodingException {
    return new BigInteger(130, new SecureRandom()).toString(32);
}

When requesting the token, the server does not only return the token, but also a small script that in case someone uses browser to inspect element (and browser navbar) and such the script will run and the token will be cleared. Servlet returns something like this:

_html += "<head>"
    + "<script> "
    + "window.onload=function(){\n"
    + "       document.body.innerHTML = \"\";\n"
    + "    }"
    + "window.location.href='http://mywebsite.com' "
    + "</script>"
    + "</head>"
    + "<body>"
    + "[" + token+ "]"
    + "</body>"
    + "</html>";

First empties the body then navigates back to wherever we want. javascript/jquery will however, catch the entire content as string, then I simply extract the string between [ and ]. This token is only available for the next request, so every AJAX request will have its unique token. On the 2nd reques the token just used is deleted.

After I get the token I append it as parameter to whatever link i request, something like this:

ajaxRequestObjet = $.ajax({
    url: "http://localhost:8084/mywebsite.com/servlet", //<-- local tomcat server
    method: "POST",
    data: "type=AJAX&page=some-article&token=fmf5p81m6e56n4va3nkfu2ns8n"
});

This method works fine against someone who inspects the website manually and try to use the links, but what about java/php/IIS servers that do this automaticly?

For this ask for header! Something like this:

boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With")); 

It will be true only and only if XMLHttpRequest exists....

There is one last thing to keep in mind. Make sure 'Access-Control-Allow-Origin' header is NOT present in your app to make sure that any javascript NOT in your server wont get the server resources. If this header does not exist, chrome will return this:

XMLHttpRequest cannot load http://localhost:8084/mywebsite.com/servlet. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

Java server was in tomcat and I had another apache for this tests, this is the small html present in apache which gave the error above:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

    <script>
    ajaxRequestObjet = $.ajax({
        url: "http://localhost:8084/mywebsite.com/servlet",
        method: "POST",
        data: "type=AJAX&page=Token"
    });

    ajaxRequestObjet.done(function (msg) { 
        alert(msg);
    });

    </script>

</head>
<body>
</body>
</html>

解决方案

While you can not control this 100%... there are a few options..

Try using the same methods that people use with Captcha scripts..

Basically when the user loads the form / page.. You generate a random string/id in their PHP session and store it.. When they send the ajax requests, have your ajax check also append the string/id and require it before allowing a check to perform else return a header of 500 or something..

Using this approach with sessions, you could set a allowed limit of checks (say 5) and once the user has tried more than 5 checks, They are required to reload the page or perform a human check (eg Captcha).. Then it resets their count.. Even allow a total of say 30 within 1 hour / per IP or something.

Also use smart events to trigger when the ajax check is done, eg field/tab change or on a button press.. Or when a valid email is detected.. but say .com.au would trigger twice.

Basically this way, even if someone sniffed your JS files and tried to automate the email checker.. It would require them finding a way to append the string/id that you generate and also limit their amount of requests performed.

Beyond this, there is not to much more you can do easily.. But there are still a few other idea's.

Most of them would work around using a PHP session / cookie.. Say for example if they check and find 3 email addresses.. Then again you set that as a limit and force them to require a manual submission or something.

See how the above suggestion goes for you, any questions do feel free to ask. But may take me a day or two to reply as weekend.. Also research how Captcha scripts work as plenty of source code for them.. As they work on the same idea.

Time Delays will simply look bad / make your site appear slow / bug the user with waiting for a response.

You need to limit the amount of look up's per session / ip address.. Otherwise there is always a way to get past these checks.. Basically once they hit a limit.. Force the user/ip/session to wait a few minutes/hours and verify them with a Captcha script so it can not be scripted...

Javascript Security / Hiding The Source

While you can not do this truly, you can do certain things generate the JS using a PHP page with a JS header.. so <script src='myjscode.php'></script> and this allows PHP to check for a valid session.. So stops external requests to an extent.. But this is mostly useful for allowing JS to be only available behind a membership/login..

Multiple Checks / If Possible In This Case

Depending on your approach, is this for a user to check if they already have an account? If so.. you could combine the email check with something like their name/country/age/dob ... So they would need to select two or three correct matching values before being able to get a check/response from the ajax call?

Maybe not in your case, but just thought would add this as well.

这篇关于如何保护Ajax链接请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆