Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

GenZipher Hospital Management System

A comprehensive hospital management system focusing on web security with real-time attack demonstration capabilities.

🆕 Latest Features

Email Verification & Enhanced RBAC (Competition Edition)

  • Email Verification: All new users must verify their email with OTP codes sent via SendGrid
  • Strong Password Requirements: 12+ characters with uppercase, lowercase, numbers, and special characters
  • Default PATIENT Role: All registrations start as PATIENT (not clinician)
  • Admin-Controlled Promotions: Only admins can promote users to DOCTOR role
  • Password History: Prevents reuse of last 3 passwords
  • Role-Based Rate Limiting: Different API limits for PATIENT (100/min), DOCTOR (500/min), ADMIN (1000/min)

📖 Full documentation: See EMAIL-VERIFICATION-AND-RBAC.md

Project Overview

GenZipher is a Clinical Decision Trust Platform built to demonstrate advanced web security implementations in healthcare systems. The project includes both a functional hospital management system and an attack demonstration system that showcases 8 common security vulnerabilities and their defense mechanisms.

System Architecture

graph TD
    subgraph Client-Tier ["Client Tier (Frontend)"]
        HMS_UI["HMS Dashboard (Next.js :3000)"]
        Attack_UI["Attack Demo UI (Next.js :3001)"]
    end

    subgraph API-Tier ["API Tier (Backend)"]
        HMS_API["HMS Security API (NestJS :4000)"]
        Attack_Engine["Attack Simulator (NestJS :4001)"]
        
        subgraph Security-Modules ["HMS Core Security Layers"]
            Auth["Auth & MFA (Device Binding)"]
            Audit["Immutable Audit (Hash-chained)"]
            Verify["AI Safety (Prompt/Output)"]
            Policy["RBAC/ABAC Engine"]
            Monitor["Anomaly Detection"]
        end
        
        HMS_API --- Security-Modules
    end

    subgraph Data-Tier ["Persistence Tier"]
        DB[(PostgreSQL)]
        Cache[(Redis - Session/RateLimit)]
    end

    HMS_UI <-->|Authorized JWT| HMS_API
    Attack_UI <--> Attack_Engine
    Attack_Engine -.->|Exploit Simulation| HMS_API
    HMS_API <--> DB
    HMS_API <--> Cache
    
    style Security-Modules fill:#f0f7ff,stroke:#0056b3,stroke-width:2px
    style DB fill:#e6fffa,stroke:#2c7a7b
    style Cache fill:#e6fffa,stroke:#2c7a7b
    style HMS_API fill:#fff5f5,stroke:#c53030
Loading

Architectural Tiers

  1. Client Tier: Comprises the main Hospital Management System (HMS) and the Attack Demonstration Interface, both built using Next.js 14.
  2. API Tier: Handles business logic and security enforcement. The HMS Backend manages clinical data with high-security guards, while the Attack Engine simulates real-world exploits.
  3. Security Layer: A centralized set of modules in the HMS Backend responsible for auditing, behavioral analysis, and AI-driven safety checks.
  4. Data Tier: Uses PostgreSQL for encrypted clinical records and Redis for high-speed session management and rate-limiting counters.

Appliance Mapping

The following mapping describes the logical "appliances" that constitute the GenZipher ecosystem and their respective connectivity requirements.

graph LR
    subgraph External ["External Access"]
        User((User))
        DemoAdmin((Demo Admin))
    end

    subgraph App_Net ["Application Network"]
        direction TB
        GZ_Portal["GenZipher Secure Portal<br/>(HMS Frontend)"]
        GZ_Core["GenZipher Core Appliance<br/>(HMS Backend)"]
    end

    subgraph Lab_Net ["Security Lab Network"]
        AL_UI["Attack Lab UI<br/>(Simulator Frontend)"]
        AL_Eng["Attack Simulation Engine<br/>(Simulator Backend)"]
    end

    subgraph Data_Net ["Isolated Data Network"]
        Data_Vault["Clinical Data Vault<br/>(PostgreSQL)"]
        Secure_Cache["Secure Mesh Cache<br/>(Redis)"]
    end

    User -->|HTTPS :3000| GZ_Portal
    GZ_Portal -->|API :4000| GZ_Core
    DemoAdmin -->|HTTPS :3001| AL_UI
    AL_UI -->|API :4001| AL_Eng
    AL_Eng -.->|Attack Traffic| GZ_Core
    GZ_Core <-->|SQL :5432| Data_Vault
    GZ_Core <-->|RESP :6379| Secure_Cache
Loading

Logical Appliance Catalog

Appliance Name Software Component Port Role Security Control
GenZipher Secure Portal HMS Frontend (Next.js) 3000 User Interface & UX CSP, XSS Sanitization, Session Binding
GenZipher Core Engine HMS Backend (NestJS) 4000 Security & Logic API RBAC/ABAC, HMAC Audit, AI Safety
Attack Lab Dashboard Attack Demo Frontend 3001 Simulation Control Isolated Presentation Tier
Attack Simulation Engine Attack Demo Backend 4001 Exploit Execution Controlled Vulnerability Payload Generator
Clinical Data Vault PostgreSQL 5432 Primary Storage Field-Level AES Encryption
Secure Mesh Cache Redis 6379 State & Rate-Limiting Distributed Session Persistence
Management Console PgAdmin 5050 Database Administration Restricted SQL Access

