🎯 SIM Management Overview
RFS-Portable-BTS provides comprehensive SIM card management capabilities for IoT security testing, user authentication, and GSM network operations. This guide covers database setup, user management, and security configurations.
✅ Key Features
Complete SIM database management, user authentication, security configurations, and automated provisioning for IoT security testing scenarios.
📊 SIM Database Structure
🗄️ Database Schema
- IMSI (International Mobile Subscriber Identity)
- MSISDN (Mobile Station International ISDN Number)
- Ki (Authentication Key)
- OPc (Operator Variant Algorithm Configuration)
- User profile and permissions
- Service configurations
🔐 Security Fields
- Authentication algorithms (A3/A8)
- Ciphering keys (Kc)
- Integrity protection keys
- Access control lists
- Service restrictions
- Location area restrictions
📋 User Management
- User profiles and roles
- Service permissions
- Call restrictions
- SMS permissions
- Data service settings
- Billing and usage tracking
🔧 Database Setup
SQLite Database Creation
-- Create SIM database
CREATE TABLE sim_cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imsi VARCHAR(15) UNIQUE NOT NULL,
msisdn VARCHAR(15) UNIQUE,
ki VARCHAR(32) NOT NULL,
opc VARCHAR(32),
algorithm VARCHAR(10) DEFAULT 'A3A8',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(20) DEFAULT 'active'
);
-- User profiles table
CREATE TABLE user_profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imsi VARCHAR(15) REFERENCES sim_cards(imsi),
username VARCHAR(50),
role VARCHAR(20) DEFAULT 'user',
permissions TEXT,
restrictions TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Service configurations
CREATE TABLE service_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imsi VARCHAR(15) REFERENCES sim_cards(imsi),
service_type VARCHAR(20),
enabled BOOLEAN DEFAULT TRUE,
parameters TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Call logs
CREATE TABLE call_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imsi VARCHAR(15),
msisdn VARCHAR(15),
call_type VARCHAR(10),
duration INTEGER,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Database Initialization Script
#!/bin/bash
# Create /usr/local/bin/init-sim-db.sh
DB_PATH="/opt/yatebts/sim_database.db"
# Create database directory
sudo mkdir -p /opt/yatebts
sudo chown yatebts:yatebts /opt/yatebts
# Initialize database
sqlite3 $DB_PATH << 'EOF'
-- Create tables
CREATE TABLE sim_cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imsi VARCHAR(15) UNIQUE NOT NULL,
msisdn VARCHAR(15) UNIQUE,
ki VARCHAR(32) NOT NULL,
opc VARCHAR(32),
algorithm VARCHAR(10) DEFAULT 'A3A8',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(20) DEFAULT 'active'
);
CREATE TABLE user_profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imsi VARCHAR(15) REFERENCES sim_cards(imsi),
username VARCHAR(50),
role VARCHAR(20) DEFAULT 'user',
permissions TEXT,
restrictions TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE service_configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
imsi VARCHAR(15) REFERENCES sim_cards(imsi),
service_type VARCHAR(20),
enabled BOOLEAN DEFAULT TRUE,
parameters TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Insert default test SIM
INSERT INTO sim_cards (imsi, msisdn, ki, algorithm) VALUES
('001010000000001', '+1234567890', '00112233445566778899AABBCCDDEEFF', 'A3A8');
INSERT INTO user_profiles (imsi, username, role) VALUES
('001010000000001', 'test_user', 'admin');
EOF
echo "SIM database initialized successfully"
echo "Database location: $DB_PATH"
👥 User Management
👤 User Roles
- Admin: Full system access
- Operator: User management
- User: Basic services
- Test: Testing only
- Guest: Limited access
🔐 Permissions
- Voice call permissions
- SMS send/receive
- Data service access
- International calling
- Roaming permissions
- Emergency services
🚫 Restrictions
- Call time limits
- Data usage limits
- Geographic restrictions
- Time-based restrictions
- Service blacklists
- Cost controls
User Management Script
#!/usr/bin/env python3
# Create /usr/local/bin/sim-manager.py
import sqlite3
import hashlib
import secrets
import sys
class SIMManager:
def __init__(self, db_path="/opt/yatebts/sim_database.db"):
self.db_path = db_path
self.conn = sqlite3.connect(db_path)
self.conn.row_factory = sqlite3.Row
def add_sim(self, imsi, msisdn=None, ki=None, role='user'):
"""Add a new SIM card to the database"""
if not ki:
ki = secrets.token_hex(16).upper()
try:
cursor = self.conn.cursor()
cursor.execute("""
INSERT INTO sim_cards (imsi, msisdn, ki, algorithm)
VALUES (?, ?, ?, 'A3A8')
""", (imsi, msisdn, ki))
cursor.execute("""
INSERT INTO user_profiles (imsi, username, role)
VALUES (?, ?, ?)
""", (imsi, f"user_{imsi[-6:]}", role))
self.conn.commit()
print(f"SIM card {imsi} added successfully")
return True
except sqlite3.IntegrityError as e:
print(f"Error: SIM card {imsi} already exists")
return False
def list_sims(self):
"""List all SIM cards in the database"""
cursor = self.conn.cursor()
cursor.execute("""
SELECT s.imsi, s.msisdn, s.status, u.role, u.username
FROM sim_cards s
LEFT JOIN user_profiles u ON s.imsi = u.imsi
ORDER BY s.created_at DESC
""")
sims = cursor.fetchall()
print(f"{'IMSI':<15} {'MSISDN':<15} {'Status':<10} {'Role':<10} {'Username'}")
print("-" * 70)
for sim in sims:
print(f"{sim['imsi']:<15} {sim['msisdn'] or 'N/A':<15} {sim['status']:<10} {sim['role']:<10} {sim['username']}")
def update_user_role(self, imsi, new_role):
"""Update user role for a SIM card"""
cursor = self.conn.cursor()
cursor.execute("""
UPDATE user_profiles
SET role = ?
WHERE imsi = ?
""", (new_role, imsi))
if cursor.rowcount > 0:
self.conn.commit()
print(f"Role updated to {new_role} for SIM {imsi}")
return True
else:
print(f"SIM {imsi} not found")
return False
def delete_sim(self, imsi):
"""Delete a SIM card from the database"""
cursor = self.conn.cursor()
cursor.execute("DELETE FROM sim_cards WHERE imsi = ?", (imsi,))
if cursor.rowcount > 0:
self.conn.commit()
print(f"SIM card {imsi} deleted successfully")
return True
else:
print(f"SIM {imsi} not found")
return False
if __name__ == "__main__":
manager = SIMManager()
if len(sys.argv) < 2:
print("Usage: sim-manager.py [add|list|update|delete] [args...]")
sys.exit(1)
command = sys.argv[1]
if command == "add":
if len(sys.argv) < 3:
print("Usage: sim-manager.py add [msisdn] [role]")
sys.exit(1)
imsi = sys.argv[2]
msisdn = sys.argv[3] if len(sys.argv) > 3 else None
role = sys.argv[4] if len(sys.argv) > 4 else 'user'
manager.add_sim(imsi, msisdn, None, role)
elif command == "list":
manager.list_sims()
elif command == "update":
if len(sys.argv) < 4:
print("Usage: sim-manager.py update ")
sys.exit(1)
imsi = sys.argv[2]
new_role = sys.argv[3]
manager.update_user_role(imsi, new_role)
elif command == "delete":
if len(sys.argv) < 3:
print("Usage: sim-manager.py delete ")
sys.exit(1)
imsi = sys.argv[2]
manager.delete_sim(imsi)
else:
print("Unknown command:", command)
🔐 Security Configuration
🛡️ Authentication
- A3/A8 authentication algorithms
- Ki key management
- OPc operator variant
- Challenge-response protocols
- Session key generation
- Replay attack prevention
🔒 Encryption
- A5/1, A5/2, A5/3 ciphering
- Kc ciphering key management
- Voice encryption
- Data encryption
- Signaling protection
- Key rotation policies
🚨 Access Control
- IMSI-based access control
- Location area restrictions
- Time-based access
- Service restrictions
- Blacklist management
- Whitelist management
Security Configuration
# Add to yatebts.conf [authentication] # Authentication settings algorithm=A3A8 ki_length=16 opc_length=16 challenge_length=16 # Security policies max_auth_failures=3 auth_timeout=30 session_timeout=3600 [encryption] # Ciphering settings default_cipher=A5/3 fallback_cipher=A5/1 key_length=64 # Encryption policies force_encryption=yes encrypt_voice=yes encrypt_data=yes encrypt_signaling=yes [access_control] # Access control lists enable_imsi_filter=yes enable_location_filter=yes enable_time_filter=yes # Blacklist/Whitelist blacklist_file=/opt/yatebts/blacklist.txt whitelist_file=/opt/yatebts/whitelist.txt
📊 Service Configuration
| Service | Description | Default | Configuration |
|---|---|---|---|
| Voice Calls | GSM voice communication | Enabled | Call restrictions, time limits |
| SMS | Short Message Service | Enabled | Send/receive permissions |
| Data Services | GPRS/EDGE data | Enabled | Data limits, APN settings |
| Emergency Calls | Emergency services | Always enabled | Cannot be disabled |
| International | International calling | Disabled | Country restrictions |
| Roaming | Network roaming | Disabled | Partner network access |
Service Configuration Script
#!/bin/bash
# Create /usr/local/bin/configure-services.sh
DB_PATH="/opt/yatebts/sim_database.db"
configure_services() {
local imsi=$1
local service_type=$2
local enabled=$3
local parameters=$4
sqlite3 $DB_PATH << EOF
INSERT OR REPLACE INTO service_configs (imsi, service_type, enabled, parameters)
VALUES ('$imsi', '$service_type', $enabled, '$parameters');
EOF
echo "Service $service_type configured for SIM $imsi"
}
# Example: Configure services for test SIM
configure_services "001010000000001" "voice" "1" "max_duration=300"
configure_services "001010000000001" "sms" "1" "daily_limit=100"
configure_services "001010000000001" "data" "1" "daily_limit=100MB"
configure_services "001010000000001" "international" "0" ""
echo "Service configuration completed"
📈 Monitoring and Logging
📊 Usage Monitoring
- Call duration tracking
- Data usage monitoring
- SMS count tracking
- Connection time logging
- Location tracking
- Service usage statistics
📝 Audit Logging
- Authentication attempts
- Service access logs
- Configuration changes
- Security events
- Error logging
- Performance metrics
Monitoring Script
#!/bin/bash
# Create /usr/local/bin/sim-monitor.sh
DB_PATH="/opt/yatebts/sim_database.db"
LOG_FILE="/var/log/sim-monitor.log"
monitor_usage() {
echo "$(date): Starting SIM usage monitoring" >> $LOG_FILE
# Get active connections
active_connections=$(sqlite3 $DB_PATH "SELECT COUNT(*) FROM sim_cards WHERE status='active'")
echo "$(date): Active SIM cards: $active_connections" >> $LOG_FILE
# Get recent call activity
recent_calls=$(sqlite3 $DB_PATH "SELECT COUNT(*) FROM call_logs WHERE timestamp > datetime('now', '-1 hour')")
echo "$(date): Calls in last hour: $recent_calls" >> $LOG_FILE
# Check for high usage
high_usage=$(sqlite3 $DB_PATH "SELECT imsi FROM call_logs WHERE duration > 1800 AND timestamp > datetime('now', '-1 hour')")
if [ ! -z "$high_usage" ]; then
echo "$(date): WARNING: High usage detected for SIM: $high_usage" >> $LOG_FILE
fi
}
# Run monitoring
monitor_usage
# Schedule regular monitoring
echo "*/5 * * * * /usr/local/bin/sim-monitor.sh" | crontab -
🔧 Troubleshooting
❌ Common Issues
- SIM not recognized
- Authentication failures
- Service access denied
- Database connection errors
- Permission issues
- Configuration errors
🔍 Diagnostic Commands
- Check database integrity
- Verify SIM configuration
- Test authentication
- Monitor system logs
- Check service status
- Validate permissions
Diagnostic Script
#!/bin/bash
# Create /usr/local/bin/sim-diagnostics.sh
DB_PATH="/opt/yatebts/sim_database.db"
echo "=== SIM Database Diagnostics ==="
# Check database file
if [ -f "$DB_PATH" ]; then
echo "✓ Database file exists: $DB_PATH"
echo "✓ Database size: $(du -h $DB_PATH | cut -f1)"
else
echo "✗ Database file not found: $DB_PATH"
exit 1
fi
# Check database integrity
echo "Checking database integrity..."
sqlite3 $DB_PATH "PRAGMA integrity_check;" | grep -q "ok" && echo "✓ Database integrity OK" || echo "✗ Database integrity issues"
# Check table structure
echo "Checking table structure..."
tables=$(sqlite3 $DB_PATH ".tables")
echo "✓ Tables found: $tables"
# Check SIM count
sim_count=$(sqlite3 $DB_PATH "SELECT COUNT(*) FROM sim_cards")
echo "✓ Total SIM cards: $sim_count"
# Check active SIMs
active_count=$(sqlite3 $DB_PATH "SELECT COUNT(*) FROM sim_cards WHERE status='active'")
echo "✓ Active SIM cards: $active_count"
# Check recent activity
recent_calls=$(sqlite3 $DB_PATH "SELECT COUNT(*) FROM call_logs WHERE timestamp > datetime('now', '-24 hours')")
echo "✓ Calls in last 24h: $recent_calls"
echo "=== Diagnostics Complete ==="
🚀 Configure SIM Management
Set up comprehensive SIM card management for your RFS-Portable-BTS
📖 Installation Guide 🔧 Troubleshooting 💬 Community Support