Interview Questions

1) Write a function that takes a string as input and returns true if it's a valid IPv4 address, otherwi


import re

def is_valid_ip(ip):
    pattern = r'^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
    return bool(re.match(pattern, ip))

# Test cases
print(is_valid_ip("192.168.1.1"))  # True
print(is_valid_ip("256.256.256.256"))  # False
print(is_valid_ip("1.1.1"))  # False

Explanation:

  • This function uses a regular expression to check if the string matches the format of an IPv4 address.
  • The valid values for each octet in the IP address must be between 0 and 255.

2) Write a function to encrypt a string using the XOR encryption technique with a given key.


def xor_encrypt_decrypt(input_string, key):
    # Encrypting/Decrypting is the same operation with XOR
    result = ''.join(chr(ord(char) ^ key) for char in input_string)
    return result

# Test cases
key = 123  # XOR key
original_text = "Hello, World!"
encrypted_text = xor_encrypt_decrypt(original_text, key)
decrypted_text = xor_encrypt_decrypt(encrypted_text, key)

print(f"Original: {original_text}")
print(f"Encrypted: {encrypted_text}")
print(f"Decrypted: {decrypted_text}")

Explanation:

  • XOR encryption is a simple symmetric encryption method that applies the XOR operation between the data and a key.
  • Encrypting or decrypting the data with the same key will result in the original data.

3) Write a function to hash a password using the SHA-256 algorithm in Python.


import hashlib

def hash_password(password):
    # Hash the password using SHA-256
    hashed_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
    return hashed_password

# Test case
password = "SecurePassword123"
hashed_password = hash_password(password)
print(f"Hashed password: {hashed_password}")

Explanation:

  • This function uses Python's hashlib library to hash a password using the SHA-256 algorithm.
  • The encode('utf-8') method is used to convert the password to bytes, as the hashlib functions expect byte input.

4) Write a function that salts a password with a random string and hashes it using SHA-256 to prevent r


import hashlib
import os

def hash_password_with_salt(password):
    # Generate a random salt
    salt = os.urandom(16)
    
    # Combine password with salt and hash using SHA-256
    salted_password = password.encode('utf-8') + salt
    hashed_password = hashlib.sha256(salted_password).hexdigest()
    
    # Return both the salt and the hashed password
    return salt.hex(), hashed_password

# Test case
password = "SecurePassword123"
salt, hashed_password = hash_password_with_salt(password)
print(f"Salt: {salt}")
print(f"Hashed Password: {hashed_password}")

Explanation:

  • The os.urandom(16) function is used to generate a 16-byte random salt.
  • The salt is combined with the password before being hashed with SHA-256 to ensure the result is different even if two users have the same password.
  • Salting prevents attackers from using precomputed tables (rainbow tables) to quickly reverse hash values.

5) Write a function that checks if a given string contains potential SQL Injection payloads (e.g., DROP


import re

def detect_sql_injection(input_string):
    # Define common SQL Injection patterns
    patterns = [r"(\b(SELECT|DROP|INSERT|UPDATE|DELETE)\b)",
                r"(--|\#|\*|;|/\*|\*/)",
                r"(\b(OR|AND)\b\s+\d\s*=\s*\d)"]
    
    for pattern in patterns:
        if re.search(pattern, input_string, re.IGNORECASE):
            return True  # Potential SQL injection found
    return False  # No SQL injection detected

# Test cases
print(detect_sql_injection("SELECT * FROM users WHERE username = 'admin'"))  # True
print(detect_sql_injection("admin' OR 1=1 --"))  # True
print(detect_sql_injection("user input"))  # False

Explanation:

  • This function checks for common patterns of SQL injection using regular expressions.
  • It looks for dangerous keywords (like SELECT, DROP, OR 1=1), SQL comment syntax (--, #, etc.), and suspicious logical statements that could indicate an SQL injection attempt.

6) Write a function to encrypt and decrypt a string using Caesar cipher with a given shift.


def caesar_cipher(text, shift, mode='encrypt'):
    result = ""
    
    # Shift the text based on the operation mode
    if mode == 'decrypt':
        shift = -shift
    
    for char in text:
        if char.isalpha():  # Only shift alphabetic characters
            shift_base = 65 if char.isupper() else 97
            result += chr((ord(char) - shift_base + shift) % 26 + shift_base)
        else:
            result += char  # Non-alphabetic characters remain unchanged
    
    return result

# Test cases
original_text = "Hello, World!"
shift = 3
encrypted_text = caesar_cipher(original_text, shift, mode='encrypt')
decrypted_text = caesar_cipher(encrypted_text, shift, mode='decrypt')

print(f"Original: {original_text}")
print(f"Encrypted: {encrypted_text}")
print(f"Decrypted: {decrypted_text}")

Explanation:

  • Caesar cipher is a simple encryption technique where each letter in the plaintext is shifted by a certain number of positions in the alphabet.
  • The function handles both encryption and decryption by adjusting the shift value and ensuring that the shift wraps around the alphabet using modulo 26.

7) Write a function to check if a CSRF token is present and valid in a request header.


import secrets

