Thanks to visit codestin.com
Credit goes to github.com

Skip to content

maycon/racing-bank

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

7 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿฆ Racing Bank - Educational Banking System

Version API Android License

โš ๏ธ WARNING

This application was developed for educational purposes only to demonstrate race condition vulnerabilities in concurrent systems. It has intentional security vulnerabilities and MUST NOT BE USED IN PRODUCTION.


๐Ÿ“‹ About

Racing Bank is a complete banking system consisting of:

  1. Backend API - FastAPI with intentional race condition vulnerabilities
  2. Android App - Mobile application with retro cyberpunk visual design

This project was created as an educational demonstration for TRECO and TREM, showing in practice how race conditions can affect financial systems.


๐ŸŽฏ Features

Complete Banking System

  • โœ… Two-factor authentication (TOTP)
  • โœ… Deposits and withdrawals
  • โœ… Account-to-account transfers
  • โœ… Investment fund operations
  • โœ… Transaction statements
  • โœ… Interactive dashboard

Educational Vulnerabilities

  • โŒ Double spending in transfers
  • โŒ Lost updates in deposits
  • โŒ Investment inconsistencies
  • โŒ Phantom reads in queries
  • โŒ Race conditions in all operations

๐Ÿ—๏ธ Project Structure

racing-bank/
โ”œโ”€โ”€ api/                          # FastAPI Backend
โ”‚   โ”œโ”€โ”€ routes/                   # API endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ auth_routes.py       # Authentication & onboarding
โ”‚   โ”‚   โ”œโ”€โ”€ account_routes.py    # Deposits & withdrawals
โ”‚   โ”‚   โ”œโ”€โ”€ transfer_routes.py   # Transfers
โ”‚   โ”‚   โ””โ”€โ”€ fund_routes.py       # Investments
โ”‚   โ”œโ”€โ”€ config.py                 # Configuration
โ”‚   โ”œโ”€โ”€ database.py               # SQLAlchemy models
โ”‚   โ”œโ”€โ”€ auth.py                   # JWT & TOTP
โ”‚   โ”œโ”€โ”€ schemas.py                # Pydantic schemas
โ”‚   โ”œโ”€โ”€ main.py                   # Entry point
โ”‚   โ”œโ”€โ”€ requirements.txt          # Python dependencies
โ”‚   โ”œโ”€โ”€ Dockerfile                # API container
โ”‚   โ”œโ”€โ”€ compose.yaml              # Docker Compose
โ”‚   โ””โ”€โ”€ README.md                 # API documentation
โ”‚
โ”œโ”€โ”€ app/                          # Android Application
โ”‚   โ”œโ”€โ”€ src/main/
โ”‚   โ”‚   โ”œโ”€โ”€ java/com/hacknroll/bank/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ data/            # Repository & API client
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ ui/              # Activities & Fragments
โ”‚   โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ auth/        # Login & Registration
โ”‚   โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ main/        # Dashboard & Operations
โ”‚   โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ splash/      # Splash screen
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ utils/           # Utilities
โ”‚   โ”‚   โ””โ”€โ”€ res/                 # Resources (layouts, themes)
โ”‚   โ”œโ”€โ”€ build.gradle.kts         # Build configuration
โ”‚   โ””โ”€โ”€ README.md                # App documentation
โ”‚
โ”œโ”€โ”€ docs/                         # Additional documentation
โ”‚   โ”œโ”€โ”€ RACE_CONDITIONS.md       # Detailed vulnerability examples
โ”‚   โ”œโ”€โ”€ API_GUIDE.md             # Complete API reference
โ”‚   โ”œโ”€โ”€ ANDROID_SETUP.md         # Android development setup
โ”‚   โ””โ”€โ”€ SECURITY.md              # Security considerations
โ”‚
โ”œโ”€โ”€ scripts/                      # Utility scripts
โ”‚   โ”œโ”€โ”€ setup.sh                 # Quick setup script
โ”‚   โ”œโ”€โ”€ demo.sh                  # Demo data loader
โ”‚   โ””โ”€โ”€ test_race_conditions.py  # Race condition tests
โ”‚
โ”œโ”€โ”€ .gitignore                    # Git ignore rules
โ”œโ”€โ”€ LICENSE                       # License file
โ””โ”€โ”€ README.md                     # This file

