उत्तर: साइबर सिक्योरिती का मतलब है digital information और computer systems को unauthorized access, attacks, damage या theft से बचाना। यह एक comprehensive approach है जो technology, processes और people को combine करता है।
मुख्य घटक:
Hardware Security: Physical devices की protection
Software Security: Programs और applications की security
Network Security: Data transmission की protection
Information Security: Sensitive data की confidentiality, integrity और availability
CIA Triad की विस्तृत व्याख्या:
Confidentiality (गोपनीयता):
केवल authorized users को ही information access करनी चाहिए
Encryption techniques का use
Access controls implement करना
Data classification systems
उदाहरण: Bank account details केवल account holder को दिखना चाहिए
Integrity (अखंडता):
Data accurate और complete होना चाहिए
Unauthorized modifications से बचाव
Digital signatures का use
Hash functions for verification
उदाहरण: Medical records में कोई unauthorized changes नहीं होने चाहिए
Availability (उपलब्धता):
Systems और data जब जरूरत हो तब accessible होना चाहिए
Downtime minimize करना
Backup और disaster recovery plans
Load balancing techniques
उदाहरण: ATM machines 24/7 available रहनी चाहिए
Risk Management Fundamentals:
Risk की परिभाषा: Risk = Threat × Vulnerability × Impact
Threat Assessment:
Internal threats (employees, contractors)
External threats (hackers, cybercriminals)
Natural disasters
Technical failures
Vulnerability Identification:
System weaknesses
Process gaps
Human errors
Outdated software
Risk Mitigation Strategies:
Risk Avoidance: Risk को पूरी तरह avoid करना
Risk Mitigation: Risk को reduce करना
Risk Transfer: Insurance के through risk transfer करना
Risk Acceptance: Calculated risk को accept करना
A. Malware (विस्तृत विवरण)
1. Viruses:
परिभाषा: Self-replicating programs जो host files को infect करते हैं
कैसे काम करते हैं: Host program के साथ attach होकर spread होते हैं
प्रकार:
File Viruses: Executable files को target करते हैं
Boot Sector Viruses: System boot process को affect करते हैं
Macro Viruses: Document files (Word, Excel) में hide होते हैं
बचाव: Antivirus software, regular updates, suspicious files न खोलना
2. Worms:
परिभाषा: Self-contained programs जो network के through spread होते हैं
Viruses से अंतर: Host file की जरूरत नहीं, independently replicate होते हैं
Famous Examples:
Morris Worm (1988): Internet का पहला major worm
Conficker Worm (2008): Millions of computers infected
Impact: Network bandwidth consume करते हैं, system resources exhaust करते हैं
Prevention: Network segmentation, patch management, firewall rules
3. Trojans:
परिभाषा: Legitimate software के रूप में disguise होकर malicious activities करते हैं
प्रकार:
Banking Trojans: Financial information steal करते हैं
Remote Access Trojans (RATs): System को remotely control करते हैं
Rootkit Trojans: System के deep level में hide होते हैं
Distribution Methods: Email attachments, fake software downloads, USB drives
Detection: Behavioral analysis, signature-based detection
4. Ransomware:
परिभाषा: Files को encrypt करके ransom मांगते हैं
Types:
Crypto Ransomware: Files को encrypt करता है
Locker Ransomware: पूरे system को lock करता है
Famous Attacks:
WannaCry (2017): 300,000+ computers affected globally
Petya/NotPetya: Ukraine को specifically target किया
Prevention Strategy:
Regular backups (3-2-1 rule)
Employee training
Network segmentation
Patch management
Email filtering
B. Phishing और Social Engineering
Phishing की विस्तृत व्याख्या:
1. Email Phishing:
Method: Legitimate organizations के नाम से fake emails भेजना
Common Tactics:
Urgent action required messages
Prize/lottery winning notifications
Account suspension warnings
Fake invoice attachments
Red Flags:
Grammar mistakes
Generic greetings
Suspicious sender addresses
Urgent language
2. Spear Phishing:
Definition: Specific individuals या organizations को target करना
Research Phase: Target के बारे में detailed information collect करना
Customization: Personalized messages create करना
Example: CEO के नाम से CFO को email भेजना
3. Whaling:
Target: High-profile individuals (CEOs, politicians)
Sophistication: Highly crafted attacks
Impact: Significant financial या reputational damage
Social Engineering Techniques:
1. Pretexting:
Method: False scenario create करके information extract करना
Example: IT support के नाम से password पूछना
2. Baiting:
Method: Tempting offer के through malware distribute करना
Example: Free USB drives में malware
3. Quid Pro Quo:
Method: Service के बदले में information मांगना
Example: Technical support के बहाने system access लेना
4. Tailgating/Piggybacking:
Method: Authorized person के साथ restricted area में entry
Prevention: Access control systems, employee awareness
C. Network Attacks
1. DDoS (Distributed Denial of Service):
Types of DDoS Attacks:
Volume-Based Attacks:
UDP Floods: Random ports पर UDP packets भेजना
ICMP Floods: Ping requests से server overwhelm करना
Other spoofed packet floods
Protocol Attacks:
SYN Flood: TCP connection के SYN requests भेजना
Ping of Death: Oversized packets भेजना
Smurf Attack: ICMP broadcast address abuse
Application Layer Attacks:
HTTP Flood: Legitimate HTTP requests की high volume
Slowloris: Partial HTTP requests भेजकर connections को hold करना
Zero-day DDoS: Application vulnerabilities exploit करना
DDoS Mitigation Strategies:
Content Delivery Networks (CDNs)
Load balancers
Rate limiting
Traffic analysis और filtering
Blackholing suspicious traffic
2. Man-in-the-Middle (MITM) Attacks:
Attack Scenarios:
Wi-Fi Eavesdropping: Public Wi-Fi पर traffic intercept करना
Email Hijacking: Email communications को intercept करना
DNS Spoofing: DNS responses को manipulate करना
ARP Spoofing: Local network पर MAC addresses spoof करना
Prevention Methods:
Strong encryption (HTTPS, VPN)
Certificate pinning
Public key verification
Secure Wi-Fi protocols
Current Threat Landscape (2024-2025):
1. Financial Impact:
Global cybercrime cost: $8 trillion annually
Average data breach cost: $4.45 million
Ransomware payments: $1.1 billion in 2023
Identity theft losses: $52 billion
2. Attack Frequency:
Cyberattack every 39 seconds
95% of successful attacks are due to human error
43% of attacks target small businesses
Healthcare sector: 88% increase in attacks
3. Emerging Threats:
AI-powered attacks
Supply chain attacks
Cloud-native threats
IoT botnets
Deepfake technology abuse
Industry-Specific Threats:
Healthcare:
Patient data theft
Medical device hacking
Ransomware attacks on hospitals
HIPAA compliance violations
Financial Services:
ATM skimming
Credit card fraud
Mobile banking attacks
Cryptocurrency theft
Critical Infrastructure:
Power grid attacks
Water system compromise
Transportation disruption
Communication network failures
TCP/IP Protocol Suite विस्तृत विवरण:
Layer 1 - Physical Layer:
Function: Raw bit transmission over physical medium
Security Concerns:
Cable tapping
Electromagnetic interference
Physical access to network infrastructure
Security Measures:
Secured cable installation
TEMPEST shielding
Physical access controls
Layer 2 - Data Link Layer:
Protocols: Ethernet, Wi-Fi, ARP
Security Issues:
MAC address spoofing
ARP poisoning
Switch flooding attacks
Security Solutions:
MAC address filtering
Port security
Dynamic ARP inspection
802.1X authentication
Layer 3 - Network Layer:
Protocols: IP, ICMP, OSPF, BGP
Security Threats:
IP spoofing
Routing table poisoning
ICMP redirects
Security Measures:
IPSec
Routing protocol authentication
Access control lists (ACLs)
Layer 4 - Transport Layer:
Protocols: TCP, UDP
Security Issues:
TCP hijacking
SYN flood attacks
Port scanning
Security Solutions:
Connection state monitoring
Port filtering
TCP sequence number randomization
OSI Model और Security Implications:
Application Layer (Layer 7) Security:
Threats: SQL injection, XSS, buffer overflows
Controls: Input validation, output encoding, secure coding practices
Presentation Layer (Layer 6) Security:
Function: Encryption, compression, data formatting
Security Role: SSL/TLS encryption, data compression security
Session Layer (Layer 5) Security:
Function: Session establishment और management
Security: Session tokens, timeout controls, secure session termination
Subnetting और VLANs:
Subnetting Benefits for Security:
Network segmentation
Broadcast domain isolation
Better access control
Reduced attack surface
VLAN Security Implementation:
VLAN Hopping Prevention:
Disable unused ports
Use explicit tagging
Implement VLAN ACLs
Inter-VLAN Routing Security:
Router ACLs
Firewall between VLANs
VLAN-based access policies
A. Firewalls (विस्तृत विवरण)
Firewall Types और Functions:
1. Packet Filtering Firewalls:
Operation: Header information examine करते हैं
Criteria: Source/destination IP, ports, protocol type
Advantages: Fast processing, low cost
Limitations: Cannot inspect application data, stateless
Use Cases: Basic network perimeter security
2. Stateful Inspection Firewalls:
Operation: Connection state track करते हैं
Features:
Connection table maintenance
Dynamic rule creation
Return traffic validation
Advantages: Better security than packet filtering, context awareness
Configuration Example:
Allow outbound HTTP (port 80)Allow return traffic for established connectionsBlock unsolicited inbound connections
3. Application Gateway Firewalls (Proxy Firewalls):
Operation: Application layer पर traffic inspect करते हैं
Process:
Client connects to proxy
Proxy validates request
Proxy forwards to server
Response filtered और forwarded
Advantages: Deep packet inspection, application awareness
Disadvantages: Performance overhead, protocol specific
4. Next-Generation Firewalls (NGFW):
Features:
Deep packet inspection
Intrusion prevention
Application identification
User identity integration
Threat intelligence
Vendors: Palo Alto, Fortinet, Check Point, Cisco
Firewall Configuration Best Practices:
Rule Management:
Default deny policy
Least privilege principle
Regular rule review और cleanup
Documentation और change management
Logging और Monitoring:
Connection logs
Blocked traffic analysis
Performance monitoring
Security event correlation
B. Intrusion Detection Systems (IDS)
IDS Types और Detailed Explanation:
1. Network-based IDS (NIDS):
Deployment: Network segments पर sensors
Detection Methods:
Signature-based: Known attack patterns
Anomaly-based: Baseline behavior deviation
Protocol analysis: Protocol violations detect करना
Advantages: Network-wide visibility, real-time monitoring
Challenges: Encrypted traffic, high-speed networks
2. Host-based IDS (HIDS):
Installation: Individual hosts पर agents
Monitoring Areas:
File integrity
System calls
Log files
Registry changes (Windows)
Advantages: Detailed host activity, encrypted traffic visibility
Disadvantages: Resource consumption, management overhead
IDS Detection Techniques:
Signature-based Detection:
Method: Predefined patterns matching
Database: Regularly updated signature database
Pros: Low false positives, fast detection
Cons: Cannot detect unknown attacks, signature maintenance
Anomaly-based Detection:
Method: Statistical analysis, machine learning
Process:
Baseline establishment
Real-time comparison
Deviation threshold alerting
Pros: Zero-day attack detection
Cons: High false positives, baseline management
Behavioral Analysis:
User behavior analytics (UBA)
Entity behavior analytics (EBA)
Machine learning algorithms
C. Intrusion Prevention Systems (IPS)
IPS vs IDS Differences:
IDS Characteristics:
Passive monitoring
Out-of-band deployment
Detection और alerting
No traffic blocking
IPS Characteristics:
Active protection
Inline deployment
Detection और prevention
Real-time traffic blocking
IPS Deployment Models:
1. Inline Mode:
Position: Direct traffic path में
Action: Malicious traffic को block करता है
Risk: Single point of failure
Mitigation: High availability configuration
2. Passive Mode:
Position: Traffic copy receive करता है
Action: Detection और alerting only
Advantage: No network disruption risk
IPS Response Actions:
Packet dropping: Malicious packets को discard करना
Connection reset: TCP connections terminate करना
Source blocking: Attacker IP को temporary block करना
Rate limiting: Suspicious traffic को throttle करना
Wi-Fi Security Protocols Evolution
WEP (Wired Equivalent Privacy):
Year: 1997
Key Size: 40-bit या 104-bit
Vulnerabilities:
Weak encryption algorithm (RC4)
Static keys
IV collision attacks
Key recovery within minutes
Status: Deprecated, never use
WPA (Wi-Fi Protected Access):
Year: 2003
Improvements over WEP:
TKIP (Temporal Key Integrity Protocol)
Dynamic key generation
Message integrity check
Vulnerabilities: TKIP weaknesses, still vulnerable
Recommendation: Upgrade to WPA2/WPA3
WPA2 (Wi-Fi Protected Access 2):
Year: 2004
Features:
AES encryption
CCMP (Counter Mode CBC-MAC Protocol)
Strong authentication methods
Modes:
Personal (PSK): Pre-shared key
Enterprise (802.1X): RADIUS authentication
Vulnerabilities: KRACK attack (2017), but still secure with patches
WPA3 (Wi-Fi Protected Access 3):
Year: 2018
Enhancements:
SAE (Simultaneous Authentication of Equals)
Forward secrecy
Protection against offline attacks
Enhanced open networks
Features:
192-bit security suite for enterprise
Easy Connect for IoT devices
Opportunistic Wireless Encryption (OWE)
Wi-Fi Security Best Practices:
Network Configuration:
Use WPA3 (or WPA2 if WPA3 unavailable)
Strong passphrase (20+ characters)
Disable WPS (Wi-Fi Protected Setup)
Change default SSID
Disable SSID broadcast (security through obscurity)
Enable MAC address filtering (additional layer)
Enterprise Wi-Fi Security:
802.1X authentication
RADIUS server integration
Certificate-based authentication
Network Access Control (NAC)
VLAN segregation for different user types
Windows Security (विस्तृत गाइड)
User Account Control (UAC) Deep Dive:
UAC Levels:
Always Notify: सभी changes के लिए prompt
Notify (Default): Programs के changes के लिए prompt
Notify (No Desktop Dimming): Same as default लेकिन कम secure
Never Notify: कोई prompts नहीं (least secure)
UAC Bypass Techniques (Awareness के लिए):
DLL hijacking
Registry manipulation
Token manipulation
Process hollowing
UAC Best Practices:
Default level पर रखें
Standard user accounts use करें
Administrator accounts केवल जरूरत के लिए
Group Policy से UAC enforce करें
Group Policy Detailed Configuration:
Security Settings:
Password Policy:
Minimum length: 14 characters
Complexity requirements: Enable
Maximum age: 60 days
Password history: 24 passwords
Account Lockout Policy:
Lockout threshold: 5 attempts
Lockout duration: 30 minutes
Reset counter: 30 minutes
Audit Policy Configuration:
Logon events: Success और Failure
Object access: Failure
Privilege use: Success और Failure
Account management: Success और Failure
Policy change: Success
System events: Success और Failure
Windows Defender Configuration:
Real-time Protection Settings:
Real-time protection: Enable
Cloud-delivered protection: Enable
Automatic sample submission: Enable
Tamper protection: Enable
Scan Settings:
Daily quick scan
Weekly full scan
USB/removable device scan
Email और web protection
Advanced Features:
Controlled folder access (Ransomware protection)
Network protection
Application control
Device control
Registry Security:
Critical Registry Keys:
HKEY_LOCAL_MACHINE\Software: Software settings
HKEY_LOCAL_MACHINE\System: System configuration
HKEY_USERS: User profiles
HKEY_CURRENT_CONFIG: Hardware configuration
Registry Security Measures:
Regular registry backups
Access control lists (ACLs)
Registry monitoring tools
Disable remote registry access
Registry cleanup utilities
Linux Security (Comprehensive Guide)
File Permissions Deep Understanding:
Permission Types:
Read (r): File content देख सकते हैं
Write (w): File modify कर सकते हैं
Execute (x): File को run कर सकते हैं
Permission Categories:
Owner (u): File का owner
Group (g): File के group के members
Others (o): बाकी सभी users
Advanced Permissions:
Setuid (s): File को owner के permissions से run करना
Setgid (s): File को group के permissions से run करना
Sticky bit (t): Directory में केवल owner files delete कर सकता है
Permission Examples:
chmod 755 file.txt # rwxr-xr-x
chmod 644 document # rw-r--r--
chmod 600 private.key # rw-------
chmod 4755 sudo # rwsr-xr-x (setuid)
sudo और su Commands:
sudo Configuration (/etc/sudoers):
# User privilege specification
user1 ALL=(ALL:ALL) ALL
user2 ALL=(root) /usr/bin/systemctl
# Group privileges
%admin ALL=(ALL) ALL
%sudo ALL=(ALL:ALL) ALL
# No password for specific commands
user3 ALL=(ALL) NOPASSWD: /usr/bin/apt-get
sudo Best Practices:
Use visudo command for editing
Least privilege principle
Time-based access restrictions
Command logging और monitoring
Regular privilege review
SELinux (Security-Enhanced Linux):
SELinux Modes:
Enforcing: Policies enforce होती हैं
Permissive: Violations log होते हैं लेकिन block नहीं
Disabled: SELinux completely off
SELinux Contexts:
User: SELinux user identity
Role: User के allowed roles
Type: Object का type/domain
Level: Multi-level security (MLS)
Common SELinux Commands:
getenforce # Current mode check
setenforce 0 # Permissive mode
setenforce 1 # Enforcing mode
ls -Z # File contexts देखना
ps -Z # Process contexts देखना
setsebool -P httpd_can_network_connect on # Boolean setting
System Hardening Checklist:
Service Management:
Unnecessary services disable करें
Service permissions check करें
Regular service audits
Port scanning और service enumeration
Network Security:
iptables/firewalld configuration
SSH hardening
Network service security
VPN और remote access
File System Security:
Disk encryption (LUKS)
Mount options (noexec, nosuid)
File integrity monitoring
Backup और recovery procedures
Secure Coding Practices
Input Validation:
Validation Types:
Syntactic Validation: Format और structure check
Semantic Validation: Business logic के against check
Length Validation: Input size restrictions
Type Validation: Data type verification
Validation Implementation:
# Python example
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(pattern, email):
raise ValueError("Invalid email format")
if len(email) > 254:
raise ValueError("Email too long")
return True
def validate_input(user_input, max_length=100):
# Length check
if len(user_input) > max_length:
return False
# Dangerous characters check
dangerous_chars = ['<', '>', '"', "'", '&', ';']
if any(char in user_input for char in dangerous_chars):
return False
return True
Output Encoding:
Context-Specific Encoding:
HTML Encoding: < becomes <, > becomes >
JavaScript Encoding: Special characters escape करना
URL Encoding: Reserved characters को percent-encode करना
SQL Encoding: Database-specific escaping
OWASP Top 10 Vulnerabilities (2023)
1. Injection Attacks:
SQL Injection:
-- Vulnerable query
SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'
-- Attack input
username: admin' OR '1'='1' --
password: anything
-- Resulting query
SELECT * FROM users WHERE username = 'admin' OR '1'='1' --' AND password = 'anything'
Prevention:
Parameterized queries/prepared statements
Stored procedures
Input validation
Least privilege database access
2. Broken Authentication:
Common Issues:
Weak password requirements
Session management flaws
Credential stuffing vulnerabilities
Missing multi-factor authentication
Secure Implementation:
# Password hashing
import bcrypt
def hash_password(password):
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed
def verify_password(password, hashed):
return bcrypt.checkpw(password.encode('utf-8'), hashed)
# Session management
import secrets
import time
def generate_session_token():
return secrets.token_urlsafe(32)
def validate_session(token, created_time, timeout=3600):
if time.time() - created_time > timeout:
return False
# Additional validation logic
return True
3. Sensitive Data Exposure:
Data Classification:
Public: No restrictions
Internal: Company employees only
Confidential: Limited access
Restricted: Highest security level
Encryption Implementation:
from cryptography.fernet import Fernet
# Generate key
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# Encrypt data
def encrypt_data(data):
return cipher_suite.encrypt(data.encode())
# Decrypt data
def decrypt_data(encrypted_data):
return cipher_suite.decrypt(encrypted_data).decode()
4. XML External Entities (XXE):
Attack Example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<root>
<data>&xxe;</data>
</root>
Prevention:
Disable external entity processing
Input validation
Use less complex data formats (JSON)
Regular security testing
5. Broken Access Control:
Common Flaws:
Missing authorization checks
Insecure direct object references
Privilege escalation
CORS misconfigurations
Secure Implementation:
# Role-based access control
class AccessControl:
def __init__(self):
self.permissions = {
'admin': ['read', 'write', 'delete', 'execute'],
'user': ['read', 'write'],
'guest': ['read']
}
def check_permission(self, user_role, action, resource):
if user_role not in self.permissions:
return False
if action not in self.permissions[user_role]:
return False
# Additional resource-specific checks
return self.resource_check(user_role, resource)
Symmetric vs Asymmetric Encryption
Symmetric Encryption विस्तृत विवरण:
Characteristics:
Same key for encryption और decryption
Fast processing speed
Suitable for large data volumes
Key distribution challenge
Common Algorithms:
1. AES (Advanced Encryption Standard):
Key Sizes: 128, 192, 256 bits
Block Size: 128 bits
Modes: ECB, CBC, CFB, OFB, GCM
Usage: File encryption, VPN, Wi-Fi security
AES Implementation Example:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
def aes_encrypt(plaintext, key):
# Generate random IV
iv = os.urandom(16)
# Create cipher
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
# Pad plaintext to block size
padded_plaintext = plaintext + b' ' * (16 - len(plaintext) % 16)
# Encrypt
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
return iv + ciphertext
2. DES (Data Encryption Standard):
Key Size: 56 bits (64 bits with parity)
Block Size: 64 bits
Status: Deprecated due to small key size
Replacement: 3DES, AES
3. 3DES (Triple DES):
Method: Apply DES three times
Key Options: 2-key या 3-key
Security: Better than DES लेकिन AES preferred
Performance: Slower than AES
Asymmetric Encryption विस्तृत विवरण:
Characteristics:
Key pair: Public और private key
Slower than symmetric encryption
No key distribution problem
Used for key exchange और digital signatures
RSA Algorithm Deep Dive:
Key Generation Process:
Choose two large prime numbers (p, q)
Calculate n = p × q
Calculate φ(n) = (p-1)(q-1)
Choose public exponent e (commonly 65537)
Calculate private exponent d = e^(-1) mod φ(n)
RSA Encryption/Decryption:
Encryption: C = M^e mod n
Decryption: M = C^d mod n
Key Sizes: 1024, 2048, 4096 bits (2048+ recommended)
RSA Implementation Example:
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
# Generate RSA key pair
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
public_key = private_key.public_key()
# Encrypt data
def rsa_encrypt(message, public_key):
encrypted = public_key.encrypt(
message.encode(),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return encrypted
# Decrypt data
def rsa_decrypt(encrypted_message, private_key):
decrypted = private_key.decrypt(
encrypted_message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return decrypted.decode()
ECC (Elliptic Curve Cryptography):
Advantages over RSA:
Smaller key sizes for equivalent security
Faster computations
Lower power consumption
Better for mobile devices
Common Curves:
P-256: NIST standard curve
P-384: Higher security level
Curve25519: High performance, secure
secp256k1: Used in Bitcoin
ECC vs RSA Security Comparison:
ECC 256-bit ≈ RSA 3072-bit
ECC 384-bit ≈ RSA 7680-bit
ECC 521-bit ≈ RSA 15360-bit
Hash Functions विस्तृत विवरण
Hash Function Properties:
Deterministic: Same input always produces same output
Fixed Output Size: Regardless of input size
Fast Computation: Efficient to calculate
Avalanche Effect: Small input change causes large output change
One-way Function: Computationally infeasible to reverse
Collision Resistant: Hard to find two inputs with same hash
SHA Family:
SHA-1:
Output Size: 160 bits
Status: Deprecated (collision attacks found)
Last Use: Legacy systems only
SHA-2 Family:
SHA-224: 224-bit output
SHA-256: 256-bit output (most common)
SHA-384: 384-bit output
SHA-512: 512-bit output
SHA-3 (Keccak):
Different Design: Sponge construction
Outputs: 224, 256, 384, 512 bits
Advantage: Different mathematical foundation than SHA-2
Hash Function Applications:
1. Password Storage:
import hashlib
import secrets
def hash_password(password):
# Generate salt
salt = secrets.token_hex(16)
# Hash password with salt
password_hash = hashlib.pbkdf2_hmac(
'sha256',
password.encode('utf-8'),
salt.encode('utf-8'),
100000 # iterations
)
return salt + password_hash.hex()
def verify_password(password, stored_hash):
salt = stored_hash[:32] # First 32 characters are salt
hash_to_check = stored_hash[32:]
password_hash = hashlib.pbkdf2_hmac(
'sha256',
password.encode('utf-8'),
salt.encode('utf-8'),
100000
)
return password_hash.hex() == hash_to_check
2. File Integrity Checking:
def calculate_file_hash(filename):
sha256_hash = hashlib.sha256()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
sha256_hash.update(chunk)
return sha256_hash.hexdigest()
def verify_file_integrity(filename, expected_hash):
actual_hash = calculate_file_hash(filename)
return actual_hash == expected_hash
3. Digital Signatures:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
def sign_message(message, private_key):
signature = private_key.sign(
message.encode(),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return signature
def verify_signature(message, signature, public_key):
try:
public_key.verify(
signature,
message.encode(),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True
except:
return False
Key Management
Key Lifecycle Management:
1. Key Generation:
Entropy Sources: Hardware random number generators
Key Strength: Adequate length for security level
Algorithm Selection: Appropriate for use case
Quality Assurance: Statistical randomness testing
2. Key Distribution:
Secure Channels: TLS, VPN, physical delivery
Key Escrow: Trusted third party storage
Key Agreement Protocols: Diffie-Hellman, ECDH
Certificate Authorities: PKI infrastructure
3. Key Storage:
Hardware Security Modules (HSMs): Dedicated cryptographic devices
Key Stores: Software-based secure storage
Access Controls: Authentication और authorization
Backup और Recovery: Secure key backup procedures
4. Key Usage:
Purpose Limitation: Keys used only for intended purpose
Usage Monitoring: Track key operations
Performance Optimization: Caching strategies
Load Balancing: Distribute cryptographic operations
5. Key Rotation:
Scheduled Rotation: Regular key updates
Event-driven Rotation: Compromise या suspected exposure
Backward Compatibility: Support for multiple key versions
Seamless Transition: Minimize service disruption
6. Key Destruction:
Secure Deletion: Cryptographic erasure
Physical Destruction: Hardware disposal
Audit Trail: Document key destruction
Compliance Requirements: Regulatory obligations
Advanced Encryption Standard (AES)
AES Modes of Operation:
1. ECB (Electronic Codebook):
Method: Each block encrypted independently
Problem: Identical plaintext blocks produce identical ciphertext
Use Case: Never recommended for sensitive data
Vulnerability: Pattern recognition possible
2. CBC (Cipher Block Chaining):
Method: Each block XORed with previous ciphertext block
IV Required: Random initialization vector
Advantages: Identical blocks produce different ciphertext
Disadvantages: Sequential processing, padding oracle attacks
3. CFB (Cipher Feedback):
Method: Block cipher used as stream cipher
Characteristics: Self-synchronizing
Error Propagation: Limited to one block
Use Case: Streaming data
4. OFB (Output Feedback):
Method: Block cipher generates keystream
Characteristics: No error propagation
Synchronization: Must maintain between sender/receiver
Use Case: Error-prone channels
5. GCM (Galois/Counter Mode):
Features: Authenticated encryption
Benefits: Confidentiality + integrity
Performance: Parallelizable
Use Case: Modern applications (TLS 1.3)
AES Implementation Best Practices:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
import os
class AESCipher:
def __init__(self, key):
self.key = key
def encrypt_cbc(self, plaintext):
# Generate random IV
iv = os.urandom(16)
# Pad plaintext
padder = padding.PKCS7(128).padder()
padded_data = padder.update(plaintext.encode()) + padder.finalize()
# Encrypt
cipher = Cipher(algorithms.AES(self.key), modes.CBC(iv))
encryptor = cipher.encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
return iv + ciphertext
def decrypt_cbc(self, encrypted_data):
# Extract IV and ciphertext
iv = encrypted_data[:16]
ciphertext = encrypted_data[16:]
# Decrypt
cipher = Cipher(algorithms.AES(self.key), modes.CBC(iv))
decryptor = cipher.decryptor()
padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
# Remove padding
unpadder = padding.PKCS7(128).unpadder()
plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()
return plaintext.decode()
def encrypt_gcm(self, plaintext, associated_data=None):
# Generate random nonce
nonce = os.urandom(12)
# Encrypt with authentication
cipher = Cipher(algorithms.AES(self.key), modes.GCM(nonce))
encryptor = cipher.encryptor()
if associated_data:
encryptor.authenticate_additional_data(associated_data)
ciphertext = encryptor.update(plaintext.encode()) + encryptor.finalize()
return nonce + encryptor.tag + ciphertext
Public Key Infrastructure (PKI)
PKI Components:
1. Certificate Authority (CA):
Root CA: Top-level authority
Intermediate CA: Delegate certificate issuance
Registration Authority (RA): Verify identity before issuance
Certificate Repository: Store और distribute certificates
2. Digital Certificates:
X.509 Standard: Most common certificate format
Certificate Fields:
Subject: Certificate holder information
Issuer: CA information
Public Key: Holder's public key
Validity Period: Not before/not after dates
Serial Number: Unique identifier
Signature: CA's digital signature
Certificate Lifecycle:
1. Certificate Request (CSR):
# Generate private key
openssl genrsa -out private.key 2048
# Generate CSR
openssl req -new -key private.key -out certificate.csr
# CSR contains:
# - Public key
# - Subject information
# - Requested extensions
2. Certificate Issuance:
Identity verification
Policy compliance check
Certificate generation
CA signature application
3. Certificate Deployment:
Certificate installation
Chain of trust verification
Revocation checking
Renewal scheduling
4. Certificate Revocation:
CRL (Certificate Revocation List): Periodic list of revoked certificates
OCSP (Online Certificate Status Protocol): Real-time revocation checking
OCSP Stapling: Server provides OCSP response
Trust Models:
1. Hierarchical Trust:
Root CA at top
Intermediate CAs below
End-entity certificates at bottom
Chain of trust validation
2. Web of Trust:
Peer-to-peer trust relationships
Multiple trust paths
Used in PGP/GPG
Decentralized model
3. Cross-Certification:
Multiple independent CAs
Mutual recognition agreements
Bridge CAs for interconnection
SSL/TLS Implementation
TLS Handshake Process:
1. Client Hello:
Supported cipher suites
Random number generation
Session ID (if resuming)
Supported extensions
2. Server Hello:
Selected cipher suite
Server random number
Server certificate
Optional: certificate request
3. Key Exchange:
Client verifies server certificate
Client generates pre-master secret
Pre-master secret encrypted with server's public key
Client sends encrypted pre-master secret
4. Session Keys Generation:
Master secret derived from pre-master secret
Session keys derived from master secret
Separate keys for encryption और MAC
5. Finished Messages:
Both parties send encrypted/authenticated "Finished" message
Handshake completion confirmation
TLS Security Features:
1. Cipher Suites:
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
│ │ │ │ │ │ │
│ │ │ │ │ │ └── Hash function
│ │ │ │ │ └────── Encryption mode
│ │ │ │ └────────── Encryption algorithm
│ │ │ └─────────────── Key size
│ │ └─────────────────── Authentication
│ └──────────────────────── Key exchange
└───────────────────────────── Protocol version
2. Perfect Forward Secrecy:
Ephemeral key exchange (ECDHE, DHE)
Session keys independent of long-term keys
Past communications remain secure even if private key compromised
3. TLS 1.3 Improvements:
Reduced handshake rounds
Mandatory forward secrecy
Simplified cipher suite selection
Enhanced security algorithms
Email Security (PGP/GPG)
PGP (Pretty Good Privacy) Overview:
Key Features:
Hybrid encryption (symmetric + asymmetric)
Digital signatures
Compression
Radix-64 encoding
PGP Process:
1. Encryption Process:
1. Generate random session key
2. Encrypt message with session key (symmetric)
3. Encrypt session key with recipient's public key
4. Combine encrypted session key + encrypted message
5. Optional: Compress and encode
2. Digital Signature Process:
1. Hash the message
2. Encrypt hash with sender's private key
3. Attach signature to message
4. Recipient verifies with sender's public key
GPG (GNU Privacy Guard) Usage:
Key Management:
# Generate key pair
gpg --gen-key
# List keys
gpg --list-keys
gpg --list-secret-keys
# Export public key
gpg --export --armor user@example.com > public.key
# Import public key
gpg --import public.key
# Sign a key
gpg --sign-key user@example.com
Encryption/Decryption:
# Encrypt file
gpg --encrypt --recipient user@example.com file.txt
# Decrypt file
gpg --decrypt file.txt.gpg
# Sign file
gpg --sign file.txt
# Verify signature
gpg --verify file.txt.gpg
Disk Encryption
Full Disk Encryption (FDE):
Windows - BitLocker:
Setup Process:
Enable BitLocker on system drive
Choose authentication method (TPM, PIN, USB key)
Save recovery key securely
Encrypt drive (can continue working during encryption)
BitLocker Modes:
TPM Only: Automatic unlock with TPM
TPM + PIN: Require PIN at boot
TPM + USB: Require USB key
USB Only: For systems without TPM
Group Policy Configuration:
Computer Configuration > Policies > Administrative Templates > Windows Components > BitLocker Drive Encryption
- Require additional authentication at startup
- Configure minimum PIN length
- Allow enhanced PINs for startup
- Configure recovery options
Linux - LUKS (Linux Unified Key Setup):
Setup Process:
# Create encrypted partition
cryptsetup luksFormat /dev/sdb1
# Open encrypted partition
cryptsetup luksOpen /dev/sdb1 encrypted_volume
# Create filesystem
mkfs.ext4 /dev/mapper/encrypted_volume
# Mount filesystem
mount /dev/mapper/encrypted_volume /mnt/secure
Key Management:
# Add key slot
cryptsetup luksAddKey /dev/sdb1
# Remove key slot
cryptsetup luksRemoveKey /dev/sdb1
# Change key
cryptsetup luksChangeKey /dev/sdb1
# Backup header
cryptsetup luksHeaderBackup /dev/sdb1 --header-backup-file header.backup
File-Level Encryption:
EncFS (Encrypted Filesystem):
# Create encrypted directory
encfs ~/encrypted ~/decrypted
# Mount encrypted directory
encfs ~/encrypted ~/decrypted
# Unmount
fusermount -u ~/decrypted
AxCrypt (Windows):
Right-click encryption
Password-based encryption
Automatic re-encryption
Secure deletion
Cloud Encryption
Encryption Models:
1. Server-Side Encryption:
Data encrypted by cloud provider
Provider manages encryption keys
Transparent to applications
Easier to implement
2. Client-Side Encryption:
Data encrypted before uploading
Client manages encryption keys
Zero-knowledge architecture
Higher security but more complex
3. Hybrid Approach:
Combination of both methods
Different encryption for different data types
Balanced security और usability
AWS Encryption Services:
S3 Encryption Options:
import boto3
# Server-side encryption with S3-managed keys
s3_client = boto3.client('s3')
s3_client.put_object(
Bucket='my-bucket',
Key='my-file.txt',
Body=b'file content',
ServerSideEncryption='AES256'
)
# Server-side encryption with KMS
s3_client.put_object(
Bucket='my-bucket',
Key='my-file.txt',
Body=b'file content',
ServerSideEncryption='aws:kms',
SSEKMSKeyId='arn:aws:kms:region:account:key/key-id'
)
# Client-side encryption
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# Encrypt before upload
encrypted_data = cipher_suite.encrypt(b'file content')
s3_client.put_object(
Bucket='my-bucket',
Key='my-file.txt',
Body=encrypted_data
)
Azure Encryption:
Storage Service Encryption (SSE): Automatic encryption
Azure Key Vault: Key management service
Client-side encryption: Using Azure libraries
Transparent Data Encryption (TDE): For SQL databases
Google Cloud Encryption:
Default encryption: All data encrypted at rest
Cloud KMS: Managed key service
Customer-managed keys: Full control over keys
Customer-supplied keys: Bring your own keys
Ethical Hacking Methodology
Penetration Testing Phases:
1. Pre-Engagement:
Scope Definition: Target systems और boundaries
Rules of Engagement: Permitted और prohibited activities
Legal Authorization: Written permission documents
Timeline: Testing schedule और milestones
Contact Information: Emergency contacts और escalation procedures
2. Intelligence Gathering:
Passive Reconnaissance: Information collection without target interaction
Active Reconnaissance: Direct interaction with target systems
OSINT: Open Source Intelligence gathering
Social Engineering: Human-based information gathering
3. Threat Modeling:
Asset Identification: Critical systems और data
Attack Vectors: Possible entry points
Threat Actors: Potential attackers और their capabilities
Risk Assessment: Likelihood और impact evaluation
4. Vulnerability Assessment:
Automated Scanning: Tools-based vulnerability detection
Manual Testing: Human analysis और verification
False Positive Elimination: Verify actual vulnerabilities
Prioritization: Risk-based vulnerability ranking
5. Exploitation:
Proof of Concept: Demonstrate vulnerability exploitation
Privilege Escalation: Gain higher-level access
Lateral Movement: Spread through network
Data Exfiltration: Simulate data theft (if authorized)
6. Post-Exploitation:
Persistence: Maintain access (if authorized)
Cleanup: Remove tools और artifacts
Documentation: Detailed findings record
Evidence Collection: Screenshots और logs
7. Reporting:
Executive Summary: High-level findings for management
Technical Details: Detailed vulnerability information
Risk Assessment: Business impact evaluation
Recommendations: Specific remediation steps
Legal और Ethical Considerations
Legal Framework:
Authorization Requirements:
Written Permission: Signed agreement before testing
Scope Limitations: Clear boundaries और restrictions
Liability Coverage: Insurance और legal protection
Compliance Requirements: Industry-specific regulations
Ethical Guidelines:
Minimum Necessary: Only perform required testing
Data Protection: Safeguard discovered information
Disclosure: Responsible vulnerability disclosure
Professional Conduct: Maintain ethical standards
International Laws:
Computer Fraud and Abuse Act (CFAA): US federal law
UK Computer Misuse Act: UK cybercrime legislation
European Cybercrime Laws: GDPR compliance
Local Regulations: Country-specific requirements
Types of Penetration Testing
1. Black Box Testing:
Knowledge Level: No prior information about target
Approach: Simulate external attacker
Advantages: Realistic attack simulation
Disadvantages: Time-consuming, may miss internal vulnerabilities
2. White Box Testing:
Knowledge Level: Complete information about target
Approach: Comprehensive security assessment
Advantages: Thorough testing, efficient resource use
Disadvantages: May not reflect real-world attacks
3. Gray Box Testing:
Knowledge Level: Partial information about target
Approach: Hybrid methodology
Advantages: Balanced approach, realistic scenarios
Disadvantages: Requires careful scope definition
Testing Types by Target:
Network Penetration Testing:
External Testing: Internet-facing systems
Internal Testing: Internal network infrastructure
Wireless Testing: Wi-Fi networks और protocols
VPN Testing: Remote access solutions
Web Application Testing:
OWASP Methodology: Structured approach
Authentication Testing: Login mechanisms
Session Management: Session handling
Input Validation: Data sanitization
Mobile Application Testing:
Static Analysis: Code review
Dynamic Analysis: Runtime testing
Network Communication: API security
Local Storage: Data protection
Social Engineering Testing:
Phishing Campaigns: Email-based attacks
Vishing: Voice-based social engineering
Physical Security: Facility access testing
USB Drops: Malicious device testing
Passive Reconnaissance Techniques
OSINT (Open Source Intelligence):
1. Domain Information Gathering:
WHOIS Lookup:
# Command line WHOIS
whois example.com
# Information gathered:
# - Registrar information
# - Registration dates
# - Contact information
# - Name servers
# - Status information
DNS Enumeration:
# DNS record types
dig example.com A # IPv4 addresses
dig example.com AAAA # IPv6 addresses
dig example.com MX # Mail servers
dig example.com NS # Name servers
dig example.com TXT # Text records
dig example.com SOA # Start of Authority
# Zone transfer attempt
dig @ns1.example.com example.com AXFR
# Reverse DNS lookup
dig -x 192.168.1.1
Subdomain Enumeration:
# Using different tools
subfinder -d example.com
amass enum -d example.com
sublist3r -d example.com
# DNS brute forcing
dnsrecon -d example.com -t brt
2. Search Engine Intelligence:
Google Dorking:
# Find specific file types
site:example.com filetype:pdf
site:example.com filetype:xls
site:example.com filetype:doc
# Find login pages
site:example.com inurl:login
site:example.com inurl:admin
site:example.com inurl:wp-admin
# Find sensitive information
site:example.com intext:"password"
site:example.com intext:"confidential"
site:example.com intext:"internal use only"
# Find specific technologies
site:example.com inurl:phpmyadmin
site:example.com intext:"powered by"
site:example.com intext:"index of"
# Find error messages
site:example.com intext:"sql error"
site:example.com intext:"warning:"
site:example.com intext:"error:"
Shodan Intelligence:
# Search for specific services
shodan search "apache"
shodan search "iis"
shodan search "nginx"
# Search by port
shodan search port:22
shodan search port:3389
shodan search port:445
# Search by country
shodan search country:US
shodan search city:"New York"
# Search by organization
shodan search org:"Example Corp"
# Combined searches
shodan search "apache" country:US port:80
3. Social Media Intelligence:
Professional Networks:
LinkedIn: Employee information, organizational structure
GitHub: Code repositories, configuration files
Twitter: Public communications, announcements
Facebook: Personal information, relationships
Information Gathering Tools:
# theHarvester - Email and subdomain gathering
theHarvester -d example.com -b google,bing,linkedin
# Maltego - Relationship mapping
# (GUI tool for relationship analysis)
# Recon-ng - Reconnaissance framework
recon-ng
[recon-ng][default] > modules search
[recon-ng][default] > modules load discovery/info_disclosure/interesting_files
Active Reconnaissance
Network Scanning:
1. Host Discovery:
# Ping sweep
nmap -sn 192.168.1.0/24
# ARP scan (local network)
arp-scan -l
arp-scan 192.168.1.0/24
# TCP SYN ping
nmap -PS 192.168.1.0/24
# UDP ping
nmap -PU 192.168.1.0/24
2. Port Scanning:
Nmap Scanning Techniques:
# TCP SYN scan (default)
nmap -sS target.com
# TCP connect scan
nmap -sT target.com
# UDP scan
nmap -sU target.com
# Comprehensive scan
nmap -sS -sU -T4 -A -v target.com
# Specific ports
nmap -p 80,443,22,21,25 target.com
# Port range
nmap -p 1-1000 target.com
# All ports
nmap -p- target.com
# Top ports
nmap --top-ports 1000 target.com
3. Service Enumeration:
# Service version detection
nmap -sV target.com
# Aggressive scan
nmap -A target.com
# Script scanning
nmap -sC target.com
nmap --script vuln target.com
nmap --script smb-enum-shares target.com
# Specific service enumeration
nmap -p 80 --script http-* target.com
nmap -p 22 --script ssh-* target.com
nmap -p 21 --script ftp-* target.com
4. OS Fingerprinting:
# OS detection
nmap -O target.com
# Aggressive OS detection
nmap -O --osscan-guess target.com
# IPv6 OS detection
nmap -6 -O target.com
Web Application Reconnaissance:
1. Technology Stack Identification:
# Whatweb
whatweb target.com
# Wappalyzer (browser extension)
# Identifies technologies used
# Builtwith
builtwith target.com
# Netcraft
# Online service for technology detection
2. Directory and File Enumeration:
# Gobuster
gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt
# Dirbuster (GUI tool)
# Directory brute forcing
# Feroxbuster
feroxbuster -u http://target.com -w /usr/share/wordlists/dirb/common.txt
# Custom wordlists
# SecLists: Comprehensive wordlists
# /usr/share/seclists/Discovery/Web-Content/
3. Parameter Discovery:
# Arjun
arjun -u http://target.com/page.php
# Paramspider
paramspider -d target.com
# Manual testing
# Analyze forms and JavaScript
# Look for hidden parameters
Scanning Tools विस्तृत विवरण
1. Nmap Advanced Usage:
Nmap Scripting Engine (NSE):
# List available scripts
nmap --script-help all
# Run specific script categories
nmap --script auth target.com
nmap --script broadcast target.com
nmap --script brute target.com
nmap --script discovery target.com
nmap --script dos target.com
nmap --script exploit target.com
nmap --script fuzzer target.com
nmap --script intrusive target.com
nmap --script malware target.com
nmap --script safe target.com
nmap --script version target.com
nmap --script vuln target.com
# Custom script execution
nmap --script http-sql-injection target.com
nmap --script smb-vuln-ms17-010 target.com
nmap --script ssl-cert,ssl-enum-ciphers target.com
Nmap Output Formats:
# Normal output
nmap target.com
# XML output
nmap -oX scan.xml target.com
# Greppable output
nmap -oG scan.gnmap target.com
# All formats
nmap -oA scan target.com
# Script