Security concerns, communication with database etc.

Everything else that doesn't fall into one of the other categories.
User avatar
Kurzer
Posts: 90
Joined: Mon May 26, 2014 9:33 am

Security concerns, communication with database etc.

Post by Kurzer »

Hello colleagues,

Note: This post was also published in the German PureBasic Forum in the SpiderBasic section.

I'm not very experienced in programming with SpiderBasic, but I'm still planning to do a "medium-small" project with Spider. At the moment I'm still working with the demo version of Spidebasic to see if I can implement all parts of the planned project.

With some topics for the realization of the project I can't judge if my approach is ok or if it could be done better in another way.

What exactly is it about?
It's about a web application that should be protected by a login and that communicates via several PHP modules via HttpRequest() to interact with a database and the filesystem of the webserver.

So I have a program part that runs on the client browser and will be written in Spiderbasic (or after compiling in JavaScript). Here the whole GUI, its logic and the loading, processing and displaying of data is realized.

The other part of the program is on the server and is called by SpiderBasic via HttpRequest(). The parameters are transferred by POST.

With the following points I do not know yet what approach is the best:

1) the topic login and authorization to use the SpiderBasic application at all.

If I would write the web application in pure PHP/HTML, I would program a login screen and store the user's permissions in a session variable after a successful login. When calling other PHP pages that belong to the application, I would read the session variable with the permission level and react accordingly in the PHP script (either continue the script or abort it with a error message if the permission is not sufficient).

But how do I do that within SpiderBasic?

a) I could implement the login screen directly in the SpiderBasic application, so that I can decide directly in SpiderBasic whether the user is allowed to continue working with the application or is kicked out immediately.

Now SpiderBasic is finally JavaScript and runs on the user's browser. Wouldn't it be possible for the user to analyze and modify the JavaScript code to bypass the login check? That would be a security risk. Unfortunately I am not very familiar with JavaScript. :|

b) I could implement the login screen in PHP, then directly fill the session variables with the user's authorization and, if the login was successful, forward them to the SpiderBasic application.

Here a similar problem arises nevertheless. The SpiderBasic application is started by calling the corresponding *.html file. The URL of the SpiderBasic application can then be seen either directly in the URL gadget of the browser or by using the browser's developer tools. If you know this URL, you could also call it directly without the login process. Then the login check would be completely bypassed.

b2) I could send a query from the SpiderBasic application to the web server to see if the current user has the appropriate permission (HttpRequest() to a PHP script that handles authentication). But again: JavaScript runs on the browser and I don't know if this call or its return value could be compromised by an attacker.

c) For additional security I could proceed as described under b2) and have the PHP authentication module return a token if the authorization was positive. This token would then have to be sent with all communication with the web server. This means every time the SpiderBasic application sends requests to the web server to acces the file system or database, it sends also this token. Only if the token sent is identical to the token of the successfully logged on user, the request is executed.

Thus, an unauthorized user could see and partially use the GUI of the SpiderBasic application, but everything related to server communication would fail.

Whether all this is then sufficiently secure, I cannot judge.

I would be very happy to hear from experts on this topic. :-)


2) Passing parameters to a Spiderbasic application.
You can pass parameters to a PHP script via POST or GET. You can also pass parameters to a PureBasic program, which you can get with ProgramParameter().

For SpiderBasic I haven't found anything like this yet.

It might be useful with regard to the login topic, if I could tell the SpiderBasic application that the user has sufficient permissions when it is called.


3) Secure database queries
Again I am afraid that the JavaScript code can be changed to do mischief or to get unauthorized access to data.

This is about the secure coding of database queries in Spiderbasic.

The whole thing is realized by calling the HttpRequest() function of a PHP script, which then takes over the actual communication with the database and returns the result of the query to the SpiderBasic application.
Probably such a module has been developed a thousand times (CRUD module), but unfortunately I'm not further into the topic.

a) From a logical common sense point of view, I would say that it is highly dangerous to keep the entire SQL query inside the SpiderBasic application and send it to the PHP module. For example "Select id_user From users Where name = "Smith" and PasswordHash = "blahblah". An attacker could certainly manipulate the query to cause damage to the database.

b) One could abstract the functionality.
The PHP module would get the following parameters:
- Command (a flag indicating whether a select, delete, update or insert should be performed)
- Table (Indicator which specifies which table is mined - The indicator must not be the same as the table name!)
- Values (Which data fields should be returned)
- Clause (restrictions, i.e. the where clause of the SQL statement)

