A PHP session for all requests - php

I have read some similar questions but all of them about answering to a human client behind a browser which is not my case. I need to answer another server using sessions, so no browser and cookie!
What I'm working on: I'm creating a telegram bot (using telegram webHook mode and PHP) which gets a user's message (handed by telegram server) and checks if it is the right answer. In each of the states of Yes/No, bot will do the proper action. So there is a database here to read the right answer from and lots of recieved messages to be checked. The whole code would be executed for each message.
Question: How can I use sessions to respond to all of the requests comming from a server (telegram server)? Since there is a lot of requests, so retrieving information from MySQL database each time whould cause low performance. Is there any other better solution for that?

AS fusion3k told you, sessions are stored in files and are not designed for handle a large amount of data. In the same way, session needs cookie for working.
If yout information does'nt change between request, you can use memcached for caching.

Related

Does HTTPS make POST data encrypted?

I am new to the world of programming and I have learnt enough about basic CRUD-type web applications using HTML-AJAX-PHP-MySQL. I have been learning to code as a hobby and as a result have only been using a WAMP/XAMP setup (localhost). I now want to venture into using a VPS and learning to set it up and eventually open up a new project for public use.
I notice that whenever I send form data to my PHP file using AJAX or even a regular POST, if I open the Chrome debugger, and go to "Network", I can see the data being sent, and also to which backend PHP file it is sending the data to.
If a user can see this, can they intercept this data, modify it, and send it to the same backend PHP file? If they create their own simple HTML page and send the POST data to my PHP backend file, will it work?
If so, how can I avoid this? I have been reading up on using HTTPS but I am still confused. Would using HTTPS mean I would have to alter my code in any way?
The browser is obviously going to know what data it is sending, and it is going to show it in the debugger. HTTPS encrypts that data in transit and the remote server will decrypt it upon receipt; i.e. it protects against any 3rd parties in the middle being able to read or manipulate the data.
This may come as a shock to you (or perhaps not), but communication with your server happens exclusively over HTTP(S). That is a simple text protocol. Anyone can send arbitrary HTTP requests to your server at any time from anywhere. HTTPS encrypted or not. If you're concerned about somebody manipulating the data being sent through the browsers debugger tools… your concerns are entirely misdirected. There are many simpler ways to send any arbitrary crafted HTTP request to your server without even going to your site.
Your server can only rely on the data it receives and must strictly validate the given data on its own merits. Trying to lock down the client side in any way is futile.
This is even simpler than that.
Whether you are using GET or POST to transmit parameters, the HTTP request is sent to your server by the user's client, whether it's a web browser, telnet or anything else. The user can know what these POST parameters are simply because it's the user who sends them - regardless of the user's personal involvement in the process.
You are taking the problem from the wrong end.
One of the most important rules of programming is :
Never trust user entries is a basic rule of programming ! Users can and will make mistakes, and some of them will try to damage you or steal from you.
Welcome into the club.
Therefore, you must not allow your code to perform any operation that could damage you in any way if the POST or GET parameters you receive aren't what you expect, be it by mistake or from malicious intents. If your code, by the way it's designed, renders you vulnerable to harm simply by sending specific POST values to one of your pages, then your design is at fault and you should redo it taking that problematic into account.
That problematic being a major issue while designing programs, you will find plenty of documentation, tutorials and tips regarding how to prevent your code to turn against you.
Don't worry, that's not that hard to handle, and the fact that you came up with that concern by yourself show how good you are at figuring things out and how commited you are to produce good code, there is no reason why you should fail.
Feel free to post another question if you are stuck regarding a particular matter while taking on your security update.
HTTPS encrypts in-transit, so won't address this issue.
You cannot trust anything client-side. Any data sent via a webform can be set to whatever the client wants. They don't even have to intercept it. They can just modify the HTML on the page.
There is no way around this. You can, and should, do client side validation. But, since this is typically just JavaScript, it can be modified/disabled.
Therefore, you must validate all data server side when it is received. Digits should be digits, strip any backslashes or invalid special characters, etc.
Everyone can send whatever they want to your application. HTTPS just means that they can't see and manipulate what others send to your application. But you always have to work under the assumption that what is sent to your application as POST, GET, COOKIE or whatever is evil.
In HTTPS, the TLS channel is established before and HTTP data is transfered so, from that point of view, there is no difference between GET and POST requests.
It is encrypted but that is only supposed to protects against mitm attacks.
your php backend has no idea where the data it receives comes from which is why you have to assume any data it receives comes straight from a hacker.
Since you can't protect against unsavoury data being sent you have to ensure that you handle all data received safely. Some steps to take involve ensuring that any files uploaded can't be executed (i.e. if someone uploads a php file instead of an image), ensuring that data received never directly interacts with the database (i.e. https://xkcd.com/327/), & ensuring you don't trust someone just because they say they are logged in as a user.
To protect further do some research into whatever you are doing with the received post data and look up the best practices for whatever it is.

Is it possible to pull data from HTML5's local storage and save to server database?

I have an idea for a social web app and part of the idea is to pull data from localstorage onto the server database. The reason for this is say you have an idea and you want to put it on your next status for this social app, but you have no signal and wireless anywhere. You write out the status on the app and it saves it to the localstorage for use when they get back to somewhere where they can connect their phone online.
They then get to a place where they can go online, the app then detects that there is a change in the localstorage and then pulls it from there and saves to the server database.
Is this at all possible, if so how would you go about implementing it?
If it's not at all possible, do you think this could be sometime in the future?
I look forward to hearing from your comments and answers on this one as I think it could be quite a big discussion.
Yes it's possible, why wouldn't it be? When you pull data from the local storage, the data works just like any other Javascript variable, there are no restrictions that would stop you sending it to a server other than the lack of Internet connection.
how would you go about implementing it?
First you'd need to detect the connection status, see this question. So when a user tries to update their status, it checks if the connection is online and if it isn't then save it to local storage.
Use the methods in the linked question to detect when the connection comes back up, and at that point pull the data from local storage and send it to the server via ajax, then clear the local storage to prevent duplicate data being sent.
You can periodically check navigator.onLine in your Javascript to get the online status of a device. Note that while
navigator.onLine == false
safely tells you that a device of offline,
navigator.onLine == true
doesn't necessarily mean it has access to the internet and can perform the request, just that it is connected to some sort of network.
Once you assume that the device is not offline you'd send an ajax request (I recommend using jQuery's $.ajax function) in which you POST the data from your localStorage
(localStorage.getItem('dataToPull'))
to a PHP script, which then inserts it into your MySQL database.
If that ajax request fails, and you're sure it's not getting a PHP/MySQL error, it's safe to assume that although the device is connected to a network and navigator.onLine is true, there's no internet connectivity. You can then do some error handling, e.g. poll the device again in 5 minutes.