Technology Stack

Backend

  • NestJS 11.x (Node.js framework)
  • TypeScript
  • PostgreSQL 18 (Native Windows installation)
  • Prisma ORM
  • Redis (Session management & caching)
  • JWT with Multi-Factor Authentication
  • WebSocket (socket.io for real-time updates)

Frontend

  • Next.js 14 with React
  • TypeScript
  • Tailwind CSS
  • Axios for API communication
  • Real-time WebSocket connections

Security Features

  • Input validation and sanitization
  • Parameterized queries (SQL injection prevention)
  • Content Security Policy (XSS prevention)
  • Session device binding
  • Role-Based Access Control (RBAC)
  • Attribute-Based Access Control (ABAC)
  • AI prompt injection detection
  • Hash-chained immutable audit logs
  • Behavioral anomaly detection
  • Rate limiting and throttling

Project Structure

Genzipher1.0/
├── backend/                    # Main NestJS backend API
│   ├── src/
│   │   ├── auth/              # Authentication & MFA
│   │   ├── audit/             # Immutable audit logging
│   │   ├── monitoring/        # Security monitoring
│   │   ├── incident/          # Incident management
│   │   ├── ai-verification/   # AI safety checks
│   │   ├── data-protection/   # Field-level encryption
│   │   └── prisma/            # Database service
│   └── prisma/
│       └── schema.prisma      # Database schema
├── frontend/                   # Main HMS Next.js frontend
│   ├── app/
│   │   ├── login/             # Login page
│   │   ├── dashboard/         # Main dashboard
│   │   │   ├── audit/         # Audit log viewer
│   │   │   ├── monitoring/    # Security monitoring
│   │   │   └── incidents/     # Incident management
│   │   └── layout.tsx
│   └── lib/
│       └── api-client.ts      # API client with auth
├── attack-demo-backend/        # Attack simulator backend
│   └── src/
│       └── attack/
│           ├── simulators/    # 8 attack simulators
│           ├── attack.controller.ts
│           └── attack.gateway.ts
├── attack-demo-frontend/       # Attack demo UI
│   └── app/
│       └── page.tsx           # Attack execution interface
├── docs/                       # Additional documentation
├── docker-compose.yml          # Docker services (Redis, PgAdmin)
└── GETTING-STARTED.md          # Quick start guide

Database Schema

The system uses PostgreSQL with 10 tables:

  • User: User accounts with hashed passwords
  • Session: Active user sessions with device binding
  • Device: Registered user devices
  • AuditLog: Immutable audit trail with hash chaining
  • AccessRequest: Just-in-time access requests
  • Policy: Access control policies (RBAC/ABAC)
  • Incident: Security incident tracking
  • Patient: Patient medical records (encrypted PHI)
  • AIInteraction: AI system usage logs
  • RateLimit: API rate limiting records

Installation & Setup

Prerequisites

  • Node.js 18+ and npm
  • PostgreSQL 18 (Windows native installation)
  • Redis (via Docker or native)
  • Git

Quick Start

  1. Clone the repository:
git clone <repository-url>
cd Genzipher1.0
  1. Install dependencies:
# Backend
cd backend
npm install

# Frontend
cd ../frontend
npm install

# Attack Demo Backend
cd ../attack-demo-backend
npm install

# Attack Demo Frontend
cd ../attack-demo-frontend
npm install
  1. Configure environment variables:

Backend (.env):

DATABASE_URL="postgresql://genzipher:genzipher_secure_password@localhost:5432/genzipher_db?schema=public"
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=genzipher_redis_password
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRATION=15m
JWT_REFRESH_SECRET=your-super-secret-refresh-token-key
JWT_REFRESH_EXPIRATION=7d
PORT=5000
NODE_ENV=development
CORS_ORIGIN=http://localhost:3000,http://localhost:3001
ENCRYPTION_KEY=your-32-character-encryption-key-change-this
AUDIT_SIGNATURE_SECRET=your-audit-signature-secret-key-for-hmac-signing

Frontend (.env.local):

NEXT_PUBLIC_API_URL=http://localhost:5000
NEXT_PUBLIC_WS_URL=ws://localhost:5000
  1. Setup PostgreSQL database:
# Create database and user (run in PostgreSQL)
CREATE USER genzipher WITH PASSWORD 'genzipher_secure_password';
CREATE DATABASE genzipher_db OWNER genzipher;
GRANT ALL ON SCHEMA public TO genzipher;
  1. Run Prisma migrations:
cd backend
npx prisma db push
  1. Start services in separate terminals:

Terminal 1 - Main Backend:

cd backend
npm run start:dev

Terminal 2 - Main Frontend:

cd frontend
npm run dev

Terminal 3 - Attack Demo Backend:

cd attack-demo-backend
npm run start:dev

Terminal 4 - Attack Demo Frontend:

