Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions MohamadMahdiReisi/Problem1_PostgreSQL/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM postgres:latest

ENV POSTGRES_USER=amir
ENV POSTGRES_PASSWORD=barari
ENV POSTGRES_DB=mydatabase
ENV POSTGRES_PORT=5432

RUN mkdir -p /docker-entrypoint-initdb.d

EXPOSE ${POSTGRES_PORT}

HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
CMD pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}

VOLUME /var/lib/postgresql/data
163 changes: 163 additions & 0 deletions MohamadMahdiReisi/Problem1_PostgreSQL/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,164 @@

# PostgreSQL Docker Deployment with Persistent Storage

![PostgreSQL Logo](https://www.postgresql.org/media/img/about/press/elephant.png)

## Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Quick Start](#quick-start)
- [Detailed Usage](#detailed-usage)
- [Data Persistence Verification](#data-persistence-verification)
- [Maintenance](#maintenance)
- [Troubleshooting](#troubleshooting)
- [Security Considerations](#security-considerations)
- [Contributing](#contributing)
- [License](#license)

## Overview

This project provides a complete solution for deploying PostgreSQL in Docker with persistent storage, designed specifically for:
- Development environments
- Learning database concepts
- Capture The Flag (CTF) challenges
- Application prototyping

## Features

✔ **Persistent Data Storage** - Uses Docker volumes to maintain data between container restarts
✔ **Pre-configured Environment** - Ready-to-use database with user credentials
✔ **Simple Operations** - Includes sample SQL commands for basic CRUD operations
✔ **Verification Scripts** - Commands to validate data persistence
✔ **Production-ready Foundation** - Can be extended for more complex deployments

## Quick Start

### 1. Deploy the Container
```bash
docker run -d \
--name postgres_ctf \
-e POSTGRES_USER=ctf_user \
-e POSTGRES_PASSWORD=ctf_password \
-e POSTGRES_DB=ctf_db \
-p 5432:5432 \
-v postgres_data:/var/lib/postgresql/data \
postgres:latest
```

### 2. Connect and Test
```bash
docker exec -it postgres_ctf psql -U ctf_user -d ctf_db -c "SELECT version();"
```

## Detailed Usage

### Database Initialization
The container automatically:
- Creates the specified user (`ctf_user`)
- Creates the default database (`ctf_db`)
- Sets up the persistent volume

### Common Operations

**Create Table:**
```sql
CREATE TABLE challenges (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
points INTEGER NOT NULL,
category VARCHAR(50),
is_active BOOLEAN DEFAULT true
);
```

**Insert Data:**
```sql
INSERT INTO challenges (name, points, category) VALUES
('SQL Injection', 100, 'Web'),
('Buffer Overflow', 200, 'Binary'),
('Cryptanalysis', 150, 'Crypto');
```

**Query Data:**
```sql
-- Basic query
SELECT * FROM challenges;

-- Filtered query
SELECT name, points FROM challenges WHERE points > 120;

-- Aggregation
SELECT category, AVG(points) as avg_points FROM challenges GROUP BY category;
```

## Data Persistence Verification

1. **Stop and remove the container**
```bash
docker stop postgres_ctf
docker rm postgres_ctf
```

2. **Redeploy with same volume**
```bash
docker run -d \
--name postgres_ctf_new \
-v postgres_data:/var/lib/postgresql/data \
-p 5432:5432 \
postgres:latest
```

3. **Verify data integrity**
```bash
docker exec -it postgres_ctf_new psql -U ctf_user -d ctf_db -c "SELECT * FROM challenges;"
```

## Maintenance

### Backup Database
```bash
docker exec postgres_ctf pg_dump -U ctf_user -d ctf_db > ctf_backup.sql
```

### Restore Database
```bash
cat ctf_backup.sql | docker exec -i postgres_ctf psql -U ctf_user -d ctf_db
```

### Monitor Performance
```bash
docker exec -it postgres_ctf psql -U ctf_user -d ctf_db -c "SELECT * FROM pg_stat_activity;"
```

## Troubleshooting

| Issue | Solution |
|-------|----------|
| Connection refused | Check if container is running: `docker ps` |
| Authentication failed | Verify credentials in environment variables |
| Volume not persisting | Confirm volume mount: `docker inspect postgres_ctf` |
| Port conflicts | Change host port mapping (e.g., `-p 5433:5432`) |

## Security Considerations

For production environments, we recommend:
1. Using complex passwords
2. Enabling SSL connections
3. Implementing network isolation
4. Regular backups
5. Monitoring access logs

## Contributing

We welcome contributions! Please:
1. Fork the repository
2. Create a feature branch
3. Submit a pull request

## License

MIT License - See [LICENSE](LICENSE) for details.

---

**Pro Tip**: For advanced configurations, check out the [official PostgreSQL Docker image documentation](https://hub.docker.com/_/postgres).
3 changes: 3 additions & 0 deletions MohamadMahdiReisi/Problem2_Redis/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FROM redis

EXPOSE 6379
116 changes: 116 additions & 0 deletions MohamadMahdiReisi/Problem2_Redis/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,117 @@
# Redis Server Setup with Docker and Python Integration

## Table of Contents
- [Overview](#overview)
- [Prerequisites](#prerequisites)
- [Redis Server Deployment](#redis-server-deployment)
- [Python Programs for Redis Operations](#python-programs-for-redis-operations)
- [Redis Monitoring](#redis-monitoring)
- [Demonstration](#demonstration)
- [Cleanup](#cleanup)
- [Troubleshooting](#troubleshooting)
- [License](#license)

## Overview

This solution demonstrates how to:
1. Deploy a Redis server in Docker
2. Implement Python programs for Redis operations
3. Monitor Redis activity using RedisInsight
4. Document the inter-process communication

## Prerequisites

- Docker installed
- Python 3.6+ with `redis-py` package (`pip install redis`)
- (Optional) RedisInsight for monitoring

## Redis Server Deployment

### 1. Launch Redis Container
```bash
docker run -d --name redis_server -p 6379:6379 redis:latest
```

### 2. Verify Connection
```bash
docker exec -it redis_server redis-cli ping
# Should respond with "PONG"
```

## Python Programs for Redis Operations

### Program 1: Redis Writer (`redis_writer.py`)
```python
import redis
import time

r = redis.Redis(host='localhost', port=6379, db=0)

# Set key-value pairs
r.set('server:name', 'Redis CTF Server')
r.set('server:uptime', '24 hours')
r.hset('user:1001', mapping={'name': 'Alice', 'score': '850'})

# Publish messages
for i in range(3):
r.publish('ctf-channel', f'Message {i+1} from writer')
time.sleep(1)
```

### Program 2: Redis Reader (`redis_reader.py`)
```python
import redis

r = redis.Redis(host='localhost', port=6379, db=0)

# Retrieve key-value pairs
print("Key-Value Pairs:")
print(f"Server Name: {r.get('server:name').decode('utf-8')}")
print(f"Server Uptime: {r.get('server:uptime').decode('utf-8')}")
print(f"User Data: {r.hgetall('user:1001')}")

# Subscribe to channel
pubsub = r.pubsub()
pubsub.subscribe('ctf-channel')

print("\nWaiting for messages...")
for message in pubsub.listen():
if message['type'] == 'message':
print(f"Received: {message['data'].decode('utf-8')}")
```

### Running the Programs
1. First terminal:
```bash
python3 redis_writer.py
```

2. Second terminal:
```bash
python3 redis_reader.py
```

### Screenshot Checklist
**desierd output**
<img src="./../../shots/q2/Screenshot from 2025-05-12 01-45-19.png" width="400" alt="">
<img src="./../../shots/q2/Screenshot from 2025-05-12 01-45-47.png" width="400" alt="">

## Demonstration

### Video Script (30 seconds)
1. Show Redis container running (`docker ps`)
2. Execute `redis_writer.py` (terminal)
3. Execute `redis_reader.py` (terminal)
4. Show RedisInsight with real-time data
5. Stop container (`docker stop redis_server`)

## Cleanup

```bash
docker stop redis_server
docker rm redis_server
```

## License

MIT License - See [LICENSE](LICENSE) for details.
16 changes: 16 additions & 0 deletions MohamadMahdiReisi/Problem2_Redis/redis_reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import redis

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

keys = ["amir", "ali", "reza"]
for key in keys:
value = r.get(key)
print(f"Key: {key}, Value: {value}")

pubsub = r.pubsub()
pubsub.subscribe("task_updates")
print("Subscribed to channel 'task_updates'. Waiting for messages...")

for message in pubsub.listen():
if message["type"] == "message":
print(f"Received: {message['data']}")
17 changes: 17 additions & 0 deletions MohamadMahdiReisi/Problem2_Redis/redis_writer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import redis
import time

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

r.set("amir", "healthy")
r.set("ali", "sick")
r.set("reza", "dead")

print("Set key-value pairs")

channel = "task_updates"
for i in range(3):
message = f"Task update {i+1}: Processing..."
r.publish(channel, message)
print(f"Published: {message}")
time.sleep(1)
5 changes: 5 additions & 0 deletions MohamadMahdiReisi/Problem3_Celery/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# .env
REDIS_URL=redis://localhost:6379/0
DEFAULT_IMAGE=ctg_postgre
DB_PASSWORD=barari
MAX_CONTAINERS=10
Loading