# A mock function to generate and store a CSRF token in a session
def generate_csrf_token():
    return secrets.token_hex(16)

# Function to check if the CSRF token in the request matches the stored token
def check_csrf_token(request_token, session_token):
    if request_token == session_token:
        return True  # CSRF token is valid
    return False  # CSRF token is invalid

# Example usage
session_token = generate_csrf_token()  # Simulate storing a CSRF token in a session
request_token = session_token  # Simulate a valid CSRF token in the request

is_valid = check_csrf_token(request_token, session_token)
print(f"CSRF Token is valid: {is_valid}")

Explanation:

  • This function checks if the CSRF token passed in the request header matches the one stored in the user's session.
  • Using a library like secrets for generating secure random tokens ensures that the CSRF token is unpredictable.

8) Write a function to simulate a brute-force attack by guessing a password using a dictionary of poss


def brute_force_crack(password, dictionary):
    for word in dictionary:
        if word == password:
            return f"Password cracked: {word}"
    return "Password not found in dictionary"

# Test case
password = "admin123"
dictionary = ["password", "123456", "admin123", "qwerty"]
result = brute_force_crack(password, dictionary)
print(result)

Explanation:

  • This function simulates a brute-force attack by trying each word from a given dictionary to find the password.
  • Brute-force attacks are inefficient but can be successful if weak passwords are used or the attacker has access to a dictionary of common passwords.

9) Write a function to detect if a password is strong based on common criteria.


import re

def is_strong_password(password):
    if len(password) < 8:
        return False
    if not re.search(r"[a-z]", password):
        return False
    if not re.search(r"[A-Z]", password):
        return False
    if not re.search(r"[0-9]", password):
        return False
    if not re.search(r"[\W_]", password):  # Non-word characters (special characters)
        return False
    return True

# Test cases
print(is_strong_password("Password123!"))  # True
print(is_strong_password("weakpassword"))  # False
print(is_strong_password("12345"))  # False

Explanation:

  • This function checks the length of the password and uses regular expressions to validate the presence of lowercase letters, uppercase letters, digits, and special characters.
  • If any condition is not met, the password is considered weak.

10) Write a function to detect potential XSS attempts by checking if the input string contains common HT


import re

def detect_xss(input_string):
    xss_patterns = [
        r"<script.*?>.*?</script>",  # Matches <script> tags
        r"javascript:.*",  # Matches JavaScript pseudo-protocol
        r"on\w+\s*=",  # Matches event handlers (e.g., onclick=, onload=)
    ]
    
    for pattern in xss_patterns:
        if re.search(pattern, input_string, re.IGNORECASE):
            return True  # Potential XSS attack detected
    return False  # No XSS detected

# Test cases
print(detect_xss("<script>alert('XSS');</script>"))  # True
print(detect_xss("Hello, World!"))  # False
print(detect_xss('<a href="javascript:alert(1)">Click me</a>'))  # True

Explanation:

  • The function looks for patterns that are commonly used in XSS attacks, such as <script> tags and JavaScript event handlers (onclick, onload, etc.).
  • It returns True if any suspicious pattern is detected.

11) Write a function to encode and decode a string using Base64 encoding.


import base64

def base64_encode(input_string):
    encoded_bytes = base64.b64encode(input_string.encode('utf-8'))
    return encoded_bytes.decode('utf-8')

def base64_decode(encoded_string):
    decoded_bytes = base64.b64decode(encoded_string)
    return decoded_bytes.decode('utf-8')

# Test cases
encoded = base64_encode("Hello, World!")
print(f"Encoded: {encoded}")

decoded = base64_decode(encoded)
print(f"Decoded: {decoded}")

Explanation:

  • Base64 encoding is commonly used to encode binary data in a text format (e.g., for email attachments or URL-safe encoding).
  • base64.b64encode and base64.b64decode are used to handle the encoding and decoding process in Python.

12) Write a function to check whether a given server supports weak SSL/TLS configurations, such as weak


import ssl
import socket

def check_ssl_configuration(hostname, port=443):
    context = ssl.create_default_context()
    
    try:
        # Connect to the server and wrap the connection in SSL
        connection = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=hostname)
        connection.connect((hostname, port))
        
        # Get the SSL certificate
        ssl_info = connection.getpeercert()
        
        # Check if the SSL/TLS version and cipher suite are considered weak
        cipher_suite = connection.cipher()
        if cipher_suite:
            cipher_name = cipher_suite[0]
            if 'RC4' in cipher_name or '3DES' in cipher_name:
                return f"Warning: Weak cipher suite detected: {cipher_name}"
            else:
                return f"SSL/TLS connection is secure with cipher suite: {cipher_name}"
        else:
            return "Unable to determine the cipher suite."
    except Exception as e:
        return f"SSL/TLS check failed: {e}"

# Test case
hostname = "www.google.com"
print(check_ssl_configuration(hostname))

Explanation:

  • The function uses the ssl and socket libraries to establish an SSL/TLS connection with the server and retrieve information about the SSL configuration.
  • It checks if the cipher suite contains weak algorithms like RC4 or 3DES, which are considered insecure.