cd attack-demo-frontend
npm run dev
  1. Start Redis (if using Docker):
docker-compose up -d redis

Access Points

Demo Accounts

Two pre-configured accounts are available:

  1. Admin Account:

  2. Doctor Account:

Attack Demonstration System

The attack demo system provides live demonstrations of 8 security vulnerabilities:

  1. SQL Injection - Database attack prevention
  2. XSS Attack - Script injection defense
  3. Session Hijacking - Token theft protection
  4. Privilege Escalation - Access control enforcement
  5. Data Exfiltration - Bulk data extraction prevention
  6. Audit Log Tampering - Hash-chain integrity verification
  7. AI Prompt Injection - LLM security controls
  8. Insider Threat Detection - Behavioral analysis

Each scenario shows:

  • Real-time attack execution
  • Defense mechanism activation
  • Step-by-step blocking process
  • Security controls that prevented the attack

API Endpoints

Authentication

  • POST /api/auth/register - User registration
  • POST /api/auth/login - User login with device fingerprinting
  • POST /api/auth/mfa/setup - MFA setup
  • POST /api/auth/mfa/verify - MFA verification
  • POST /api/auth/refresh - Token refresh
  • POST /api/auth/logout - User logout
  • GET /api/auth/me - Current user info

Audit Logs

  • GET /api/audit/logs - Retrieve audit logs
  • GET /api/audit/timeline/:resourceType/:resourceId - Resource timeline
  • POST /api/audit/verify - Verify audit log integrity

Monitoring

  • GET /api/monitoring/sessions - Active sessions
  • POST /api/monitoring/anomaly-check - Check for anomalies
  • POST /api/monitoring/sessions/:sessionId/terminate - Terminate session

Incidents

  • GET /api/incidents - List incidents
  • GET /api/incidents/statistics - Incident statistics
  • GET /api/incidents/:id - Get incident details
  • POST /api/incidents - Create incident
  • PATCH /api/incidents/:id/status - Update incident status
  • POST /api/incidents/:id/contain - Contain incident

Attack Demo

  • GET /api/attack/scenarios - List attack scenarios
  • POST /api/attack/execute/:scenario - Execute attack simulation

Security Implementation Highlights

Authentication

  • Password hashing with bcrypt
  • JWT access tokens (15 minute expiry)
  • Refresh tokens (7 day expiry)
  • TOTP-based Multi-Factor Authentication
  • Device fingerprinting for session binding

Authorization

  • Role-Based Access Control (RBAC)
  • Attribute-Based Access Control (ABAC)
  • Just-in-time access with approval workflow
  • Policy-based permission system

Data Protection

  • Field-level encryption for PHI
  • Data masking based on user role
  • Secure key management
  • Encrypted data at rest

Audit & Monitoring

  • Immutable audit logs with hash chaining
  • Real-time security monitoring
  • Behavioral anomaly detection
  • Automated incident response
  • WebSocket-based real-time alerts

Input Validation

  • DTO validation with class-validator
  • SQL injection prevention via Prisma ORM
  • XSS prevention with Content Security Policy
  • Request sanitization
  • Rate limiting and throttling

AI Security

  • Prompt injection detection
  • PHI leakage prevention
  • Pattern-based risk assessment
  • Automated content filtering

Development

Running Tests

cd backend
npm run test

cd ../frontend
npm run test

Building for Production

# Backend
cd backend
npm run build

# Frontend
cd frontend
npm run build

Database Migrations

cd backend
npx prisma migrate dev --name migration_name
npx prisma generate

Troubleshooting

Database Connection Issues

If you encounter database authentication errors:

  1. Verify PostgreSQL service is running
  2. Check credentials in .env file
  3. Ensure database and user exist
  4. Grant proper permissions to genzipher user

Port Already in Use

If ports are occupied:

# Windows
netstat -ano | findstr ":3000"
netstat -ano | findstr ":5000"
# Kill process by PID
taskkill /PID <process_id> /F

Frontend Not Loading

  1. Clear Next.js cache: rm -rf .next
  2. Reinstall dependencies: npm install
  3. Check environment variables in .env.local
  4. Restart development server

Architecture Decisions

Why NestJS?

  • Enterprise-grade structure with modules
  • Built-in dependency injection
  • TypeScript first-class support
  • Excellent for large-scale applications

Why Prisma?

  • Type-safe database access
  • Automatic migrations
  • Prevents SQL injection by design
  • Great developer experience

Why Native PostgreSQL?

  • Direct connection without Docker networking
  • Better performance on Windows
  • Easier debugging and management
  • Production-like setup

Why Next.js?

  • Server-side rendering for better security
  • File-based routing
  • Built-in API routes
  • Excellent performance

Contributing

This is an academic project for demonstration purposes. For significant changes:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Submit a pull request

License

This project is developed for genzipher competition as part of a security demonstration.

Credits

Developed by: Gmora Purpose: Hospital Management Security Demonstration Framework: NestJS + Next.js + PostgreSQL

Additional Resources

For detailed implementation information, refer to GETTING-STARTED.md in the project root.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages