From 1ed9bdfa5547cb863f0d99c1cea2b2cd7604b544 Mon Sep 17 00:00:00 2001 From: Dongho Kim Date: Tue, 7 Apr 2026 17:41:25 +0200 Subject: [PATCH] initial commit --- .gitignore | 31 + backend/backend.Dockerfile | 27 + backend/package.json | 14 + backend/server.js | 196 +++++ docker-compose.yml | 26 + frontend/dev.Dockerfile | 5 + frontend/index.html | 13 + frontend/package.json | 26 + frontend/postcss.config.js | 6 + frontend/src/App.tsx | 404 +++++++++++ frontend/src/index.css | 31 + frontend/src/main.tsx | 10 + frontend/tailwind.config.js | 11 + frontend/tsconfig.json | 21 + frontend/tsconfig.node.json | 11 + frontend/vite.config.ts | 18 + protonvpn-wg-confgen/.github/workflows/ci.yml | 124 ++++ .../.github/workflows/release.yml | 37 + protonvpn-wg-confgen/.gitignore | 52 ++ protonvpn-wg-confgen/.golangci.yml | 107 +++ protonvpn-wg-confgen/.goreleaser.yaml | 76 ++ protonvpn-wg-confgen/API_REFERENCE.md | 149 ++++ protonvpn-wg-confgen/LICENSE | 674 ++++++++++++++++++ protonvpn-wg-confgen/Makefile | 89 +++ protonvpn-wg-confgen/README.md | 326 +++++++++ protonvpn-wg-confgen/cmd/protonvpn-wg/main.go | 104 +++ protonvpn-wg-confgen/go.mod | 19 + protonvpn-wg-confgen/go.sum | 68 ++ protonvpn-wg-confgen/internal/api/types.go | 165 +++++ protonvpn-wg-confgen/internal/auth/auth.go | 503 +++++++++++++ protonvpn-wg-confgen/internal/auth/errors.go | 82 +++ protonvpn-wg-confgen/internal/auth/session.go | 210 ++++++ protonvpn-wg-confgen/internal/config/flags.go | 120 ++++ protonvpn-wg-confgen/internal/config/types.go | 48 ++ .../internal/constants/api.go | 37 + .../internal/constants/defaults.go | 14 + .../internal/constants/session.go | 9 + .../internal/constants/wireguard.go | 17 + protonvpn-wg-confgen/internal/vpn/client.go | 148 ++++ protonvpn-wg-confgen/internal/vpn/servers.go | 165 +++++ protonvpn-wg-confgen/pkg/timeutil/duration.go | 148 ++++ protonvpn-wg-confgen/pkg/timeutil/parser.go | 81 +++ .../pkg/validation/username.go | 31 + protonvpn-wg-confgen/pkg/wireguard/config.go | 140 ++++ .../pkg/wireguard/config_test.go | 119 ++++ 45 files changed, 4712 insertions(+) create mode 100644 .gitignore create mode 100644 backend/backend.Dockerfile create mode 100644 backend/package.json create mode 100644 backend/server.js create mode 100644 docker-compose.yml create mode 100644 frontend/dev.Dockerfile create mode 100644 frontend/index.html create mode 100644 frontend/package.json create mode 100644 frontend/postcss.config.js create mode 100644 frontend/src/App.tsx create mode 100644 frontend/src/index.css create mode 100644 frontend/src/main.tsx create mode 100644 frontend/tailwind.config.js create mode 100644 frontend/tsconfig.json create mode 100644 frontend/tsconfig.node.json create mode 100644 frontend/vite.config.ts create mode 100644 protonvpn-wg-confgen/.github/workflows/ci.yml create mode 100644 protonvpn-wg-confgen/.github/workflows/release.yml create mode 100644 protonvpn-wg-confgen/.gitignore create mode 100644 protonvpn-wg-confgen/.golangci.yml create mode 100644 protonvpn-wg-confgen/.goreleaser.yaml create mode 100644 protonvpn-wg-confgen/API_REFERENCE.md create mode 100644 protonvpn-wg-confgen/LICENSE create mode 100644 protonvpn-wg-confgen/Makefile create mode 100644 protonvpn-wg-confgen/README.md create mode 100644 protonvpn-wg-confgen/cmd/protonvpn-wg/main.go create mode 100644 protonvpn-wg-confgen/go.mod create mode 100644 protonvpn-wg-confgen/go.sum create mode 100644 protonvpn-wg-confgen/internal/api/types.go create mode 100644 protonvpn-wg-confgen/internal/auth/auth.go create mode 100644 protonvpn-wg-confgen/internal/auth/errors.go create mode 100644 protonvpn-wg-confgen/internal/auth/session.go create mode 100644 protonvpn-wg-confgen/internal/config/flags.go create mode 100644 protonvpn-wg-confgen/internal/config/types.go create mode 100644 protonvpn-wg-confgen/internal/constants/api.go create mode 100644 protonvpn-wg-confgen/internal/constants/defaults.go create mode 100644 protonvpn-wg-confgen/internal/constants/session.go create mode 100644 protonvpn-wg-confgen/internal/constants/wireguard.go create mode 100644 protonvpn-wg-confgen/internal/vpn/client.go create mode 100644 protonvpn-wg-confgen/internal/vpn/servers.go create mode 100644 protonvpn-wg-confgen/pkg/timeutil/duration.go create mode 100644 protonvpn-wg-confgen/pkg/timeutil/parser.go create mode 100644 protonvpn-wg-confgen/pkg/validation/username.go create mode 100644 protonvpn-wg-confgen/pkg/wireguard/config.go create mode 100644 protonvpn-wg-confgen/pkg/wireguard/config_test.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f5bc69a --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Node.js +node_modules/ +npm-debug.log +yarn-error.log + +# Environment Variables (CRITICAL) +.env +.env.* +!.env.example + +# Build Outputs +dist/ +build/ +bin/ +server/ + +# Generated WireGuard configs +*.conf + +# OS/Editor Files +.DS_Store +.idea/ +.vscode/ +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +# ProtonVPN local DBs or cache if generated locally +*.db diff --git a/backend/backend.Dockerfile b/backend/backend.Dockerfile new file mode 100644 index 0000000..7f40eb5 --- /dev/null +++ b/backend/backend.Dockerfile @@ -0,0 +1,27 @@ +# Multi-stage build for Go + Node.js Backend +# Stage 1: Build Go binary +FROM golang:1.24-alpine AS builder +# Use latest stable go that works (docker tag might not have 1.25.6 yet, alpine is fine) +# Since the go.mod says 1.25.6, we'll let it use the toolchain if 1.24 is the base, or we just rely on standard go compilation. +RUN apk add --no-cache git make gcc musl-dev + +WORKDIR /src +COPY protonvpn-wg-confgen/ ./ +ENV GOTOOLCHAIN=auto +RUN go build -o /bin/protonvpn-wg-confgen cmd/protonvpn-wg/main.go + +# Stage 2: Node.js Backend Production setup +FROM node:22-alpine +WORKDIR /app + +# Install CA certs needed for Proton API calls +RUN apk add --no-cache ca-certificates tzdata + +# Copy the compiled Go binary from Stage 1 +COPY --from=builder /bin/protonvpn-wg-confgen /usr/local/bin/protonvpn-wg-confgen + +# Setup the Node JS backend +COPY backend/package.json ./ +RUN npm install +COPY backend/ ./ +CMD ["npm", "run", "dev"] diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..0ab20f3 --- /dev/null +++ b/backend/package.json @@ -0,0 +1,14 @@ +{ + "name": "protonvpn-webui-backend", + "version": "1.0.0", + "type": "module", + "scripts": { + "start": "node server.js", + "dev": "node --watch server.js" + }, + "dependencies": { + "express": "^4.19.2", + "cors": "^2.8.5", + "helmet": "^7.1.0" + } +} diff --git a/backend/server.js b/backend/server.js new file mode 100644 index 0000000..b3c6511 --- /dev/null +++ b/backend/server.js @@ -0,0 +1,196 @@ +import express from 'express'; +import cors from 'cors'; +import { spawn } from 'child_process'; +import crypto from 'crypto'; +import path from 'path'; +import fs from 'fs/promises'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const app = express(); +const port = process.env.PORT || 3000; + +app.use(cors()); +app.use(express.json()); + +// In-memory process store for SSE and interactive stdin +const activeTasks = new Map(); + +// Helper to construct command arguments +function buildArgs(body, outputFile) { + const args = []; + + const username = body.username || process.env.PROTON_USERNAME; + const password = body.password || process.env.PROTON_PASSWORD; + + if (username) { + args.push('-username', username); + } + if (password) { + args.push('-password', password); + } + if (body.countries) { + args.push('-countries', body.countries); // e.g., "US,NL" + } + + args.push('-output', outputFile); + + if (body.p2pOnly) args.push('-p2p-only'); + if (body.secureCore) args.push('-secure-core'); + if (body.freeOnly) args.push('-free-only'); + if (body.ipv6) args.push('-ipv6'); + if (body.accelerator === false) args.push('-accelerator=false'); + if (body.duration) args.push('-duration', body.duration); + + // We use clear-session to force fresh auth if needed, or default behavior + // For web UI, maybe we want to always force clear session so it doesn't use old cached sessions + // that belong to root from inside docker? Let's give user option, typical web user wants it fresh. + args.push('-clear-session'); + + return args; +} + +app.post('/api/generate', async (req, res) => { + const taskId = crypto.randomUUID(); + const outputFile = path.join(__dirname, `protonvpn-${taskId}.conf`); + + const args = buildArgs(req.body, outputFile); + + // Default to system PATH if compiled, handle local testing fallback + let binPath = 'protonvpn-wg-confgen'; + + console.log(`Starting task ${taskId}: ${binPath} ${args.join(' ')}`); + + // Create process + const child = spawn(binPath, args); + + // Store task + activeTasks.set(taskId, { + child, + outputFile, + clients: [] + }); + + child.stdout.on('data', (data) => { + const text = data.toString(); + console.log(`[${taskId} stdout]`, text); + broadcastToClients(taskId, 'log', { text }); + + // Check for interactive prompts from Go tool + if (text.includes('2FA Code:')) { + broadcastToClients(taskId, 'require_2fa', {}); + } + }); + + child.stderr.on('data', (data) => { + const text = data.toString(); + console.log(`[${taskId} stderr]`, text); + broadcastToClients(taskId, 'log', { text, error: true }); + }); + + child.on('close', async (code) => { + console.log(`[${taskId} exited with code ${code}]`); + let fileContent = null; + let success = code === 0; + + if (success) { + try { + fileContent = await fs.readFile(outputFile, 'utf8'); + // Clean up the file + await fs.unlink(outputFile).catch(() => {}); + } catch (err) { + console.error('Failed to read configuration file', err); + success = false; + } + } + + broadcastToClients(taskId, 'complete', { success, code, fileContent }); + + // Cleanup task memory shortly after complete + setTimeout(() => { + const task = activeTasks.get(taskId); + if (task) { + task.clients.forEach(c => c.end()); + activeTasks.delete(taskId); + } + }, 5000); + }); + + child.on('error', (err) => { + console.error(`[${taskId} ERROR]`, err); + broadcastToClients(taskId, 'log', { text: `Failed to start process: ${err.message}`, error: true }); + broadcastToClients(taskId, 'complete', { success: false, code: -1 }); + }); + + res.json({ taskId }); +}); + +// SSE endpoint +app.get('/api/stream/:taskId', (req, res) => { + const { taskId } = req.params; + const task = activeTasks.get(taskId); + + if (!task) { + return res.status(404).send('Task not found'); + } + + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + res.flushHeaders(); + + task.clients.push(res); + + req.on('close', () => { + task.clients = task.clients.filter(client => client !== res); + }); +}); + +app.post('/api/2fa', (req, res) => { + const { taskId, code } = req.body; + const task = activeTasks.get(taskId); + + if (!task) { + return res.status(404).json({ error: 'Task not found' }); + } + + if (!task.child.stdin.writable) { + return res.status(400).json({ error: 'Process not accepting input' }); + } + + // Write the code followed by newline to the process stdin + task.child.stdin.write(`${code}\n`); + res.json({ success: true }); +}); + +const POPULAR_COUNTRIES = [ + { code: 'US', name: 'United States' }, + { code: 'NL', name: 'Netherlands' }, + { code: 'CH', name: 'Switzerland' }, + { code: 'JP', name: 'Japan' }, + { code: 'UK', name: 'United Kingdom' }, + { code: 'DE', name: 'Germany' }, + { code: 'CA', name: 'Canada' }, + { code: 'FR', name: 'France' }, + { code: 'SE', name: 'Sweden' }, + { code: 'IS', name: 'Iceland' } +]; + +app.get('/api/countries', (req, res) => { + res.json(POPULAR_COUNTRIES); +}); + +// Helper for SSE +function broadcastToClients(taskId, eventName, data) { + const task = activeTasks.get(taskId); + if (!task) return; + + const payload = `event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`; + task.clients.forEach(client => client.write(payload)); +} + +app.listen(port, () => { + console.log(`Backend server running on http://localhost:${port}`); +}); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..c94627d --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,26 @@ +services: + backend: + build: + context: . + dockerfile: backend/backend.Dockerfile + ports: + - "3000:3000" + volumes: + - ./backend:/app + - /app/node_modules + environment: + - PORT=3000 + env_file: + - .env + + frontend: + build: + context: ./frontend + dockerfile: dev.Dockerfile + ports: + - "5173:5173" + volumes: + - ./frontend:/app + - /app/node_modules + depends_on: + - backend diff --git a/frontend/dev.Dockerfile b/frontend/dev.Dockerfile new file mode 100644 index 0000000..4c742cb --- /dev/null +++ b/frontend/dev.Dockerfile @@ -0,0 +1,5 @@ +FROM node:22-alpine +WORKDIR /app +COPY package.json ./ +RUN npm install +CMD ["npm", "run", "dev", "--", "--host"] diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..e35a447 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + ProtonVPN Config Generator + + +
+ + + diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..215a318 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,26 @@ +{ + "name": "protonvpn-webui-frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", + "preview": "vite preview" + }, + "dependencies": { + "react": "^18.3.1", + "react-dom": "^18.3.1", + "tailwindcss": "^3.4.4", + "postcss": "^8.4.38", + "autoprefixer": "^10.4.19" + }, + "devDependencies": { + "@types/react": "^18.3.3", + "@types/react-dom": "^18.3.0", + "@vitejs/plugin-react": "^4.3.1", + "typescript": "^5.2.2", + "vite": "^5.3.4" + } +} diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js new file mode 100644 index 0000000..2e7af2b --- /dev/null +++ b/frontend/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 0000000..94cabf4 --- /dev/null +++ b/frontend/src/App.tsx @@ -0,0 +1,404 @@ +import React, { useState, useEffect, useRef } from 'react'; + +const COUNTRIES = [ + { code: 'AR', name: 'Argentina' }, + { code: 'AU', name: 'Australia' }, + { code: 'AT', name: 'Austria' }, + { code: 'BE', name: 'Belgium' }, + { code: 'BR', name: 'Brazil' }, + { code: 'BG', name: 'Bulgaria' }, + { code: 'CA', name: 'Canada' }, + { code: 'CL', name: 'Chile' }, + { code: 'CO', name: 'Colombia' }, + { code: 'CR', name: 'Costa Rica' }, + { code: 'HR', name: 'Croatia' }, + { code: 'CY', name: 'Cyprus' }, + { code: 'CZ', name: 'Czechia' }, + { code: 'DK', name: 'Denmark' }, + { code: 'EE', name: 'Estonia' }, + { code: 'FI', name: 'Finland' }, + { code: 'FR', name: 'France' }, + { code: 'GE', name: 'Georgia' }, + { code: 'DE', name: 'Germany' }, + { code: 'GR', name: 'Greece' }, + { code: 'HK', name: 'Hong Kong' }, + { code: 'HU', name: 'Hungary' }, + { code: 'IS', name: 'Iceland' }, + { code: 'IN', name: 'India' }, + { code: 'IE', name: 'Ireland' }, + { code: 'IL', name: 'Israel' }, + { code: 'IT', name: 'Italy' }, + { code: 'JP', name: 'Japan' }, + { code: 'LV', name: 'Latvia' }, + { code: 'LT', name: 'Lithuania' }, + { code: 'LU', name: 'Luxembourg' }, + { code: 'MY', name: 'Malaysia' }, + { code: 'MX', name: 'Mexico' }, + { code: 'MD', name: 'Moldova' }, + { code: 'NL', name: 'Netherlands' }, + { code: 'NZ', name: 'New Zealand' }, + { code: 'NO', name: 'Norway' }, + { code: 'PE', name: 'Peru' }, + { code: 'PH', name: 'Philippines' }, + { code: 'PL', name: 'Poland' }, + { code: 'PT', name: 'Portugal' }, + { code: 'RO', name: 'Romania' }, + { code: 'RS', name: 'Serbia' }, + { code: 'SG', name: 'Singapore' }, + { code: 'SK', name: 'Slovakia' }, + { code: 'SI', name: 'Slovenia' }, + { code: 'ZA', name: 'South Africa' }, + { code: 'KR', name: 'South Korea' }, + { code: 'ES', name: 'Spain' }, + { code: 'SE', name: 'Sweden' }, + { code: 'CH', name: 'Switzerland' }, + { code: 'TW', name: 'Taiwan' }, + { code: 'TR', name: 'Turkey' }, + { code: 'UA', name: 'Ukraine' }, + { code: 'AE', name: 'United Arab Emirates' }, + { code: 'UK', name: 'United Kingdom' }, + { code: 'US', name: 'United States' }, + { code: 'VN', name: 'Vietnam' } +]; + +const getFlagImg = (countryCode: string) => { + return ( + {countryCode} + ); +}; + +export default function App() { + const [selectedCountries, setSelectedCountries] = useState([]); + const [isCountryOpen, setIsCountryOpen] = useState(false); + const [options, setOptions] = useState({ + p2pOnly: true, + secureCore: false, + freeOnly: false, + ipv6: false, + accelerator: true, + duration: '365d' + }); + + const [taskId, setTaskId] = useState(null); + const [isGenerating, setIsGenerating] = useState(false); + const [logs, setLogs] = useState<{text: string, error?: boolean}[]>([]); + const [require2FA, setRequire2FA] = useState(false); + const [twoFACode, setTwoFACode] = useState(''); + const [downloadData, setDownloadData] = useState(null); + + const logsEndRef = useRef(null); + + useEffect(() => { + logsEndRef.current?.scrollIntoView({ behavior: 'smooth' }); + }, [logs]); + + const toggleCountry = (code: string) => { + setSelectedCountries(prev => + prev.includes(code) ? prev.filter(c => c !== code) : [...prev, code] + ); + }; + + const handleGenerate = async (e: React.FormEvent) => { + e.preventDefault(); + if (selectedCountries.length === 0) { + alert("Please select at least one country"); + return; + } + + setIsGenerating(true); + setLogs([]); + setRequire2FA(false); + setDownloadData(null); + setTaskId(null); + + try { + const res = await fetch('/api/generate', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + countries: selectedCountries.join(','), + ...options + }) + }); + + const { taskId } = await res.json(); + setTaskId(taskId); + + const es = new EventSource(`/api/stream/${taskId}`); + + es.addEventListener('log', (e) => { + const data = JSON.parse(e.data); + setLogs(prev => [...prev, data]); + }); + + es.addEventListener('require_2fa', () => { + setRequire2FA(true); + }); + + es.addEventListener('complete', (e) => { + const data = JSON.parse(e.data); + setLogs(prev => [...prev, { text: `Process completed with code ${data.code}` }]); + setIsGenerating(false); + if (data.success && data.fileContent) { + setDownloadData(data.fileContent); + } + es.close(); + }); + + es.onerror = () => { + setLogs(prev => [...prev, { text: 'Lost connection to stream', error: true }]); + setIsGenerating(false); + es.close(); + }; + + } catch (err) { + setLogs([{ text: `Failed to initiate generation: ${err}`, error: true }]); + setIsGenerating(false); + } + }; + + const submit2FA = async (e: React.FormEvent) => { + e.preventDefault(); + if (!taskId || !twoFACode) return; + + setRequire2FA(false); + setLogs(prev => [...prev, { text: `> Submitting 2FA Code: ***`, error: false }]); + + await fetch('/api/2fa', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ taskId, code: twoFACode }) + }); + + setTwoFACode(''); + }; + + const downloadFile = () => { + if (!downloadData) return; + const blob = new Blob([downloadData], { type: 'text/plain' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `protonvpn-${selectedCountries.join('_')}.conf`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }; + + return ( +
+ {/* Background aesthetic */} +
+
+ +
+
+
+

+ Proton WireGuard +

+

Headless Configuration Generator

+
+

+ Powered by open-source protonvpn-wg-confgen +

+
+ +
+ + {/* Controls Panel */} +
+

Connection Settings

+ +
+ + +
+ +
+ + + {isCountryOpen && ( +
+
+ {COUNTRIES.map(country => ( + + ))} +
+
+ )} +
+
+ +
+ +
+ {[ + { key: 'p2pOnly', label: 'P2P Optimized' }, + { key: 'secureCore', label: 'Secure Core' }, + { key: 'freeOnly', label: 'Free Tier Only' }, + { key: 'ipv6', label: 'Enable IPv6' }, + { key: 'accelerator', label: 'VPN Accelerator' } + ].map(opt => ( + + ))} +
+
+ +
+ +
+
+
+ + {/* Terminal / Output Panel */} +
+
+
+
+
+ generator.log +
+ +
+ {logs.length === 0 && !isGenerating && ( +

Waiting for execution...

+ )} + {logs.map((log, i) => ( +
+ {log.text.split('\n').map((line, j) => ( +
{line}
+ ))} +
+ ))} +
+
+ + {/* Success Download */} + {downloadData && ( +
+ +
+ )} +
+ +
+
+ + {/* 2FA Modal */} + {require2FA && ( +
+
+

+ + + + Two-Factor Auth +

+

Your Proton account requires a TOTP code to authenticate the VPN API.

+ +
+ setTwoFACode(e.target.value.replace(/\D/g, ''))} + placeholder="000 000" + className="w-full bg-black/60 border border-white/10 rounded-xl px-4 py-4 text-center text-2xl tracking-widest font-mono focus:outline-none focus:border-[#6d4aff] transition-colors mb-6" + /> + +
+
+
+ )} +
+ ); +} diff --git a/frontend/src/index.css b/frontend/src/index.css new file mode 100644 index 0000000..48fd95b --- /dev/null +++ b/frontend/src/index.css @@ -0,0 +1,31 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +:root { + --color-proton-purple: #6d4aff; + --color-proton-dark: #121015; + --color-proton-card: #1c1924; + --color-proton-accent: #937bff; + --color-proton-green: #2bbd7e; + --font-sans: "Inter", system-ui, sans-serif; +} + +body { + background-color: var(--color-proton-dark); +} + +/* Custom scrollbar for terminal */ +.terminal-scroll::-webkit-scrollbar { + width: 8px; +} +.terminal-scroll::-webkit-scrollbar-track { + background: rgba(0,0,0,0.2); +} +.terminal-scroll::-webkit-scrollbar-thumb { + background: rgba(109, 74, 255, 0.4); + border-radius: 4px; +} +.terminal-scroll::-webkit-scrollbar-thumb:hover { + background: rgba(109, 74, 255, 0.6); +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx new file mode 100644 index 0000000..3d7150d --- /dev/null +++ b/frontend/src/main.tsx @@ -0,0 +1,10 @@ +import React from 'react' +import ReactDOM from 'react-dom/client' +import App from './App.tsx' +import './index.css' + +ReactDOM.createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js new file mode 100644 index 0000000..dca8ba0 --- /dev/null +++ b/frontend/tailwind.config.js @@ -0,0 +1,11 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: [ + "./index.html", + "./src/**/*.{js,ts,jsx,tsx}", + ], + theme: { + extend: {}, + }, + plugins: [], +} diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json new file mode 100644 index 0000000..3934b8f --- /dev/null +++ b/frontend/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"], + "references": [{ "path": "./tsconfig.node.json" }] +} diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json new file mode 100644 index 0000000..97ede7e --- /dev/null +++ b/frontend/tsconfig.node.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "strict": true + }, + "include": ["vite.config.ts"] +} diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts new file mode 100644 index 0000000..dbcbafa --- /dev/null +++ b/frontend/vite.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [ + react(), + ], + server: { + host: '0.0.0.0', // needed for docker + port: 5173, + proxy: { + '/api': { + target: 'http://backend:3000', + changeOrigin: true + } + } + } +}) diff --git a/protonvpn-wg-confgen/.github/workflows/ci.yml b/protonvpn-wg-confgen/.github/workflows/ci.yml new file mode 100644 index 0000000..d9f8a9e --- /dev/null +++ b/protonvpn-wg-confgen/.github/workflows/ci.yml @@ -0,0 +1,124 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +env: + GO_VERSION: "1.25.6" + GOLANGCI_LINT_VERSION: "v2.8.0" + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Go + uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + + - name: Run go fmt + run: | + if [ -n "$(gofmt -s -l . | grep -v '^vendor/')" ]; then + echo "Go code is not formatted:" + gofmt -s -d . | grep -v '^vendor/' + exit 1 + fi + + - name: Run go vet + run: go vet ./... + + - name: Run golangci-lint + uses: golangci/golangci-lint-action@1e7e51e771db61008b38414a730f564565cf7c20 # v9.2.0 + with: + version: ${{ env.GOLANGCI_LINT_VERSION }} + + test: + name: Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Go + uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + + - name: Run tests + run: go test -v -race ./... + + build: + name: Build (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Go + uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + + - name: Build (native) + run: go build -o build/protonvpn-wg-confgen${{ matrix.os == 'windows-latest' && '.exe' || '' }} cmd/protonvpn-wg/main.go + + cross-compile: + name: Cross-compile + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + # Linux + - goos: linux + goarch: amd64 + - goos: linux + goarch: arm64 + - goos: linux + goarch: arm + # macOS + - goos: darwin + goarch: amd64 + - goos: darwin + goarch: arm64 + # Windows + - goos: windows + goarch: amd64 + ext: .exe + - goos: windows + goarch: arm64 + ext: .exe + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Set up Go + uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + + - name: Build ${{ matrix.goos }}/${{ matrix.goarch }} + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + CGO_ENABLED: "0" + run: | + mkdir -p build + go build -o build/protonvpn-wg-confgen-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.ext }} cmd/protonvpn-wg/main.go + + - name: Upload artifact + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + with: + name: protonvpn-wg-confgen-${{ matrix.goos }}-${{ matrix.goarch }} + path: build/protonvpn-wg-confgen-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.ext }} diff --git a/protonvpn-wg-confgen/.github/workflows/release.yml b/protonvpn-wg-confgen/.github/workflows/release.yml new file mode 100644 index 0000000..a2a86bb --- /dev/null +++ b/protonvpn-wg-confgen/.github/workflows/release.yml @@ -0,0 +1,37 @@ +name: Release + +on: + push: + tags: + - "v*" + +permissions: + contents: write + +env: + GO_VERSION: "1.25.6" + +jobs: + release: + name: Release + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + + - name: Set up Go + uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a # v6.4.0 + with: + distribution: goreleaser + version: "~> v2" + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/protonvpn-wg-confgen/.gitignore b/protonvpn-wg-confgen/.gitignore new file mode 100644 index 0000000..354885a --- /dev/null +++ b/protonvpn-wg-confgen/.gitignore @@ -0,0 +1,52 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool +*.out + +# Go vendor directory +vendor/ + +# Build directory +build/ + +# Binary +protonvpn-wg-confgen + +# IDE specific files +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS specific files +.DS_Store +Thumbs.db + +# Configuration files generated by the tool +*.conf + +# Session files +.protonvpn-session.json + +# Temporary files +*.tmp +*.bak + +# Log files +*.log + +# Debug and reference libraries +.debug-libs/ + +# Claude Code +.claude/ +CLAUDE.md diff --git a/protonvpn-wg-confgen/.golangci.yml b/protonvpn-wg-confgen/.golangci.yml new file mode 100644 index 0000000..2f9cde4 --- /dev/null +++ b/protonvpn-wg-confgen/.golangci.yml @@ -0,0 +1,107 @@ +# yaml-language-server: $schema=https://golangci-lint.run/jsonschema/golangci.v2.jsonschema.json +version: "2" + +linters: + enable: + # Default linters + - errcheck + - govet + - ineffassign + - staticcheck + - unused + # Code quality + - gocritic + - gocognit + - gocyclo + - revive + - misspell + - unconvert + - dupl + - prealloc + # Error handling + - nilerr + - errorlint + # Security + - gosec + # Style & formatting + - whitespace + - wastedassign + # Best practices + - exhaustive + - nolintlint + - goconst + - nakedret + - nestif + - bodyclose + - usestdlibvars + - copyloopvar + - intrange + + settings: + revive: + severity: warning + rules: + - name: blank-imports + - name: context-as-argument + - name: error-return + - name: error-strings + - name: error-naming + - name: exported + - name: package-comments + - name: range + - name: receiver-naming + - name: indent-error-flow + - name: superfluous-else + + gocyclo: + min-complexity: 15 + + gocognit: + min-complexity: 30 + + gocritic: + enabled-tags: + - diagnostic + - experimental + - opinionated + - performance + - style + + dupl: + threshold: 100 + + goconst: + min-len: 3 + min-occurrences: 3 + + nakedret: + max-func-lines: 30 + + nestif: + min-complexity: 4 + + errorlint: + errorf: true + asserts: true + comparison: true + + nolintlint: + require-explanation: true + require-specific: true + + exclusions: + paths: + - vendor + +issues: + max-issues-per-linter: 50 + max-same-issues: 10 + +run: + timeout: 5m + tests: true + +formatters: + enable: + - gofmt + - goimports diff --git a/protonvpn-wg-confgen/.goreleaser.yaml b/protonvpn-wg-confgen/.goreleaser.yaml new file mode 100644 index 0000000..4b25833 --- /dev/null +++ b/protonvpn-wg-confgen/.goreleaser.yaml @@ -0,0 +1,76 @@ +# yaml-language-server: $schema=https://goreleaser.com/static/schema.json +version: 2 + +project_name: protonvpn-wg-confgen + +before: + hooks: + - go mod tidy + +builds: + - id: protonvpn-wg-confgen + main: ./cmd/protonvpn-wg + binary: protonvpn-wg-confgen + env: + - CGO_ENABLED=0 + goos: + - linux + - darwin + - windows + goarch: + - amd64 + - arm64 + - arm + goarm: + - "7" + ignore: + # Windows ARM (32-bit) not commonly used + - goos: windows + goarch: arm + # macOS ARM (32-bit) doesn't exist + - goos: darwin + goarch: arm + ldflags: + - -s -w + +archives: + - id: default + formats: + - tar.gz + format_overrides: + - goos: windows + formats: + - zip + name_template: >- + {{ .ProjectName }}_ + {{- .Version }}_ + {{- .Os }}_ + {{- .Arch }} + {{- if .Arm }}v{{ .Arm }}{{ end }} + files: + - README.md + - LICENSE + +checksum: + name_template: "checksums.txt" + algorithm: sha256 + +changelog: + sort: asc + filters: + exclude: + - "^docs:" + - "^test:" + - "^ci:" + - "^chore:" + - Merge pull request + - Merge branch + +release: + github: + owner: '{{ envOrDefault "GITHUB_REPOSITORY_OWNER" "" }}' + name: protonvpn-wg-confgen + draft: false + prerelease: auto + mode: replace + name_template: "v{{.Version}}" diff --git a/protonvpn-wg-confgen/API_REFERENCE.md b/protonvpn-wg-confgen/API_REFERENCE.md new file mode 100644 index 0000000..130f767 --- /dev/null +++ b/protonvpn-wg-confgen/API_REFERENCE.md @@ -0,0 +1,149 @@ +# API Reference Implementation + +This project's API integration was developed by reverse-engineering ProtonVPN's authentication and VPN APIs. The implementation is based on patterns from these official Proton libraries: + +## Authentication (SRP Protocol) +- **[ProtonMail/proton-python-client](https://github.com/ProtonMail/proton-python-client)** - Python implementation of Proton's SRP authentication + - Reference for: `/auth/info`, `/auth`, `/auth/2fa`, `/auth/refresh` endpoints + - SRP protocol implementation patterns +- **[ProtonMail/go-srp](https://github.com/ProtonMail/go-srp)** - Go SRP library (direct dependency) + +## VPN API +- **[ProtonVPN/python-proton-vpn-api-core](https://github.com/ProtonVPN/python-proton-vpn-api-core)** - Official Python VPN API client + - Reference for: `/vpn/v1/certificate`, `/vpn/v1/logicals`, `/vpn/v1/sessions` endpoints + - Server filtering and selection patterns + - Certificate request format (`Duration`, `Features`) + +## Key Generation +- **[ProtonVPN/go-vpn-lib](https://github.com/ProtonVPN/go-vpn-lib)** - Ed25519 to X25519 key conversion (direct dependency) + +## Client Version +- **[ProtonVPN/proton-vpn-gtk-app](https://github.com/ProtonVPN/proton-vpn-gtk-app)** - Official Linux client + - Source for `x-pm-appversion` header value (fetched dynamically at build time) + +## API Endpoints Used + +| Endpoint | Method | Description | +|----------|--------|-------------| +| `/core/v4/auth/info` | POST | Get SRP authentication parameters | +| `/core/v4/auth` | POST | Authenticate with SRP proofs | +| `/core/v4/auth/2fa` | POST | Submit 2FA code for session upgrade | +| `/auth/refresh` | POST | Refresh session tokens | +| `/vpn/v1/certificate` | POST | Generate WireGuard certificate | +| `/vpn/v1/logicals` | GET | List available VPN servers | + +## Certificate Request Format + +The certificate request to `/vpn/v1/certificate` uses the following format: + +```json +{ + "ClientPublicKey": "", + "ClientPublicKeyMode": "EC", + "Mode": "persistent", + "DeviceName": "", + "Duration": " min", + "Features": { + "NetShieldLevel": 0, + "RandomNAT": false, + "PortForwarding": false, + "SplitTCP": true + } +} +``` + +### Feature Keys + +| Key | Type | Description | +|-----|------|-------------| +| `NetShieldLevel` | int | NetShield ad/malware blocking (0=off, 1=malware, 2=ads+malware) | +| `RandomNAT` | bool | Moderate NAT / Random NAT for gaming | +| `PortForwarding` | bool | Port forwarding support | +| `SplitTCP` | bool | VPN Accelerator (performance optimization) | + +## API Response Codes + +**Official sources:** +- [ProtonMail/protoncore_android - ResponseCodes.kt](https://github.com/ProtonMail/protoncore_android/blob/main/network/domain/src/main/kotlin/me/proton/core/network/domain/ResponseCodes.kt) - Kotlin constants (authoritative) +- [ProtonMail/proton-python-client - README.md](https://github.com/ProtonMail/proton-python-client#error-handling) - Python client error handling +- [ProtonMail/proton-python-client - api.py](https://github.com/ProtonMail/proton-python-client/blob/master/proton/api.py) - Python API implementation + +### Success Codes +| Code | Constant | Meaning | +|------|----------|---------| +| 1000 | OK | Success | +| 1001 | - | Success (multi-status) | + +### Authentication Errors +| Code | Constant | Meaning | +|------|----------|---------| +| 8002 | PASSWORD_WRONG | Incorrect password | +| 8100 | AUTH_SWITCH_TO_SSO | Switch to SSO authentication | +| 8101 | AUTH_SWITCH_TO_SRP | Switch to SRP authentication | +| 9001 | HUMAN_VERIFICATION_REQUIRED | CAPTCHA/human verification required | +| 9002 | DEVICE_VERIFICATION_REQUIRED | Device verification required | +| 9101 | SCOPE_REAUTH_LOCKED | Scope re-authentication locked | +| 9102 | SCOPE_REAUTH_PASSWORD | Scope re-authentication requires password | + +### Account Errors +| Code | Constant | Meaning | +|------|----------|---------| +| 10001 | ACCOUNT_FAILED_GENERIC | Generic account failure | +| 10002 | ACCOUNT_DELETED | Account has been deleted | +| 10003 | ACCOUNT_DISABLED | Account has been disabled | + +### Version Errors +| Code | Constant | Meaning | +|------|----------|---------| +| 5003 | APP_VERSION_BAD | App version no longer supported | +| 5005 | API_VERSION_INVALID | API version invalid | +| 5099 | APP_VERSION_NOT_SUPPORTED_FOR_EXTERNAL_ACCOUNTS | App version not supported for external accounts | + +### Other Errors +| Code | Constant | Meaning | +|------|----------|---------| +| 6001 | BODY_PARSE_FAILURE | Request body parse failure | +| 12081 | USER_CREATE_NAME_INVALID | Invalid username during creation | +| 12087 | USER_CREATE_TOKEN_INVALID | Invalid token during user creation | + +### VPN-Specific Codes (observed, not in official docs) +| Code | Meaning | Notes | +|------|---------|-------| +| 9100 | 2FA required for VPN | VPN certificate endpoint requires 2FA-authenticated session | +| 10013 | Mailbox password required | Legacy 2-password mode (proton-python-client says "RefreshToken invalid") | + +**Note:** Codes 9100 and 10013 were observed during VPN operations but are not documented in the official protoncore_android library. Their meanings may vary by context. + +## Required Headers + +All authenticated requests require these headers: + +``` +Authorization: Bearer +x-pm-uid: +x-pm-appversion: linux-vpn@X.Y.Z +User-Agent: ProtonVPN/X.Y.Z (Linux; Ubuntu) +Content-Type: application/json +``` + +**Important**: Using a web client version (like `web-vpn-settings@X.Y.Z`) may trigger CAPTCHA challenges. Always use the Linux client version format. + +## Token Refresh + +The token refresh endpoint expects: + +```json +{ + "ResponseType": "token", + "GrantType": "refresh_token", + "RefreshToken": "", + "RedirectURI": "http://protonmail.ch" +} +``` + +## Local Reference Libraries + +For debugging and verification, reference implementations are cloned in `.debug-libs/`: +- `proton-python-client` - SRP authentication reference +- `python-proton-vpn-api-core` - VPN API reference +- `proton-vpn-gtk-app` - Linux client reference diff --git a/protonvpn-wg-confgen/LICENSE b/protonvpn-wg-confgen/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/protonvpn-wg-confgen/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/protonvpn-wg-confgen/Makefile b/protonvpn-wg-confgen/Makefile new file mode 100644 index 0000000..b475548 --- /dev/null +++ b/protonvpn-wg-confgen/Makefile @@ -0,0 +1,89 @@ +.PHONY: build build-all clean test fmt vet lint install vendor run dev show-version + +BINARY_NAME=protonvpn-wg-confgen +BUILD_DIR=build +CMD_DIR=cmd/protonvpn-wg +MODULE=protonvpn-wg-confgen + +# Fetch latest ProtonVPN Linux client version from GitHub (with fallback) +PROTON_VERSION_URL=https://raw.githubusercontent.com/ProtonVPN/proton-vpn-gtk-app/stable/versions.yml +PROTON_VERSION ?= $(shell curl -sf "$(PROTON_VERSION_URL)" 2>/dev/null | head -1 | cut -d' ' -f2 || echo "4.13.1") + +# ldflags to inject version at build time +LDFLAGS=-ldflags "-X '$(MODULE)/internal/constants.AppVersion=linux-vpn@$(PROTON_VERSION)' \ + -X '$(MODULE)/internal/constants.UserAgent=ProtonVPN/$(PROTON_VERSION) (Linux; Ubuntu)'" + +# Build the binary +build: + @echo "Building $(BINARY_NAME) with ProtonVPN client version $(PROTON_VERSION)..." + @mkdir -p $(BUILD_DIR) + @go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME) $(CMD_DIR)/main.go + +# Build for multiple platforms +build-all: + @echo "Building for multiple platforms with ProtonVPN client version $(PROTON_VERSION)..." + @mkdir -p $(BUILD_DIR) + @echo " Linux amd64..." + @GOOS=linux GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 $(CMD_DIR)/main.go + @echo " Linux arm64..." + @GOOS=linux GOARCH=arm64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm64 $(CMD_DIR)/main.go + @echo " Linux arm..." + @GOOS=linux GOARCH=arm go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm $(CMD_DIR)/main.go + @echo " macOS amd64..." + @GOOS=darwin GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64 $(CMD_DIR)/main.go + @echo " macOS arm64..." + @GOOS=darwin GOARCH=arm64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 $(CMD_DIR)/main.go + @echo " Windows amd64..." + @GOOS=windows GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe $(CMD_DIR)/main.go + @echo " Windows arm64..." + @GOOS=windows GOARCH=arm64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-windows-arm64.exe $(CMD_DIR)/main.go + @echo "Done!" + +# Clean build artifacts +clean: + @echo "Cleaning..." + @rm -rf $(BUILD_DIR) + @rm -f $(BINARY_NAME) + +# Run tests +test: + @echo "Running tests..." + @go test -v ./... + +# Format code +fmt: + @echo "Formatting code..." + @go fmt ./... + +# Run go vet +vet: + @echo "Running go vet..." + @go vet ./... + +# Run golangci-lint (requires golangci-lint to be installed) +lint: + @echo "Running linter..." + @golangci-lint run + +# Install the binary +install: build + @echo "Installing $(BINARY_NAME)..." + @cp $(BUILD_DIR)/$(BINARY_NAME) $(GOPATH)/bin/$(BINARY_NAME) + +# Update vendor directory +vendor: + @echo "Updating vendor..." + @go mod vendor + +# Run the application +run: build + @./$(BUILD_DIR)/$(BINARY_NAME) $(ARGS) + +# Development build with race detector +dev: + @echo "Building with race detector and ProtonVPN client version $(PROTON_VERSION)..." + @go build -race $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-dev $(CMD_DIR)/main.go + +# Show current ProtonVPN version that would be used +show-version: + @echo "ProtonVPN client version: $(PROTON_VERSION)" diff --git a/protonvpn-wg-confgen/README.md b/protonvpn-wg-confgen/README.md new file mode 100644 index 0000000..6cd0a6e --- /dev/null +++ b/protonvpn-wg-confgen/README.md @@ -0,0 +1,326 @@ +# ProtonVPN WireGuard Config Generate + +[![CI](https://github.com/hatemosphere/protonvpn-wg-confgen/actions/workflows/ci.yml/badge.svg)](https://github.com/hatemosphere/protonvpn-wg-confgen/actions/workflows/ci.yml) +[![Release](https://img.shields.io/github/v/release/hatemosphere/protonvpn-wg-confgen?include_prereleases)](https://github.com/hatemosphere/protonvpn-wg-confgen/releases/latest) +[![Go Report Card](https://goreportcard.com/badge/github.com/hatemosphere/protonvpn-wg-confgen)](https://goreportcard.com/report/github.com/hatemosphere/protonvpn-wg-confgen) +[![License: GPL-3.0](https://img.shields.io/badge/License-GPL--3.0-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) + +A Go program that generates WireGuard configuration files for ProtonVPN servers with automatic selection of the best servers from specified countries with support of generic filters. + +## Motivation + +I wanted to automatically rotate VPN servers on my private HTPC Linux host running WireGuard, and since I'm already paying for a Proton bundle subscription, why not just use theirs? Unfortunately, as of the time of writing, they didn't have a good programmatic headless way to generate WireGuard profiles, so I did my research and reverse-engineered their APIs (which was a pain in the butt) and created this. The idea is to run this code as a daemon and restart the WireGuard client on profile file change. + +## Features + +- Authenticates with ProtonVPN using username/password +- Opnionally persists and refreshes login session, to function in headless mode after entering password once +- Supports 2FA authentication (TOTP only, no FIDO2/security keys) +- Creates persistent WireGuard configurations (visible in ProtonVPN dashboard) +- Automatically selects the best server (highest score, lowest load) from specified countries +- Supports both Free tier and paid tier servers (Plus and ProtonMail) +- Filters servers by features (P2P support, Secure Core) +- Generates WireGuard configuration files +- Supports VPN accelerator feature +- IPv6 support + +## Installation + +1. Clone the repository: +```bash +git clone https://github.com/hatemosphere/protonvpn-wg-confgen +cd protonvpn-wg-confgen +``` + +2. Build the program: +```bash +make build +``` + +Or manually with Go: +```bash +go build -o build/protonvpn-wg-confgen cmd/protonvpn-wg/main.go +``` + +## Usage + +```bash +./build/protonvpn-wg-confgen -username -countries [options] +``` + +### Options + +- `-username`: ProtonVPN username (optional, will prompt if not provided) +- `-countries`: Comma-separated list of country codes (e.g., US,NL,CH) **[Required]** +- `-output`: Output WireGuard configuration file (default: protonvpn.conf) +- `-ipv6`: Enable IPv6 support (default: false) +- `-dns`: Comma-separated list of DNS servers (defaults based on IPv6 setting) +- `-allowed-ips`: Comma-separated list of allowed IPs (defaults based on IPv6 setting) +- `-accelerator`: Enable VPN accelerator (default: true) +- `-api-url`: ProtonVPN API URL (default: https://vpn-api.proton.me) +- `-p2p-only`: Use only P2P-enabled servers (default: true) +- `-secure-core`: Use only Secure Core servers for multi-hop VPN (default: false) +- `-free-only`: Use only Free tier servers (tier 0) (default: false) +- `-device-name`: Device name for WireGuard config (auto-generated if empty) +- `-debug`: Enable debug output showing all filtered servers (default: false) +- `-duration`: Certificate duration (default: 365d). Examples: 30m, 24h, 7d, 1h30m. Maximum: 365d +- `-clear-session`: Clear saved session and force re-authentication +- `-no-session`: Don't save or use session persistence +- `-force-refresh`: Force session refresh even if not close to expiration (requires re-authentication) +- `-session-duration`: Session cache duration (default: 0 = use API expiration). Examples: 12h, 24h, 7d. Max: 30d + +### Examples + +1. Generate config for best P2P server in US or Netherlands: +```bash +./build/protonvpn-wg-confgen -username myusername -countries US,NL +``` + +2. Generate config with custom DNS and output file: +```bash +./build/protonvpn-wg-confgen -username myusername -countries CH,DE -dns 1.1.1.1,8.8.8.8 -output switzerland.conf +``` + +3. Disable VPN accelerator: +```bash +./build/protonvpn-wg-confgen -username myusername -countries US -accelerator=false +``` + +4. Generate config with 30-day duration: +```bash +./build/protonvpn-wg-confgen -username myusername -countries US -duration 30d +``` + +5. Generate config without saving session (always prompt for password): +```bash +./build/protonvpn-wg-confgen -username myusername -countries US -no-session +``` + +6. Use session with 24-hour expiration: +```bash +./build/protonvpn-wg-confgen -username myusername -countries US -session-duration 24h +``` + +7. Enable IPv6 support: +```bash +./build/protonvpn-wg-confgen -username myusername -countries US -ipv6 +``` + +8. Use Secure Core servers for enhanced privacy: +```bash +./build/protonvpn-wg-confgen -username myusername -countries NL,US -secure-core +``` + +9. Debug mode to see all available servers: +```bash +./build/protonvpn-wg-confgen -username myusername -countries US -debug +``` + +10. Use Free tier servers only: +```bash +./build/protonvpn-wg-confgen -username myusername -countries US,NL -free-only +``` + +## IPv6 Support + +By default, the tool generates IPv4-only configurations. When you enable IPv6 with the `-ipv6` flag: + +- **Interface Address**: Both IPv4 (10.2.0.2/32) and IPv6 (2a07:b944::2:2/128) addresses are assigned +- **DNS Servers**: IPv4 DNS (10.2.0.1) and IPv6 DNS (2a07:b944::2:1) - both ProtonVPN's internal DNS servers +- **Allowed IPs**: Both IPv4 (0.0.0.0/0) and IPv6 (::/0) routes are included + +You can override the defaults by explicitly specifying `-dns` and `-allowed-ips` flags. + +## Secure Core + +Secure Core is ProtonVPN's premium feature that routes your traffic through multiple servers before leaving the VPN network: + +- First hop: Through secure servers in privacy-friendly countries (Switzerland, Iceland, Sweden) +- Second hop: To your chosen destination country +- Provides additional protection against network-based attacks +- Use the `-secure-core` flag to enable this feature +- Note: Secure Core servers may have higher latency due to the multi-hop routing + +**Important Notes:** +- Secure Core servers don't support P2P, so P2P filtering is automatically disabled when using `-secure-core` +- The country filter always applies to **exit countries** - where your traffic appears to come from +- Server names show both entry and exit countries (e.g., "IS-NL#1" = Iceland → Netherlands) +- Entry countries for Secure Core are always privacy-friendly: Switzerland (CH), Iceland (IS), Sweden (SE) + +## Authentication + +**Important:** This tool only works with Proton accounts configured in [Single Password Mode](https://proton.me/support/single-password). This is the default for all new Proton accounts. If your account uses the legacy 2-password mode (separate login and mailbox passwords), you'll need to switch to single password mode first. + +The program supports the following authentication methods: + +1. **Username/Password**: Enter your ProtonVPN credentials +2. **2FA (TOTP only)**: If enabled, you'll be prompted for your 6-digit authenticator code + +**Important 2FA Limitation:** This tool only supports **TOTP-based 2FA** (authenticator apps like Google Authenticator, Authy, 1Password, etc.). **FIDO2/WebAuthn security keys are NOT supported** because they require browser/platform APIs for the challenge-response protocol. + +If you use a security key as your only 2FA method, you have two options: +- Add TOTP as an additional 2FA method in your [Proton account security settings](https://account.proton.me/u/0/vpn/account-password) +- Use a security key that also supports TOTP (like YubiKey with Yubico Authenticator) + +### Session Persistence + +The program saves your authentication session to avoid re-entering credentials: +- Sessions are stored in `~/.protonvpn-session.json` with secure permissions (0600) +- ProtonVPN sessions expire after 30 days (from API `ExpiresIn` field) +- Session duration is configurable with `-session-duration` (default: 0 = use API's 30 days) +- Custom durations are capped at the API's expiration time +- Sessions show time until expiration when reused +- Sessions are automatically verified before use +- Sessions automatically refresh when less than 7 days remain +- Use `-clear-session` flag to force re-authentication +- Use `-force-refresh` flag to force refresh even if not expiring soon +- Use `-no-session` flag to disable session persistence entirely +- Sessions are user-specific and won't be used for different usernames + +## Using the Generated Configuration + +Once you have the WireGuard configuration file, you can use it with any WireGuard client: + +### Linux +```bash +sudo wg-quick up ./protonvpn.conf +``` + +### macOS (with WireGuard installed) +```bash +sudo wg-quick up ./protonvpn.conf +``` + +### Windows/GUI clients +Import the configuration file into your WireGuard client. + +## Server Tier Support + +By default, the tool excludes Free tier servers and only uses paid tier servers (Plus and ProtonMail): +- **Free tier (tier 0)**: Available with `-free-only` flag. Limited server selection, no P2P support +- **Plus tier (tier 2)**: Default. Full feature support including P2P and Secure Core +- **ProtonMail tier (tier 3)**: Default. Included with Proton bundle subscriptions + +**Important Notes:** +- When using `-free-only`, P2P filtering is automatically disabled since Free servers don't support P2P +- Free tier servers have limited availability and may have higher load +- Secure Core requires Plus or higher subscription + +## Requirements + +- Go 1.25 or higher +- ProtonVPN account (Free tier or paid subscription) + +## Security Notes + +- The program generates a new WireGuard private key for each run +- Configuration files contain sensitive information and are saved with 0600 permissions +- Never share your WireGuard configuration files +- Persistent configurations appear in your ProtonVPN dashboard and can be revoked there +- Certificates are valid for the specified duration (default: 365 days, max: 365 days) + +## Project Structure + +``` +. +├── cmd/ +│ └── protonvpn-wg/ # Main application entry point +│ └── main.go # CLI entry point +├── internal/ # Private application code +│ ├── api/ # API types and data structures +│ │ └── types.go # ProtonVPN API response types +│ ├── auth/ # Authentication logic +│ │ ├── auth.go # SRP authentication implementation +│ │ ├── errors.go # Custom error types +│ │ └── session.go # Session management and refresh +│ ├── config/ # Configuration handling +│ │ ├── flags.go # Command-line flag parsing +│ │ └── types.go # Config struct and validation +│ ├── constants/ # Application constants +│ │ ├── api.go # API endpoints and headers +│ │ ├── defaults.go # Default configuration values +│ │ ├── session.go # Session-related constants +│ │ └── wireguard.go # WireGuard network constants +│ └── vpn/ # VPN functionality +│ ├── client.go # Certificate generation +│ └── servers.go # Server selection logic +├── pkg/ # Public packages +│ ├── timeutil/ # Time and duration utilities +│ │ ├── formatter.go # Duration formatting +│ │ └── parser.go # Duration parsing +│ ├── validation/ # Input validation +│ │ └── validation.go # Username and country code validation +│ └── wireguard/ # WireGuard configuration +│ ├── config.go # Config file generation +│ └── config_test.go # Config generation tests +├── vendor/ # Vendored dependencies +├── Makefile # Build automation +├── go.mod # Go module definition +├── go.sum # Module checksums +└── README.md # This file +``` + +## Development + +```bash +# Format code +make fmt + +# Run tests +make test + +# Run linter (requires golangci-lint) +make lint + +# Build for multiple platforms +make build-all + +# Clean build artifacts +make clean +``` + +## Troubleshooting + +### CAPTCHA Verification Required (Error 9001) + +If you encounter "CAPTCHA verification required" error: + +1. **Login via ProtonVPN website first**: This can help establish your account as legitimate +2. **Try from a different IP**: VPN or residential IPs may work better than datacenter IPs +3. **Wait and retry**: Sometimes waiting a few hours helps +4. **Use saved sessions**: Once authenticated, sessions are saved to avoid repeated CAPTCHA challenges + +### App Version Errors (Error 5003) + +If you see "This version of the app is no longer supported": +- The app version is automatically fetched from ProtonVPN's GitHub at build time +- Rebuild with `make build` to get the latest version +- Override manually if needed: `make build PROTON_VERSION=X.Y.Z` +- Check current version: `make show-version` + +### Two-Password Mode Error (Code 10013) + +If you see "unexpected mailbox password request - account might still be in 2-password mode": +- Your Proton account is using the legacy 2-password mode (separate login and mailbox passwords) +- This tool only supports [Single Password Mode](https://proton.me/support/single-password) +- To switch: Go to Proton account settings → Security → Password mode → Switch to single password +- Note: Single password mode is the default for all new Proton accounts since ~2020 + +### 2FA Required for VPN (Error 9100) + +If authentication succeeds but you get error 9100 when getting the VPN certificate: +- Your account has 2FA enabled, but ProtonVPN's device trust mechanism allowed login without 2FA +- The VPN certificate endpoint requires a session that was authenticated with 2FA +- **Solution**: Run with `-clear-session` flag to force re-authentication, which should prompt for 2FA +- If 2FA prompt still doesn't appear, try from a different IP/network to bypass device trust +- This can also occur if your account uses 2-password mode (see error 10013 above) + +## API Reference + +For detailed API documentation including endpoints, request formats, response codes, and reference implementations, see [API_REFERENCE.md](API_REFERENCE.md). + +## License + +This project is licensed under the [GNU General Public License v3.0](LICENSE). + +This is required because the project uses [ProtonVPN/go-vpn-lib](https://github.com/ProtonVPN/go-vpn-lib) which is licensed under GPL-3.0. diff --git a/protonvpn-wg-confgen/cmd/protonvpn-wg/main.go b/protonvpn-wg-confgen/cmd/protonvpn-wg/main.go new file mode 100644 index 0000000..90f6caa --- /dev/null +++ b/protonvpn-wg-confgen/cmd/protonvpn-wg/main.go @@ -0,0 +1,104 @@ +// Package main provides the command-line interface for generating ProtonVPN WireGuard configurations. +package main + +import ( + "fmt" + "os" + "strings" + + "protonvpn-wg-confgen/internal/api" + "protonvpn-wg-confgen/internal/auth" + "protonvpn-wg-confgen/internal/config" + "protonvpn-wg-confgen/internal/vpn" + "protonvpn-wg-confgen/pkg/wireguard" + + "github.com/ProtonVPN/go-vpn-lib/ed25519" +) + +func main() { + if err := run(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } +} + +func run() error { + // Parse configuration + cfg, err := config.Parse() + if err != nil { + config.PrintUsage() + return err + } + + // Authenticate + authClient := auth.NewClient(cfg) + session, err := authClient.Authenticate() + if err != nil { + return fmt.Errorf("authentication failed: %w", err) + } + fmt.Println("Authentication successful!") + + // Generate key pair + keyPair, err := ed25519.NewKeyPair() + if err != nil { + return fmt.Errorf("failed to generate key pair: %w", err) + } + cfg.ClientPrivateKey = keyPair.ToX25519Base64() + + // Create VPN client + vpnClient := vpn.NewClient(cfg, session) + + // Get VPN certificate + vpnInfo, err := vpnClient.GetCertificate(keyPair) + if err != nil { + return fmt.Errorf("failed to get VPN certificate: %w", err) + } + + // Get server list + servers, err := vpnClient.GetServers() + if err != nil { + return fmt.Errorf("failed to get servers: %w", err) + } + + // Select best server + selector := vpn.NewServerSelector(cfg) + server, err := selector.SelectBest(servers) + if err != nil { + return err + } + + // Build feature list string + features := api.GetFeatureNames(server.Features) + featureStr := "" + if len(features) > 0 { + featureStr = fmt.Sprintf(", Features: %s", strings.Join(features, ", ")) + } + + fmt.Printf("Selected server: %s (Country: %s, City: %s, Tier: %s, Load: %d%%, Score: %.2f, Servers: %d%s)\n", + server.Name, server.ExitCountry, server.City, api.GetTierName(server.Tier), + server.Load, server.Score, len(server.Servers), featureStr) + + // Get best physical server + physicalServer := vpn.GetBestPhysicalServer(server) + if physicalServer == nil { + return fmt.Errorf("no physical servers available") + } + + // Generate WireGuard configuration + generator := wireguard.NewConfigGenerator(cfg) + if err := generator.Generate(server, physicalServer, cfg.ClientPrivateKey); err != nil { + return fmt.Errorf("failed to generate WireGuard config: %w", err) + } + + fmt.Printf("WireGuard configuration written to: %s\n", cfg.OutputFile) + + // Note about persistence + if vpnInfo.DeviceName != "" { + fmt.Printf("Device name: %s (visible in ProtonVPN dashboard)\n", vpnInfo.DeviceName) + } + + // Show final success + fmt.Printf("\nSuccessfully generated config for %s\n", server.ExitCountry) + + return nil +} diff --git a/protonvpn-wg-confgen/go.mod b/protonvpn-wg-confgen/go.mod new file mode 100644 index 0000000..7630c65 --- /dev/null +++ b/protonvpn-wg-confgen/go.mod @@ -0,0 +1,19 @@ +module protonvpn-wg-confgen + +go 1.25.6 + +require ( + github.com/ProtonMail/go-srp v0.0.7 + github.com/ProtonVPN/go-vpn-lib v0.0.0-20260122061324-3e8ad1be9349 + golang.org/x/term v0.39.0 +) + +require ( + github.com/ProtonMail/bcrypt v0.0.0-20211005172633-e235017c1baf // indirect + github.com/ProtonMail/go-crypto v1.3.0 // indirect + github.com/cloudflare/circl v1.6.2 // indirect + github.com/cronokirby/saferith v0.33.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + golang.org/x/crypto v0.47.0 // indirect + golang.org/x/sys v0.40.0 // indirect +) diff --git a/protonvpn-wg-confgen/go.sum b/protonvpn-wg-confgen/go.sum new file mode 100644 index 0000000..025fd93 --- /dev/null +++ b/protonvpn-wg-confgen/go.sum @@ -0,0 +1,68 @@ +github.com/ProtonMail/bcrypt v0.0.0-20210511135022-227b4adcab57/go.mod h1:HecWFHognK8GfRDGnFQbW/LiV7A3MX3gZVs45vk5h8I= +github.com/ProtonMail/bcrypt v0.0.0-20211005172633-e235017c1baf h1:yc9daCCYUefEs69zUkSzubzjBbL+cmOXgnmt9Fyd9ug= +github.com/ProtonMail/bcrypt v0.0.0-20211005172633-e235017c1baf/go.mod h1:o0ESU9p83twszAU8LBeJKFAAMX14tISa0yk4Oo5TOqo= +github.com/ProtonMail/go-crypto v0.0.0-20230321155629-9a39f2531310/go.mod h1:8TI4H3IbrackdNgv+92dI+rhpCaLqM0IfpgCgenFvRE= +github.com/ProtonMail/go-crypto v1.3.0 h1:ILq8+Sf5If5DCpHQp4PbZdS1J7HDFRXz/+xKBiRGFrw= +github.com/ProtonMail/go-crypto v1.3.0/go.mod h1:9whxjD8Rbs29b4XWbB8irEcE8KHMqaR2e7GWU1R+/PE= +github.com/ProtonMail/go-srp v0.0.7 h1:Sos3Qk+th4tQR64vsxGIxYpN3rdnG9Wf9K4ZloC1JrI= +github.com/ProtonMail/go-srp v0.0.7/go.mod h1:giCp+7qRnMIcCvI6V6U3S1lDDXDQYx2ewJ6F/9wdlJk= +github.com/ProtonVPN/go-vpn-lib v0.0.0-20260122061324-3e8ad1be9349 h1:1BgRubBCnxoG9cA4vn3O9n1CPuzMRWC5tK9JcIYuAw4= +github.com/ProtonVPN/go-vpn-lib v0.0.0-20260122061324-3e8ad1be9349/go.mod h1:zNATEdp1+/2tD0ggij9aP55zXqKIkVT2/Wn2YE7FjLc= +github.com/bwesterb/go-ristretto v1.2.0/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= +github.com/cloudflare/circl v1.1.0/go.mod h1:prBCrKB9DV4poKZY1l9zBXg2QJY7mvgRvtMxxK7fi4I= +github.com/cloudflare/circl v1.6.2 h1:hL7VBpHHKzrV5WTfHCaBsgx/HGbBYlgrwvNXEVDYYsQ= +github.com/cloudflare/circl v1.6.2/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= +github.com/cronokirby/saferith v0.33.0 h1:TgoQlfsD4LIwx71+ChfRcIpjkw+RPOapDEVxa+LhwLo= +github.com/cronokirby/saferith v0.33.0/go.mod h1:QKJhjoqUtBsXCAVEjw38mFqoi7DebT7kthcD7UzbnoA= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= +golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY= +golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/yaml.v3 v3.0.0-20220521103104-8f96da9f5d5e h1:3i3ny04XV6HbZ2N1oIBw1UBYATHAOpo4tfTF83JM3Z0= +gopkg.in/yaml.v3 v3.0.0-20220521103104-8f96da9f5d5e/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/protonvpn-wg-confgen/internal/api/types.go b/protonvpn-wg-confgen/internal/api/types.go new file mode 100644 index 0000000..a25a3b9 --- /dev/null +++ b/protonvpn-wg-confgen/internal/api/types.go @@ -0,0 +1,165 @@ +// Package api defines the data structures for ProtonVPN API responses. +package api + +// AuthInfoResponse represents the response from the auth info endpoint +type AuthInfoResponse struct { + Code int `json:"Code"` + Version int `json:"Version"` + Modulus string `json:"Modulus"` + ServerEphemeral string `json:"ServerEphemeral"` + Salt string `json:"Salt"` + SRPSession string `json:"SRPSession"` + TwoFA struct { + Enabled int `json:"Enabled"` + TOTP int `json:"TOTP"` + } `json:"2FA"` +} + +// AuthRequest represents the authentication request payload +type AuthRequest struct { + Username string `json:"Username"` + ClientEphemeral string `json:"ClientEphemeral"` + ClientProof string `json:"ClientProof"` + SRPSession string `json:"SRPSession"` + TwoFactorCode string `json:"TwoFactorCode,omitempty"` +} + +// Session represents a ProtonVPN session +type Session struct { + Code int `json:"Code"` + AccessToken string `json:"AccessToken"` + RefreshToken string `json:"RefreshToken"` + TokenType string `json:"TokenType"` + Scopes []string `json:"Scopes"` + UID string `json:"UID"` + UserID string `json:"UserID"` + EventID string `json:"EventID"` + ServerProof string `json:"ServerProof"` + PasswordMode int `json:"PasswordMode"` + ExpiresIn int `json:"ExpiresIn"` // Session expiration in seconds + TwoFA struct { + Enabled int `json:"Enabled"` + TOTP int `json:"TOTP"` + } `json:"2FA"` +} + +// VPNInfo represents VPN certificate information +type VPNInfo struct { + Code int `json:"Code"` + Error string `json:"Error,omitempty"` + SerialNumber string `json:"SerialNumber"` + ClientKeyFingerprint string `json:"ClientKeyFingerprint"` + ClientKey string `json:"ClientKey"` + Certificate string `json:"Certificate"` + ExpirationTime int64 `json:"ExpirationTime"` + RefreshTime int64 `json:"RefreshTime"` + Mode string `json:"Mode"` + DeviceName string `json:"DeviceName"` + ServerPublicKeyMode string `json:"ServerPublicKeyMode"` + ServerPublicKey string `json:"ServerPublicKey"` + Features struct { + Bouncing bool `json:"bouncing"` + ModerateNAT bool `json:"moderate-nat"` + NetshieldLevel int `json:"netshield-level"` + PortForwarding bool `json:"port-forwarding"` + VPNAccelerator bool `json:"vpn-accelerator"` + } `json:"Features"` +} + +// LogicalServer represents a ProtonVPN logical server +type LogicalServer struct { + ID string `json:"ID"` + Name string `json:"Name"` + EntryCountry string `json:"EntryCountry"` + ExitCountry string `json:"ExitCountry"` + Domain string `json:"Domain"` + Tier int `json:"Tier"` + Features int `json:"Features"` + Region string `json:"Region"` + City string `json:"City"` + Score float64 `json:"Score"` + Load int `json:"Load"` + Status int `json:"Status"` + Servers []PhysicalServer `json:"Servers"` + HostCountry string `json:"HostCountry"` + Location struct { + Lat float64 `json:"Lat"` + Long float64 `json:"Long"` + } `json:"Location"` +} + +// PhysicalServer represents a physical VPN server +type PhysicalServer struct { + ID string `json:"ID"` + EntryIP string `json:"EntryIP"` + ExitIP string `json:"ExitIP"` + Domain string `json:"Domain"` + Status int `json:"Status"` + Label string `json:"Label"` + X25519PublicKey string `json:"X25519PublicKey"` + Generation int `json:"Generation"` + ServicesDownReason string `json:"ServicesDownReason"` +} + +// LogicalsResponse represents the response from the logicals endpoint +type LogicalsResponse struct { + Code int `json:"Code"` + LogicalServers []LogicalServer `json:"LogicalServers"` +} + +// Server feature constants +const ( + FeatureSecureCore = 1 + FeatureTor = 2 + FeatureP2P = 4 + FeatureStreaming = 8 + FeatureIPv6 = 16 +) + +// Server tier constants +const ( + TierFree = 0 + TierPlus = 2 + TierPM = 3 +) + +// Password mode constants +const ( + PasswordModeSingle = 1 + PasswordModeTwo = 2 +) + +// GetTierName returns a human-readable name for the server tier +func GetTierName(tier int) string { + switch tier { + case TierFree: + return "Free" + case TierPlus: + return "Plus" + case TierPM: + return "ProtonMail" + default: + return "Unknown" + } +} + +// GetFeatureNames returns a list of enabled features for a server +func GetFeatureNames(features int) []string { + var result []string + if features&FeatureSecureCore != 0 { + result = append(result, "SecureCore") + } + if features&FeatureTor != 0 { + result = append(result, "Tor") + } + if features&FeatureP2P != 0 { + result = append(result, "P2P") + } + if features&FeatureStreaming != 0 { + result = append(result, "Streaming") + } + if features&FeatureIPv6 != 0 { + result = append(result, "IPv6") + } + return result +} diff --git a/protonvpn-wg-confgen/internal/auth/auth.go b/protonvpn-wg-confgen/internal/auth/auth.go new file mode 100644 index 0000000..e5094f6 --- /dev/null +++ b/protonvpn-wg-confgen/internal/auth/auth.go @@ -0,0 +1,503 @@ +// Package auth handles ProtonVPN authentication using the SRP protocol. +package auth + +import ( + "bufio" + "bytes" + "crypto/tls" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" + + "protonvpn-wg-confgen/internal/api" + "protonvpn-wg-confgen/internal/config" + "protonvpn-wg-confgen/internal/constants" + "protonvpn-wg-confgen/pkg/timeutil" + + "github.com/ProtonMail/go-srp" + "golang.org/x/term" +) + +// Client handles ProtonVPN authentication +type Client struct { + config *config.Config + httpClient *http.Client + sessionStore *SessionStore +} + +// NewClient creates a new authentication client +func NewClient(cfg *config.Config) *Client { + return &Client{ + config: cfg, + sessionStore: NewSessionStore(), + httpClient: &http.Client{ + Timeout: 30 * time.Second, + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: false, + MinVersion: tls.VersionTLS12, + }, + }, + }, + } +} + +// handleSessionRefresh attempts to refresh a session and save it if successful +func (c *Client) handleSessionRefresh(savedSession *api.Session, reason string) (*api.Session, error) { + fmt.Println(reason) + refreshedSession, err := RefreshSession(c.httpClient, c.config.APIURL, savedSession) + if err != nil { + fmt.Printf("Token refresh failed: %v\n", err) + fmt.Println("Re-authenticating with password...") + fmt.Println("(Your trusted device status for MFA will be preserved)") + _ = c.sessionStore.Delete() + return nil, err + } + + fmt.Println("Session refreshed successfully!") + // Check if refresh token was rotated + if savedSession.RefreshToken != refreshedSession.RefreshToken { + fmt.Println("Refresh token was rotated") + } + + // Save the refreshed session + if !c.config.NoSession { + sessionDuration, _ := timeutil.ParseSessionDuration(c.config.SessionDuration) + if err := c.sessionStore.Save(refreshedSession, c.config.Username, sessionDuration); err != nil { + fmt.Printf("Warning: Failed to save refreshed session: %v\n", err) + } + } + + return refreshedSession, nil +} + +// tryExistingSession attempts to use an existing saved session +func (c *Client) tryExistingSession() (*api.Session, error) { + savedSession, timeUntilExpiry, err := c.sessionStore.Load(c.config.Username) + if err != nil { + fmt.Printf("Warning: Failed to load saved session: %v\n", err) + return nil, err + } + + if savedSession == nil { + return nil, nil + } + + // Determine what to do with the saved session + switch { + case c.config.ForceRefresh: + reason := fmt.Sprintf("Forcing session refresh (current session expires in %s)", timeutil.HumanizeDuration(timeUntilExpiry)) + return c.handleSessionRefresh(savedSession, reason) + + case timeUntilExpiry < time.Duration(constants.SessionRefreshDays)*24*time.Hour && timeUntilExpiry > 0: + reason := fmt.Sprintf("Session expires soon (in %s), attempting refresh...", timeutil.HumanizeDuration(timeUntilExpiry)) + return c.handleSessionRefresh(savedSession, reason) + + case VerifySession(c.httpClient, c.config.APIURL, savedSession): + fmt.Printf("Using saved session (expires in %s)\n", timeutil.HumanizeDuration(timeUntilExpiry)) + return savedSession, nil + + default: + fmt.Println("Saved session invalid, re-authenticating...") + _ = c.sessionStore.Delete() + return nil, nil + } +} + +// Authenticate performs the full authentication flow +func (c *Client) Authenticate() (*api.Session, error) { + if err := c.ensureUsername(); err != nil { + return nil, err + } + + // Try existing session unless clearing or disabled + if session := c.handleExistingSession(); session != nil { + return session, nil + } + + if err := c.ensurePassword(); err != nil { + return nil, err + } + + // Perform fresh authentication + session, err := c.performFreshAuth() + if err != nil { + return nil, err + } + + // Handle session scope upgrade if needed + if err := c.upgradeSessionIfNeeded(session); err != nil { + return nil, err + } + + c.saveSessionIfEnabled(session) + return session, nil +} + +// handleExistingSession handles session clearing or reuse +func (c *Client) handleExistingSession() *api.Session { + if c.config.ClearSession { + fmt.Println("Clearing saved session...") + _ = c.sessionStore.Delete() + return nil + } + + if c.config.NoSession { + return nil + } + + session, err := c.tryExistingSession() + if err == nil && session != nil { + return session + } + return nil +} + +// performFreshAuth performs SRP authentication and returns a new session +func (c *Client) performFreshAuth() (*api.Session, error) { + authInfo, err := c.getAuthInfo() + if err != nil { + return nil, fmt.Errorf("failed to get auth info: %w", err) + } + + clientProofs, err := c.generateSRPProofs(authInfo) + if err != nil { + return nil, err + } + + authReq := c.buildAuthRequest(authInfo, clientProofs) + + // Handle 2FA if needed + if authInfo.TwoFA.Enabled == constants.EnabledTrue && authInfo.TwoFA.TOTP == constants.EnabledTrue { + code, err := c.get2FACode() + if err != nil { + return nil, err + } + authReq["TwoFactorCode"] = code + } + + session, err := c.sendAuthRequest(authReq) + if err != nil { + return nil, err + } + + // Verify server proof + if session.ServerProof != base64.StdEncoding.EncodeToString(clientProofs.ExpectedServerProof) { + return nil, fmt.Errorf("server proof verification failed") + } + + return session, nil +} + +// generateSRPProofs generates SRP client proofs for authentication +func (c *Client) generateSRPProofs(authInfo *api.AuthInfoResponse) (*srp.Proofs, error) { + auth, err := srp.NewAuth( + authInfo.Version, + c.config.Username, + []byte(c.config.Password), + authInfo.Salt, + authInfo.Modulus, + authInfo.ServerEphemeral, + ) + if err != nil { + return nil, fmt.Errorf("failed to create SRP auth: %w", err) + } + + proofs, err := auth.GenerateProofs(2048) + if err != nil { + return nil, fmt.Errorf("failed to generate SRP proofs: %w", err) + } + return proofs, nil +} + +// buildAuthRequest builds the authentication request payload +func (c *Client) buildAuthRequest(authInfo *api.AuthInfoResponse, proofs *srp.Proofs) map[string]interface{} { + return map[string]interface{}{ + "Username": c.config.Username, + "ClientEphemeral": base64.StdEncoding.EncodeToString(proofs.ClientEphemeral), + "ClientProof": base64.StdEncoding.EncodeToString(proofs.ClientProof), + "SRPSession": authInfo.SRPSession, + "PersistentCookies": 0, + } +} + +// upgradeSessionIfNeeded upgrades session with 2FA if VPN scope is missing +func (c *Client) upgradeSessionIfNeeded(session *api.Session) error { + hasVPNScope, hasTwoFactorScope := c.checkSessionScopes(session) + + if hasVPNScope || !hasTwoFactorScope { + return nil + } + + fmt.Println("Session lacks VPN scope - 2FA verification required to upgrade session...") + code, err := c.get2FACode() + if err != nil { + return fmt.Errorf("failed to get 2FA code: %w", err) + } + + updatedScopes, err := c.submit2FA(session, code) + if err != nil { + return fmt.Errorf("2FA verification failed: %w", err) + } + session.Scopes = updatedScopes + fmt.Println("2FA verified - session upgraded with VPN scope") + return nil +} + +// checkSessionScopes checks if session has VPN and twofactor scopes +func (c *Client) checkSessionScopes(session *api.Session) (hasVPN, hasTwoFactor bool) { + for _, scope := range session.Scopes { + switch scope { + case "vpn": + hasVPN = true + case "twofactor": + hasTwoFactor = true + } + } + return +} + +// saveSessionIfEnabled saves the session if persistence is enabled +func (c *Client) saveSessionIfEnabled(session *api.Session) { + if c.config.NoSession { + return + } + + sessionDuration, err := timeutil.ParseSessionDuration(c.config.SessionDuration) + if err != nil { + fmt.Printf("Warning: Invalid session duration, using default: %v\n", err) + sessionDuration = 0 + } + + if err := c.sessionStore.Save(session, c.config.Username, sessionDuration); err != nil { + fmt.Printf("Warning: Failed to save session: %v\n", err) + } +} + +func (c *Client) ensureUsername() error { + if c.config.Username == "" { + fmt.Print("Username (without @protonmail.com): ") + reader := bufio.NewReader(os.Stdin) + username, err := reader.ReadString('\n') + if err != nil { + return fmt.Errorf("error reading username: %w", err) + } + c.config.Username = strings.TrimSpace(username) + if c.config.Username == "" { + return fmt.Errorf("username cannot be empty") + } + } + return nil +} + +func (c *Client) ensurePassword() error { + if c.config.Password == "" { + fmt.Print("Password: ") + passwordBytes, err := term.ReadPassword(int(os.Stdin.Fd())) + fmt.Println() + if err != nil { + return fmt.Errorf("error reading password: %w", err) + } + c.config.Password = string(passwordBytes) + } + return nil +} + +func (c *Client) get2FACode() (string, error) { + fmt.Print("2FA Code: ") + reader := bufio.NewReader(os.Stdin) + code, err := reader.ReadString('\n') + if err != nil { + return "", fmt.Errorf("error reading 2FA code: %w", err) + } + code = strings.TrimSpace(code) + + // Validate that code is numeric (TOTP codes are 6 digits) + if code == "" { + return "", fmt.Errorf("2FA code cannot be empty") + } + + for _, c := range code { + if c < '0' || c > '9' { + return "", fmt.Errorf("2FA code must be numeric (TOTP only).\n" + + "FIDO2/WebAuthn security keys are not supported.\n" + + "Please ensure you have TOTP (authenticator app) configured as your 2FA method") + } + } + + return code, nil +} + +func (c *Client) getAuthInfo() (*api.AuthInfoResponse, error) { + reqBody := map[string]interface{}{ + "Username": c.config.Username, + "Intent": "Proton", + } + + body, err := json.Marshal(reqBody) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, c.config.APIURL+"/core/v4/auth/info", bytes.NewBuffer(body)) + if err != nil { + return nil, err + } + + c.setHeaders(req) + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(respBody)) + } + + var authInfo api.AuthInfoResponse + if err := json.Unmarshal(respBody, &authInfo); err != nil { + return nil, fmt.Errorf("failed to parse auth info: %w", err) + } + + if authInfo.Code != CodeSuccess { + return nil, fmt.Errorf("failed to get auth info, code: %d", authInfo.Code) + } + + // Validate required fields + if authInfo.Modulus == "" { + return nil, fmt.Errorf("received empty modulus from auth info") + } + if authInfo.ServerEphemeral == "" { + return nil, fmt.Errorf("received empty server ephemeral from auth info") + } + + return &authInfo, nil +} + +func (c *Client) sendAuthRequest(authReq map[string]interface{}) (*api.Session, error) { + body, err := json.Marshal(authReq) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, c.config.APIURL+"/core/v4/auth", bytes.NewBuffer(body)) + if err != nil { + return nil, err + } + + c.setHeaders(req) + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("authentication HTTP error %d: %s", resp.StatusCode, string(respBody)) + } + + var session api.Session + if err := json.Unmarshal(respBody, &session); err != nil { + return nil, err + } + + // Handle mailbox password request (2-password mode) + // Code 10013 means the account uses legacy 2-password mode which requires a separate mailbox password + // VPN doesn't need mailbox decryption, but the auth flow requires completing it + if session.Code == CodeMailboxPasswordError { + return nil, fmt.Errorf("your account uses legacy 2-password mode which is not supported.\n" + + "Please switch to single-password mode:\n" + + " 1. Go to account.proton.me\n" + + " 2. Settings → All settings → Account and password → Passwords\n" + + " 3. Switch to 'One-password mode'\n" + + "This is recommended by Proton for most users and is required for this tool") + } + + if session.Code != CodeSuccess { + return nil, NewError(session.Code) + } + + return &session, nil +} + +func (c *Client) setHeaders(req *http.Request) { + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-pm-appversion", constants.AppVersion) + req.Header.Set("User-Agent", constants.UserAgent) +} + +// submit2FA submits a 2FA code to upgrade the session with additional scopes (like VPN) +func (c *Client) submit2FA(session *api.Session, code string) ([]string, error) { + reqBody := map[string]interface{}{ + "TwoFactorCode": code, + } + + body, err := json.Marshal(reqBody) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, c.config.APIURL+"/core/v4/auth/2fa", bytes.NewBuffer(body)) + if err != nil { + return nil, err + } + + // Need to include auth headers for 2FA upgrade + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", session.AccessToken)) + req.Header.Set("x-pm-uid", session.UID) + req.Header.Set("x-pm-appversion", constants.AppVersion) + req.Header.Set("User-Agent", constants.UserAgent) + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("2FA HTTP error %d: %s", resp.StatusCode, string(respBody)) + } + + // Parse response to get updated scopes + var twoFAResp struct { + Code int `json:"Code"` + Scopes []string `json:"Scopes"` + Error string `json:"Error,omitempty"` + } + if err := json.Unmarshal(respBody, &twoFAResp); err != nil { + return nil, fmt.Errorf("failed to parse 2FA response: %w", err) + } + + if twoFAResp.Code != CodeSuccess { + if twoFAResp.Error != "" { + return nil, fmt.Errorf("2FA failed (code %d): %s", twoFAResp.Code, twoFAResp.Error) + } + return nil, NewError(twoFAResp.Code) + } + + return twoFAResp.Scopes, nil +} diff --git a/protonvpn-wg-confgen/internal/auth/errors.go b/protonvpn-wg-confgen/internal/auth/errors.go new file mode 100644 index 0000000..ab93993 --- /dev/null +++ b/protonvpn-wg-confgen/internal/auth/errors.go @@ -0,0 +1,82 @@ +package auth + +import ( + "errors" + "fmt" + + "protonvpn-wg-confgen/internal/constants" +) + +// Error codes from ProtonVPN API +// Official source: github.com/ProtonMail/protoncore_android/.../ResponseCodes.kt +// See API_REFERENCE.md for full documentation. +const ( + CodeSuccess = constants.APICodeSuccess + CodeWrongPassword = 8002 // PASSWORD_WRONG: Incorrect password + CodeWrongPasswordFormat = 8004 // Password format is incorrect (observed) + CodeCaptchaRequired = 9001 // HUMAN_VERIFICATION_REQUIRED: CAPTCHA needed + Code2FARequiredForVPN = 9100 // VPN-specific: certificate endpoint requires 2FA session (not in official docs) + CodeAccountDeleted = 10002 // ACCOUNT_DELETED: Account has been deleted + CodeAccountDisabled = 10003 // ACCOUNT_DISABLED: Account has been disabled + CodeMailboxPasswordError = 10013 // Legacy 2-password mode / invalid refresh token (context-dependent) +) + +// Error represents an authentication error with ProtonVPN-specific error code +type Error struct { + Code int + Message string +} + +// Error implements the error interface +func (e Error) Error() string { + return e.Message +} + +// NewError creates a new authentication error from an API response code +func NewError(code int) error { + message := getErrorMessage(code) + return Error{ + Code: code, + Message: message, + } +} + +// getErrorMessage returns a human-readable error message for a given error code +func getErrorMessage(code int) string { + switch code { + case CodeWrongPassword: + return "incorrect username or password" + case CodeWrongPasswordFormat: + return "password format is incorrect" + case CodeCaptchaRequired: + return "CAPTCHA verification required" + case Code2FARequiredForVPN: + return "2FA required for VPN operations - your session was authenticated without 2FA (device trust). Use -clear-session to force re-authentication with 2FA" + case CodeAccountDeleted: + return "account has been deleted" + case CodeAccountDisabled: + return "account has been disabled" + case CodeMailboxPasswordError: + return "account uses legacy 2-password mode - please switch to single-password mode at account.proton.me" + default: + return fmt.Sprintf("authentication failed with code: %d", code) + } +} + +// IsAccountError checks if the error is an account status error (deleted or disabled) +func IsAccountError(err error) bool { + var authErr Error + if !errors.As(err, &authErr) { + return false + } + return authErr.Code == CodeAccountDeleted || authErr.Code == CodeAccountDisabled +} + +// IsCaptchaError checks if the error requires CAPTCHA verification +func IsCaptchaError(err error) bool { + var authErr Error + if !errors.As(err, &authErr) { + return false + } + return authErr.Code == CodeCaptchaRequired +} diff --git a/protonvpn-wg-confgen/internal/auth/session.go b/protonvpn-wg-confgen/internal/auth/session.go new file mode 100644 index 0000000..b21c88a --- /dev/null +++ b/protonvpn-wg-confgen/internal/auth/session.go @@ -0,0 +1,210 @@ +package auth + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "time" + + "protonvpn-wg-confgen/internal/api" + "protonvpn-wg-confgen/internal/constants" +) + +// SessionStore handles persistent session storage +type SessionStore struct { + filePath string +} + +// NewSessionStore creates a new session store +func NewSessionStore() *SessionStore { + homeDir, err := os.UserHomeDir() + if err != nil { + // Fallback to current directory + homeDir = "." + } + + return &SessionStore{ + filePath: filepath.Join(homeDir, constants.SessionFileName), + } +} + +// SavedSession represents a session with metadata +type SavedSession struct { + Session *api.Session `json:"session"` + Username string `json:"username"` + SavedAt time.Time `json:"saved_at"` + ExpiresAt time.Time `json:"expires_at"` +} + +// Save stores the session to disk +func (s *SessionStore) Save(session *api.Session, username string, duration time.Duration) error { + savedSession := &SavedSession{ + Session: session, + Username: username, + SavedAt: time.Now(), + } + + // Calculate expiration based on API response + apiExpiration := time.Now().Add(time.Duration(session.ExpiresIn) * time.Second) + + if duration == 0 { + // Use the API's expiration + savedSession.ExpiresAt = apiExpiration + } else { + // Use the user-specified duration, but cap it at API expiration + userExpiration := time.Now().Add(duration) + if userExpiration.After(apiExpiration) { + savedSession.ExpiresAt = apiExpiration + } else { + savedSession.ExpiresAt = userExpiration + } + } + + data, err := json.MarshalIndent(savedSession, "", " ") + if err != nil { + return fmt.Errorf("failed to marshal session: %w", err) + } + + err = os.WriteFile(s.filePath, data, constants.SessionFileMode) + if err != nil { + return fmt.Errorf("failed to write session file: %w", err) + } + + return nil +} + +// Load retrieves a saved session from disk +func (s *SessionStore) Load(username string) (*api.Session, time.Duration, error) { + data, err := os.ReadFile(s.filePath) + if err != nil { + if os.IsNotExist(err) { + return nil, 0, nil // No saved session + } + return nil, 0, fmt.Errorf("failed to read session file: %w", err) + } + + var savedSession SavedSession + err = json.Unmarshal(data, &savedSession) + if err != nil { + return nil, 0, fmt.Errorf("failed to unmarshal session: %w", err) + } + + // Check if session is for the same user + if savedSession.Username != username { + return nil, 0, nil + } + + // Check if session has expired + now := time.Now() + if now.After(savedSession.ExpiresAt) { + // Delete expired session + _ = s.Delete() + return nil, 0, nil + } + + // Calculate time until expiration + timeUntilExpiry := savedSession.ExpiresAt.Sub(now) + + return savedSession.Session, timeUntilExpiry, nil +} + +// Delete removes the saved session +func (s *SessionStore) Delete() error { + err := os.Remove(s.filePath) + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("failed to delete session file: %w", err) + } + return nil +} + +// GetPath returns the session file path +func (s *SessionStore) GetPath() string { + return s.filePath +} + +// RefreshSession attempts to refresh the session using the refresh token. +// It returns a new session with updated tokens if successful. +func RefreshSession(httpClient *http.Client, apiURL string, oldSession *api.Session) (*api.Session, error) { + // Based on proton-python-client/proton/api.py refresh() method + reqBody := map[string]interface{}{ + "ResponseType": "token", + "GrantType": "refresh_token", + "RefreshToken": oldSession.RefreshToken, + "RedirectURI": "http://protonmail.ch", + } + + body, err := json.Marshal(reqBody) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, apiURL+"/auth/refresh", bytes.NewBuffer(body)) + if err != nil { + return nil, err + } + + // Set standard headers + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-pm-appversion", constants.AppVersion) + req.Header.Set("User-Agent", constants.UserAgent) + + // Include auth headers for refresh + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", oldSession.AccessToken)) + req.Header.Set("x-pm-uid", oldSession.UID) + + resp, err := httpClient.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + if resp.StatusCode == http.StatusOK { + var session api.Session + if err := json.Unmarshal(respBody, &session); err != nil { + return nil, err + } + if constants.IsSuccessCode(session.Code) { + return &session, nil + } + } + + // If refresh fails, return error to trigger re-authentication + return nil, fmt.Errorf("refresh failed (status %d): %s", resp.StatusCode, string(respBody)) +} + +// VerifySession checks if a session is still valid by making a test API request. +func VerifySession(httpClient *http.Client, apiURL string, session *api.Session) bool { + // Make a simple request to verify the session + req, err := http.NewRequest(http.MethodGet, apiURL+"/vpn/v1/logicals", http.NoBody) + if err != nil { + return false + } + + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", session.AccessToken)) + req.Header.Set("x-pm-uid", session.UID) + req.Header.Set("x-pm-appversion", constants.AppVersion) + req.Header.Set("User-Agent", constants.UserAgent) + + resp, err := httpClient.Do(req) + if err != nil { + return false + } + defer func() { _ = resp.Body.Close() }() + + // If we get a 401, the session is invalid + if resp.StatusCode == http.StatusUnauthorized { + return false + } + + // Any 2xx response means the session is valid + return resp.StatusCode >= 200 && resp.StatusCode < 300 +} diff --git a/protonvpn-wg-confgen/internal/config/flags.go b/protonvpn-wg-confgen/internal/config/flags.go new file mode 100644 index 0000000..e33dbe1 --- /dev/null +++ b/protonvpn-wg-confgen/internal/config/flags.go @@ -0,0 +1,120 @@ +// Package config handles command-line argument parsing and configuration management. +package config + +import ( + "flag" + "fmt" + "os" + "strings" + + "protonvpn-wg-confgen/internal/constants" + "protonvpn-wg-confgen/pkg/validation" +) + +// Parse parses command-line flags and returns a Config +func Parse() (*Config, error) { + cfg := &Config{} + + var countriesFlag string + var dnsServersFlag string + var allowedIPsFlag string + + // Set default DNS and allowed IPs based on IPv6 support + defaultDNS := constants.DefaultDNSIPv4 + defaultAllowedIPs := constants.DefaultAllowedIPsIPv4 + + // Authentication flags + flag.StringVar(&cfg.Username, "username", "", "ProtonVPN username") + flag.StringVar(&cfg.Password, "password", "", "ProtonVPN password (will prompt if not provided)") + + // Server selection flags + flag.StringVar(&countriesFlag, "countries", "", "Comma-separated list of country codes (e.g., US,NL,CH)") + flag.BoolVar(&cfg.P2PServersOnly, "p2p-only", constants.DefaultP2POnly, "Use only P2P-enabled servers") + flag.BoolVar(&cfg.SecureCoreOnly, "secure-core", false, "Use only Secure Core servers (multi-hop through privacy-friendly countries)") + flag.BoolVar(&cfg.FreeOnly, "free-only", false, "Use only Free tier servers (tier 0)") + + // Output configuration + flag.StringVar(&cfg.OutputFile, "output", "protonvpn.conf", "Output WireGuard configuration file") + flag.StringVar(&cfg.DeviceName, "device-name", "", "Device name for WireGuard config (auto-generated if empty)") + + // Network configuration + flag.BoolVar(&cfg.EnableIPv6, "ipv6", false, "Enable IPv6 support") + flag.StringVar(&dnsServersFlag, "dns", "", "Comma-separated list of DNS servers (defaults based on IPv6 setting)") + flag.StringVar(&allowedIPsFlag, "allowed-ips", "", "Comma-separated list of allowed IPs (defaults based on IPv6 setting)") + flag.BoolVar(&cfg.EnableAccelerator, "accelerator", true, "Enable VPN accelerator") + + // Certificate configuration + flag.StringVar(&cfg.Duration, "duration", constants.DefaultCertDuration, "Certificate duration (e.g., 30m, 24h, 7d, 1h30m). Max: 365d") + + // Session management + flag.BoolVar(&cfg.ClearSession, "clear-session", false, "Clear saved session and force re-authentication") + flag.BoolVar(&cfg.NoSession, "no-session", false, "Don't save or use session persistence") + flag.BoolVar(&cfg.ForceRefresh, "force-refresh", false, "Force session refresh even if not expired") + flag.StringVar(&cfg.SessionDuration, "session-duration", "0", "Session cache duration (e.g., 12h, 24h, 7d). 0 = no expiration") + + // Advanced configuration + flag.StringVar(&cfg.APIURL, "api-url", constants.DefaultAPIURL, "ProtonVPN API URL") + flag.BoolVar(&cfg.Debug, "debug", false, "Enable debug output") + + flag.Parse() + + // Validate required flags + if countriesFlag == "" { + return nil, fmt.Errorf("countries flag is required") + } + + // Parse and validate country codes + cfg.Countries = parseCountries(countriesFlag) + for _, country := range cfg.Countries { + if !validation.IsValidCountryCode(country) { + return nil, fmt.Errorf("invalid country code: %s", country) + } + } + + // Set defaults based on IPv6 setting + if cfg.EnableIPv6 { + defaultDNS = fmt.Sprintf("%s,%s", constants.DefaultDNSIPv4, constants.DefaultDNSIPv6) + defaultAllowedIPs = fmt.Sprintf("%s,%s", constants.DefaultAllowedIPsIPv4, constants.DefaultAllowedIPsIPv6) + } + + // Use defaults if flags are empty + if dnsServersFlag == "" { + dnsServersFlag = defaultDNS + } + if allowedIPsFlag == "" { + allowedIPsFlag = defaultAllowedIPs + } + + // Parse lists (with space trimming) + cfg.DNSServers = parseCommaSeparatedList(dnsServersFlag) + cfg.AllowedIPs = parseCommaSeparatedList(allowedIPsFlag) + + // Clean up username + cfg.Username = validation.CleanUsername(cfg.Username) + + return cfg, nil +} + +// parseCommaSeparatedList parses a comma-separated string into a trimmed slice +func parseCommaSeparatedList(input string) []string { + parts := strings.Split(input, ",") + var result []string + for _, part := range parts { + part = strings.TrimSpace(part) + if part != "" { + result = append(result, part) + } + } + return result +} + +// parseCountries parses and normalizes country codes +func parseCountries(countriesFlag string) []string { + return parseCommaSeparatedList(strings.ToUpper(countriesFlag)) +} + +// PrintUsage prints usage information +func PrintUsage() { + fmt.Fprintf(os.Stderr, "Usage: %s -username -countries [options]\n\n", os.Args[0]) + flag.PrintDefaults() +} diff --git a/protonvpn-wg-confgen/internal/config/types.go b/protonvpn-wg-confgen/internal/config/types.go new file mode 100644 index 0000000..b6f4170 --- /dev/null +++ b/protonvpn-wg-confgen/internal/config/types.go @@ -0,0 +1,48 @@ +package config + +import "fmt" + +// Config holds all configuration options +type Config struct { + // Authentication + Username string + Password string + + // Server selection + Countries []string + P2PServersOnly bool + SecureCoreOnly bool + FreeOnly bool + + // Output configuration + OutputFile string + ClientPrivateKey string + DeviceName string + + // Network configuration + DNSServers []string + AllowedIPs []string + EnableAccelerator bool + EnableIPv6 bool + + // Certificate configuration + Duration string + + // Session management + ClearSession bool + NoSession bool + ForceRefresh bool + SessionDuration string + + // Advanced configuration + APIURL string + Debug bool +} + +// ValidateCredentials checks if we have the required credentials +func (c *Config) ValidateCredentials() error { + if c.Username == "" { + return fmt.Errorf("username is required") + } + return nil +} diff --git a/protonvpn-wg-confgen/internal/constants/api.go b/protonvpn-wg-confgen/internal/constants/api.go new file mode 100644 index 0000000..4a84e2f --- /dev/null +++ b/protonvpn-wg-confgen/internal/constants/api.go @@ -0,0 +1,37 @@ +// Package constants defines constants used throughout the application. +package constants + +// API endpoints +const ( + DefaultAPIURL = "https://vpn-api.proton.me" + AuthInfoPath = "/core/v4/auth/info" + AuthPath = "/core/v4/auth" + RefreshPath = "/auth/refresh" + CertificatePath = "/vpn/v1/certificate" + LogicalsPath = "/vpn/v1/logicals" +) + +// API version headers - can be overridden at build time via ldflags: +// go build -ldflags "-X .../internal/constants.AppVersion=linux-vpn@X.Y.Z" +var ( + AppVersion = "linux-vpn@4.13.1" + UserAgent = "ProtonVPN/4.13.1 (Linux; Ubuntu)" +) + +// API response codes +// Reference: proton-python-client/proton/api.py checks for codes 1000 and 1001 +const ( + APICodeSuccess = 1000 + APICodeMultiStatus = 1001 // Also indicates success in some contexts +) + +// IsSuccessCode checks if an API response code indicates success +func IsSuccessCode(code int) bool { + return code == APICodeSuccess || code == APICodeMultiStatus +} + +// Server/feature status values +const ( + StatusOnline = 1 + EnabledTrue = 1 +) diff --git a/protonvpn-wg-confgen/internal/constants/defaults.go b/protonvpn-wg-confgen/internal/constants/defaults.go new file mode 100644 index 0000000..ad4e91f --- /dev/null +++ b/protonvpn-wg-confgen/internal/constants/defaults.go @@ -0,0 +1,14 @@ +package constants + +// Certificate defaults +const ( + DefaultCertDuration = "365d" + MaxCertDuration = 365 // days + CertMode = "persistent" + PublicKeyMode = "EC" +) + +// Server selection defaults +const ( + DefaultP2POnly = true +) diff --git a/protonvpn-wg-confgen/internal/constants/session.go b/protonvpn-wg-confgen/internal/constants/session.go new file mode 100644 index 0000000..ba9349f --- /dev/null +++ b/protonvpn-wg-confgen/internal/constants/session.go @@ -0,0 +1,9 @@ +package constants + +// Session defaults +const ( + SessionFileName = ".protonvpn-session.json" + SessionFileMode = 0o600 // Read/write for owner only + SessionRefreshDays = 7 // Refresh when less than 7 days remain + SessionExpirySeconds = 2592000 // 30 days in seconds (from API) +) diff --git a/protonvpn-wg-confgen/internal/constants/wireguard.go b/protonvpn-wg-confgen/internal/constants/wireguard.go new file mode 100644 index 0000000..eb360c9 --- /dev/null +++ b/protonvpn-wg-confgen/internal/constants/wireguard.go @@ -0,0 +1,17 @@ +package constants + +// WireGuard defaults +const ( + WireGuardPort = 51820 + DefaultMTU = 1420 + + // IPv4 configuration + WireGuardIPv4 = "10.2.0.2/32" + DefaultDNSIPv4 = "10.2.0.1" + DefaultAllowedIPsIPv4 = "0.0.0.0/0" + + // IPv6 configuration + WireGuardIPv6 = "2a07:b944::2:2/128" + DefaultDNSIPv6 = "2a07:b944::2:1" + DefaultAllowedIPsIPv6 = "::/0" +) diff --git a/protonvpn-wg-confgen/internal/vpn/client.go b/protonvpn-wg-confgen/internal/vpn/client.go new file mode 100644 index 0000000..8b66a38 --- /dev/null +++ b/protonvpn-wg-confgen/internal/vpn/client.go @@ -0,0 +1,148 @@ +// Package vpn manages VPN certificate generation and server interactions. +package vpn + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "time" + + "protonvpn-wg-confgen/internal/api" + "protonvpn-wg-confgen/internal/config" + "protonvpn-wg-confgen/internal/constants" + "protonvpn-wg-confgen/pkg/timeutil" + + "github.com/ProtonVPN/go-vpn-lib/ed25519" +) + +// Client handles VPN operations +type Client struct { + config *config.Config + session *api.Session + httpClient *http.Client +} + +// NewClient creates a new VPN client +func NewClient(cfg *config.Config, session *api.Session) *Client { + return &Client{ + config: cfg, + session: session, + httpClient: &http.Client{Timeout: 10 * time.Second}, + } +} + +// GetCertificate generates a VPN certificate +func (c *Client) GetCertificate(keyPair *ed25519.KeyPair) (*api.VPNInfo, error) { + publicKeyPEM, err := keyPair.PublicKeyPKIXPem() + if err != nil { + return nil, fmt.Errorf("failed to get public key PEM: %w", err) + } + + // Use provided device name or generate one + deviceName := c.config.DeviceName + if deviceName == "" { + deviceName = fmt.Sprintf("WireGuard-%s-%d", c.config.Username, time.Now().Unix()) + } + + // Parse duration + durationStr, err := timeutil.ParseToMinutes(c.config.Duration) + if err != nil { + return nil, fmt.Errorf("failed to parse duration: %w", err) + } + + // Build certificate request matching official ProtonVPN API format + // Feature keys from: python-proton-vpn-api-core/proton/vpn/session/fetcher.py + certReq := map[string]interface{}{ + "ClientPublicKey": publicKeyPEM, + "ClientPublicKeyMode": "EC", + "Mode": "persistent", // Create persistent configuration + "DeviceName": deviceName, + "Duration": durationStr, + "Features": map[string]interface{}{ + "NetShieldLevel": 0, // NetShield disabled + "RandomNAT": false, // Moderate NAT disabled + "PortForwarding": false, // Port forwarding disabled + "SplitTCP": c.config.EnableAccelerator, // VPN Accelerator (called SplitTCP in API) + }, + } + + certJSON, err := json.Marshal(certReq) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, c.config.APIURL+"/vpn/v1/certificate", bytes.NewBuffer(certJSON)) + if err != nil { + return nil, err + } + + c.setHeaders(req) + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var vpnInfo api.VPNInfo + if err := json.Unmarshal(body, &vpnInfo); err != nil { + return nil, err + } + + if !constants.IsSuccessCode(vpnInfo.Code) { + // Include the actual API error message if available + if vpnInfo.Error != "" { + return nil, fmt.Errorf("VPN certificate error (code %d): %s", vpnInfo.Code, vpnInfo.Error) + } + return nil, fmt.Errorf("failed to get VPN certificate, code: %d", vpnInfo.Code) + } + + return &vpnInfo, nil +} + +// GetServers fetches the list of VPN servers +func (c *Client) GetServers() ([]api.LogicalServer, error) { + req, err := http.NewRequest(http.MethodGet, c.config.APIURL+"/vpn/v1/logicals", http.NoBody) + if err != nil { + return nil, err + } + + c.setHeaders(req) + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var response api.LogicalsResponse + if err := json.Unmarshal(body, &response); err != nil { + return nil, err + } + + if !constants.IsSuccessCode(response.Code) { + return nil, fmt.Errorf("API returned error code: %d", response.Code) + } + + return response.LogicalServers, nil +} + +func (c *Client) setHeaders(req *http.Request) { + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.session.AccessToken)) + req.Header.Set("x-pm-uid", c.session.UID) + req.Header.Set("x-pm-appversion", constants.AppVersion) + req.Header.Set("User-Agent", constants.UserAgent) +} diff --git a/protonvpn-wg-confgen/internal/vpn/servers.go b/protonvpn-wg-confgen/internal/vpn/servers.go new file mode 100644 index 0000000..c7b521a --- /dev/null +++ b/protonvpn-wg-confgen/internal/vpn/servers.go @@ -0,0 +1,165 @@ +package vpn + +import ( + "errors" + "fmt" + "sort" + "strings" + + "protonvpn-wg-confgen/internal/api" + "protonvpn-wg-confgen/internal/config" + "protonvpn-wg-confgen/internal/constants" +) + +// ServerSelector handles server selection logic +type ServerSelector struct { + config *config.Config +} + +// NewServerSelector creates a new server selector +func NewServerSelector(cfg *config.Config) *ServerSelector { + return &ServerSelector{config: cfg} +} + +// SelectBest selects the best server based on configuration +func (s *ServerSelector) SelectBest(servers []api.LogicalServer) (*api.LogicalServer, error) { + filtered := s.filterServers(servers) + + if s.config.Debug { + s.printDebugServerList(filtered) + } + + if len(filtered) == 0 { + return nil, s.buildNoServersError() + } + + // Sort servers: first by score (descending), then by load (ascending) + sort.Slice(filtered, func(i, j int) bool { + // If scores are different, higher score wins + if filtered[i].Score != filtered[j].Score { + return filtered[i].Score > filtered[j].Score + } + // If scores are equal, lower load wins + return filtered[i].Load < filtered[j].Load + }) + + return &filtered[0], nil +} + +func (s *ServerSelector) filterServers(servers []api.LogicalServer) []api.LogicalServer { + var filtered []api.LogicalServer + + for i := range servers { + if s.isServerEligible(&servers[i]) { + filtered = append(filtered, servers[i]) + } + } + + return filtered +} + +func (s *ServerSelector) isServerEligible(server *api.LogicalServer) bool { + // Skip offline servers + if server.Status != constants.StatusOnline { + return false + } + + // Filter by tier based on -free-only flag + if s.config.FreeOnly { + // When free-only is enabled, only accept Free tier servers + if server.Tier != api.TierFree { + return false + } + } else { + // Otherwise, filter out free tier servers + if server.Tier == api.TierFree { + return false + } + } + + // Filter by P2P support if requested (but not when using Secure Core or Free tier) + if s.config.P2PServersOnly && !s.config.SecureCoreOnly && !s.config.FreeOnly && server.Features&api.FeatureP2P == 0 { + return false + } + + // Filter by Secure Core if requested + if s.config.SecureCoreOnly && server.Features&api.FeatureSecureCore == 0 { + return false + } + + // Filter by country + if !s.isCountryMatch(server) { + return false + } + + // Skip servers with no physical servers + if len(server.Servers) == 0 { + return false + } + + return true +} + +func (s *ServerSelector) isCountryMatch(server *api.LogicalServer) bool { + for _, country := range s.config.Countries { + if server.ExitCountry == country { + return true + } + } + return false +} + +func (s *ServerSelector) buildNoServersError() error { + errMsg := fmt.Sprintf("No suitable servers found for countries: %v", s.config.Countries) + + if s.config.SecureCoreOnly { + errMsg += " with Secure Core" + } else if s.config.P2PServersOnly { + errMsg += " with P2P support" + } + + return errors.New(errMsg) +} + +// GetBestPhysicalServer returns the best physical server from a logical server +func GetBestPhysicalServer(server *api.LogicalServer) *api.PhysicalServer { + if len(server.Servers) == 0 { + return nil + } + + // Find the first online physical server + for i := range server.Servers { + if server.Servers[i].Status == constants.StatusOnline { + return &server.Servers[i] + } + } + + // If no online servers, return the first one + return &server.Servers[0] +} + +// printDebugServerList prints a debug list of filtered servers +func (s *ServerSelector) printDebugServerList(servers []api.LogicalServer) { + fmt.Printf("\nDEBUG: Found %d servers after filtering:\n", len(servers)) + fmt.Println("==================================================================================") + fmt.Printf("%-15s | %-18s | %-12s | Load | Score | Features\n", "Server", "City", "Tier") + fmt.Println("----------------------------------------------------------------------------------") + + for i := range servers { + features := api.GetFeatureNames(servers[i].Features) + featureStr := "-" + if len(features) > 0 { + featureStr = strings.Join(features, ", ") + } + + fmt.Printf("%-15s | %-18s | %-12s | %3d%% | %.2f | %s\n", + servers[i].Name, + servers[i].City, + api.GetTierName(servers[i].Tier), + servers[i].Load, + servers[i].Score, + featureStr) + } + + fmt.Println("==================================================================================") +} diff --git a/protonvpn-wg-confgen/pkg/timeutil/duration.go b/protonvpn-wg-confgen/pkg/timeutil/duration.go new file mode 100644 index 0000000..d51332c --- /dev/null +++ b/protonvpn-wg-confgen/pkg/timeutil/duration.go @@ -0,0 +1,148 @@ +// Package timeutil provides time-related utility functions. +package timeutil + +import ( + "fmt" + "strings" + "time" +) + +// pluralize returns singular or plural form based on count +func pluralize(count int, singular, plural string) string { + if count == 1 { + return fmt.Sprintf("1 %s", singular) + } + return fmt.Sprintf("%d %s", count, plural) +} + +// formatTimeComponents formats non-zero time components into a string +func formatTimeComponents(parts []string) string { + return strings.Join(parts, " ") +} + +// formatWeeksAndDays formats weeks and remaining days +func formatWeeksAndDays(days int) []string { + var parts []string + weeks := days / 7 + remainingDays := days % 7 + + if weeks > 0 { + parts = append(parts, pluralize(weeks, "week", "weeks")) + } + if remainingDays > 0 { + parts = append(parts, pluralize(remainingDays, "day", "days")) + } + return parts +} + +// formatHoursMinutes formats hours and minutes +func formatHoursMinutes(hours, minutes int) string { + switch { + case hours > 0 && minutes > 0: + return fmt.Sprintf("%d hours %d minutes", hours, minutes) + case hours > 0: + return fmt.Sprintf("%d hours", hours) + default: + return fmt.Sprintf("%d minutes", minutes) + } +} + +// formatDaysHoursMinutes formats days, hours, and minutes into a string +func formatDaysHoursMinutes(days, hours, minutes int) string { + // Simple days format (less than a week) + if days < 7 { + return formatSimpleDays(days, hours, minutes) + } + + // Weeks format + parts := formatWeeksAndDays(days) + if hours > 0 || minutes > 0 { + parts = append(parts, formatHoursMinutes(hours, minutes)) + } + return formatTimeComponents(parts) +} + +// formatSimpleDays formats days less than a week with hours and minutes +func formatSimpleDays(days, hours, minutes int) string { + if hours == 0 && minutes == 0 { + return pluralize(days, "day", "days") + } + if minutes == 0 { + return fmt.Sprintf("%d days %d hours", days, hours) + } + return fmt.Sprintf("%d days %d hours %d minutes", days, hours, minutes) +} + +// HumanizeDuration converts a duration to a human-readable format with high precision. +// It shows progressively less detail for longer durations: +// - Less than a minute: "less than a minute" +// - Less than an hour: "X minutes" +// - Less than a day: "X hours Y minutes" +// - Less than a week: "X days Y hours Z minutes" +// - Less than a month: "X weeks Y days Z hours W minutes" +// - Longer periods: months and years with appropriate detail +func HumanizeDuration(d time.Duration) string { + if d < 0 { + return "expired" + } + + if d < time.Minute { + return "less than a minute" + } + + if d < time.Hour { + return pluralize(int(d.Minutes()), "minute", "minutes") + } + + if d < 24*time.Hour { + return formatHoursDuration(d) + } + + days := int(d.Hours() / 24) + hours := int(d.Hours()) % 24 + minutes := int(d.Minutes()) % 60 + + if days < 30 { + return formatDaysHoursMinutes(days, hours, minutes) + } + + if days < 365 { + return formatMonthsDuration(days) + } + + return formatYearsDuration(days) +} + +// formatHoursDuration formats durations less than a day +func formatHoursDuration(d time.Duration) string { + hours := int(d.Hours()) + minutes := int(d.Minutes()) % 60 + if minutes == 0 { + return pluralize(hours, "hour", "hours") + } + return fmt.Sprintf("%d hours %d minutes", hours, minutes) +} + +// formatMonthsDuration formats durations between 30 and 365 days +func formatMonthsDuration(days int) string { + months := days / 30 + remainingDays := days % 30 + if remainingDays == 0 { + return pluralize(months, "month", "months") + } + return fmt.Sprintf("%d months %d days", months, remainingDays) +} + +// formatYearsDuration formats durations of 365 days or more +func formatYearsDuration(days int) string { + years := days / 365 + remainingDays := days % 365 + if remainingDays == 0 { + return pluralize(years, "year", "years") + } + if remainingDays < 30 { + return fmt.Sprintf("%d years %d days", years, remainingDays) + } + months := remainingDays / 30 + return fmt.Sprintf("%d years %d months", years, months) +} diff --git a/protonvpn-wg-confgen/pkg/timeutil/parser.go b/protonvpn-wg-confgen/pkg/timeutil/parser.go new file mode 100644 index 0000000..54df88e --- /dev/null +++ b/protonvpn-wg-confgen/pkg/timeutil/parser.go @@ -0,0 +1,81 @@ +package timeutil + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// parseDaysDuration handles duration strings like "7d", "30d", "365d" +func parseDaysDuration(durationStr string) (time.Duration, error) { + if !strings.HasSuffix(durationStr, "d") { + return 0, fmt.Errorf("not a day duration format") + } + + daysStr := strings.TrimSuffix(durationStr, "d") + days, err := strconv.Atoi(daysStr) + if err != nil { + return 0, fmt.Errorf("invalid day value: %s", daysStr) + } + + return time.Duration(days) * 24 * time.Hour, nil +} + +// ParseDuration parses a duration string that can be either Go duration or "Xd" format +func ParseDuration(durationStr string) (time.Duration, error) { + // Try days format first + if duration, err := parseDaysDuration(durationStr); err == nil { + return duration, nil + } + + // Fall back to standard Go duration + return time.ParseDuration(durationStr) +} + +// ParseToMinutes parses a duration string and converts it to minutes for the ProtonVPN API. +// Accepts formats like "7d", "30d", "365d", "30m", "24h", "1h30m". +// Returns the duration in "XXX min" format as expected by the API. +func ParseToMinutes(durationStr string) (string, error) { + duration, err := ParseDuration(durationStr) + if err != nil { + return "", fmt.Errorf("invalid duration format: %s", durationStr) + } + + // Convert to minutes + minutes := int(duration.Minutes()) + if minutes < 1 { + return "", fmt.Errorf("duration must be at least 1 minute") + } + + // Max 365 days = 525600 minutes + maxMinutes := 365 * 24 * 60 + if minutes > maxMinutes { + return "", fmt.Errorf("duration cannot exceed 365 days") + } + + return fmt.Sprintf("%d min", minutes), nil +} + +// ParseSessionDuration parses a session duration string for local caching. +// Accepts formats like "7d", "30d", or standard Go duration strings. +// Returns 0 to indicate "use API default". +func ParseSessionDuration(durationStr string) (time.Duration, error) { + // Handle "0" as use API default + if durationStr == "0" { + return 0, nil + } + + duration, err := ParseDuration(durationStr) + if err != nil { + return 0, fmt.Errorf("invalid session duration format: %s", durationStr) + } + + // Validate max duration (30 days) + maxDuration := 30 * 24 * time.Hour + if duration > maxDuration { + return 0, fmt.Errorf("session duration cannot exceed 30 days (got: %s)", duration) + } + + return duration, nil +} diff --git a/protonvpn-wg-confgen/pkg/validation/username.go b/protonvpn-wg-confgen/pkg/validation/username.go new file mode 100644 index 0000000..d1abebf --- /dev/null +++ b/protonvpn-wg-confgen/pkg/validation/username.go @@ -0,0 +1,31 @@ +// Package validation provides input validation utilities. +package validation + +import ( + "strings" +) + +// CleanUsername removes email domain suffixes from username. +// ProtonVPN usernames don't include the email domain. +func CleanUsername(username string) string { + username = strings.TrimSpace(username) + username = strings.TrimSuffix(username, "@protonmail.com") + username = strings.TrimSuffix(username, "@proton.me") + username = strings.TrimSuffix(username, "@pm.me") + return username +} + +// IsValidCountryCode checks if a country code is valid (2 letters). +func IsValidCountryCode(code string) bool { + return len(code) == 2 && isAlpha(code) +} + +// isAlpha checks if a string contains only alphabetic characters. +func isAlpha(s string) bool { + for _, r := range s { + if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') { + return false + } + } + return true +} diff --git a/protonvpn-wg-confgen/pkg/wireguard/config.go b/protonvpn-wg-confgen/pkg/wireguard/config.go new file mode 100644 index 0000000..2238992 --- /dev/null +++ b/protonvpn-wg-confgen/pkg/wireguard/config.go @@ -0,0 +1,140 @@ +// Package wireguard generates WireGuard configuration files. +package wireguard + +import ( + "bytes" + "fmt" + "os" + "strings" + "text/template" + "time" + + "protonvpn-wg-confgen/internal/api" + "protonvpn-wg-confgen/internal/config" + "protonvpn-wg-confgen/internal/constants" +) + +// wireguardConfigTemplate is the template for generating WireGuard configuration +const wireguardConfigTemplate = `[Interface] +PrivateKey = {{.PrivateKey}} +{{.AddressLine}} +DNS = {{.DNS}} + +[Peer] +PublicKey = {{.PublicKey}} +AllowedIPs = {{.AllowedIPs}} +Endpoint = {{.Endpoint}}:{{.Port}} +` + +// configData holds the data for the WireGuard config template +type configData struct { + PrivateKey string + AddressLine string + DNS string + PublicKey string + AllowedIPs string + Endpoint string + Port int +} + +// ConfigGenerator generates WireGuard configuration files +type ConfigGenerator struct { + config *config.Config + template *template.Template +} + +// NewConfigGenerator creates a new configuration generator +func NewConfigGenerator(cfg *config.Config) *ConfigGenerator { + tmpl := template.Must(template.New("wireguard").Parse(wireguardConfigTemplate)) + return &ConfigGenerator{ + config: cfg, + template: tmpl, + } +} + +// Generate creates a WireGuard configuration file +func (g *ConfigGenerator) Generate(server *api.LogicalServer, physicalServer *api.PhysicalServer, privateKey string) error { + content, err := g.buildConfig(server, physicalServer, privateKey) + if err != nil { + return err + } + + if err := os.WriteFile(g.config.OutputFile, []byte(content), 0o600); err != nil { + return fmt.Errorf("failed to write config file: %w", err) + } + + return nil +} + +func (g *ConfigGenerator) buildConfig(server *api.LogicalServer, physicalServer *api.PhysicalServer, privateKey string) (string, error) { + // Build metadata header + metadata := g.buildMetadata(server, physicalServer) + + data := configData{ + PrivateKey: privateKey, + AddressLine: g.buildAddressLine(), + DNS: strings.Join(g.config.DNSServers, ", "), + PublicKey: physicalServer.X25519PublicKey, + AllowedIPs: strings.Join(g.config.AllowedIPs, ", "), + Endpoint: physicalServer.EntryIP, + Port: constants.WireGuardPort, + } + + var buf bytes.Buffer + if err := g.template.Execute(&buf, data); err != nil { + return "", fmt.Errorf("failed to execute template: %w", err) + } + + return metadata + buf.String(), nil +} + +func (g *ConfigGenerator) buildAddressLine() string { + if g.config.EnableIPv6 { + return fmt.Sprintf("Address = %s, %s", constants.WireGuardIPv4, constants.WireGuardIPv6) + } + return fmt.Sprintf("Address = %s", constants.WireGuardIPv4) +} + +func (g *ConfigGenerator) buildMetadata(server *api.LogicalServer, physicalServer *api.PhysicalServer) string { + var metadata strings.Builder + + metadata.WriteString("# ProtonVPN WireGuard Configuration\n") + metadata.WriteString(fmt.Sprintf("# Generated: %s\n", time.Now().Format("2006-01-02 15:04:05 MST"))) + if g.config.DeviceName != "" { + metadata.WriteString(fmt.Sprintf("# Device: %s\n", g.config.DeviceName)) + } + metadata.WriteString("#\n") + metadata.WriteString("# Server Information:\n") + metadata.WriteString(fmt.Sprintf("# - Name: %s\n", server.Name)) + metadata.WriteString(fmt.Sprintf("# - Country: %s\n", server.ExitCountry)) + metadata.WriteString(fmt.Sprintf("# - City: %s\n", server.City)) + metadata.WriteString(fmt.Sprintf("# - Tier: %s\n", api.GetTierName(server.Tier))) + metadata.WriteString(fmt.Sprintf("# - Load: %d%%\n", server.Load)) + metadata.WriteString(fmt.Sprintf("# - Score: %.2f\n", server.Score)) + + // Add features if any + features := api.GetFeatureNames(server.Features) + if len(features) > 0 { + metadata.WriteString(fmt.Sprintf("# - Features: %s\n", strings.Join(features, ", "))) + } + + // Add physical server info + metadata.WriteString("#\n") + metadata.WriteString("# Physical Server:\n") + metadata.WriteString(fmt.Sprintf("# - ID: %s\n", physicalServer.ID)) + metadata.WriteString(fmt.Sprintf("# - Entry IP: %s\n", physicalServer.EntryIP)) + if physicalServer.ExitIP != physicalServer.EntryIP { + metadata.WriteString(fmt.Sprintf("# - Exit IP: %s\n", physicalServer.ExitIP)) + } + + // Add secure core routing info if applicable + if server.EntryCountry != server.ExitCountry && server.EntryCountry != "" { + metadata.WriteString("#\n") + metadata.WriteString(fmt.Sprintf("# Secure Core Routing: %s → %s\n", + server.EntryCountry, server.ExitCountry)) + } + + metadata.WriteString("#\n\n") + + return metadata.String() +} diff --git a/protonvpn-wg-confgen/pkg/wireguard/config_test.go b/protonvpn-wg-confgen/pkg/wireguard/config_test.go new file mode 100644 index 0000000..2e6137e --- /dev/null +++ b/protonvpn-wg-confgen/pkg/wireguard/config_test.go @@ -0,0 +1,119 @@ +package wireguard + +import ( + "strings" + "testing" + + "protonvpn-wg-confgen/internal/api" + "protonvpn-wg-confgen/internal/config" +) + +func TestConfigGeneration(t *testing.T) { + cfg := &config.Config{ + DNSServers: []string{"10.2.0.1"}, + AllowedIPs: []string{"0.0.0.0/0"}, + OutputFile: "test.conf", + } + + generator := NewConfigGenerator(cfg) + + server := &api.LogicalServer{ + Name: "Test-Server", + } + + physicalServer := &api.PhysicalServer{ + EntryIP: "192.168.1.1", + X25519PublicKey: "testPublicKey123=", + } + + privateKey := "testPrivateKey456=" + + result, err := generator.buildConfig(server, physicalServer, privateKey) + if err != nil { + t.Fatalf("buildConfig failed: %v", err) + } + + // Check that config starts with comment header + if !strings.HasPrefix(result, "# ProtonVPN WireGuard Configuration") { + t.Errorf("Expected config to start with header comment, got:\n%s", result[:100]) + } + + // Check that metadata is present + if !strings.Contains(result, "# - Name: Test-Server") { + t.Errorf("Expected server name in metadata") + } + + // Check for proper WireGuard sections + if !strings.Contains(result, "[Interface]") { + t.Error("Expected [Interface] section") + } + + if !strings.Contains(result, "[Peer]") { + t.Error("Expected [Peer] section") + } + + // Verify key content + expectedContent := []string{ + "PrivateKey = testPrivateKey456=", + "Address = 10.2.0.2/32", + "DNS = 10.2.0.1", + "PublicKey = testPublicKey123=", + "AllowedIPs = 0.0.0.0/0", + "Endpoint = 192.168.1.1:51820", + } + + for _, expected := range expectedContent { + if !strings.Contains(result, expected) { + t.Errorf("Expected config to contain '%s'\nGot:\n%s", expected, result) + } + } + + // Check section order: [Interface] should come before [Peer] + interfaceIdx := strings.Index(result, "[Interface]") + peerIdx := strings.Index(result, "[Peer]") + if interfaceIdx >= peerIdx { + t.Error("[Interface] section should come before [Peer] section") + } +} + +func TestConfigGenerationWithIPv6(t *testing.T) { + cfg := &config.Config{ + DNSServers: []string{"10.2.0.1", "2a07:b944::2:1"}, + AllowedIPs: []string{"0.0.0.0/0", "::/0"}, + OutputFile: "test.conf", + EnableIPv6: true, + } + + generator := NewConfigGenerator(cfg) + + server := &api.LogicalServer{ + Name: "Test-Server", + } + + physicalServer := &api.PhysicalServer{ + EntryIP: "192.168.1.1", + X25519PublicKey: "testPublicKey123=", + } + + privateKey := "testPrivateKey456=" + + result, err := generator.buildConfig(server, physicalServer, privateKey) + if err != nil { + t.Fatalf("buildConfig failed: %v", err) + } + + // Check that IPv6 address is included + if !strings.Contains(result, "Address = 10.2.0.2/32, 2a07:b944::2:2/128") { + t.Errorf("Expected IPv6 address in config, got:\n%s", result) + } + + // Check DNS servers + if !strings.Contains(result, "DNS = 10.2.0.1, 2a07:b944::2:1") { + t.Errorf("Expected both DNS servers in config, got:\n%s", result) + } + + // Check AllowedIPs + if !strings.Contains(result, "AllowedIPs = 0.0.0.0/0, ::/0") { + t.Errorf("Expected both IPv4 and IPv6 in AllowedIPs, got:\n%s", result) + } +}