๐Ÿš€ Quick Start

Option 1: Docker (Recommended)

# 1. Clone the repository
git clone https://github.com/maycon/racing-bank.git
cd racing-bank

# 2. Start the API with Docker Compose
cd api
docker-compose up -d

# 3. View logs to get TOTP secrets for demo users
docker-compose logs api

# API will be available at http://localhost:8000
# Interactive docs at http://localhost:8000/docs

Option 2: Manual Setup

API Setup

# Navigate to API directory
cd api

# Install Python dependencies
pip install -r requirements.txt

# Start MariaDB (or use Docker)
docker run -d -p 3306:3306 \
  -e MYSQL_ROOT_PASSWORD=root \
  -e MYSQL_DATABASE=bankao \
  mariadb:11

# Run the API
python main.py

Android App Setup

# Open Android Studio
# File โ†’ Open โ†’ Select racing-bank/app directory

# Configure API endpoint (if not using emulator)
# Edit app/src/main/java/.../data/api/RetrofitClient.kt
# Change BASE_URL to your machine's IP

# Run the app on emulator or device

๐Ÿ“ฑ Using the System

1. Start the API

cd api
docker-compose up -d

2. Get Demo User Credentials

docker-compose logs api | grep "TOTP secret"

Demo users:

  • alice / alice123 (Balance: $1,000)
  • bob / bob123 (Balance: $500)

3. Setup 2FA

  • Use Google Authenticator or similar app
  • Scan QR code or enter TOTP secret manually

4. Login via Android App

  • Open the app
  • Enter username and password
  • Enter 6-digit TOTP code
  • Start banking!

5. Try API Directly

# Login
curl -X POST http://localhost:8000/login \
  -H "Content-Type: application/json" \
  -d '{"username": "alice", "password": "alice123"}'

# 2FA (use TOTP code from authenticator)
curl -X POST http://localhost:8000/2fa \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <temp_token>" \
  -d '{"token": "123456"}'

# Check balance
curl -X GET http://localhost:8000/balance \
  -H "Authorization: Bearer <access_token>"

๐Ÿ› Race Condition Demonstrations

Example 1: Double Spending Attack

# Alice has $100, attempts to transfer $80 twice simultaneously
# Both checks pass ($100 >= $80) โœ“
# Both transfers execute
# Result: Alice has -$60 (overdraft!)

# Terminal 1
curl -X POST http://localhost:8000/transfer \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"to_username": "bob", "amount": 80}' &

# Terminal 2 (run immediately)
curl -X POST http://localhost:8000/transfer \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"to_username": "bob", "amount": 80}' &

Example 2: Lost Updates

# Using Python to trigger concurrent deposits
import concurrent.futures
import requests

def deposit(amount):
    return requests.post(
        "http://localhost:8000/deposit",
        headers={"Authorization": f"Bearer {TOKEN}"},
        json={"amount": amount}
    )

# Start balance: $100
# Execute 10 concurrent deposits of $10 each
# Expected: $200
# Actual: ~$110-$150 (lost updates!)

with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
    futures = [executor.submit(deposit, 10) for _ in range(10)]
    results = [f.result() for f in futures]

Example 3: Investment Fund Inconsistency

# Multiple users subscribing to fund simultaneously
# Can result in incorrect share price calculations

for i in {1..5}; do
  curl -X POST http://localhost:8000/subscribe \
    -H "Authorization: Bearer $TOKEN_USER_$i" \
    -d '{"amount": 1000}' &
done

See docs/RACE_CONDITIONS.md for detailed explanations and more examples.


๐Ÿ› ๏ธ Technology Stack