Protecting API - JS Frontend and PHP Backend

Iam searching for an good implementation to protect my Backend written in PHP.
Scenario:
Server 1 (www.domain.com)
Servers only JS/HTML to the Client
Server 2 (www.domain2.com)
Is Running an PHP Server wich is responding to Server 1 with JSON Data (rendered by an Javascript Template engine on Sevrer1).
How can i stop others to grab the JSON Response from Server1?
I know i can add somekind of API key but it is stored in JS (everyone can read it), i know i could check if the request is from Server 1 IP, but it is not a big deal to fake such a request.
Making internal calls from Server1 to Server2 is a solution, not exposing Server1 to the internet, and adding it to a private network might help.
Even if someone works around a way out, you could add validations like making sure that the request origin is from the authorized source (in your case Server2).
If the request origin is from another source, simply return without processing.
If you're still paranoid about it, you can always keep adding more mechanisms like hash-based message authentication code
One thing you can do is to create a session cookie on the server 1 and simultaneously store that session value in the database on server 2. Whenever someone makes a request from server 1 you append the request with the cookie value and send it to server 2 while making API calls. The server 2 serves back the JSON only when the incoming session ID matches with the one stored in the database.
This is not foolproof. Someone can hack the cookies, you will need to clear up the session once the users log out.
The other way, as you mentioned, is using a server side scripting language on server 1.
Why not just create some short-life tokens and share them only server-side, then embed in JS code?
Source

PHP Equivalent to Authorized ASP.NET WebMethod (AJAX)?

