-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_letsencrypt.py
More file actions
284 lines (241 loc) · 10.6 KB
/
setup_letsencrypt.py
File metadata and controls
284 lines (241 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#!/usr/bin/env python3
"""
Let's Encrypt SSL Certificate Setup Helper for QuickFileManager
This script helps you set up HTTPS with Let's Encrypt certificates.
It provides guidance and can update your config.yml automatically.
Prerequisites:
- Domain name pointing to your server
- Certbot installed (sudo apt-get install certbot)
- Server running on standard HTTP port initially
"""
import os
import sys
import yaml
import subprocess
from urllib.parse import urlsplit
from config import get_config, save_config
def print_banner():
print("=" * 60)
print("QuickFileManager - Let's Encrypt SSL Setup Helper")
print("=" * 60)
print()
def check_certbot():
"""Check if certbot is installed"""
try:
result = os.system("certbot --version > /dev/null 2>&1")
return result == 0
except:
return False
def get_cert_path(domain):
"""Get the expected certificate paths for a domain inside local ssl directory"""
current_dir = os.path.dirname(os.path.abspath(__file__))
ssl_dir = os.path.join(current_dir, "ssl")
cert_path = os.path.join(ssl_dir, "live", domain, "fullchain.pem")
key_path = os.path.join(ssl_dir, "live", domain, "privkey.pem")
return cert_path, key_path
def check_certificates(domain):
"""Check if certificates exist for the domain"""
cert_path, key_path = get_cert_path(domain)
return os.path.exists(cert_path) and os.path.exists(key_path)
def _safe_int_port(value, fallback):
try:
port = int(value)
if 1 <= port <= 65535:
return port
except (TypeError, ValueError):
pass
return fallback
def normalize_domain_input(raw_value):
"""Normalize user input into (public_https_domain, certbot_domain)."""
if not raw_value:
return None, None
value = raw_value.strip()
if not value:
return None, None
# Accept both bare hostnames and full URLs from the user.
parse_target = value if value.startswith(('http://', 'https://')) else f"//{value}"
parsed = urlsplit(parse_target)
hostname = (parsed.hostname or '').strip().lower()
if not hostname:
return None, None
public_domain = f"https://{hostname}"
return public_domain, hostname
def update_config_ssl(certbot_domain, public_domain, ip="0.0.0.0"):
"""Update config.yml with SSL settings"""
config = get_config()
# Use relative paths for the config file to be portable
cert_path = f"./ssl/live/{certbot_domain}/fullchain.pem"
key_path = f"./ssl/live/{certbot_domain}/privkey.pem"
# Update server configuration
if 'server' not in config:
config['server'] = {}
config['server']['domain'] = public_domain
if ip:
config['server']['host'] = ip
# Keep application ports stable when enabling SSL.
existing_http_port = config['server'].get('port', 5000)
existing_https_port = config['server'].get('ssl_port', 5001)
config['server']['port'] = _safe_int_port(existing_http_port, 5000)
config['server']['ssl_port'] = _safe_int_port(existing_https_port, 5001)
# Update SSL configuration
config['ssl'] = {
'enabled': True,
'cert_file': cert_path,
'key_file': key_path,
'force_https': True
}
save_config(config)
print(f"✓ Updated config.yml with SSL settings and domain for {public_domain}")
return True
def get_certbot_command(domain, ip="0.0.0.0", port="80"):
"""Generate the certbot command with local directories and binding options"""
current_dir = os.path.dirname(os.path.abspath(__file__))
ssl_dir = os.path.join(current_dir, "ssl")
cmd = [
"certbot", "certonly", "--standalone", "-d", domain,
"--config-dir", ssl_dir,
"--work-dir", ssl_dir,
"--logs-dir", ssl_dir,
"--non-interactive", "--agree-tos", "-m", f"admin@{domain}"
]
if ip and ip != "0.0.0.0":
cmd.extend(["--http-01-address", ip])
if port and port != "80":
cmd.extend(["--http-01-port", port])
return cmd
def print_instructions(domain, ip="0.0.0.0", port="80"):
"""Print step-by-step instructions"""
print(f"Instructions for setting up Let's Encrypt SSL for {domain}:")
print()
print("1. STOP QuickFileManager if it's running")
print()
print("2. Run certbot to obtain certificates:")
cmd = get_certbot_command(domain, ip, port)
# Filter out non-interactive flags for manual run instructions
manual_cmd = [c for c in cmd if c not in ["--non-interactive", "--agree-tos", "-m", f"admin@{domain}"]]
print(f" sudo {' '.join(manual_cmd)}")
print()
print("3. If successful, certificates will be saved to:")
cert_path, key_path = get_cert_path(domain)
print(f" Certificate: {cert_path}")
print(f" Private Key: {key_path}")
print()
print("4. Set environment variables or update config:")
print(" Option A - Let this script update config.yml automatically")
print(" Run this script again after generating the certificates.")
print()
print(" Option B - Update config.yml manually:")
print(" ssl:")
print(" enabled: true")
print(f" cert_file: ./ssl/live/{domain}/fullchain.pem")
print(f" key_file: ./ssl/live/{domain}/privkey.pem")
print()
print("5. Start QuickFileManager:")
print(" sudo python app.py")
print(" (sudo may be needed if binding to port 443; adjust config to standard ports if needed)")
print()
def generate_ssl(domain, ip="0.0.0.0", port="80"):
"""Automatically run certbot to generate SSL certificates"""
print(f"Generating SSL certificates for {domain}...")
current_dir = os.path.dirname(os.path.abspath(__file__))
ssl_dir = os.path.join(current_dir, "ssl")
os.makedirs(ssl_dir, exist_ok=True)
cmd = get_certbot_command(domain, ip, port)
try:
is_unix_sudo = False
# Use sudo if we are on Unix and not root
if os.name != 'nt' and hasattr(os, 'geteuid') and os.geteuid() != 0:
cmd = ["sudo"] + cmd
is_unix_sudo = True
print("Running certbot with sudo. You may be prompted for your password.")
subprocess.run(cmd, check=True)
# If we used sudo, the generated files are owned by root.
# We must change ownership back to the current user so Python can read them!
if is_unix_sudo:
try:
uid = os.geteuid()
gid = os.getegid() if hasattr(os, 'getegid') else uid
print("Adjusting permissions on generated certificates so your user can read them...")
subprocess.run(["sudo", "chown", "-R", f"{uid}:{gid}", ssl_dir], check=True)
except Exception as e:
print(f"Warning: Failed to auto-adjust permissions on {ssl_dir}. You may need to manually chown it. Error: {e}")
print("\n✓ Certificates generated successfully!")
return True
except subprocess.CalledProcessError as e:
print(f"\n❌ Error generating certificates. Certbot exited with code {e.returncode}")
print("Make sure port 80 is not in use and your domain points to this server.")
return False
except Exception as e:
print(f"\n❌ Unexpected error: {e}")
return False
def main():
print_banner()
# Check if certbot is available
if not check_certbot():
print("❌ Certbot not found!")
print("Please install certbot first:")
print(" Ubuntu/Debian: sudo apt-get install certbot")
print(" CentOS/RHEL: sudo yum install certbot")
print(" Other: https://certbot.eff.org/instructions")
sys.exit(1)
print("✓ Certbot found")
print()
# Get domain name
user_domain = input("Enter your public domain (e.g., filemanager.example.com or https://filemanager.example.com): ").strip()
public_domain, certbot_domain = normalize_domain_input(user_domain)
if not public_domain or not certbot_domain:
print("A valid domain is required (hostname or URL).")
sys.exit(1)
print(f"\nPublic domain (saved to config): {public_domain}")
print(f"Certbot domain (used for certificate issuance): {certbot_domain}")
config = get_config()
server_config = config.get('server', {})
default_ip = server_config.get('host', '0.0.0.0')
default_port = "80"
# Check if certificates already exist
if check_certificates(certbot_domain):
print(f"✓ Certificates found for {certbot_domain}")
cert_path, key_path = get_cert_path(certbot_domain)
print(f" Certificate: {cert_path}")
print(f" Private Key: {key_path}")
update_choice = input("\nUpdate config.yml with these certificate paths? (y/n): ").lower()
if update_choice == 'y':
update_config_ssl(certbot_domain, public_domain, default_ip)
print("\n✓ Configuration updated!")
print("You can now start QuickFileManager with HTTPS (ensure port config is suitable):")
print(" python app.py")
else:
print("\nManual configuration:")
print("server config:")
print(f" domain: {public_domain}")
print("ssl config:")
print(" enabled: true")
print(f" cert_file: ./ssl/live/{certbot_domain}/fullchain.pem")
print(f" key_file: ./ssl/live/{certbot_domain}/privkey.pem")
else:
print(f"❌ No certificates found for {certbot_domain}")
print("\nCertbot standalone configuration:")
ip = input(f"Enter listening IP for Certbot [default: {default_ip}]: ").strip()
if not ip:
ip = default_ip
port = input(f"Enter listening Port for Certbot [default: {default_port}]: ").strip()
if not port:
port = default_port
print("\nWould you like to:")
print("1. Automatically generate SSL certificates now")
print("2. See step-by-step setup instructions")
print("3. Exit")
choice = input("Choose (1-3): ").strip()
if choice == '1':
print()
if generate_ssl(certbot_domain, ip, port):
update_choice = input("\nUpdate config.yml automatically? (y/n): ").lower()
if update_choice == 'y':
update_config_ssl(certbot_domain, public_domain, ip)
print("\n✓ Setup complete! You can now start QuickFileManager.")
elif choice == '2':
print()
print_instructions(certbot_domain, ip, port)
print(f"\nAfter obtaining certificates, run this script again to update config.yml")
if __name__ == "__main__":
main()