Backend (API)

  • Framework: FastAPI 0.115.0
  • Server: Uvicorn (ASGI)
  • Database: MariaDB 11
  • ORM: SQLAlchemy 2.0
  • Auth: PyJWT + PyOTP (TOTP)
  • Validation: Pydantic v2

Frontend (Android)

  • Language: Kotlin 1.9.0
  • Min SDK: API 24 (Android 7.0)
  • Target SDK: API 34 (Android 14)
  • Architecture: MVVM + Repository Pattern
  • Networking: Retrofit 2 + OkHttp 3
  • UI: Material Design 3
  • Security: EncryptedSharedPreferences

๐Ÿ“š Documentation


๐Ÿ”’ Security Notes

โš ๏ธ Intentional Vulnerabilities

This project demonstrates the following security issues:

  1. No database transaction isolation - All operations are vulnerable
  2. No pessimistic/optimistic locking - Concurrent modifications not prevented
  3. No idempotency checks - Operations can be duplicated
  4. No rate limiting - Enables automated attacks
  5. Weak password hashing - SHA-256 instead of bcrypt/argon2
  6. TOTP secrets exposed - Printed in logs for demo purposes

โœ… For Production Use

To make this production-ready, you must:

  1. Implement proper database transactions

    with session.begin():
        account = session.query(Account).with_for_update().filter_by(id=user_id).one()
        account.balance -= amount
        session.commit()
  2. Use optimistic locking with version numbers

    class Account(Base):
        version = Column(Integer, default=0)
  3. Implement idempotency keys

    @app.post("/transfer")
    async def transfer(
        request: TransferRequest,
        idempotency_key: str = Header(...)
    ):
        # Check if operation already executed
  4. Add rate limiting

    from slowapi import Limiter
    limiter = Limiter(key_func=get_remote_address)
    
    @app.post("/transfer")
    @limiter.limit("10/minute")
    async def transfer(...):
  5. Use strong password hashing

    from passlib.context import CryptContext
    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  6. Never expose secrets in responses or logs

  7. Always use HTTPS in production

  8. Implement proper error handling without leaking information


๐Ÿงช Testing

Unit Tests (Demonstrating Race Conditions)

cd scripts
python test_race_conditions.py

Load Testing

# Install Apache Bench
sudo apt-get install apache2-utils

# Test concurrent deposits
ab -n 1000 -c 50 -m POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -p deposit.json \
  http://localhost:8000/deposit

Android UI Tests

cd app
./gradlew connectedAndroidTest

๐Ÿค Contributing

This is an educational project. Contributions are welcome for:

  1. Additional race condition examples
  2. Better documentation
  3. More test scenarios
  4. UI/UX improvements in the Android app

Important: Keep the vulnerabilities intact - that's the educational purpose!

How to Contribute

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-example)
  3. Commit your changes (git commit -m 'Add race condition example')
  4. Push to the branch (git push origin feature/amazing-example)
  5. Open a Pull Request

๐Ÿ“– Learning Resources

Race Conditions & Concurrency

FastAPI & SQLAlchemy

Android Development


๐Ÿ‘ฅ Authors

  • Maycon Vitali - Initial work - GitHub

๐Ÿ™ Acknowledgments

  • Created as demonstration for TREM
  • Inspired by real-world banking vulnerabilities
  • Thanks to the open-source community

๐Ÿ“„ License

This project is for educational purposes only.

DO NOT USE IN PRODUCTION - The code intentionally contains security vulnerabilities to demonstrate race conditions in concurrent systems.


โšก Support

For questions about race conditions or concurrency issues:

  • Open an issue on GitHub
  • Check the documentation in docs/
  • Review the code comments explaining each vulnerability

๐ŸŽฎ Hack N Roll Racing Bank - Banking with intentional bugs for educational purposes! ๐Ÿ’ฐ๐Ÿ›

About

๐Ÿฆ Hack N Roll Racing Bank

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published