The whole thing is probably just as insecure as a), except that an attacker have to think about it a little longer.

c) You could put the entire function and the entire SQL into the PHP module and program all the commands or queries that the SpiderBasic program needs.

Then you would only send the following to the PHP module:
- Command (specifies what is required)
- Values[] (the values to be entered in the table during an Update or Insert Command)

The PHP module would then unfortunately have to contain a lot of redundant code, because a separate function would have to be written for each command.

For example:
Command = "CHECKUSER"
Value1 = "Smith"
Value2 = "blahblah"
-> Check if the user with the name "Smith" and the password hash "blahblah" exists in the table user and has the permission to use the application. Returns 0/1 if so.

Command = "GETPRODUCT"
Value1 = "1309"
-> Return the record of the product with the ID 1309 from the table products. The transfer to Spider then as JSON string.

Command = "UPDATEUSEREMAIL"
Value1 = "3"
Value2 = "meineemail@gmx.de"
-> Update the field Email of the user with ID 3 in the table user with the value 'meineemail@gmx.de'. Returns 0 or 1 depending on the success of the action.


As already mentioned under 1c), for better security I could pass a token parameter with every call of the PHP database module. The token contains a random character sequence or a checksum, which was generated by the authentication module after the successful login.

But as I said, this is all just logical mind and "dangerous semi-knowing" ;-)
If anyone here has a clue about this stuff, then I am really grateful for links or hints.

Oh, there are two more things I can think of:

4) In the "CreateApp" dialog, in the "Web" tab below, there is the "Post processing:" section.
Is this something like an IDE tool which is started after compilation? So you could for example specify a batch to transfer the compilation directly to the web server?

5) I notice that when creating a web application, the folder containing the SpiderBasic libraries is always the same size. This means then that Spider does not do it like PureBasic and does not just copy the libs used by the program, but always copies all the libs?

Greetings Kurzer

(Mostly) Translated with http://www.DeepL.com/Translator (free version)
SB 2.32 x86, Browser: Iron Portable V. 88.0.4500.0 (Chromium based), User age in 2023: 55y
"Happiness is a pet." | "Never run a changing system!"
User avatar
Paul
Posts: 195
Joined: Wed Feb 26, 2014 6:46 pm
Location: Canada
Contact:

Re: Security concerns, communication with database etc.

Post by Paul »

First thing, ProgramParameter() also works with SpiderBasic so you can use that command to get variables when starting a SpiderBasic app.

I have written a number of web apps now that communicate with CGI apps on my server written in PureBasic which talks to a database (either MariaDB or PostgreSQL) and then sends the requested data back to the SpiderBasic app.
The SB app starts with a login screen asking for User/Pass and sends it to the PB app (CGI). PB app checks the User/Pass against whats in the database and if it matches, it sends back confirmation the SB app can proceed.
Now, every command or query that needs to happen in the database from the SB app is sent to the PB app for processing and every query also includes the User/Pass and is always verified in the PB app before performing a query and returning data.
If someone were to modify the SB app to bypass the login it wouldn't really matter since the correct User/Pass is required for every query on the PB side.



And when uploading the Web app, instead of having multiple instances of SpiderBasic libraries all over I copy the javascript folder (found under C:\SpiderBasic\Libraries\ ) and put it in the root folder of my server and rename it to 'sbresources'.

Now in the Create App Window....
Enter an App name and select an icon in PNG format.
My web server is mapped to my Windows box as 'webserver' so for HTML filename I simple put: \\webserver\html\myapp\index.html
I like to name the javascript file the same as my app name to for JavaScript filename I put: myapp.js
And because I'm sharing the SpiderBasic javascript files between all my apps and I copied them to the root of my webserver, for SpiderBasic libraries path I put: ../sbresources
If I'm ready for production I will uncheck "Enable debugger"
Now if I press the "Create App" button it will generate an html file and a js file on the webserver whcih I can access online using http://mydomain.com/myapp

Note: If I didn't have my web server mapped to my windows box I would have to put in a local folder when entering the HTML filename then copy or upload the generated files to my web server.


Hope this helps ;)
User avatar
Kurzer
Posts: 90
Joined: Mon May 26, 2014 9:33 am

