I have a following system on my PHP site like twitter. To follow another a user, the user will click a follow button on the profile of a user they want to follow.
I then send an ajax post request with the ID of the user they want to follow.
I'm trying to work out how to prevent a user spam following everyone by writing this in the browser console:
for(var i = 0; i<10000000; i++){
followUser(i) // followUser is the ajax request
}
My proposed solution is:
Add a single use token to each request and check against the token stored in the session, like CSRF/double-submit protection.
Is there any problems with that solution? I looked at using anonymous JavaScript functions but it seems more secure to prevent these things on the server side not the client.
Is there any problems with that solution?
If you store the token in the per-document DOM/JS context, then you potentially break navigation and multi-tab usage of your application. (eg imagine Following someone then clicking Back and Following someone on the previous page. The old page's token is now invalid and the operation fails.) This is the reason single-use CSRF tokens are generally a bad thing.
it seems more secure to prevent these things on the server side not the client.
Indeed, but a single-use token doesn't really prevent a user making mass requests, it just means they have to grab a new token each time.
It sounds like what you would really need is some kind of server-side rate-limiting solution. That could be implemented at the server level (mod_evasive et al) and/or in the application (necessary if you want targeted limiting of particular functions identified as sensitive).
What's your threat model? Having one account follow everyone doesn't immediately seem like a attack; what's the negative impact and why would an attacker want to do it? If it's something like “to cause a nuisance by sending follow notifications to everyone” maybe a better answer would lie in providing better tools to manage/ignore notifications, for example.
Related
Here's a security problem I've encountered a couple of times when building small web-based projects interacting with a REST API service. For example, let's say you're building a casual JavaScript-based game where you want a leaderboard of highscores, so you need to post the scores of users to a database.
The easiest solution would be to build a simple web service, e.g. using PHP, Node.js or Python, that accepts GET request and saves the results to a database. Let's imagine the API looks something like this:
GET https://www.example.com/api/highscore?name=SuperGoat31&score=500
Creating such an API for posting highscores has some obvious drawbacks. A malicious user could write a three-line piece of PHP code to spam the database full of false results, for example:
for ($i = 0; $i < 100; i++) {
file_get_contents("https://www.example.com/api/highscore?name=SuperGoat31&score=5000000");
}
So, I'm looking for a way to prevent that. This mostly relates to small hobby or hackathon projects that just need some kind of protection that will prevent the most obvious of attacks, not large enterprise applications that need strict security. A couple of things I could think of:
1. Some form of authentication
An obvious way to solve this would be to have user accounts and only allow requests from logged-in users. This unfortunately has the drawback of putting up a large barrier for users, who need to get an account first. It would also require building a whole authentication workflow with password recovery and properly encrypting passwords and the like.
2. One-time token based protection
Generate a token on the server side and serve that to the user on first load, then only allow requests that serve that specific token. Simple enough, but also very easy to circumvent by finding the requests in a browser web inspector and using that for the three-line PHP script.
3. Log IP address's and ban when malicious use happens
This could work, but I feel it's not very privacy friendly. Also, logging IP addresses would require GDPR consent from users in Europe. Also doesn't prevent the actual spamming itself so you might to first clean up the mess before you start banning IP addresses.
4. Use an external service
There are services that provide solutions to this problem. For example, in the past I've used Google's reCAPTCHA to prevent malicious use. But that also means integrating an external service, making sure you keep it up to date, concerns about the privacy aspects (esp. regarding a service like reCAPTCHA), etc. It feels a bit much for a weekend project.
5. Throttle requests
I feel this is probably the easiest solution that actually works for a bit. This does require some form of IP address logging (which might give the problems stated in 3), but at least you can delete those IP addresses pretty quickly afterwards.
But I'm sure there are other methods I've missed, so I would be curious to see other ways of tackling this problem.
Taking into account all mentioned limitations, I would recommend using a combination of methods:
Simple session authentication based on one-time token
Script obfuscation
Request encryption with integrity control
Example:
let req_obj = {
user: 'SuperGoat31',
score: 123456,
sessionId: '4d2NhIgMWDuzarfAY0qT3g8U2ax4HCo7',
};
req_obj.hash = someCustomHashFunc(JSON.stringify(req_obj));
// now, req_obj.hash = "y0UXBY0rYkxMrJJPdoSgypd"
let req_string = "https://www.example.com/api/cmd?name=" +
req_obj.user +
"&data=" +
Buffer.from(JSON.stringify(req_obj)).toString('base64');
// now, your requests will look like that:
"https://www.example.com/api/cmd?name=SuperGoat31&data=eyJ1c2VyIjoiU3VwZXJHb2F0MzEiLCJzY29yZSI6MTIzNDU2LCJzZXNzaW9uSWQiOiI0ZDJOaElnTVdEdXphcmZBWTBxVDNnOFUyYXg0SENvNyIsImhhc2giOiJ5MFVYQlkwcllreE1ySkpQZG9TZ3lwZCJ9"
For casual players, this allows start playing very quickly, as no explicit registration is required. Upon generation, token might be saved as cookie for repetitive use, but this is not necessary, single-time use would also suffice. No personal info gathered.
However, if short-term storage of some client information is an option, the token might be not just some random bytes, but an encrypted string, containing some parameters, such as random salt + IP address + nickname + agent id + etc. In this case you may start silently ignore certain requests from fraudulent clients upon detection.
Obviously, this would be very easy to crack for a professional, but this is not our goal. When such simple methods are mixed with several kilobytes of logic of the game and obfuscated, figuring out how to deal with it would require significant amount of knowledge and time, which might serve as a sufficient barrier.
As it is all about balance between convenience and protection, you may implement some additional scoring logic to detect cheating attempts, like final score cannot end with '0', or cannot be even, etc. This would allow you to count cheating attempts (in addition to counting forged requests) and then estimate efficiency of implemented combination of methods.
Your list of solutions are mostly mitigations, and they are good ideas if they are your only tools. The list seems pretty exhaustive.
2 major ways to actually solve this problem are:
Remove the incentive of cheating. There's no point submitting a fake score if you are the only person who can see the score. Think about the purpose of why you even want a global high-score list. Maybe there's another way you can reach your objective that makes it uninteresting (or undesirable) to cheat.
Have the server completely manage (or duplicate) the game state. You can't cheat if the server calculates the score. For example, if you're modelling a chess game the server can compute every valid move, preventing clients from submitting moves that wouldn't be possible.
It's possible that for your specific case neither are possible, but if you can't adopt either of these strategies you are stuck to imperfect detection mechanisms.
I suspect that a perfect solution will be elusive because two of
your wishes are, perhaps, contradictory:
"You need to post the scores of users to a database" but... "prevent
the most obvious of attacks" without "Some form of authentication."
The most obvious of attacks are those from users without some form
of authentication.
You wish this system to work without placing an undue burden on
your users. You wish to avoid the usual login and password
authentication which can be cumbersome for users.
I think there is a way to accomplish what you want by creating a
very simple form of authentication by the use of a one-time token
based protection. And I would also incorporate IP tracking against
abuse. In other words, let's combine your options 1 and 2 and 3 in
the following way.
You already have implied that you will maintain a database, and that
within the database, user names will be unique (otherwise you couldn't
record unique high scores). Let people sign up freely by submitting
their requested user name, which you'll accept if not already used
by someone prior. Track the sign-up requests by IP address to detect
and prevent abuse: too many sign-ups from one IP address within a given timeframe. So far, the burden is all at the server end, not on the user.
When you process a valid sign-up (i.e. new user name) into the
database, you will also generate, record into the database, and return to the user a shared secret (a token) that will be used by the
Time-based One-time Password (TOTP) algorithm.
Don't reinvent this.
See:
Time-based One-Time Password
FreeOTP
OneTimePass
When you return a token to the user, it will be in the form of a "QR Code"
QR code
which the user will scan and store with his "Google Authenticator" or
equivalent TOTP application.
When the user returns to your web site to update his high score, he
will authenticate himself using his Google Authenticator" or
equivalent TOTP application. These are often used for "second factor"
authentication, 2FA (Multi-factor authentication), but because
of your need for less strict security, you'll be using the TOTP
authentication as the primary and only form of authentication.
So we have combined a form of authentication which doesn't place a
very high burden on the user (apps already widely available and in
use), with one-time token based protection (provided by the TOTP
app) and a little bit of IP address-based abuse protection for the initial sign-ups.
On of the weaknesses of my proposal is that a user may share his
TOTP token with another person, who may then impersonate him. But this
is no different from the risk of password sharing. And there will
be no "recover my lost password" option.
I would tackle this in a slightly different way: usernames/gamertags. Depending on how frequently you find gamertags and usernames sharing the same IP. So if you only accept a maximum of, say, 5 gamertags per IP, and you also throttle the frequency of updates per gamertag, you have a fairly spam-resistant system.
I would recommend a mix of code obfuscation and using web sockets to request the score, rather than post the score. Something like socket.io (https://socket.io/) where the server sends a request with a code in it and your game responds with the score and that code changed in some way.
Obviously a hacker could look through your code for how your game responds to requests and rewrite it, which is where the obfuscation is important, but it does at least hide the obvious network traffic and prevents them posting scores whenever they feel like it.
I would suggest using reCAPTCHA V2.
Admittedly, v3 provides better protection, but it is hard to implement, so go with v2.
Come on, it is just a few lines of code.
How it should work (according to me):
You are at the main page willing to play the game
You solve the reCAPTCHA
Then the app sends a one-time token with a script tag which establishes a websocket request with your server (using socket.io) with the one-time token and then it is destroyed immediately (from the server as well as the client) after establishment of a connection
Your server validates the token and accepts the request of websocket and then it will send the HTML content
Just create a div and set the value using obj.innerHTML
You can use styles in body (I guess)
And the most important point is obfuscating your code.
Security
Websockets are harder to reverse engineer in a test environment
Even if they create a web socket, it won't respond, because they don't know the one-time token
It prevents script blocking (as the script loads everything on the page)
It provides real-time communication
The only way out is to somehow get your hands on Google's reCAPTCHA token which is impossible, because it means going against Google
You can’t reuse any token (however immediate it be), because it was destroyed from both the sides
One more last tip: set a timeout for the one-time token to about 15 seconds
How will it help? It will prevent someone (extremely malicious) from pausing the Chrome debugger and get the token and put it in their stuff as 15 seconds is ok for slow networks also, but not a human
I've been fiddling around with this issue for quiet some time but couldn't come up with a satisfying solution so far.
We are currently in the process of creating a new public API, which will be used by widgets to get information but also to post back information to the system (like a contact form). As the widgets will be implementend as web components and can be implemented on any page, we don't have control over how the widgets are delivered.
The issue I'm facing now is: how can we protect the API from unwanted submissions (apart from general form validation) so that we can be quiet sure that it's either a submission from that form or that it's a legit POST to the API?
My concerns are, that everything in this case is spoofable (e.g. fetching a form token and submitting it as a header, validating origin headers,...), as it could easily be spoofed i.e. with Postman. I'd be more than happy for any of your experiences and tips into the right direction.
I think you could try:
Rate limit based on IP
Rate limits on general insertions
Require email validation after send (if you have this data)
Save sender IP and check with old data, to know if someoe is abusing (a monitoring tip, but maybe is not bad idea)
Captcha to avoid malicious senders (but not at all)
Have you implemented anything similar? Maybe by seeing what you have, we can see what's missing.
It is also complicated by being public, and allowing access from any system. Perhaps it would be a good idea to evaluate an authentication system, and authenticate from the widget itself, incorporating a rate lim by key.
If you have a public API without authentication,
all you can do is make access as hard as possible for hackers.
In other words: put more/complex locks on the door ... but any lock can be picked
"Lock" code using the URI
The method we used to keep a WebComponent "safe",
was to load the WebComponent from a long URI:
(Modern browsers don't have a 2048 character URI limit any more)
https://domain/p1/p2/customeElements/define/secure-api/HTMLElement/p7/p8/webcomponent.js
The component code then decodes the URI to
let p = [domain,p1,p2,"customElements","define","secure-api","HTMLElement",p7,p8]
to execute JavaScript:
window[p[3]][p[4]](p[5],class extends window[p[6]]{ ...
More locks
If you throw in some BtoA/AtoB and String.reverse() conversions
https://domain/AH=V/CV=/==QYvRnY/aW5uZXJ/IVE1M/webcomponent.js
You have deterred most potential hackers
More locks
By generating webcomponent.js server-side to use the /domain/ part,
that long URI can be the (unique) handshake between Server and Client
More complex locks
Since all state is in the URI, it is easy to apply an address shifting mechanism,
every request can be a different URI (makes PostMan unusable and a real pain to debug also :-)
[and we applied some other trickery I won't explain here]
It won't keep hackers out, but will delay them long enough for the majority to give up.
And a mousetrap
In our code/URI encoding we also included a reference to a unique "mousetrap" URI.
If we detect 404 activity in that subdir, we know someone is actively picking a lock.
And.. we can interactively lead/direct them to more mousetraps.
We have only had one attempt thus far.
One telephone call (because we know the buyers Domain) was enough to make them stop.
Hello IT manager of [very-big-well-known] IT company X,
if we detect hacking attempts from your company IP address nn.nn.nn.nn,
by law we would have to report this to the authorities
HTH
I'm trying to make a user log in just once, and have his information on all the servers. Any changes made to the user's information will instantly be available for all servers. Is this possible to do without having each user "log in" separately for each server?
Sort of like the $_SESSION for php, but for Node.js
Design 1 -
What I think would be best to do, but don't know how to share socket data between servers, perhaps using something like PHP's $_SESSION?
Design 2 -
What I'm currently doing:
User uses socket.emit to main.js
main.js adds user information onto the emit
main.js emits to the appropriate server
Appropriate server emits back to main.js
main.js finally emits back to user
This seems awfully inefficient and feels wrong
If your information is primarily static, you can try something similar to JWT. These are cryptographically signed tokens that your authenticating server can provide and the user can carry around. This token may contain information about the user that you want each server to have available without having the user accessing it.
If it's not, you may be looking into sharing a database across all servers, and have that be the point of synchronization between them.
Updates based on our comments (so they can be removed later):
If you decide to use auto-contained JWT tokens, you don't need to be making trips to the database at all. These tokens will contain all the information required, but it will be transparent to the end user that won't have insight into their contents.
Also, once you understand the JWT standard, you don't necessarily have to work with JSON objects, since it is just the serialization approach that you can switch by another one.
You'd provide one of these tokens to your user on authentication (or whenever required), and then you'd require that user to provide that token to the other servers when requesting information or behavior from them. The token will become your synchronization approach.
I have a web site with following functionality: An user comes to www.mysite.com/page.php. Javascript on that page makes ajax API call to www.mysite.com/api.php and shows results on the same page www.mysite.com/page.php
I'm afraid of situation where somebody starts to use my api.php on own software, because using www.mysite.com/api.php costs me a bit money. Therefore I want that only users that have visited the page www.mysite.com/page.php can get valid results from www.mysite.com/api.php . There won't be any way for users to log in to my web site.
What would be the right way to do this? I guess I could start a session when an user comes to page.php and then somehow maybe first check on api.php that a session with valid session id exists?
If you just want the user to visit page.php before using api.php, the session is the way to go.
Typically, if you want a "soft" protection you use the POST verb to get results from your site. Then, if the user goes the the URL in their browser and just types the api.php call they will not get a result. This doesn't protect your site but it keeps search engines away from that url reasonably well and accidental browsing to it.
Otherwise, there are lots of authentication plugins for php.
http://www.homeandlearn.co.uk/php/php14p1.html for example.
You can check the request in several ways such as Token validation, Session validation or even by Server 'HTTP_REFERER' variable
Check the referrer with $_SERVER['HTTP_REFERER'] if its outside the domain block it.
Beware that people can alter their REFERER so its not secure.
Another better solution might be a CAPTCHA like this one from google https://www.google.com/recaptcha/intro/index.html
Cookies, HTTP-Referer, additional POST-Data or some form data, that you send in an hidden input field aren't secure enough to be sure, that the user comes from your site.
Everything of it can be easily changed by user, by modifying the http-headerdata (or if you use cookies, by changing the cookie-file on the client machine).
I would prefer the PHP-Session combined with an good protection against bots (ex. a Honeypot), because it's not so easy to hi-jack, if you use them properly.
Please note: If there is a bot especially for your site, you lost anyway. So there isn't a 100% protection.
Previously I had posted a program and asked about handling cookies in Javascript.
I had posted one code and u can find it in my other question.
Many gave good answers and I aslo tried their solutions. But since I am new to this html and javascript may be I dont know how to find bugs and debug it.
So can anybody please post their solution for this problem.
I want a webpage to be created in which it should check a cookie upon loading. If the cookie is 20 mins older it has to go to login page(ask for usename and password). Otherwise no login is required and it should directly come to one page(it is being designed).
So if anybody is already having a similar or exact code(in which time cookie is maintained) kindly post it.
Regards
Chaithra
It sounds like you're trying to implement a login system using javascript. If this is the case, STOP. All forms of authentication should take place on the server side, and you can use sessions to determine how long it has been since activity from that account. "Cracking" client-side (eg: javascript) security measures is laughably easy.
Short answer - This is a pretty good tutorial...click here...
Better answer - If you're going to create a login system you need to understand cookies, sessions, forms, and security (injection!!!) before you start on anything that is implemented for serious use. You should know to avoid client-side scripting for things like login before you even start. I'd recommend you keep looking at tutorials. You might want to look at things like the difference between different languages and when best to use which.
As nickf said, session timeout is best handled by the server side. The presence of a cookie is used to locate the session, not to implement the timeout. Session cookies are usually what's used to track session state - not the ones that expire. They last as long as the browser is open.
The server side, when processing a request, uses the cookie's value (usually a long random, hard to guess string) to locate the user's session. If the session isn't present, it can respond with a redirect to the login page.
EDIT: In the comments you said you're using goAhead - I'm having difficulty accessing their wiki but assuming it's close to Microsoft's ASP, see this link from webmaster-talk's asp-forum for an example of how to process a login. The part to note on the login page is:
session("UserID") = rs.Fields("usrName")
and the part that checks on each page load the sessions is still good is:
if (session("UserID") = "") then
response.redirect("default.asp")
This is like I outlined in the notes below, driving the timeout detection from the server side and letting the framework (goAhead in your case) do all the cookie magic and timeout on inactivity.