It's rare, but I have to pay MS a compliment: the ASP.NET WebMethod (AJAX) authorization is a dream, regarding my desire for security and laziness.
Encosia's ASP.NET page methods are only as secure as you make them absolutely fits those needs. ASP.NET is actually workable for me now. Free at last! (From the noble but disastrous AJAXControlToolkit).
Anyways, the problem is, that's for work. I'm not buying the MS architecture when LAMP's out there for free. I'm new to AJAX, and I can't seem to find a clear answer on how to authorize AJAX calls to PHP in the same way as Encosia above.
Can anyone suggest the PHP equivalent of what Encosia does in the link above?
Thanks in advance!
More Details
OK, let me be more specific. Encosia's solution above gives 401 denied to anyone not logged in trying to access a webmethod. Neat, clean, easy. Before, I tried to user session data to give access, but it, unknowingly to me, forced synchronous mode. Nono.
I need both, for my site. I need to be able to give 401 denieds on certain pages if a user isn't logged in. I need to be able to allow anyone to call other phps via ajax regardless of login.
Clarity
Bottom line: I don't want anyone accessing certain AJAX PHPs unless if they are logged in. I don't care what the response or any other details as long as its' still AJAX. How to?
Not really clear from the question, but if you want to only allow access to your AJAX server side listening scripts (maybe XML or JSON output) to users that have either authed or are on the related page,then how about adding a session identifier to your JS AJAX requests? In the server side script you can check that identifier against maybe a DB table holding your current sessions.
For extra security, you could check against IP, a cookie etc. These are all values that you can set when the session is started.
The main thing you need to ask yourself is this:
If a user is either logged in or browsing, what kind of access to the database do you really want / need to give? Each application will have its own needs. If you are going to have AJAX listeners on your server, then all that's needed is a quick look at Firebug (example) to see where your scripts are and the format of the requests. This could allow a potential security hole to be found. Make sure all your incoming requests are correctly treated so as to remove the possibility of injection attacks.

Can GET Requests Contain Hidden Data or Paramters?

For my school, we have to do these "Advisory Lessons" that tell you about College, etc. After completing the lesson, I am wondering if I would be able to replicate the same process using a set of requests from a PHP script with cURL.
I went through the lesson again, this time with Firebug on and an HTTP Analyzer.
Much to my surprise, the only GET requests were sent out during the entire lesson.
In case your curious, here is what the "Lesson" window looks like. It's sort of powerpoint-type thing where you read the slide and then some slides have questions on them. At the end, there is a quiz and if you don't pass it, the lesson doesn't count.
My question is this: If I were to setup a PHP/cURL script that logged into my account, and then made every single one of those requests, would the lesson be counted as complete?
Now obviously it's impossible for you guys to know how their server works and such...
I guess what I am saying is, is there any hidden content or fields that you can pass through a GET request? It just doesn't seem like the lesson window is passing enough info to the server for it to know if the lesson was complete or not.
Thanks so much for any advice and tips on my project!
EDIT: Here is my official test run (please don't do it too many times):
As many of you hinted, it did not work....but I am still not completely sure why.
Like you say, we can't speak to the details of their server, but it is possible to do these kinds of things with GET requests only because servers can use cookies and store state (associated with these cookies) on the server.
This gives the appearance, probably, of passing extra hidden information to the server.
You can research cookies, and even that jsessionid thing that is appearing in their URLs. That BTW tips you off that they are using at least some Java. :)
The lesson application may very well be storing data in a session or some other persistant data store server-side and using a token from your browser (usually a cookie or a GET parameter) to look up that data when needed.
Its a kinda complicated task. With only cURL you can't emulate execution of javascript code, AJAX requests etc
I am not sure what you are trying to do. For one HTTP is stateless protocol meaning the server gets request and gives a response to that particular request (that might be GET, POST or whatever and might have some request parameters). Statefullness in system usage is usually achieved by server creating a session and setting up a cookie on client side to pass session id in later requests. Session id is used to recognize the client and track his session. Everything you send during request is plain text. What response you get most likely will depend on session state and will also be a plain text. There is nothing hidden on a client side about client side. You just don't get to know what information server keeps in session and how requests are processed based on that and information you give during requests.

Categories