Re: Security concerns, communication with database etc.

Post by Kurzer »

Hi Paul,

thank you for your comments and explanations.
It is very helpful for me to learn how others are doing this job.

I will be able to use this information well. Now I just have to finish the effort estimation and the customer has to place the order. :-D

But then Fred/Andre will definitely get an order for SpiderBasic from me. Now that I'm slowly gaining insight by testing around with some SB snipplets, it is also very interesting for private projects.
SB 2.32 x86, Browser: Iron Portable V. 88.0.4500.0 (Chromium based), User age in 2023: 55y
"Happiness is a pet." | "Never run a changing system!"
User avatar
Kurzer
Posts: 90
Joined: Mon May 26, 2014 9:33 am

Re: Security concerns, communication with database etc.

Post by Kurzer »

Paul wrote:First thing, ProgramParameter() also works with SpiderBasic so you can use that command to get variables when starting a SpiderBasic app.
Ah, great hint. I missed it, because I looked for the section "process" in the SpiderBasic helpfile (this is the section where the command ProgramParemeter will be found in the PureBasic helpfile). :D
SB 2.32 x86, Browser: Iron Portable V. 88.0.4500.0 (Chromium based), User age in 2023: 55y
"Happiness is a pet." | "Never run a changing system!"
bbanelli
Posts: 107
Joined: Mon Jul 13, 2015 7:40 am

Re: Security concerns, communication with database etc.

Post by bbanelli »

kurzer wrote:a) I could implement the login screen directly in the SpiderBasic application, so that I can decide directly in SpiderBasic whether the user is allowed to continue working with the application or is kicked out immediately.

Now SpiderBasic is finally JavaScript and runs on the user's browser. Wouldn't it be possible for the user to analyze and modify the JavaScript code to bypass the login check? That would be a security risk. Unfortunately I am not very familiar with JavaScript. :
To what end?

Regardless if you are using opaque (session) tokens (which you would always verify against some sort of database in your backend) or something like JWT, you should validate session with each request related to backend process, so unauthorised user can't access that resource anyway.

Thus, even if someone bypasses business logic you implemented in SB, it would have no effect since no data would be returned from your backend unless a valid session token is provided.

Be advised to check how SB handles CORS requests; according to the documentation, "Due to security constraints, it is only possible to execute a request on the same domain.", which makes it impossible to use HTTP only cookies which would be preferable security measure for sharing session information.

