Introduction
In this tutorial, we'll explore how to protect your AI applications from security vulnerabilities similar to the one reported with Google's Gemini. We'll learn how to set up a basic security testing framework using Python that can help identify weak passwords and credential reuse issues in your systems. This is crucial because the recent Google incident shows that even powerful AI systems can be compromised through simple security misconfigurations.
By the end of this tutorial, you'll have a working Python script that simulates a security audit to detect weak passwords and credential reuse in your applications.
Prerequisites
Before starting this tutorial, you'll need:
- A computer with Python 3.6 or higher installed
- Basic understanding of Python programming concepts
- Access to a terminal or command prompt
- Internet connection for downloading dependencies
Step-by-Step Instructions
Step 1: Set Up Your Python Environment
First, we need to create a dedicated folder for our security testing project and set up a virtual environment to keep our dependencies isolated.
mkdir ai_security_test
cd ai_security_test
python3 -m venv security_env
source security_env/bin/activate # On Windows: security_env\Scripts\activate
Why we do this: Using a virtual environment ensures that our project dependencies don't interfere with other Python projects on your system, making it easier to manage and maintain.
Step 2: Install Required Libraries
We'll need a few Python libraries to help us with our security testing. Install them using pip:
pip install requests
Why we do this: The requests library will help us simulate network requests to test how our applications handle authentication.
Step 3: Create the Security Testing Script
Now, let's create our main security testing script. Create a file named security_audit.py:
import requests
import hashlib
import time
from datetime import datetime
class SecurityAudit:
def __init__(self):
self.test_users = [
{'username': 'admin', 'password': 'admin123'},
{'username': 'user1', 'password': 'password'},
{'username': 'test', 'password': 'test123'},
{'username': 'admin', 'password': 'admin123'} # Duplicate credential
]
self.common_passwords = ['password', '123456', 'admin123', 'password123', 'qwerty']
self.weak_passwords = []
self.credential_reuse = []
def check_password_strength(self, password):
"""
Check if password is in common list or too weak
"""
if password in self.common_passwords:
return False
if len(password) < 8:
return False
if not any(c.isupper() for c in password):
return False
if not any(c.islower() for c in password):
return False
if not any(c.isdigit() for c in password):
return False
return True
def test_credential_reuse(self):
"""
Check for duplicate credentials
"""
seen_credentials = set()
for user in self.test_users:
credential_key = (user['username'], user['password'])
if credential_key in seen_credentials:
self.credential_reuse.append(user)
else:
seen_credentials.add(credential_key)
def run_audit(self):
"""
Run complete security audit
"""
print('Starting Security Audit...')
print(f'Date: {datetime.now()}\n')
# Check password strength
print('Checking password strength...')
for user in self.test_users:
if not self.check_password_strength(user['password']):
self.weak_passwords.append(user)
print(f'\tWeak password found: {user["username"]} - {user["password"]}')
# Check for credential reuse
print('\nChecking for credential reuse...')
self.test_credential_reuse()
if self.credential_reuse:
print('\tCredential reuse detected:')
for user in self.credential_reuse:
print(f'\t\t{user["username"]} - {user["password"]}')
else:
print('\tNo credential reuse detected.')
print('\nAudit complete!')
# Run the audit
if __name__ == '__main__':
audit = SecurityAudit()
audit.run_audit()
Why we do this: This script simulates how a security audit might work by checking for weak passwords and credential reuse, which were key issues in the Google Gemini incident.
Step 4: Run the Security Audit
Now, run your security audit script:
python security_audit.py
Why we do this: Running the script will show you how it detects weak passwords and credential reuse, similar to what security researchers would find in real systems.
Step 5: Simulate Real-World Network Testing
Let's enhance our script to simulate network-based authentication testing:
import requests
import time
class NetworkSecurityAudit(SecurityAudit):
def __init__(self):
super().__init__()
self.test_endpoints = [
'http://example.com/api/login',
'http://api.example.com/auth',
'http://secure.example.com/login'
]
def test_authentication_endpoint(self, endpoint, username, password):
"""
Simulate authentication request to an endpoint
"""
try:
# In a real scenario, this would be a real HTTP request
print(f'Testing endpoint: {endpoint}')
print(f'\tUsername: {username}')
print(f'\tPassword: {password}')
# Simulate a delay to mimic network request
time.sleep(0.1)
# In a real test, you'd check the HTTP response
# For now, we'll just simulate a successful login
print('\t\tAuthentication attempt completed')
except Exception as e:
print(f'\t\tError testing endpoint: {e}')
def run_network_audit(self):
"""
Run network-based security audit
"""
print('\nStarting Network Security Audit...')
for user in self.test_users:
for endpoint in self.test_endpoints:
self.test_authentication_endpoint(endpoint, user['username'], user['password'])
print('\nNetwork audit complete!')
# Run the enhanced audit
if __name__ == '__main__':
audit = NetworkSecurityAudit()
audit.run_audit()
audit.run_network_audit()
Why we do this: This extension shows how security audits might test actual network endpoints to verify how your applications handle authentication requests.
Step 6: Implement Basic Password Hashing Protection
Let's add password hashing to our script to demonstrate how to properly store passwords:
import hashlib
import secrets
# Add this method to your SecurityAudit class
def hash_password(self, password):
"""
Hash a password using SHA-256 with salt
"""
salt = secrets.token_hex(16)
salted_password = password + salt
hashed = hashlib.sha256(salted_password.encode()).hexdigest()
return hashed, salt
def verify_password(self, password, salt, stored_hash):
"""
Verify a password against its hash
"""
salted_password = password + salt
hashed = hashlib.sha256(salted_password.encode()).hexdigest()
return hashed == stored_hash
# Test the hashing functionality
if __name__ == '__main__':
audit = SecurityAudit()
# Test hashing
password = 'my_secure_password'
hashed, salt = audit.hash_password(password)
print(f'Original password: {password}')
print(f'Hashed password: {hashed}')
print(f'Salt: {salt}')
# Test verification
is_valid = audit.verify_password(password, salt, hashed)
print(f'Password verification: {is_valid}')
Why we do this: Password hashing with salt is a fundamental security practice that protects against password breaches, even if your database is compromised.
Summary
In this tutorial, we've learned how to create a basic security testing framework that can help identify weak passwords and credential reuse issues in AI applications. We've covered:
- Setting up a Python environment for security testing
- Creating scripts to detect weak passwords
- Identifying credential reuse patterns
- Simulating network authentication testing
- Implementing password hashing with salt
These techniques are essential for protecting AI systems from vulnerabilities like those demonstrated in the Google Gemini incident. Remember that security is an ongoing process, and regular audits should be part of your development workflow.
While this tutorial provides a basic framework, real-world security testing involves much more sophisticated tools and methodologies. Always consult with security professionals when implementing security measures for production systems.