Cybersecurity Page - Orikyx DevSec Hub
Encryption
Encryption is a process of converting data into a secret code to prevent unauthorized access.
# Python example for AES encryption
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CBC)
data = b"Sensitive Data"
encrypted = cipher.encrypt(pad(data, AES.block_size))
Hashing
Hashing is the process of converting data into a fixed-size value or key, which is typically a hash value.
# Python example for SHA256 hashing
import hashlib
data = "Password123"
hashed_data = hashlib.sha256(data.encode()).hexdigest()
SSL/TLS
SSL/TLS provides secure communication over a computer network. It's used to encrypt the data transferred between clients and servers.
# Python example for SSL context creation
import ssl
import socket
context = ssl.create_default_context()
connection = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname="example.com")
connection.connect(("example.com", 443))
Input Validation
Input validation ensures that the input provided by users is sanitized and doesn't contain malicious data.
# Python example for input validation
import re
email = "test@example.com"
if re.match(r"[^@]+@[^@]+\.[^@]+", email):
print("Valid email!")
else:
print("Invalid email!")
Network Programming
Network programming refers to writing software that allows data to be sent and received over a network, such as creating servers or clients for communication.
# Python example for a simple server
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("0.0.0.0", 8080))
server_socket.listen(5)
print("Server listening on port 8080...")
client_socket, addr = server_socket.accept()
print(f"Connection from {addr}")
client_socket.send(b"Hello, Client!")
client_socket.close()
Authentication
Authentication is the process of verifying the identity of a user or system.
# Python example for simple username/password authentication
user_db = {"admin": "password123", "user": "mypassword"}
username = input("Enter username: ")
password = input("Enter password: ")
if user_db.get(username) == password:
print("Authentication successful!")
else:
print("Authentication failed.")
Advanced Encryption
Advanced encryption techniques, such as RSA, offer secure data transfer using public and private keys.
# Python example for RSA encryption
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()
cipher = PKCS1_OAEP.new(RSA.import_key(public_key))
encrypted = cipher.encrypt(b"Sensitive data")
SQL Injection Prevention
SQL Injection is a code injection technique that exploits vulnerabilities in an application's software by manipulating SQL queries.
# Python example for preventing SQL injection using parameterized queries
import sqlite3
connection = sqlite3.connect('example.db')
cursor = connection.cursor()
username = "admin"
password = "password123"
cursor.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
result = cursor.fetchone()
if result:
print("Login successful!")
else:
print("Invalid login.")
XSS Prevention
Cross-Site Scripting (XSS) attacks inject malicious scripts into web pages viewed by other users.
/* JavaScript example for preventing XSS by sanitizing user input */
function sanitizeInput(input) {
return input.replace(/.*?<\/script>/g, "");
}
const userInput = "";
console.log(sanitizeInput(userInput)); // Returns empty string
Session Management
Session management involves securely handling user sessions, including token management and session expiration.
# Python example for session token generation
import secrets
session_token = secrets.token_urlsafe(16)
print(f"Session Token: {session_token}")
Web Security Best Practices
Web security best practices include securing cookies, using HTTPS, and preventing attacks like CSRF and XSS.
# Python example for secure cookie handling with Flask
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/')
def home():
resp = make_response("Hello, world!")
resp.set_cookie('username', 'admin', secure=True, httponly=True)
return resp
CSRF Prevention
Cross-Site Request Forgery (CSRF) attacks trick a user into performing actions on a web application where they are authenticated.
# Python example using Flask to implement CSRF protection
from flask import Flask, session
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.secret_key = 'your_secret_key'
csrf = CSRFProtect(app)
@app.route('/submit', methods=['POST'])
def submit():
# Handle form submission
return "Form submitted!"
DNS Spoofing Mitigation
DNS Spoofing occurs when a malicious actor manipulates DNS queries to redirect users to fraudulent sites. Mitigation involves using DNSSEC (Domain Name System Security Extensions).
# DNSSEC is enabled on the server for DNS Spoofing mitigation
# Command to check if DNSSEC is enabled on Linux
dig +dnssec example.com
Malware Analysis
Malware analysis involves examining malicious software to understand its behavior, origins, and impacts. Static and dynamic analysis are the two primary types of analysis.
# Static analysis using Python's pefile to inspect a Windows executable (PE format)
import pefile
pe = pefile.PE("malware.exe")
for entry in pe.DIRECTORY_ENTRY_IMPORT:
print(f"Imported DLL: {entry.dll.decode()}")
Privilege Escalation
Privilege escalation occurs when an attacker gains higher privileges than intended, such as administrative or root access. Mitigation involves hardening system permissions and monitoring for suspicious activity.
# Example of using sudo to escalate privileges on Linux
# Always avoid giving unnecessary sudo access
sudo su -
Zero-Day Exploits
A zero-day exploit refers to an attack that takes advantage of a vulnerability before the vendor is aware of it and can patch the issue.
# Example of vulnerability exploitation (educational)
# Never use this code in production, it's just for understanding the concept
import socket
target_ip = "target_ip"
target_port = 80
# Simple script to demonstrate an unpatched vulnerability being exploited
# Note: This is for demonstration purposes only
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target_ip, target_port))
sock.send(b"GET / HTTP/1.1\r\nHost: vulnerable-site.com\r\n\r\n")
response = sock.recv(1024)
print(response)