In that case, unless there is a way to do it (like Axios has "withCredentials" or fetch's "credentials" option) and you are in situation of using CORS, it presents a deal breaker for using SB.
"If you lie to the compiler, it will get its revenge."
Henry Spencer
http://www.pci-z.com/
User avatar
Kurzer
Posts: 90
Joined: Mon May 26, 2014 9:33 am

Re: Security concerns, communication with database etc.

Post by Kurzer »

Hello bbanelli,

thank you for your contribution. I will definitely take your input into consideration.

But why do I necessarily need a cookie?
What if I use exclusively a session that is created after a successful login?

For example:

Login.php // Is called by login.html form where the user enters his email and password.

Code: Select all

<?php
  // some needed includes here

  session_start();
  
  $user_id = -1;
  $user_profile = -1;
  $user_firstname = '';
  $user_lastname = '';

  // Check the login parameters
  if (isset($_POST['email']))
    $email = $_POST['email'];
    
  if (isset($_POST['password']))
    $password = $_POST['password'];  
  
  // Check whether the user exists in the database and the password hash is correct
  if (validateUserAccount($email, $password, $user_id, $user_profile, $user_firstname, $user_lastname) == TRUE) {
    // Check whether the user have permission to log in
    if (checkUserPermission ($user_id, PERMISSION_LOGIN, PERMISSION_LEVEL0) == TRUE) {
      storeUserData($user_id, $user_profile, $user_firstname, $user_lastname);
      echo '<script type="text/javascript"> window.location = "MySBApp.html" </script>';
    }
    else {
      echo '<script type="text/javascript"> window.location = "login_denied.html" </script>';
    }
  }
  else {
    echo '<script type="text/javascript"> window.location = "login_failed.html" </script>';
  }
?>
Them I have an include with the function isUserLoggedIn(). This function checks if the user is still logged in.

includes/logincheck.php

Code: Select all

// ...
  function isUserLoggedIn () {

    if (isset($_SESSION['user_id'])) {
      if ($_SESSION['user_id'] > -1)
        return TRUE;
      else
        return FALSE;
    }
    else
      return FALSE;
  }
// ...
The following check is then called in each PHP module called from the SpiderBasic program.

Code: Select all

// ...
  // some needed includes here 
  
  session_start();
  
  // Check if the user is logged in
  if (!isUserLoggedIn()) {
    session_destroy();
    echo '<script type="text/javascript"> window.location = "login.html" </script>';
    exit;
  }

  // here follows the real code for this module
// ...
Is that not safe enough? What advantage would the cookie bring?

CORS: As far as I understood the CORS topic, it doesn't concern me, because the whole application and the PHP modules will be on the same server.
SB 2.32 x86, Browser: Iron Portable V. 88.0.4500.0 (Chromium based), User age in 2023: 55y
"Happiness is a pet." | "Never run a changing system!"
bbanelli
Posts: 107
Joined: Mon Jul 13, 2015 7:40 am

Re: Security concerns, communication with database etc.

Post by bbanelli »

Hi,

as far as I am aware, but I know very little about PHP, its sessions are sent by cookie as default. Otherwise, how would your client return session to the server? There are options for passing them through GET request itself, but that is plainly stupid in 2020, IMNSHO.

By not using cookie for sensitive information (but storing them in local/session storage or similar approach), your client is subjected to very cheap forms of compromising security token.

In any case, by using HTTP Only and Secure cookies, with adequate Same Site attribute, you will make significant improvement in preventing XSS attack vector. This is not sufficient by default, but it will make most of the effort to harden your security properly.

HTH,

Bruno
"If you lie to the compiler, it will get its revenge."
Henry Spencer
http://www.pci-z.com/
User avatar
Kurzer
Posts: 90
Joined: Mon May 26, 2014 9:33 am

Re: Security concerns, communication with database etc.

Post by Kurzer »

Hello, Bruno,

you're right about the use of cookies. With my PHP login this seems to happen completely transparent in the background.
The login example I posted above is from another project that I implemented in pure PHP and HTML.

When I look at the generated cookies in the developer tools of my browser, a PHPSession cookie is indeed generated after successful login. This was new to me.

Image

The connection itself is a secure connection (https://), but there is nothing in the "secure" column of the cookie. I don't know if this is security relevant.

Image

The parameters are sent via POST from the HTML Form.

Code: Select all

    <form name="login" method="POST">
      <input type="text" name="email" placeholder="Emailadresse" value=""/>
      <br><br>
      <input type="password" name="password" placeholder="Passwort"/>
      <br><br>

      <input type="submit" value="Anmelden" formaction="login.php"/>
    </form>
I am not a good web expert. I rather work in many areas and know my way around a bit, but I don't have any expert knowledge. I learned a lot just by reading tutorials and documentation. Then you only know what you have really read. For example, I did not read the whole PHP documentation :-D.

Greetings
Markus
SB 2.32 x86, Browser: Iron Portable V. 88.0.4500.0 (Chromium based), User age in 2023: 55y
"Happiness is a pet." | "Never run a changing system!"
bbanelli
Posts: 107
Joined: Mon Jul 13, 2015 7:40 am

Re: Security concerns, communication with database etc.

Post by bbanelli »

Hi Markus,

we have all started from scratch, my friend, nobody was born knowing it all. Well, except politicians, perhaps... ;)

Anyway, as you have noticed, your PHP session is distributed via cookie. By making it a Secure cookie, it will be distributed only if connection is HTTPS on both parties; in your case, since you will be using PHP, it should be done without saying. Just make sure to create appropriate HTTP->HTTPS redirections in your web server setup.

As for HTTP only cookie, if you try accessing this cookie via JS, you would be able to get its data with current configuration. By making it HTTP only, your client's responsibility would be to send cookie with the request, but your client's JS code would not be able to access it or tamper with it in any case.

That is the reason why this is preferable method of distributing sensitive information, which your session token in the cookie is.

Naturally, be advised that there are some browser compatibility needed for this to function properly, so unless you have prerequisite to support trash like IE or archaic versions of Chrome/Firefox/Safari/Opera, you should generally be good to go.

HTH,

Bruno
"If you lie to the compiler, it will get its revenge."
Henry Spencer
http://www.pci-z.com/
Post Reply