Compare commits

..
111 Commits
Author SHA1 Message Date
parkel a033d85d1f Merge pull request 'Prepare Coulobre v0.8.0-rc.1 for server testing' (#108) from release/v0.8.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #108
2026-11-22 17:01:43 +01:00
parkel 48c8d7f2d9 Prepare Coulobre v0.8.0-rc.1
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 16:46:06 +01:00
parkel 9be7d6b039 Run the panel installer tests in CI 2026-11-22 16:46:06 +01:00
parkel 067e303b81 Merge pull request 'Add browser, interactive, and automated panel installers' (#107) from feature/panel-installers into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #107
2026-11-22 16:44:01 +01:00
parkel 8f9d399ce4 Add interactive, unattended, and browser installer workflows
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 16:39:27 +01:00
parkel 55586e39bf Build a shared installer for the panel and hosting roles 2026-11-22 16:39:27 +01:00
parkel 71643a9bde Merge pull request 'Send scheduled account backups to an off-site repository' (#105) from feature/offsite-account-backups into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #105
2026-11-22 16:17:01 +01:00
parkel 0b93754e4c Configure and monitor off-site copies in the hosting panel
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 16:14:55 +01:00
parkel ab16c9db62 Queue off-site transfers and protect their local sources 2026-11-22 16:14:55 +01:00
parkel 6b78db3684 Transfer and verify encrypted account archives through restic 2026-11-22 16:14:55 +01:00
parkel af58151ee2 Merge pull request 'Schedule jobs for hosted websites' (#104) from feature/website-scheduled-jobs into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #104
2026-11-22 16:04:27 +01:00
parkel 8e17527ab0 Allow the receiver to terminate overdue website jobs
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 15:42:39 +01:00
parkel a01f318330 Use the existing node protocol for job requests 2026-11-22 15:39:49 +01:00
parkel 30f19727c5 Expose scheduled website jobs in the hosting panel 2026-11-22 15:38:27 +01:00
parkel 92fea45f84 Schedule website jobs with hosting plan limits and run tracking 2026-11-22 15:38:27 +01:00
parkel c944f9cb23 Run scheduled jobs under the provisioned website identity 2026-11-22 15:38:27 +01:00
parkel 539569ccb7 Merge pull request 'Add a browser file manager for websites' (#103) from feature/website-file-manager into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #103
2026-11-22 15:27:37 +01:00
parkel 4fdb4d29c5 Keep file actions readable on smaller screens
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 12:39:52 +01:00
parkel 9d97d4993b Keep the site identity switch available under systemd 2026-11-22 12:36:19 +01:00
parkel 19ed42083a Add the website file manager to the panel 2026-11-22 12:30:53 +01:00
parkel d54e3924ac Add a scoped web-node service for website files 2026-11-22 12:30:53 +01:00
parkel 651ee0fbe1 Merge pull request 'Host independent websites within a hosting account' (#102) from feature/independent-websites into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #102
2026-11-22 12:17:44 +01:00
parkel db62940063 Document and verify independent website workflows
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 12:10:07 +01:00
parkel 86d91303d4 Manage independent websites and their account lifecycle 2026-11-22 12:06:10 +01:00
parkel bd88b64ca6 Give independent websites separate node and archive identities 2026-11-22 12:06:10 +01:00
parkel 526106b7a0 Merge pull request 'Let resellers onboard customers and provision hosting resources' (#101) from feature/reseller-customer-onboarding into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #101
2026-11-22 11:53:09 +01:00
parkel 98bf8e127b Document and verify reseller account boundaries
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 11:43:42 +01:00
parkel 2846e83644 Delegate customer onboarding and provisioning to resellers 2026-11-22 11:43:42 +01:00
parkel 957979c00e Merge pull request 'Protect panel sign-in and customer password recovery' (#99) from feature/protect-panel-sign-in into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #99
2026-11-22 11:36:02 +01:00
parkel 58f589343d Document and verify panel authentication workflows
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 11:30:58 +01:00
parkel 2e9caf5498 Protect privileged sign-in and customer password recovery 2026-11-22 11:30:58 +01:00
parkel 0143543abd Merge pull request 'Prepare Coulobre v0.7.0 for mail and DNS parity' (#98) from feature/mail-dns-parity into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #98
2026-11-22 11:11:38 +01:00
parkel 8419cf3d88 Complete mailbox retirement without active Dovecot sessions
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 11:08:22 +01:00
parkel 9a73cc78d6 Retain routing state until retirement publishes safely 2026-11-22 11:05:15 +01:00
parkel 0404880176 Set the v0.7.0 release candidate version 2026-11-22 11:03:26 +01:00
parkel b7bc6b988b Manage hosted mail routing and scheduled automatic replies 2026-11-22 11:03:26 +01:00
parkel a8b51ce629 Support delegated DNS editing and additional record types 2026-11-22 11:02:45 +01:00
parkel aba83d299d Merge pull request 'Prepare Coulobre v0.6.0 for migration and panel usability' (#87) from release/v0.6.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #87
2026-11-22 08:14:51 +01:00
parkel db86430433 Preserve managed directory modes during manual migration
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 01:04:31 +01:00
parkel 1b61fd0e6d Prepare Coulobre Panel v0.6.0 release candidate 2026-11-22 01:01:09 +01:00
parkel 596a163deb Assess cPanel and Plesk account backup formats 2026-11-22 01:01:09 +01:00
parkel eb12419c84 Improve hosting account navigation and mobile panel layout 2026-11-22 01:01:09 +01:00
parkel f11891efea Restore database, mailbox, and DNS data from DirectAdmin backups 2026-11-22 01:01:09 +01:00
parkel 3636213934 Merge pull request 'Prepare the Coulobre v0.5.0-rc.1 release candidate' (#86) from release/v0.5.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #86
2026-11-22 00:45:24 +01:00
parkel 99a41714e8 Document v0.5.0 upgrade and deployment checks
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 00:40:51 +01:00
parkel cc59dc6047 Prepare Coulobre Panel v0.5.0 release candidate 2026-11-22 00:40:51 +01:00
parkel 61f7a3f5cd Merge pull request 'Add opt-in host firewalling with nftables and Fail2ban' (#85) from feature/host-firewall into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #85
2026-11-22 00:38:57 +01:00
parkel 402e531e48 Document host firewall profiles and safe operation
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 00:35:34 +01:00
parkel 8a0f9e0064 Add opt-in host firewall and authentication bans 2026-11-22 00:35:34 +01:00
parkel 54ce662b61 Merge pull request 'Install and enrol remote mail and DNS nodes' (#84) from feature/remote-node-bootstrap into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #84
2026-11-22 00:19:46 +01:00
parkel 896988d430 Document the remote node setup and enrolment workflow
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 00:16:11 +01:00
parkel 7c9d9ed541 Bootstrap and enrol remote mail and DNS nodes 2026-11-22 00:16:11 +01:00
parkel f6888a11b9 Merge pull request 'Select a PHP-FPM version per website' (#83) from feature/site-php-runtime into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #83
2026-11-22 00:00:04 +01:00
parkel f9641ef64a Document multi-PHP deployment and website version changes
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 23:58:45 +01:00
parkel 0c8a28b7e2 Select and persist a PHP-FPM series for each website 2026-11-21 23:57:07 +01:00
parkel b249cf06a9 Merge pull request 'Support single-server deployments on Debian 13' (#82) from feature/debian-single-server into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #82
2026-11-21 23:34:01 +01:00
parkel d9e7273452 Document and verify single-server deployments on Debian 13
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 23:32:53 +01:00
parkel 7a1602e5b0 Allow tar to open the private mailbox snapshot directory 2026-11-21 23:32:15 +01:00
parkel 766477214b Use Debian 13 PHP-FPM packages for managed websites 2026-11-21 23:21:08 +01:00
parkel a7220a31e0 Merge pull request 'Allow audited customer support writes' (#80) from feature/audited-support-writes into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #80
2026-11-21 23:11:12 +01:00
parkel 3b4157f514 Document and verify writable customer support sessions
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 23:05:37 +01:00
parkel 930b692328 Allow scoped and audited writes during customer support 2026-11-21 23:05:37 +01:00
parkel 6e73e342ab Merge pull request 'Prepare the Coulobre v0.4.0-rc.1 release candidate' (#79) from release/v0.4.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #79
2026-11-21 22:53:49 +01:00
parkel 8ecd4a41eb Prepare Coulobre Panel v0.4.0 release candidate
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 22:35:49 +01:00
parkel 10476cce57 Merge pull request 'Back up and restore mailboxes on a separate mail node' (#78) from feature/remote-mailbox-backup into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #78
2026-11-21 22:34:03 +01:00
parkel 386525d314 Back up and recover remote mailboxes from the panel
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 22:18:59 +01:00
parkel 13cb45dfe4 Stream native mailbox archives over a constrained SSH transport 2026-11-21 22:18:59 +01:00
parkel d076f111b6 Merge pull request 'Check and provision mail-domain DNS' (#77) from feature/mail-domain-dns-checks into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #77
2026-11-21 22:06:30 +01:00
parkel ef95ed9521 Check mail-domain DNS and provide provider setup records
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 22:04:15 +01:00
parkel 004a8b4d81 Provision DKIM and publish managed mail DNS records 2026-11-21 22:04:15 +01:00
parkel bb617a99ee Merge pull request 'Add SpamAssassin filtering for Postfix mail nodes' (#74) from feature/mail-spam-filtering into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #74
2026-11-21 21:39:48 +01:00
parkel 7d380f093d Monitor SpamAssassin services on mail nodes
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 21:00:42 +01:00
parkel de9a560f6a Integrate SpamAssassin with Postfix mail delivery 2026-11-21 21:00:42 +01:00
parkel 3afdbb08ad Merge pull request 'Open the selected mailbox in Roundcube' (#73) from feature/roundcube-mailbox-signon into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #73
2026-11-21 20:52:27 +01:00
parkel 653d365645 Document and package the Roundcube sign-on plugin
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 20:18:11 +01:00
parkel 07b26838c9 Add mailbox-scoped sign-on for Roundcube 2026-11-21 20:18:05 +01:00
parkel 8f9c5c0c94 Merge pull request 'Prepare the Coulobre v0.3.0-rc.1 release candidate' (#72) from release/v0.3.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #72
2026-11-21 19:56:02 +01:00
parkel 92d48be5fa Prepare Coulobre Panel v0.3.0 release candidate
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 19:45:59 +01:00
parkel e31f4e0608 Merge pull request 'Retire hosting accounts and release managed resource names' (#71) from feature/account-retirement into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #71
2026-11-21 19:44:11 +01:00
parkel 48bc3776b4 Verify and document account retirement policies
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 19:40:19 +01:00
parkel 103783c5d8 Manage hosting account retirement and name release in the panel 2026-11-21 19:40:19 +01:00
parkel 47a4d4e6cb Archive and detach managed resources on hosting nodes 2026-11-21 19:40:19 +01:00
parkel f1d0d8ff3e Merge pull request 'Rotate database and mailbox passwords from the panel' (#70) from feature/service-credential-rotation into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #70
2026-11-21 19:24:30 +01:00
parkel 0ab0eebfc6 Deploy remote mailbox credentials over a dedicated SSH relay
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 19:23:01 +01:00
parkel 651f041e84 Confirm and audit credential rotation in the panel 2026-11-21 19:23:01 +01:00
parkel c2655b57f5 Rotate managed database and mailbox passwords on their nodes 2026-11-21 19:23:01 +01:00
parkel f7d9336bdb Merge pull request 'Manage reseller access, hosting plans, and accounts in the panel' (#69) from feature/reseller-management into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #69
2026-11-21 19:09:38 +01:00
parkel df924c0025 Verify and document reseller policy and audit history
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 19:08:45 +01:00
parkel 7ec11a69b3 Manage reseller access, plans, and accounts in the panel 2026-11-21 19:08:45 +01:00
parkel 9bef23b5e4 Merge pull request 'Suspend and resume hosting account services' (#68) from feature/account-suspension into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #68
2026-11-21 19:01:21 +01:00
parkel 296401a436 Manage hosting service suspension in the panel
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 18:55:41 +01:00
parkel deaa18b2f3 Add reversible service restrictions to hosting nodes 2026-11-21 18:55:41 +01:00
parkel 1f1a6f4e1d Merge pull request 'Verify core release artifacts against their Git revision' (#67) from chore/check-core-release-artifacts into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #67
2026-11-21 18:38:53 +01:00
parkel 24ddc7a4af Run artifact verification before pushing release tags
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 18:24:33 +01:00
parkel 945d4232cc Verify core distribution artifacts against the reviewed Git tree 2026-11-21 18:24:33 +01:00
parkel 847337bfc3 Merge pull request 'Prepare the Coulobre v0.2.0-rc.1 release candidate' (#55) from release/v0.2.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #55
2026-11-21 18:01:16 +01:00
parkel df527438da Document the in-place panel upgrade procedure
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 17:52:19 +01:00
parkel 75032fa004 Prepare Coulobre 0.2.0rc1 package metadata 2026-11-21 17:52:19 +01:00
parkel 7411d59a02 Merge pull request 'Show local and remote service health in the admin panel' (#54) from feature/admin-service-health into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #54
2026-11-21 17:50:27 +01:00
parkel 274554a555 Deploy a periodic collector and read-only remote health probes
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 17:43:17 +01:00
parkel 37b4a66ba4 Collect and display per-node service health observations 2026-11-21 17:43:17 +01:00
parkel 9a09314758 Merge pull request 'Provision mail and publish DNS on separate servers' (#53) from feature/remote-mail-dns-nodes into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #53
2026-11-21 17:36:53 +01:00
parkel 8974b55f98 Use transport-neutral DNS and mailbox failure messages
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 17:32:52 +01:00
parkel 066fbd9be3 Document separate and shared DNS and mail nodes 2026-11-21 17:31:00 +01:00
parkel dc19e4a59a Relay DNS and mailbox provisioning over restricted SSH connections 2026-11-21 17:31:00 +01:00
parkel df9f7c3284 Merge pull request 'Prepare the Coulobre v0.1.0-rc.1 release candidate' (#51) from release/v0.1.0-rc.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #51
2026-11-21 17:10:26 +01:00
parkel b9afdcb314 Document the source and wheel release checks
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 17:01:07 +01:00
parkel f6090f5646 Package the first Coulobre release candidate and deployment files 2026-11-21 17:01:07 +01:00
parkel 49a819ce85 Merge pull request 'Verify the single-server installation and account recovery' (#50) from test/single-server-preview into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #50
2026-11-21 16:59:37 +01:00
parkel 86ec070c99 Document single-server verification and account recovery drills
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-21 16:51:34 +01:00
parkel 08d132654e Merge pull request 'Track the roadmap and release workflow in Gitea' (#49) from docs/gitea-roadmap-workflow into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #49
2026-11-21 16:40:52 +01:00
294 changed files with 27380 additions and 814 deletions

No files matched your search

+10 -1
View File
@@ -51,4 +51,13 @@ jobs:
python manage.py makemigrations --check --dry-run
- name: Run tests
run: python manage.py test coulobre
run: |
python manage.py test coulobre
python -m unittest discover -s tests -p test_panel_installer.py
- name: Verify package artifacts
if: matrix.python-version == '3.14'
run: |
python -m pip install build
python -m build
python tools/check_core_release.py dist/*.tar.gz dist/*.whl
+22 -7
View File
@@ -27,13 +27,25 @@
- Maintainers assign accepted work to a milestone when it has a target
release. Issues without a milestone stay in the backlog. Add a due date
when a release date has been agreed.
- When a version is ready to ship, update the package version in
`pyproject.toml`, tag the tested commit on `main` with an annotated tag such
as `v0.1.0`, and publish the corresponding [Gitea release][releases]. Include
user-visible changes, installation or upgrade instructions, and any known
limitations. Use tags such as
`v0.1.0-rc.1` for release candidates and mark them as prereleases. Close the
milestone when its target version is published.
### Prepare a release
1. Update the package version in `pyproject.toml`. For a release candidate,
use a Python version such as `0.1.0rc1` and a matching Git tag such as
`v0.1.0-rc.1`. [Python version specifiers][versions]
2. From a clean checkout, use `python -m build` to build the source
distribution and wheel. Run
`python tools/check_core_release.py dist/*.tar.gz dist/*.whl` to compare
both packages with the reviewed Git tree. Use `--ref <tag-or-commit>`
to verify the files against a specific revision. Install the built wheel
in a fresh virtual environment and run the deployment checks.
[Build documentation][build] · [Deployment checks][deployment-checks]
3. Create an annotated tag for the tested commit on `main`. Verify the
artifacts against that local tag before pushing it. Publish the
corresponding [Gitea release][releases] with the verified source
distribution and wheel. Include user-visible changes, installation or upgrade
instructions, and known limitations. Mark a release candidate as a
prerelease. Close the milestone when its target version is published.
## Pull requests
@@ -49,6 +61,9 @@
[issues]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/issues
[milestones]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/milestones
[releases]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/releases
[versions]: https://packaging.python.org/en/latest/specifications/version-specifiers/#pre-releases
[build]: https://build.pypa.io/en/stable/
[deployment-checks]: docs/deployment.md#verify-a-new-installation
## Code style
+4
View File
@@ -0,0 +1,4 @@
include CONTRIBUTING.md manage.py
graft deploy
graft docs
graft tests
+5 -4
View File
@@ -4,11 +4,12 @@ Coulobre Panel is an open-source web hosting control panel for hosting providers
and resellers. The project is in early development.
The web panel gives operators a workspace to manage hosting accounts, request
Apache configuration previews, and follow their progress. Administrators with
permission can view the panel as a customer in a read-only support session.
Apache configuration previews, and follow their progress. Administrators
with the appropriate permissions can view the panel as a customer or
perform audited support actions on their behalf.
See [Local development](docs/development.md) to run it.
See [Single-server deployment](docs/deployment.md) to install it with Apache,
MariaDB, and RabbitMQ.
Use the [installer or manual deployment guide](docs/deployment.md) to set up
Apache, MariaDB, and RabbitMQ.
## Roadmap and releases
+5
View File
@@ -5,6 +5,7 @@ RequestHeader unset X-Forwarded-Protocol
RequestHeader unset X-Forwarded-Ssl
RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-For "expr=%{REMOTE_ADDR}"
RequestHeader set X-Coulobre-Client-IP "expr=%{REMOTE_ADDR}"
ProxyPass /static/ !
Alias /static/ /var/www/coulobre-panel-static/
@@ -14,5 +15,9 @@ Alias /static/ /var/www/coulobre-panel-static/
Require all granted
</Directory>
<LocationMatch "^/accounts/[0-9]+/(websites/[0-9]+/)?files/$">
LimitRequestBody 68157440
</LocationMatch>
ProxyPass / "unix:/run/coulobre-panel/panel.sock|http://localhost/"
ProxyPassReverse / http://localhost/
@@ -0,0 +1,9 @@
# Include in dovecot.conf or a loaded conf.d file.
auth_mechanisms = plain login
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}
+7
View File
@@ -0,0 +1,7 @@
# Include only on a mail node with dovecot-sieve installed.
protocol lmtp {
mail_plugins = $mail_plugins sieve
}
plugin {
sieve_before = file:/var/lib/coulobre-vacation/%d/%n.sieve;bindir=~/.coulobre-sieve
}
+11
View File
@@ -0,0 +1,11 @@
# Include only on a mail node with dovecot-sieve installed.
protocol lmtp {
mail_plugins {
sieve = yes
}
}
sieve_script coulobre-vacation {
type = before
path = /var/lib/coulobre-vacation/%{user | domain}/%{user | username}.sieve
bin_path = ~/.coulobre-sieve
}
+15
View File
@@ -0,0 +1,15 @@
{
"version": 1,
"profile": "public",
"services": ["web", "mail", "dns", "sftp"],
"admin_sources": ["192.0.2.10", "2001:db8::10"],
"ssh_port": 22,
"panel_ports": [80, 443],
"rates": {
"panel": 40,
"web": 120,
"mail": 30,
"dns": 100,
"ssh": 8
}
}
+66
View File
@@ -0,0 +1,66 @@
#!/bin/sh
set -eu
if [ "$(id -u)" -ne 0 ] || [ "$#" -eq 0 ]; then
echo "Run as root with one or more roles: dns mail" >&2
exit 1
fi
dns=
mail=
for role in "$@"; do
case "$role" in
dns) dns=1 ;;
mail) mail=1 ;;
*) echo "Unknown node role: $role" >&2; exit 1 ;;
esac
done
cd "$(dirname "$0")/.."
venv=/opt/coulobre
release=$(python3 -c '
import tomllib
with open("pyproject.toml", "rb") as project:
print(tomllib.load(project)["project"]["version"])
')
python3 - "$venv" <<'PY'
import os
import stat
import sys
from pathlib import Path
venv = Path(sys.argv[1])
for directory in (venv.parent, venv, venv / "bin"):
if not os.path.lexists(directory):
continue
info = directory.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
sys.exit(f"Expected a root-controlled directory at {directory}.")
PY
installed=
if [ -x "$venv/bin/python" ]; then
installed=$("$venv/bin/python" -c '
from importlib.metadata import PackageNotFoundError, version
try:
print(version("coulobre-panel"))
except PackageNotFoundError:
pass
')
if [ -n "$installed" ] && [ "$installed" != "$release" ]; then
echo "Use the matching source release or upgrade Coulobre first." >&2
exit 1
fi
fi
# Package arguments below are fixed for each supported role.
apt-get update
apt-get install --yes --no-upgrade python3-venv openssh-server socat \
${dns:+bind9 bind9-utils} \
${mail:+postfix dovecot-core dovecot-imapd dovecot-lmtpd}
if [ ! -x "$venv/bin/python" ]; then
python3 -m venv "$venv"
fi
if [ -z "$installed" ]; then
"$venv/bin/pip" install .
fi
exec "$venv/bin/coulobre-node-setup" install-receiver "$@"
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env python3
from panel_installer.cli import main
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,15 @@
Match User coulobre-health-request
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthorizedKeysFile /etc/ssh/coulobre-node-keys/%u
AuthorizedKeysCommand none
TrustedUserCAKeys none
DisableForwarding yes
PermitTunnel no
PermitTTY no
PermitUserRC no
ForceCommand /opt/coulobre/bin/coulobre-service-health
Match all
@@ -0,0 +1,20 @@
Match User coulobre-mail-archive-backup,coulobre-mail-archive-restore
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthorizedKeysFile /etc/ssh/coulobre-node-keys/%u
AuthorizedKeysCommand none
TrustedUserCAKeys none
DisableForwarding yes
PermitTunnel no
PermitTTY no
PermitUserRC no
Match User coulobre-mail-archive-backup
ForceCommand /usr/bin/socat -t 1810 STDIO UNIX-CONNECT:/run/coulobre-mail-archive-backup.sock
Match User coulobre-mail-archive-restore
ForceCommand /usr/bin/socat -t 1810 STDIO UNIX-CONNECT:/run/coulobre-mail-archive-restore.sock
Match all
@@ -0,0 +1,15 @@
Match User coulobre-mail-credential-request
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthorizedKeysFile /etc/ssh/coulobre-node-keys/%u
AuthorizedKeysCommand none
TrustedUserCAKeys none
DisableForwarding yes
PermitTunnel no
PermitTTY no
PermitUserRC no
ForceCommand /usr/bin/socat -t 92 STDIO UNIX-CONNECT:/run/coulobre-mail-credentials.sock
Match all
@@ -0,0 +1,20 @@
Match User coulobre-dns-request,coulobre-mail-request
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthorizedKeysFile /etc/ssh/coulobre-node-keys/%u
AuthorizedKeysCommand none
TrustedUserCAKeys none
DisableForwarding yes
PermitTunnel no
PermitTTY no
PermitUserRC no
Match User coulobre-dns-request
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-dns-apply.sock
Match User coulobre-mail-request
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-mail-apply.sock
Match all
@@ -0,0 +1,13 @@
Host coulobre-dns-node
HostName dns.example.org
Port 22
User coulobre-dns-request
IdentityFile /etc/coulobre-remote/dns/id_ed25519
IdentityAgent none
IdentitiesOnly yes
PreferredAuthentications publickey
UserKnownHostsFile /etc/coulobre-remote/dns/known_hosts
GlobalKnownHostsFile none
StrictHostKeyChecking yes
BatchMode yes
ConnectTimeout 5
+13
View File
@@ -0,0 +1,13 @@
Host mail-01
HostName mail.example.org
Port 22
User coulobre-health-request
IdentityFile /etc/coulobre-health/id_ed25519
UserKnownHostsFile /etc/coulobre-health/known_hosts
Host dns-01
HostName dns.example.org
Port 22
User coulobre-health-request
IdentityFile /etc/coulobre-health/id_ed25519
UserKnownHostsFile /etc/coulobre-health/known_hosts
@@ -0,0 +1,22 @@
Host coulobre-mail-archive-backup
User coulobre-mail-archive-backup
IdentityFile /etc/coulobre-remote/mail-archive-backup/id_ed25519
UserKnownHostsFile /etc/coulobre-remote/mail-archive-backup/known_hosts
Host coulobre-mail-archive-restore
User coulobre-mail-archive-restore
IdentityFile /etc/coulobre-remote/mail-archive-restore/id_ed25519
UserKnownHostsFile /etc/coulobre-remote/mail-archive-restore/known_hosts
Host coulobre-mail-archive-*
HostName mail.example.org
Port 22
IdentityAgent none
IdentitiesOnly yes
PreferredAuthentications publickey
GlobalKnownHostsFile none
StrictHostKeyChecking yes
BatchMode yes
ConnectTimeout 5
ServerAliveInterval 30
ServerAliveCountMax 3
@@ -0,0 +1,13 @@
Host coulobre-mail-credentials
HostName mail.example.org
Port 22
User coulobre-mail-credential-request
IdentityFile /etc/coulobre-remote/mail-credentials/id_ed25519
IdentityAgent none
IdentitiesOnly yes
PreferredAuthentications publickey
UserKnownHostsFile /etc/coulobre-remote/mail-credentials/known_hosts
GlobalKnownHostsFile none
StrictHostKeyChecking yes
BatchMode yes
ConnectTimeout 5
@@ -0,0 +1,13 @@
Host coulobre-mail-node
HostName mail.example.org
Port 22
User coulobre-mail-request
IdentityFile /etc/coulobre-remote/mail/id_ed25519
IdentityAgent none
IdentitiesOnly yes
PreferredAuthentications publickey
UserKnownHostsFile /etc/coulobre-remote/mail/known_hosts
GlobalKnownHostsFile none
StrictHostKeyChecking yes
BatchMode yes
ConnectTimeout 5
+23
View File
@@ -0,0 +1,23 @@
[panel]
hostname = "panel.example.net"
access = "tls"
certificate = "/etc/ssl/coulobre-panel/fullchain.pem"
key = "/etc/ssl/coulobre-panel/privkey.pem"
# For an external HTTPS proxy, use access = "proxy" with origin_ip,
# origin_port, and proxy_ip in place of the certificate and key.
[admin]
username = "operator"
email = "operator@example.net"
password_file = "/root/coulobre-admin-password"
[dns]
mode = "local"
[mail]
mode = "off"
# A local mail role requires host, certificate, and key.
# A remote DNS or mail role requires mode = "remote", host, and host_key.
# Use port = 22 or the separate node's configured SSH port.
+30
View File
@@ -1,6 +1,16 @@
DJANGO_SETTINGS_MODULE=coulobre.settings
COULOBRE_ALLOWED_HOSTS=panel.example.net
COULOBRE_HTTPS_PROXY=1
COULOBRE_REQUIRE_PRIVILEGED_MFA=1
COULOBRE_TRUST_APACHE_CLIENT_IP=1
# Set an SMTP relay for email verification and customer password resets.
# COULOBRE_SMTP_HOST=smtp.example.net
# COULOBRE_SMTP_PORT=587
# COULOBRE_SMTP_USER=
# COULOBRE_SMTP_PASSWORD=
# COULOBRE_SMTP_STARTTLS=1
# COULOBRE_EMAIL_FROM=panel@example.net
# COULOBRE_PASSWORD_RESET_ORIGIN=https://panel.example.net
COULOBRE_STATIC_ROOT=/var/www/coulobre-panel-static
COULOBRE_SECRET_KEY=
COULOBRE_DB_NAME=coulobre_panel
@@ -8,20 +18,40 @@ COULOBRE_DB_USER=coulobre
COULOBRE_DB_PASSWORD=
COULOBRE_DB_HOST=/run/mysqld/mysqld.sock
COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_SERVICE_HEALTH='{"panel-01":{"local":["panel","worker","scheduler","apache","mariadb","rabbitmq"]}}'
# COULOBRE_LOCAL_WEB_ACTIVATION=1
# COULOBRE_LOCAL_WEB_HTTPS=1
# COULOBRE_LOCAL_WEB_SFTP=1
# COULOBRE_WEB_FILE_MANAGER=1
# COULOBRE_WEBSITE_JOBS=1
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1
# These two switches also enable provisioners using the SSH service drop-ins.
# COULOBRE_LOCAL_DNS_PUBLISHING=1
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
# COULOBRE_MAIL_ROUTING=1
# COULOBRE_MAIL_VACATION=1
# COULOBRE_LOCAL_DATABASE_CREDENTIALS=1
# COULOBRE_LOCAL_MAILBOX_CREDENTIALS=1
# COULOBRE_REMOTE_MAILBOX_CREDENTIALS=1
# COULOBRE_LOCAL_DATABASE_CREDENTIALS_ROTATION=1
# COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1
# COULOBRE_REMOTE_MAILBOX_CREDENTIALS_ROTATION=1
# COULOBRE_MAIL_IMAP_HOST=mail.example.org
# COULOBRE_MAIL_MX_HOST=mx.example.org
# COULOBRE_MAIL_DNS_RESOLVERS=
# COULOBRE_MAIL_SENDING_IPS=
# COULOBRE_MAIL_MX_IPS=
# COULOBRE_MANAGE_MAIL_DNS=1
# COULOBRE_PHPMYADMIN_URL=https://tools.example.org/phpmyadmin
# COULOBRE_PHPMYADMIN_BRIDGE_KEY=
# COULOBRE_ROUNDCUBE_URL=https://webmail.example.org
# COULOBRE_ROUNDCUBE_BRIDGE_KEY=
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
# COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1
# COULOBRE_LOCAL_BACKUP_RETENTION=1
# COULOBRE_OFFSITE_BACKUP_DESTINATIONS='{"vault":"Off-site vault"}'
# COULOBRE_LOCAL_WEBSITE_RESTORE=1
# COULOBRE_LOCAL_DATABASE_RESTORE=1
# COULOBRE_LOCAL_MAILBOX_RESTORE=1
# COULOBRE_REMOTE_MAILBOX_RESTORE=1
+1
View File
@@ -0,0 +1 @@
"""Coulobre source-release installer."""
+162
View File
@@ -0,0 +1,162 @@
import argparse
import os
import sys
from getpass import getpass
from .config import (
InstallError,
check_password,
parse_plan,
platform_settings,
read_password,
read_plan,
)
from .engine import Installer
def prompt(label, default=""):
value = input(f"{label}{f' [{default}]' if default else ''}: ").strip()
return value or default
def number(value, label):
try:
return int(value)
except ValueError:
raise InstallError(f"Enter a numeric port for {label}.") from None
def interactive_plan():
panel = {"hostname": prompt("Panel hostname")}
access = panel["access"] = prompt("Panel access (tls or proxy)", "tls")
if access == "tls":
panel["certificate"] = prompt("Panel certificate path")
panel["key"] = prompt("Panel private key path")
elif access == "proxy":
panel["origin_ip"] = prompt("Private origin address")
panel["proxy_ip"] = prompt("Trusted proxy address")
panel["origin_port"] = number(
prompt("Origin port", "8080"), "the origin"
)
data = {
"panel": panel,
"admin": {
"username": prompt("Administrator username", "operator"),
"email": prompt("Administrator email"),
},
}
for name in ("dns", "mail"):
mode = prompt(f"{name.upper()} role (off, local, or remote)", "off")
target = data[name] = {"mode": mode}
if mode == "remote":
target["host"] = prompt(
f"{name.upper()} node SSH hostname or address"
)
target["port"] = number(
prompt("SSH port", "22"), f"the {name} node"
)
target["host_key"] = prompt("Verified SSH host public key file")
elif name == "mail" and mode == "local":
target["host"] = prompt("Local mail hostname")
target["certificate"] = prompt("Mail certificate path")
target["key"] = prompt("Mail private key path")
return parse_plan(data)
def get_password(path):
if path:
return read_password(path)
if not sys.stdin.isatty():
raise InstallError(
"Use a terminal or provide a private password file."
)
password = check_password(getpass("Administrator password: "))
if getpass("Repeat the administrator password: ") != password:
raise InstallError("The administrator passwords differ.")
return password
def main(argv=None):
parser = argparse.ArgumentParser(
description="Install Coulobre Panel on a fresh server."
)
modes = parser.add_mutually_exclusive_group()
modes.add_argument(
"--interactive",
action="store_true",
help="Use guided prompts (the default).",
)
modes.add_argument(
"--config",
metavar="FILE",
help="Read installation parameters from TOML.",
)
modes.add_argument(
"--web", action="store_true", help="Open the loopback setup wizard."
)
parser.add_argument(
"--admin-password-file",
help="Read the administrator password from a private file.",
)
parser.add_argument(
"--port",
type=int,
default=8765,
help="Loopback port for the web wizard.",
)
parser.add_argument(
"--check",
action="store_true",
help="Validate parameters without installing.",
)
options = parser.parse_args(argv)
if options.check and not options.config:
parser.error("--check requires --config.")
if options.port != 8765 and not options.web:
parser.error("--port requires --web.")
try:
platform_settings()
if not options.check and os.geteuid() != 0:
raise InstallError("Run the installer as root.")
if options.web:
from .web import serve_wizard
if not options.admin_password_file:
parser.error("--web requires --admin-password-file.")
return serve_wizard(
read_password(options.admin_password_file), options.port
)
if options.config:
data = read_plan(options.config)
plan = parse_plan(data)
password_path = options.admin_password_file or data["admin"].get(
"password_file"
)
if not password_path:
raise InstallError(
"Specify the administrator password file in [admin]."
)
password = read_password(password_path)
else:
plan = interactive_plan()
print(plan.description(), flush=True)
if (
prompt("Install with these settings (yes or no)", "no").lower()
!= "yes"
):
return 0
password = get_password(options.admin_password_file)
if options.check:
print(plan.description())
return 0
installer = Installer(
plan, password, lambda message: print(message, flush=True)
)
installer.install()
return 0
except (InstallError, OSError, ValueError) as error:
print(f"Coulobre installer: {error}", file=sys.stderr)
return 1
except (EOFError, KeyboardInterrupt):
print("\nInstallation input was interrupted.", file=sys.stderr)
return 1
+288
View File
@@ -0,0 +1,288 @@
import os
import re
import ssl
import stat
import tomllib
from dataclasses import asdict, dataclass
from ipaddress import ip_address
from pathlib import Path
from platform import freedesktop_os_release
PLATFORMS = {
("ubuntu", "26.04"): ("8.5", True),
("debian", "13"): ("8.4", True),
("ubuntu", "24.04"): (None, False),
}
DNS_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")
FILE_PATH = re.compile(r"/[a-zA-Z0-9_./+-]+")
USERNAME = re.compile(r"[a-zA-Z0-9@.+_-]{1,150}")
EMAIL = re.compile(r"[^\s@]+@[^\s@]+\.[^\s@]+")
class InstallError(Exception):
pass
def keys(table, allowed, label):
if not isinstance(table, dict) or table.keys() - set(allowed):
raise InstallError(f"Check the fields in the {label} section.")
def hostname(value, label):
if isinstance(value, str):
try:
value = value.encode("idna").decode("ascii").lower().rstrip(".")
labels = value.split(".")
if (
len(value) <= 253
and len(labels) >= 2
and all(DNS_LABEL.fullmatch(part) for part in labels)
):
return value
except UnicodeError:
pass
raise InstallError(f"Enter a fully qualified {label} hostname.")
def address(value, label, *, private=False):
if not isinstance(value, str) or "%" in value:
raise InstallError(f"Enter a literal IP address for {label}.")
try:
ip = ip_address(value)
except ValueError:
raise InstallError(
f"Enter a literal IP address for {label}."
) from None
if (
ip.is_unspecified
or ip.is_multicast
or (private and (ip.is_global or not ip.is_private))
):
raise InstallError(f"Enter a usable address for {label}.")
return str(ip)
def port(value, label, default):
if value is None:
return default
if type(value) is not int or not 1 <= value <= 65535:
raise InstallError(f"Enter a port from 1 to 65535 for {label}.")
return value
def file_path(value, label):
if (
not isinstance(value, str)
or not FILE_PATH.fullmatch(value)
or ".." in Path(value).parts
):
raise InstallError(f"Enter an absolute file path for {label}.")
return value
def certificate(table, label):
chain = file_path(table.get("certificate"), f"the {label} certificate")
key = file_path(table.get("key"), f"the {label} certificate key")
try:
for value in (chain, key):
resolved = Path(value).resolve(strict=True)
if any(
resolved.is_relative_to(directory)
for directory in ("/root", "/home", "/run/user")
):
raise InstallError(
f"Place the {label} TLS files outside home directories."
)
ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER).load_cert_chain(
chain, key, password=""
)
except (OSError, ValueError) as error:
raise InstallError(
f"Check the certificate and key for {label}."
) from error
return chain, key
@dataclass(frozen=True)
class Role:
mode: str
host: str = ""
port: int = 22
host_key: str = ""
certificate: str = ""
key: str = ""
def role(table, name):
if not isinstance(table, dict):
raise InstallError(f"Check the {name} section.")
mode = table.get("mode", "off")
if mode == "off" or (mode == "local" and name == "dns"):
keys(table, {"mode"}, name)
return Role(mode)
if mode == "local":
keys(table, {"mode", "host", "certificate", "key"}, name)
host = hostname(table.get("host"), "mail")
chain, key = certificate(table, "mail")
return Role(mode, host=host, certificate=chain, key=key)
if mode == "remote":
keys(table, {"mode", "host", "host_key", "port"}, name)
host = table.get("host")
try:
normalized = address(host, f"the {name} node")
except InstallError:
normalized = hostname(host, f"{name} node")
host_key = file_path(table.get("host_key"), f"the {name} SSH host key")
try:
with Path(host_key).open(encoding="ascii") as source:
key = source.read(16385)
if len(key) > 16384 or len(key.strip().splitlines()) != 1:
raise ValueError
if len(key.split()) < 2:
raise ValueError
except (OSError, ValueError):
raise InstallError(
f"Read the pinned {name} SSH public key."
) from None
return Role(
mode,
host=normalized,
port=port(table.get("port"), f"the {name} node", 22),
host_key=host_key,
)
raise InstallError(f"Choose off, local, or remote for {name}.")
@dataclass(frozen=True)
class Plan:
hostname: str
access: str
certificate: str
key: str
origin_ip: str
proxy_ip: str
origin_port: int
admin_username: str
admin_email: str
dns: Role
mail: Role
def description(self):
return (
f"https://{self.hostname}/ · {self.access} · "
f"DNS {self.dns.mode} · mail {self.mail.mode} · "
f"Administrator {self.admin_username}"
)
def record(self):
return asdict(self)
def parse_plan(data):
keys(data, {"panel", "admin", "dns", "mail"}, "installation")
panel = data.get("panel")
admin = data.get("admin")
keys(admin, {"username", "email", "password_file"}, "admin")
username = admin.get("username", "operator")
email = admin.get("email", "")
if not isinstance(username, str) or not USERNAME.fullmatch(username):
raise InstallError("Enter a valid administrator username.")
if (
not isinstance(email, str)
or len(email) > 254
or not EMAIL.fullmatch(email)
):
raise InstallError("Enter a valid administrator email address.")
if not isinstance(panel, dict):
raise InstallError("Provide a panel section.")
host = hostname(panel.get("hostname"), "panel")
access = panel.get("access", "tls")
chain = key = origin = proxy = ""
origin_port = 8080
if access == "tls":
keys(panel, {"hostname", "access", "certificate", "key"}, "panel")
chain, key = certificate(panel, "the panel")
elif access == "proxy":
keys(
panel,
{"hostname", "access", "origin_ip", "origin_port", "proxy_ip"},
"panel",
)
origin = address(panel.get("origin_ip"), "the origin", private=True)
proxy = address(
panel.get("proxy_ip"), "the reverse proxy", private=True
)
origin_port = port(panel.get("origin_port"), "the origin", 8080)
if origin_port in {80, 443}:
raise InstallError(
"Use a separate origin port for the reverse proxy."
)
else:
raise InstallError("Choose tls or proxy for panel access.")
return Plan(
host,
access,
chain,
key,
origin,
proxy,
origin_port,
username,
email,
role(data.get("dns", {}), "dns"),
role(data.get("mail", {}), "mail"),
)
def read_plan(path):
try:
with Path(path).open("rb") as source:
raw = source.read(65537)
if len(raw) > 65536:
raise ValueError
return tomllib.loads(raw.decode("utf-8"))
except (OSError, ValueError) as error:
raise InstallError("Read a valid TOML installation file.") from error
def check_password(password):
if not isinstance(password, str) or not 12 <= len(password) <= 1024:
raise InstallError(
"Use an administrator password of 12 to 1024 characters."
)
if not password.isprintable():
raise InstallError("Use a single-line administrator password.")
return password
def read_password(path):
try:
fd = os.open(
file_path(path, "the administrator password file"),
os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
)
with os.fdopen(fd, "rb") as source:
info = os.fstat(source.fileno())
if (
not stat.S_ISREG(info.st_mode)
or info.st_uid != 0
or stat.S_IMODE(info.st_mode) != 0o600
or info.st_size > 4097
):
raise OSError
password = source.read(4098).decode("utf-8").removesuffix("\n")
except (OSError, ValueError):
raise InstallError(
"Use a root-owned administrator password file with mode 0600."
) from None
return check_password(password)
def platform_settings():
try:
system = freedesktop_os_release()
return PLATFORMS[system["ID"], system["VERSION_ID"]]
except (KeyError, OSError):
raise InstallError(
"Use Ubuntu 26.04, Ubuntu 24.04, or Debian 13."
) from None
+690
View File
@@ -0,0 +1,690 @@
import fcntl
import grp
import json
import os
import pwd
import secrets
import socket
import stat
import subprocess
import sys
import time
import tomllib
from contextlib import contextmanager
from pathlib import Path
from tempfile import TemporaryDirectory
from . import roles
from .config import InstallError, platform_settings
SOURCE = Path(__file__).resolve().parents[2]
ASSETS = SOURCE / "deploy"
VENV = Path("/opt/coulobre")
BINDIR = VENV / "bin"
ETC = Path("/etc/coulobre")
ENV_FILE = ETC / "panel.env"
STATE = Path("/var/lib/coulobre-installer")
SYSTEMD = Path("/etc/systemd/system")
STATIC = Path("/var/www/coulobre-panel-static")
PATH = "/usr/sbin:/usr/bin:/sbin:/bin"
PANEL_UNITS = (
"coulobre-panel.service",
"coulobre-worker.service",
"coulobre-beat.service",
)
BASE_PACKAGES = (
"apache2",
"mariadb-server",
"rabbitmq-server",
"python3-venv",
"python3-dev",
"build-essential",
"pkg-config",
"default-libmysqlclient-dev",
"ca-certificates",
)
ADMIN_SCRIPT = """import json
import sys
import django
django.setup()
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from django.db import transaction
data = json.load(sys.stdin)
users = get_user_model().objects
with transaction.atomic():
previous = users.filter(username=data["username"]).first()
if previous is not None:
if not previous.is_superuser or previous.email != data["email"]:
sys.exit(1)
else:
validate_password(data["password"])
users.create_superuser(**data)
"""
def run(*args, label, source=None, timeout=120, env=None):
try:
result = subprocess.run(
[os.fspath(value) for value in args],
input=source,
stdin=subprocess.DEVNULL if source is None else None,
capture_output=True,
env={"PATH": PATH, "LC_ALL": "C.UTF-8", **(env or {})},
check=False,
timeout=timeout,
)
except (OSError, subprocess.TimeoutExpired):
raise InstallError(f"{label} failed or timed out.") from None
if result.returncode:
raise InstallError(f"{label} failed. Check the service and retry.")
return result.stdout.decode("utf-8", errors="replace")
def root_directory(path, mode=0o755):
if not os.path.lexists(path):
path.mkdir(mode=mode)
info = path.lstat()
if (
not stat.S_ISDIR(info.st_mode)
or info.st_uid != 0
or info.st_mode & 0o022
):
raise InstallError(f"Expected a root-controlled directory at {path}.")
def root_file(path, mode):
info = path.lstat()
if (
not stat.S_ISREG(info.st_mode)
or info.st_uid != 0
or stat.S_IMODE(info.st_mode) != mode
):
raise InstallError(f"Expected a root-owned {mode:04o} file at {path}.")
def put_file(path, content, *, mode=0o644, group=0, update=False):
root_directory(path.parent)
if os.path.lexists(path):
root_file(path, mode)
if path.stat().st_gid != group:
raise InstallError(f"Check the group ownership of {path}.")
if path.read_text(encoding="utf-8") == content:
return
if not update:
raise InstallError(f"Existing configuration differs at {path}.")
with TemporaryDirectory(dir=path.parent) as directory:
staged = Path(directory) / "new"
with staged.open("x", encoding="utf-8") as stream:
stream.write(content)
stream.flush()
os.fchown(stream.fileno(), 0, group)
os.fchmod(stream.fileno(), mode)
os.fsync(stream.fileno())
if update:
staged.replace(path)
else:
os.link(staged, path)
directory_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
def group(name):
try:
return grp.getgrnam(name)
except KeyError:
run("groupadd", "--system", name, label=f"Create group {name}")
return grp.getgrnam(name)
def identity(name, home="/nonexistent"):
try:
account = pwd.getpwnam(name)
except KeyError:
run(
"useradd",
"--system",
"--user-group",
"--no-create-home",
"--home-dir",
home,
"--shell",
"/usr/sbin/nologin",
name,
label=f"Create service user {name}",
)
account = pwd.getpwnam(name)
try:
primary_gid = grp.getgrnam(name).gr_gid
except KeyError:
raise InstallError(f"Create a private group for {name}.") from None
if (
account.pw_uid == 0
or account.pw_gid != primary_gid
or account.pw_dir != home
or account.pw_shell != "/usr/sbin/nologin"
or set(os.getgrouplist(name, account.pw_gid)) != {account.pw_gid}
):
raise InstallError(f"Review the existing service account {name}.")
return account
def install_unit(unit):
source = ASSETS / "systemd" / unit
if "/" in unit:
root_directory((SYSTEMD / unit).parent)
put_file(SYSTEMD / unit, source.read_text(encoding="utf-8"))
def install_worker(group_name, user, socket_unit, worker_unit):
group(group_name)
identity(user)
for unit in (
f"{socket_unit}.socket",
f"{socket_unit}@.service",
worker_unit,
):
install_unit(unit)
return worker_unit
def systemctl(*args):
return run(
"systemctl", *args, label=f"systemctl {' '.join(args)}", timeout=180
)
def install_packages(packages, *, mail_host=""):
status = subprocess.run(
["dpkg-query", "-W", "-f=${db:Status-Status} ${Package}\n", *packages],
stdin=subprocess.DEVNULL,
capture_output=True,
env={"PATH": PATH},
timeout=30,
check=False,
)
installed = {
line.split()[1]
for line in status.stdout.decode().splitlines()
if line.startswith("installed ")
}
if set(packages) - installed:
apt_env = {"DEBIAN_FRONTEND": "noninteractive"}
if mail_host and "postfix" not in installed:
answers = (
"postfix postfix/main_mailer_type select Internet Site\n"
f"postfix postfix/mailname string {mail_host}\n"
)
run(
"debconf-set-selections",
source=answers.encode(),
label="Choose the local Postfix installation profile",
)
run(
"apt-get",
"update",
label="Refresh the configured APT repositories",
env=apt_env,
timeout=600,
)
run(
"apt-get",
"install",
"--yes",
"--no-upgrade",
*packages,
label="Install the required APT packages",
env=apt_env,
timeout=1800,
)
def install_release(release):
root_directory(VENV.parent)
if os.path.lexists(VENV):
root_directory(VENV)
if not (BINDIR / "python").is_file():
run(
sys.executable,
"-m",
"venv",
VENV,
label="Create the Coulobre virtual environment",
)
root_directory(BINDIR)
script = (
"from importlib.util import find_spec; "
"from importlib.metadata import distributions; "
"print(next((p.version for p in distributions() "
"if p.metadata['Name'] == 'coulobre-panel'), '')); "
"print(int(bool(find_spec('gunicorn') and find_spec('MySQLdb'))))"
)
installed, ready = run(
BINDIR / "python", "-c", script, label="Check the Coulobre version"
).splitlines()
if installed and installed != release:
raise InstallError("Use the source release matching /opt/coulobre.")
if installed and ready == "1":
return
with_extras = f"{SOURCE}[server,mariadb]"
pip_env = {
key: os.environ[key]
for key in ("PIP_NO_INDEX", "PIP_FIND_LINKS")
if key in os.environ
}
run(
BINDIR / "pip",
"install",
"--disable-pip-version-check",
with_extras,
label="Install Coulobre and its Python dependencies",
env=pip_env,
timeout=1200,
)
@contextmanager
def install_lock():
root_directory(STATE, mode=0o700)
if stat.S_IMODE(STATE.stat().st_mode) != 0o700:
raise InstallError(f"Set mode 0700 on {STATE}.")
lock = os.open(
STATE / "lock", os.O_CREAT | os.O_NOFOLLOW | os.O_RDWR, 0o600
)
try:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise InstallError(
"A Coulobre installation is already running."
) from None
yield
finally:
os.close(lock)
class Installer:
def __init__(self, plan, password, progress):
self.plan = plan
self.password = password
self.progress = progress
self.state_file = STATE / "installation.json"
self.php, self.modern_mail = platform_settings()
with (SOURCE / "pyproject.toml").open("rb") as project:
self.release = tomllib.load(project)["project"]["version"]
def save_state(self):
put_file(
self.state_file,
json.dumps(self.state, indent=2) + "\n",
mode=0o600,
update=True,
)
def read_state(self):
expected = {"release": self.release, "plan": self.plan.record()}
if self.state_file.exists():
root_file(self.state_file, 0o600)
self.state = json.loads(
self.state_file.read_text(encoding="utf-8")
)
if {key: self.state.get(key) for key in expected} != expected:
raise InstallError(
"Resume with the same installation settings and release."
)
else:
if os.path.lexists(ENV_FILE):
raise InstallError(
"The panel already has a configuration. "
"Use the upgrade guide."
)
self.state = expected | {
"secret_key": secrets.token_urlsafe(48),
"database_password": secrets.token_urlsafe(36),
"broker_password": secrets.token_urlsafe(36),
}
self.save_state()
def packages(self):
packages = list(BASE_PACKAGES)
if self.php:
packages.append(f"php{self.php}-fpm")
if self.plan.dns.mode == "local":
packages.extend(("bind9", "bind9-utils"))
if self.plan.mail.mode == "local":
packages.extend(
("postfix", "dovecot-core", "dovecot-imapd", "dovecot-lmtpd")
)
if "remote" in (self.plan.dns.mode, self.plan.mail.mode):
packages.extend(("openssh-client", "socat"))
return packages
def configure_stores(self):
put_file(
Path("/etc/mysql/mariadb.conf.d/90-coulobre-loopback.cnf"),
"[mariadbd]\nbind-address=127.0.0.1\n",
)
broker_config = Path("/etc/rabbitmq")
if any(
(broker_config / name).exists()
for name in ("rabbitmq.conf", "advanced.config")
) or any((broker_config / "conf.d").glob("*.conf")):
raise InstallError("Review the existing RabbitMQ configuration.")
put_file(
Path("/etc/coulobre-rabbitmq.conf"),
"listeners.tcp.1 = 127.0.0.1:5672\n",
)
drop_in = SYSTEMD / "rabbitmq-server.service.d"
root_directory(drop_in)
put_file(
drop_in / "coulobre.conf",
"[Service]\n"
"Environment=RABBITMQ_CONFIG_FILE=/etc/coulobre-rabbitmq.conf\n",
)
systemctl("daemon-reload")
systemctl(
"enable", "--now", "mariadb.service", "rabbitmq-server.service"
)
systemctl("restart", "mariadb.service", "rabbitmq-server.service")
def mariadb(sql):
return run(
"mariadb",
"--batch",
"--skip-column-names",
"--protocol=socket",
source=sql.encode(),
label="Configure the local MariaDB database",
).strip()
if not self.state.get("stores_reserved"):
existing = mariadb(
"SELECT EXISTS(SELECT 1 FROM information_schema.schemata "
"WHERE schema_name='coulobre_panel') OR "
"EXISTS(SELECT 1 FROM mysql.user WHERE User='coulobre');"
)
if existing != "0":
raise InstallError(
"A Coulobre MariaDB database or user already exists."
)
for action in ("list_users", "list_vhosts"):
rows = run(
"rabbitmqctl", "--quiet", action, label="Inspect RabbitMQ"
)
if "coulobre" in {
row.split()[0] for row in rows.splitlines() if row.split()
}:
raise InstallError(
"A Coulobre RabbitMQ user or virtual host exists."
)
self.state["stores_reserved"] = True
self.save_state()
mariadb(
"CREATE DATABASE IF NOT EXISTS coulobre_panel "
"CHARACTER SET utf8mb4;"
"CREATE USER IF NOT EXISTS 'coulobre'@'localhost' IDENTIFIED BY "
f"'{self.state['database_password']}';"
"GRANT ALL PRIVILEGES ON coulobre_panel.* "
"TO 'coulobre'@'localhost';"
)
users = run(
"rabbitmqctl",
"--quiet",
"list_users",
label="Inspect RabbitMQ users",
)
if "coulobre" not in {
row.split()[0] for row in users.splitlines() if row.split()
}:
run(
"rabbitmqctl",
"add_user",
"coulobre",
source=(self.state["broker_password"] + "\n").encode(),
label="Create the Coulobre RabbitMQ login",
)
hosts = run(
"rabbitmqctl",
"--quiet",
"list_vhosts",
label="Inspect RabbitMQ virtual hosts",
)
if "coulobre" not in {row.strip() for row in hosts.splitlines()}:
run(
"rabbitmqctl",
"add_vhost",
"coulobre",
label="Create the Coulobre RabbitMQ virtual host",
)
run(
"rabbitmqctl",
"set_permissions",
"-p",
"coulobre",
"coulobre",
".*",
".*",
".*",
label="Grant access to the Coulobre virtual host",
)
def environment(self):
options = {
"DJANGO_SETTINGS_MODULE": "coulobre.settings",
"COULOBRE_ALLOWED_HOSTS": self.plan.hostname,
"COULOBRE_HTTPS_PROXY": "1",
"COULOBRE_REQUIRE_PRIVILEGED_MFA": "1",
"COULOBRE_TRUST_APACHE_CLIENT_IP": "1",
"COULOBRE_STATIC_ROOT": str(STATIC),
"COULOBRE_SECRET_KEY": self.state["secret_key"],
"COULOBRE_DB_NAME": "coulobre_panel",
"COULOBRE_DB_USER": "coulobre",
"COULOBRE_DB_PASSWORD": self.state["database_password"],
"COULOBRE_DB_HOST": "/run/mysqld/mysqld.sock",
"COULOBRE_BROKER_URL": (
f"amqp://coulobre:{self.state['broker_password']}@127.0.0.1:5672/coulobre"
),
"COULOBRE_LOCAL_DATABASE_PROVISIONING": "1",
}
if self.php:
options["COULOBRE_LOCAL_WEB_ACTIVATION"] = "1"
if self.plan.dns.mode != "off":
options["COULOBRE_LOCAL_DNS_PUBLISHING"] = "1"
if self.plan.mail.mode != "off":
options["COULOBRE_LOCAL_MAILBOX_PROVISIONING"] = "1"
return "".join(f"{key}={value}\n" for key, value in options.items())
def prepare_panel(self):
panel = identity("coulobre-panel")
root_directory(ETC, mode=0o750)
if not os.path.lexists(STATIC):
STATIC.mkdir(mode=0o755)
os.chown(STATIC, panel.pw_uid, panel.pw_gid)
info = STATIC.lstat()
if not stat.S_ISDIR(info.st_mode) or (info.st_uid, info.st_gid) != (
panel.pw_uid,
panel.pw_gid,
):
raise InstallError(
f"Check the directory and ownership of {STATIC}."
)
put_file(ENV_FILE, self.environment(), mode=0o600)
unit = (
"systemd-run",
"--quiet",
"--wait",
"--pipe",
"--collect",
"--uid=coulobre-panel",
"--property=EnvironmentFile=/etc/coulobre/panel.env",
str(BINDIR / "python"),
)
run(
*unit,
"-m",
"django",
"migrate",
"--noinput",
label="Apply panel migrations",
timeout=600,
)
run(
*unit,
"-m",
"django",
"collectstatic",
"--noinput",
label="Install panel static files",
)
info = {
"username": self.plan.admin_username,
"email": self.plan.admin_email,
"password": self.password,
}
run(
*unit,
"-c",
ADMIN_SCRIPT,
source=json.dumps(info).encode(),
label="Create the administrator account",
)
def apache(self):
modules = ["headers", "proxy", "proxy_http"]
if self.php:
modules.append("proxy_fcgi")
systemctl("enable", "--now", f"php{self.php}-fpm.service")
plan = self.plan
if plan.access == "tls":
modules.append("ssl")
config = (ASSETS / "apache/panel-tls.conf.example").read_text()
config = (
config.replace("panel.example.net", plan.hostname)
.replace(
"/etc/ssl/coulobre-panel/fullchain.pem", plan.certificate
)
.replace("/etc/ssl/coulobre-panel/privkey.pem", plan.key)
)
else:
modules.append("remoteip")
local = (
f"[{plan.origin_ip}]"
if ":" in plan.origin_ip
else plan.origin_ip
)
config = (ASSETS / "apache/panel-origin.conf.example").read_text()
config = (
config.replace("panel.example.net", plan.hostname)
.replace("192.168.10.20:8080", f"{local}:{plan.origin_port}")
.replace("192.168.10.10", plan.proxy_ip)
)
put_file(
ETC / "panel-proxy.inc",
(ASSETS / "apache/panel-proxy.inc").read_text(),
)
put_file(
Path("/etc/apache2/sites-available/coulobre-panel.conf"), config
)
run("a2enmod", *modules, label="Enable the Apache modules")
run(
"a2ensite", "coulobre-panel", label="Enable the panel virtual host"
)
run(
"apache2ctl",
"configtest",
label="Validate the Apache virtual host",
)
def verify_panel(self):
request = (
f"GET /sign-in/ HTTP/1.0\r\nHost: {self.plan.hostname}\r\n"
"X-Forwarded-Proto: https\r\n\r\n"
).encode()
for _ in range(20):
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
peer.settimeout(2)
peer.connect("/run/coulobre-panel/panel.sock")
peer.sendall(request)
with peer.makefile("rb") as reply:
if reply.readline(256).split()[1:2] == [b"200"]:
return
except OSError:
pass
time.sleep(1)
raise InstallError(
"The panel did not respond. Check journalctl -u coulobre-panel."
)
def install(self):
if os.geteuid() != 0 or not Path("/run/systemd/system").is_dir():
raise InstallError("Run the installer as root on a systemd host.")
with install_lock():
self.read_state()
if self.state.get("complete"):
self.progress(
"Coulobre is already installed with these settings."
)
self.verify_panel()
return
self.progress(
"Installing system packages and the Coulobre release."
)
mail = self.plan.mail
install_packages(
self.packages(),
mail_host=mail.host if mail.mode == "local" else "",
)
install_release(self.release)
self.progress("Preparing MariaDB and RabbitMQ on loopback.")
self.configure_stores()
self.progress(
"Configuring hosting service identities and provisioning."
)
workers = [
install_worker(
"coulobre-db-provisioning",
"coulobre-db-provisioner",
"coulobre-database-apply",
"coulobre-database-provisioner.service",
)
]
if self.php:
workers.append(
install_worker(
"coulobre-web-provisioning",
"coulobre-provisioner",
"coulobre-web-apply",
"coulobre-provisioner.service",
)
)
for name in ("dns", "mail"):
target = getattr(self.plan, name)
if target.mode != "off":
workers.append(roles.configure_role(self, name, target))
self.progress(
"Applying panel migrations and creating the administrator."
)
self.prepare_panel()
self.progress("Validating Apache and starting the panel services.")
self.apache()
for unit in PANEL_UNITS:
install_unit(unit)
systemctl("daemon-reload")
systemctl(
"enable", "--now", *PANEL_UNITS, *workers, "apache2.service"
)
systemctl("reload", "apache2.service")
self.verify_panel()
for key in ("secret_key", "database_password", "broker_password"):
self.state.pop(key, None)
self.state["complete"] = True
self.save_state()
self.progress(
f"Installation complete. Sign in at https://{self.plan.hostname}/"
)
+232
View File
@@ -0,0 +1,232 @@
import hashlib
import os
from pathlib import Path
from . import engine
from .config import InstallError
WORKERS = {
"dns": (
"coulobre-dns-provisioning",
"coulobre-dns-publisher",
"coulobre-dns-apply",
"coulobre-dns-publisher.service",
),
"mail": (
"coulobre-mail-provisioning",
"coulobre-mail-provisioner",
"coulobre-mail-apply",
"coulobre-mailbox-provisioner.service",
),
}
BIND_CONFIG = """options {
directory "/var/cache/bind";
recursion no;
allow-new-zones yes;
allow-query { any; };
allow-transfer { none; };
listen-on-v6 { any; };
};
"""
DOVECOT_23 = """protocols = imap lmtp
ssl = required
ssl_cert = <{certificate}
ssl_key = <{key}
mail_location = maildir:~/Maildir
first_valid_uid = {uid}
last_valid_uid = {uid}
auth_username_format = %Lu
auth_cache_size = 0
passdb {{
driver = passwd-file
args = /etc/dovecot/coulobre-users
}}
userdb {{
driver = passwd-file
args = /etc/dovecot/coulobre-users
}}
service lmtp {{
unix_listener /var/spool/postfix/private/dovecot-lmtp {{
user = postfix
group = postfix
mode = 0600
}}
}}
mail_plugins = $mail_plugins quota
protocol imap {{
mail_plugins = $mail_plugins imap_quota
}}
plugin {{
quota = count:User quota
quota_vsizes = yes
quota_grace = 0
}}
"""
def replace_stock_config(path, package, content):
engine.root_file(path, 0o644)
current = path.read_bytes()
if current == content.encode():
return
if package == "dovecot-core":
stock = Path("/usr/share/dovecot/dovecot.conf").read_bytes()
matches = current == stock
else:
manifest = engine.run(
"dpkg-query",
"-W",
"-f=${Conffiles}",
package,
label=f"Check the distribution configuration for {package}",
)
hashes = {
parts[0]: parts[1]
for line in manifest.splitlines()
if len(parts := line.split()) >= 2
}
matches = (
hashes.get(str(path))
== hashlib.md5(current, usedforsecurity=False).hexdigest()
)
if not matches:
raise InstallError(f"Existing configuration differs at {path}.")
engine.put_file(path, content, group=path.stat().st_gid, update=True)
def ensure_table(path, *, mode, group=0):
if os.path.lexists(path):
engine.root_file(path, mode)
if path.stat().st_gid != group:
raise InstallError(f"Check the group ownership of {path}.")
else:
engine.put_file(path, "", mode=mode, group=group)
def configure_dns():
engine.root_directory(Path("/etc/bind/coulobre"))
replace_stock_config(Path("/etc/bind/named.conf"), "bind9", BIND_CONFIG)
engine.run("named-checkconf", label="Validate the BIND9 configuration")
engine.systemctl("enable", "--now", "named.service")
engine.systemctl("restart", "named.service")
engine.run(
"rndc",
"-s",
"127.0.0.1",
"status",
label="Check BIND9's local RNDC connection",
)
def configure_mail(target, modern):
vmail = engine.identity("coulobre-vmail", home="/srv/coulobre-mail")
dovecot = engine.group("dovecot")
ensure_table(Path("/etc/postfix/coulobre-domains"), mode=0o644)
ensure_table(Path("/etc/postfix/coulobre-mailboxes"), mode=0o644)
ensure_table(
Path("/etc/dovecot/coulobre-users"), mode=0o640, group=dovecot.gr_gid
)
config = {
"myhostname": target.host,
"mydestination": "$myhostname, localhost",
"inet_interfaces": "all",
"virtual_mailbox_domains": (
"proxy:texthash:/etc/postfix/coulobre-domains"
),
"virtual_mailbox_maps": (
"proxy:texthash:/etc/postfix/coulobre-mailboxes"
),
"virtual_transport": "lmtp:unix:private/dovecot-lmtp",
"smtpd_reject_unlisted_recipient": "yes",
"smtpd_tls_security_level": "may",
"smtpd_tls_cert_file": target.certificate,
"smtpd_tls_key_file": target.key,
}
# Virtual mailbox routing may already belong to another service.
managed_maps = (
"virtual_mailbox_domains",
"virtual_mailbox_maps",
"virtual_transport",
)
for field in managed_maps:
default = engine.run(
"postconf", "-d", "-h", field, label="Inspect Postfix defaults"
).strip()
current = engine.run(
"postconf", "-h", field, label="Inspect Postfix routing"
).strip()
if current not in {default, config[field]}:
raise InstallError(
"Existing Postfix virtual mailbox routing differs."
)
if modern:
template = (
engine.ASSETS / "dovecot/coulobre-2.4.conf.example"
).read_text()
dovecot_config = (
template.replace(
"first_valid_uid = 103", f"first_valid_uid = {vmail.pw_uid}"
)
.replace(
"last_valid_uid = 103", f"last_valid_uid = {vmail.pw_uid}"
)
.replace(
"/etc/ssl/coulobre-mail/fullchain.pem", target.certificate
)
.replace("/etc/ssl/coulobre-mail/privkey.pem", target.key)
)
else:
dovecot_config = DOVECOT_23.format(
certificate=target.certificate,
key=target.key,
uid=vmail.pw_uid,
)
replace_stock_config(
Path("/etc/dovecot/dovecot.conf"), "dovecot-core", dovecot_config
)
engine.run("doveconf", "-n", label="Validate the Dovecot configuration")
engine.run(
"postconf",
"-e",
*(f"{key}={value}" for key, value in config.items()),
label="Configure Postfix mailbox delivery",
)
engine.run("postfix", "check", label="Validate the Postfix configuration")
engine.systemctl("enable", "--now", "postfix.service", "dovecot.service")
engine.systemctl("restart", "postfix.service", "dovecot.service")
def configure_role(installer, name, target):
group, worker, receiver, unit = WORKERS[name]
if target.mode == "remote":
node_setup = engine.BINDIR / "coulobre-node-setup"
engine.run(
node_setup,
"prepare-panel",
name,
label=f"Prepare the panel's public key for the {name} node",
)
installer.progress(
f"Checking the remote {name} node. Panel key: "
f"/etc/coulobre-remote/{name}/id_ed25519.pub"
)
engine.run(
node_setup,
"--source",
engine.SOURCE,
"enrol-panel",
name,
target.host,
target.host_key,
"--port",
str(target.port),
label=f"Enrol the {name} node. Check its receiver and panel key",
)
return unit
if os.path.lexists(engine.SYSTEMD / f"{receiver}@.service.d/remote.conf"):
raise InstallError(f"An existing relay already manages {name}.")
if name == "dns":
configure_dns()
else:
configure_mail(target, installer.modern_mail)
return engine.install_worker(group, worker, receiver, unit)
+330
View File
@@ -0,0 +1,330 @@
import hmac
import secrets
import time
from dataclasses import dataclass, field
from html import escape
from http.cookies import CookieError, SimpleCookie
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.parse import parse_qs
from .cli import number
from .config import InstallError, parse_plan, port
from .engine import Installer
COOKIE = "coulobre_installer"
MAX_FORM = 16384
FORM = """<form method="post" action="/review">
<fieldset><legend>Panel</legend>
<label>Hostname<input name="hostname" autocomplete="off" required></label>
<label>Access<select name="access">
<option value="tls">HTTPS on this server</option>
<option value="proxy">Trusted external HTTPS proxy</option></select></label>
<label>Panel certificate path<input name="certificate"></label>
<label>Panel private key path<input name="key"></label>
<label>Private origin address<input name="origin_ip"></label>
<label>Trusted proxy address<input name="proxy_ip"></label>
<label>Origin port<input name="origin_port" type="number" value="8080"></label>
</fieldset>
<fieldset><legend>Administrator</legend>
<label>Username<input name="username" value="operator" required></label>
<label>Email<input name="email" type="email" required></label>
</fieldset>
{dns}{mail}
<button type="submit">Review installation</button></form>"""
STYLE = """body{font:1rem system-ui,sans-serif;max-width:46rem;margin:auto;
padding:1rem;color:#14372e} fieldset{margin:1rem 0;border:1px solid #a9beb2;
border-radius:.4rem;padding:1rem} label{display:block;margin-bottom:.75rem}
input,select{display:block;box-sizing:border-box;width:100%;padding:.45rem;
margin-top:.25rem} button{background:#195a46;color:white;border:0;
border-radius:.3rem;padding:.75rem 1.1rem;font:inherit} summary{cursor:pointer}
:focus-visible{outline:3px solid #20875d;outline-offset:2px}
[role=alert]{color:#8c2828}"""
def role_form(name):
title = name.upper() if name == "dns" else "Mail"
local = (
'<label>Mail hostname<input name="mail_local_host"></label>'
'<label>Mail certificate path<input name="mail_certificate"></label>'
'<label>Mail private key path<input name="mail_key"></label>'
if name == "mail"
else ""
)
return f"""<fieldset><legend>{title}</legend>
<label>Role<select name="{name}_mode"><option value="off">Disabled</option>
<option value="local">Local service</option>
<option value="remote">Separate Coulobre node</option></select></label>
{local}
<details><summary>Separate node settings</summary>
<label>SSH hostname or address<input name="{name}_host"></label>
<label>SSH port<input name="{name}_port" type="number" value="22"></label>
<label>Verified SSH host public key file<input name="{name}_host_key"></label>
</details></fieldset>"""
def form_plan(fields):
access = fields.get("access", "")
panel = {"hostname": fields.get("hostname", ""), "access": access}
if access == "tls":
panel.update(
certificate=fields.get("certificate", ""),
key=fields.get("key", ""),
)
elif access == "proxy":
panel.update(
origin_ip=fields.get("origin_ip", ""),
proxy_ip=fields.get("proxy_ip", ""),
origin_port=number(
fields.get("origin_port") or "8080", "the origin"
),
)
data = {
"panel": panel,
"admin": {
"username": fields.get("username", ""),
"email": fields.get("email", ""),
},
}
for name in ("dns", "mail"):
mode = fields.get(f"{name}_mode", "off")
target = data[name] = {"mode": mode}
if mode == "remote":
target.update(
host=fields.get(f"{name}_host", ""),
host_key=fields.get(f"{name}_host_key", ""),
port=number(
fields.get(f"{name}_port") or "22", f"the {name} node"
),
)
elif name == "mail" and mode == "local":
target.update(
host=fields.get("mail_local_host", ""),
certificate=fields.get("mail_certificate", ""),
key=fields.get("mail_key", ""),
)
return parse_plan(data)
@dataclass
class Wizard:
password: str = field(repr=False)
code: str = field(
default_factory=lambda: secrets.token_urlsafe(24), repr=False
)
session: str = field(default="", repr=False)
pending: object = None
thread: Thread | None = None
progress: list[str] = field(default_factory=list)
finished: float | None = None
error: str = ""
def report(self, text):
self.progress.append(text)
print(text, flush=True)
def install(self):
try:
Installer(self.pending, self.password, self.report).install()
except (InstallError, OSError, ValueError) as error:
self.error = str(error)
self.report(f"Installation stopped. {self.error}")
finally:
self.finished = time.monotonic()
class WizardHandler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def authorized(self):
state = self.server.wizard
try:
cookies = SimpleCookie(self.headers.get("Cookie", ""))
value = cookies[COOKIE].value
except (CookieError, KeyError):
return False
return bool(state.session) and hmac.compare_digest(
value.encode(), state.session.encode()
)
def page(self, body, *, status=200, refresh=False, cookie=""):
head = '<meta http-equiv="refresh" content="2">' if refresh else ""
html = f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{head}<title>Install Coulobre Panel</title><style>{STYLE}</style></head>
<body><main><h1>Install Coulobre Panel</h1>{body}</main></body>
</html>""".encode()
self.send_response(status)
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(html)))
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header(
"Content-Security-Policy",
"default-src 'none'; style-src 'unsafe-inline'; "
"form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
)
if cookie:
self.send_header("Set-Cookie", cookie)
self.end_headers()
self.wfile.write(html)
def redirect(self, *, cookie=""):
self.send_response(303)
self.send_header("Location", "/")
self.send_header("Cache-Control", "no-store")
if cookie:
self.send_header("Set-Cookie", cookie)
self.end_headers()
def host_allowed(self):
return self.headers.get("Host") == self.server.authority
def do_GET(self):
if not self.host_allowed() or self.path != "/":
self.page(
"<p>Use the installer address shown in the terminal.</p>",
status=403,
)
return
state = self.server.wizard
if not self.authorized():
self.page(
'<form method="post" action="/authorize"><label>Setup code'
'<input type="password" name="code" '
'autocomplete="off" required>'
'</label><button type="submit">Continue</button></form>'
)
elif state.thread is not None:
steps = "".join(
f"<li>{escape(item)}</li>" for item in tuple(state.progress)
)
if state.finished is not None and not state.error:
endpoint = f"https://{state.pending.hostname}/"
steps += (
f'</ol><a href="{escape(endpoint)}">Open the panel</a>'
)
self.page(f"<ol>{steps}")
else:
self.page(f"<ol>{steps}</ol>", refresh=state.finished is None)
elif state.pending is not None:
self.page(
f"<p>{escape(state.pending.description())}</p>"
'<form method="post" action="/install">'
'<button type="submit">Install Coulobre</button></form>'
'<form method="post" action="/edit">'
'<button type="submit">Change settings</button></form>'
)
else:
self.page(
FORM.format(dns=role_form("dns"), mail=role_form("mail"))
)
def fields(self):
try:
size = int(self.headers.get("Content-Length", "0"))
if not 0 <= size <= MAX_FORM:
raise ValueError
if (
size
and self.headers.get_content_type()
!= "application/x-www-form-urlencoded"
):
raise ValueError
data = parse_qs(
self.rfile.read(size).decode("utf-8"),
keep_blank_values=True,
max_num_fields=25,
errors="strict",
)
if any(len(values) != 1 for values in data.values()):
raise ValueError
return {key: values[0] for key, values in data.items()}
except (UnicodeError, ValueError):
raise InstallError("Submit a valid installation form.") from None
def do_POST(self):
if (
not self.host_allowed()
or self.headers.get("Origin") != f"http://{self.server.authority}"
):
self.page(
"<p>Submit the form from the local installer.</p>", status=403
)
return
state = self.server.wizard
try:
data = self.fields()
if self.path == "/authorize":
given = data.get("code", "")
if state.code and hmac.compare_digest(
given.encode(), state.code.encode()
):
state.session = secrets.token_urlsafe(24)
state.code = ""
self.redirect(
cookie=(
f"{COOKIE}={state.session}; "
"HttpOnly; SameSite=Strict; Path=/"
)
)
else:
self.page(
"<p>Enter the setup code shown in the terminal.</p>",
status=403,
)
return
if not self.authorized() or state.thread is not None:
self.page(
"<p>The installation form is unavailable.</p>", status=403
)
return
if self.path == "/edit":
state.pending = None
elif self.path == "/review":
state.pending = form_plan(data)
elif self.path == "/install" and state.pending is not None:
state.thread = Thread(target=state.install)
state.thread.start()
else:
raise InstallError("Review the installation settings first.")
self.redirect()
except InstallError as error:
self.page(
f'<p role="alert">{escape(str(error))}</p>'
'<a href="/">Return to setup</a>',
status=400,
)
class WizardServer(HTTPServer):
def get_request(self):
connection, peer = super().get_request()
connection.settimeout(5)
return connection, peer
def serve_wizard(password, listen_port):
listen_port = port(listen_port, "the setup wizard", 8765)
with WizardServer(("127.0.0.1", listen_port), WizardHandler) as server:
state = server.wizard = Wizard(password)
server.authority = f"127.0.0.1:{server.server_port}"
server.timeout = 1
print(
f"Open http://{server.authority}/ locally or via an SSH tunnel.",
flush=True,
)
print(f"Setup code {state.code}", flush=True)
deadline = time.monotonic() + 1800
while state.thread is not None or time.monotonic() < deadline:
server.handle_request()
if (
state.finished is not None
and time.monotonic() - state.finished > 30
):
return 1 if state.error else 0
raise InstallError(
"The setup wizard expired without starting an installation."
)
+23
View File
@@ -0,0 +1,23 @@
<VirtualHost *:443>
ServerName webmail.example.org
DocumentRoot /opt/roundcube/public_html
SSLEngine On
SSLCertificateFile /etc/ssl/coulobre-webmail/fullchain.pem
SSLCertificateKeyFile /etc/ssl/coulobre-webmail/privkey.pem
<Directory "/opt/roundcube/public_html">
Options FollowSymLinks
AllowOverride None
DirectoryIndex index.php
Require all granted
<FilesMatch "^(index|static)\.php$">
SetHandler "proxy:unix:/run/php/coulobre-roundcube.sock|fcgi://localhost/"
</FilesMatch>
<FilesMatch "^(?!(index|static)\.php$).*\.ph(?:p|ar|tml)$">
Require all denied
</FilesMatch>
</Directory>
</VirtualHost>
+12
View File
@@ -0,0 +1,12 @@
<?php
$config['plugins'][] = 'coulobre_webmail';
$config['coulobre_panel_origin'] = 'https://panel.example.org';
$config['coulobre_bridge_key_file'] = '/etc/coulobre-roundcube/bridge.key';
$config['imap_host'] = 'ssl://mail.example.org:993';
$config['imap_conn_options'] = [
'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
];
$config['force_https'] = true;
$config['session_samesite'] = 'Lax';
+151
View File
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
/**
* Accept a single-use Coulobre ticket and use Roundcube's normal IMAP login.
*/
class coulobre_webmail extends rcube_plugin
{
private ?array $login = null;
public function init(): void
{
$this->add_hook('startup', [$this, 'startSignOn']);
$this->add_hook('authenticate', [$this, 'authenticateSignOn']);
}
public function startSignOn(array $args): array
{
if (!array_key_exists('_coulobre_ticket', $_POST)) {
return $args;
}
$roundcube = rcmail::get_instance();
$origin = $roundcube->config->get('coulobre_panel_origin', '');
if (
!is_string($origin)
|| preg_match('~\Ahttps://(?:[a-z0-9.-]+|\[[a-f0-9:]+\])(?::[0-9]{1,5})?\z~iD', $origin) !== 1
) {
$this->reject(503);
}
if (
($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST'
|| !rcube_utils::https_check()
|| ($_SERVER['HTTP_ORIGIN'] ?? '') !== $origin
) {
$this->reject(403);
}
$ticket = $_POST['_coulobre_ticket'];
if (
count($_POST) !== 1
|| !is_string($ticket)
|| preg_match('/\A[A-Za-z0-9_-]{43}\z/D', $ticket) !== 1
) {
$this->reject(400);
}
// Use the configured mail service for the selected address.
$host = $roundcube->config->get('imap_host');
if (
!is_string($host)
|| preg_match('~\A(?:ssl|tls)://(?:[a-z0-9.-]+|\[[a-f0-9:]+\])(?::[0-9]{1,5})?\z~iD', $host) !== 1
) {
$this->reject(503);
}
$keyPath = $roundcube->config->get('coulobre_bridge_key_file', '');
$key = is_string($keyPath) && is_readable($keyPath)
? trim((string) @file_get_contents($keyPath, false, null, 0, 512))
: '';
if (
!function_exists('curl_init')
|| preg_match('/\A[A-Za-z0-9_-]{32,128}\z/D', $key) !== 1
) {
$this->reject(503);
}
$this->login = $this->exchangeTicket($origin, $key, $ticket);
$this->login['host'] = $host;
// Reset the previous mailbox session after the ticket is accepted.
$roundcube->kill_session();
return ['task' => 'login', 'action' => 'login'] + $args;
}
public function authenticateSignOn(array $args): array
{
if ($this->login === null) {
return $args;
}
$login = $this->login;
$this->login = null;
return [
'host' => $login['host'],
'user' => $login['user'],
'pass' => $login['password'],
'valid' => true,
// A first visit or a cross-site POST may have no Roundcube cookie.
'cookiecheck' => false,
] + $args;
}
private function exchangeTicket(string $origin, string $key, string $ticket): array
{
$connection = curl_init($origin . '/_bridge/roundcube/');
$body = '';
curl_setopt_array($connection, [
CURLOPT_POST => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CONNECTTIMEOUT => 4,
CURLOPT_TIMEOUT => 20,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
'X-Coulobre-Bridge-Key: ' . $key,
],
CURLOPT_POSTFIELDS => http_build_query(['ticket' => $ticket]),
CURLOPT_WRITEFUNCTION => static function ($connection, string $chunk) use (&$body): int {
if (strlen($body) + strlen($chunk) > 4096) {
return 0;
}
$body .= $chunk;
return strlen($chunk);
},
]);
$success = curl_exec($connection);
$status = curl_getinfo($connection, CURLINFO_RESPONSE_CODE);
if ($status === 404) {
$this->reject(403);
}
if (!$success || $status !== 200) {
$this->reject(503);
}
$login = json_decode($body, true);
if (
!is_array($login)
|| !is_string($login['user'] ?? null)
|| strlen($login['user']) > 254
|| preg_match('/\A[a-z0-9][a-z0-9._-]*@[a-z0-9.-]+\z/D', $login['user']) !== 1
|| !is_string($login['password'] ?? null)
|| preg_match('/\A[A-Za-z0-9_-]{43}\z/D', $login['password']) !== 1
) {
$this->reject(502);
}
return $login;
}
private function reject(int $status): never
{
http_response_code($status);
header('Cache-Control: private, no-store');
header('Content-Type: text/plain; charset=UTF-8');
header('Referrer-Policy: no-referrer');
exit('Webmail sign-in could not be completed. Open the mailbox from Coulobre Panel again.');
}
}
+15
View File
@@ -0,0 +1,15 @@
[coulobre-roundcube]
user = coulobre-roundcube
group = coulobre-roundcube
listen = /run/php/coulobre-roundcube.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
pm = ondemand
pm.max_children = 4
clear_env = yes
security.limit_extensions = .php
php_admin_flag[display_errors] = off
php_admin_flag[session.use_strict_mode] = on
php_admin_flag[session.cookie_secure] = on
php_admin_flag[session.cookie_httponly] = on
+15
View File
@@ -0,0 +1,15 @@
# /etc/rspamd/override.d/dkim_signing.conf
enabled = true;
selector = "coulobre";
path = "/etc/rspamd/coulobre-dkim/$domain.$selector.key";
use_domain = "header";
use_esld = false;
try_fallback = true;
sign_authenticated = true;
sign_local = false;
sign_inbound = false;
allow_envfrom_empty = false;
allow_hdrfrom_multiple = false;
allow_hdrfrom_mismatch = false;
allow_hdrfrom_mismatch_local = false;
allow_username_mismatch = false;
@@ -0,0 +1,10 @@
# Merge these options into the existing authenticated submission service.
# Leave the public SMTP service and its inbound milters in place.
submission inet n - y - - smtpd
-o smtpd_tls_security_level=encrypt
-o smtpd_tls_auth_only=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_sasl_type=dovecot
-o smtpd_sasl_path=private/auth
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject
-o { smtpd_milters = { unix:rspamd/coulobre.sock, default_action=tempfail } }
+8
View File
@@ -0,0 +1,8 @@
# /etc/rspamd/local.d/settings.conf
coulobre_signing {
authenticated = true;
apply {
symbols_enabled = ["DKIM_SIGNED"];
flags = ["skip_process"];
}
}
@@ -0,0 +1,2 @@
# /etc/rspamd/override.d/worker-normal.inc and worker-controller.inc
enabled = false;
+7
View File
@@ -0,0 +1,7 @@
# /etc/rspamd/override.d/worker-proxy.inc
bind_socket = "/var/spool/postfix/rspamd/coulobre.sock mode=0600 owner=postfix";
milter = true;
upstream "local" {
default = true;
self_scan = true;
}
@@ -0,0 +1,3 @@
[Service]
PIDFile=/run/spamass/spamass.pid
RemainAfterExit=no
@@ -0,0 +1,2 @@
# Merge into /etc/postfix/main.cf. Keep any other smtpd_milters on this list.
smtpd_milters = { unix:spamass/spamass.sock, connect_timeout=3s, content_timeout=30s, default_action=accept }
@@ -0,0 +1,6 @@
# /etc/default/spamass-milter
# Tag mail without rewriting the subject or body. Skip authenticated SMTP.
OPTIONS="-m -I -- -d 127.0.0.1 -n 2 -t 15 --connect-retries=1"
SOCKET="/var/spool/postfix/spamass/spamass.sock"
SOCKETOWNER="spamass-milter:postfix"
SOCKETMODE="0660"
@@ -0,0 +1,2 @@
# /etc/default/spamd
OPTIONS="--listen=127.0.0.1 --allowed-ips=127.0.0.1 --username=debian-spamd --nouser-config --max-children=5 --timeout-child=15 --helper-home-dir=/var/lib/spamassassin"
@@ -0,0 +1,2 @@
[Service]
Environment=COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre off-site backup transfer socket
[Socket]
ListenStream=/run/coulobre-account-offsite.sock
SocketUser=root
SocketGroup=coulobre-offsite-requests
SocketMode=0660
Accept=yes
MaxConnections=2
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,23 @@
[Unit]
Description=Coulobre off-site backup transfer
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
StateDirectory=coulobre/offsite
StateDirectoryMode=0700
UMask=0077
ExecStart=/opt/coulobre/bin/coulobre-account-backup offsite-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=30min
TimeoutStopSec=10s
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectHome=true
ProtectSystem=strict
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
@@ -0,0 +1,2 @@
[Service]
Environment=COULOBRE_REMOTE_MAILBOX_RESTORE=1
@@ -0,0 +1,11 @@
[Unit]
Description=Coulobre remote BIND9 publishing request
[Service]
User=coulobre-dns-publisher
Group=coulobre-dns-publisher
UMask=0077
ReadWritePaths=
ExecStart=
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/dns/ssh_config coulobre-dns-node
RuntimeMaxSec=190s
@@ -1,5 +1,5 @@
[Unit]
Description=Coulobre Panel local BIND9 publishing worker
Description=Coulobre Panel BIND9 publishing worker
Requires=coulobre-dns-apply.socket
Wants=network-online.target
After=network-online.target coulobre-dns-apply.socket mariadb.service rabbitmq-server.service
+23
View File
@@ -0,0 +1,23 @@
[Unit]
Description=Coulobre Fail2ban instance
After=coulobre-firewall.service network.target
[Service]
Type=exec
UMask=0077
RuntimeDirectory=coulobre-fail2ban
RuntimeDirectoryMode=0700
StateDirectory=coulobre/firewall
StateDirectoryMode=0700
ExecStartPre=/opt/coulobre/bin/coulobre-firewall prepare-bans
ExecStart=/usr/bin/fail2ban-server -xf -c /run/coulobre-fail2ban/config -s /run/coulobre-fail2ban/fail2ban.sock -p /run/coulobre-fail2ban/fail2ban.pid
ExecReload=/opt/coulobre/bin/coulobre-firewall prepare-bans
ExecReload=/usr/bin/fail2ban-client -c /run/coulobre-fail2ban/config -s /run/coulobre-fail2ban/fail2ban.sock reload
ExecStop=/usr/bin/fail2ban-client -c /run/coulobre-fail2ban/config -s /run/coulobre-fail2ban/fail2ban.sock stop
Restart=on-failure
NoNewPrivileges=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
+20
View File
@@ -0,0 +1,20 @@
[Unit]
Description=Coulobre host firewall
Wants=network-pre.target
After=local-fs.target nftables.service
Before=network-pre.target
[Service]
Type=oneshot
RemainAfterExit=yes
UMask=0077
StateDirectory=coulobre/firewall
StateDirectoryMode=0700
ExecStart=/opt/coulobre/bin/coulobre-firewall restore
ExecReload=/opt/coulobre/bin/coulobre-firewall restore
NoNewPrivileges=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=Coulobre service health collector
Wants=network-online.target
After=network-online.target mariadb.service
[Service]
Type=oneshot
User=coulobre-health
Group=coulobre-health
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
ExecStart=/opt/coulobre/bin/python -m django collect_service_health
TimeoutStartSec=5min
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Refresh Coulobre service health observations
[Timer]
OnActiveSec=10s
OnUnitInactiveSec=1min
AccuracySec=5s
[Install]
WantedBy=timers.target
+1 -1
View File
@@ -1,6 +1,6 @@
[Unit]
Description=Coulobre local website HTTPS request
After=apache2.service php8.5-fpm.service
After=apache2.service php8.4-fpm.service php8.5-fpm.service
CollectMode=inactive-or-failed
[Service]
@@ -0,0 +1,11 @@
[Unit]
Description=Coulobre remote mailbox provisioning request
[Service]
User=coulobre-mail-provisioner
Group=coulobre-mail-provisioner
UMask=0077
StateDirectory=
ExecStart=
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail/ssh_config coulobre-mail-node
RuntimeMaxSec=190s
@@ -0,0 +1,12 @@
[Unit]
Description=Coulobre mailbox archive backup socket
[Socket]
ListenStream=/run/coulobre-mail-archive-backup.sock
SocketUser=root
SocketGroup=coulobre-mail-archive-backup
SocketMode=0660
Accept=yes
[Install]
WantedBy=sockets.target
@@ -0,0 +1,22 @@
[Unit]
Description=Coulobre mailbox archive backup request
After=postfix.service dovecot.service
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
StateDirectory=coulobre/mail-archive-work
StateDirectoryMode=0700
UMask=0077
ExecStart=/opt/coulobre/bin/coulobre-mail-node backup-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=30min
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=-/srv/coulobre-mail
@@ -0,0 +1,7 @@
[Service]
User=coulobre-mail-archive-backup
Group=coulobre-mail-archive-backup
StateDirectory=
ReadWritePaths=
ExecStart=
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail-archive.conf coulobre-mail-archive-backup
@@ -0,0 +1,12 @@
[Unit]
Description=Coulobre mailbox archive restore socket
[Socket]
ListenStream=/run/coulobre-mail-archive-restore.sock
SocketUser=root
SocketGroup=coulobre-mail-archive-restore
SocketMode=0660
Accept=yes
[Install]
WantedBy=sockets.target
@@ -0,0 +1,23 @@
[Unit]
Description=Coulobre mailbox archive restore request
After=postfix.service dovecot.service
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
StateDirectory=coulobre/mail-archive-work coulobre/mail-archive-restores
StateDirectoryMode=0700
UMask=0077
ExecStart=/opt/coulobre/bin/coulobre-mail-node restore-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=30min
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=-/srv/coulobre-mail
CapabilityBoundingSet=~CAP_SYS_RESOURCE
@@ -0,0 +1,7 @@
[Service]
User=coulobre-mail-archive-restore
Group=coulobre-mail-archive-restore
StateDirectory=
ReadWritePaths=
ExecStart=
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail-archive.conf coulobre-mail-archive-restore
@@ -0,0 +1,11 @@
[Unit]
Description=Coulobre mailbox credential socket
[Socket]
ListenStream=/run/coulobre-mail-credentials.sock
SocketUser=root
SocketGroup=coulobre-credential-requests
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
@@ -0,0 +1,20 @@
[Unit]
Description=Coulobre mailbox credential request
After=postfix.service dovecot.service
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
UMask=0077
Environment=COULOBRE_LOCAL_MAILBOX_CREDENTIALS=1
ExecStart=/opt/coulobre/bin/coulobre-service-credentials --mailbox-only
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=90s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
@@ -0,0 +1,9 @@
[Unit]
After=network-online.target
Wants=network-online.target
[Service]
User=coulobre-mail-credential-relay
ExecStart=
ExecStart=/usr/bin/ssh -T -F /etc/coulobre-remote/mail-credentials/ssh_config coulobre-mail-credentials
RuntimeMaxSec=95s
@@ -0,0 +1,4 @@
[Service]
Environment=COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1
ReadWritePaths=-/var/lib/coulobre/mail-node /etc/dovecot
RuntimeMaxSec=90s
@@ -1,5 +1,5 @@
[Unit]
Description=Coulobre Panel local mailbox provisioning worker
Description=Coulobre Panel mailbox provisioning worker
Requires=coulobre-mail-apply.socket
Wants=network-online.target
After=network-online.target coulobre-mail-apply.socket mariadb.service rabbitmq-server.service
@@ -0,0 +1,26 @@
[Unit]
Description=Coulobre Panel off-site backup worker
Requires=coulobre-account-offsite.socket
Wants=network-online.target
After=network-online.target coulobre-account-offsite.socket mariadb.service rabbitmq-server.service
[Service]
Type=exec
User=coulobre-offsite-worker
Group=coulobre-offsite-worker
SupplementaryGroups=coulobre-offsite-requests
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
UMask=0077
ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-offsite-backups --hostname=offsite-worker@%H --concurrency=1 --prefetch-multiplier=1
KillMode=mixed
TimeoutStopSec=31min
Restart=on-failure
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,6 @@
[Unit]
Requires=coulobre-mail-credentials.socket
After=coulobre-mail-credentials.socket
[Service]
SupplementaryGroups=coulobre-credential-requests
@@ -0,0 +1,6 @@
[Unit]
Requires=coulobre-website-files.socket
After=coulobre-website-files.socket
[Service]
SupplementaryGroups=coulobre-file-requests
@@ -0,0 +1,4 @@
[Service]
Environment=COULOBRE_LOCAL_DATABASE_CREDENTIALS_ROTATION=1
ReadWritePaths=-/var/lib/coulobre/database-node
RuntimeMaxSec=90s
@@ -0,0 +1,4 @@
[Service]
Environment=COULOBRE_LOCAL_MAILBOX_CREDENTIALS_ROTATION=1
ReadWritePaths=-/var/lib/coulobre/mail-node /etc/dovecot
RuntimeMaxSec=90s
+1 -1
View File
@@ -1,6 +1,6 @@
[Unit]
Description=Coulobre local web activation request
After=apache2.service php8.5-fpm.service
After=apache2.service php8.4-fpm.service php8.5-fpm.service
CollectMode=inactive-or-failed
[Service]
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre website file operation socket
[Socket]
ListenStream=/run/coulobre-website-files.sock
SocketUser=root
SocketGroup=coulobre-file-requests
SocketMode=0660
Accept=yes
MaxConnections=16
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,23 @@
[Unit]
Description=Coulobre website file operation
CollectMode=inactive-or-failed
[Service]
Type=exec
# The system manager starts this as root. An explicit User= can drop
# CAP_SETUID during setup, before the receiver changes to the website user.
WorkingDirectory=/opt/coulobre
UMask=0027
ExecStart=/opt/coulobre/bin/coulobre-web-node files-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
NoNewPrivileges=true
CapabilityBoundingSet=CAP_SYS_CHROOT CAP_SETUID CAP_SETGID CAP_DAC_READ_SEARCH
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/srv/coulobre/web
RestrictAddressFamilies=AF_UNIX
RuntimeMaxSec=2min
@@ -0,0 +1,26 @@
[Unit]
Description=Coulobre Panel website job worker
Requires=coulobre-website-jobs.socket
Wants=network-online.target
After=network-online.target coulobre-website-jobs.socket mariadb.service rabbitmq-server.service
[Service]
Type=exec
User=coulobre-website-job-worker
Group=coulobre-website-job-worker
SupplementaryGroups=coulobre-website-job-requests
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
UMask=0077
ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-website-jobs --hostname=website-jobs@%H --concurrency=2 --prefetch-multiplier=1
KillMode=mixed
TimeoutStopSec=2min
Restart=on-failure
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre website job socket
[Socket]
ListenStream=/run/coulobre-website-jobs.sock
SocketUser=root
SocketGroup=coulobre-website-job-requests
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,31 @@
[Unit]
Description=Coulobre scheduled website job
CollectMode=inactive-or-failed
[Service]
Type=exec
# The system service starts as root and switches to the website user.
WorkingDirectory=/opt/coulobre
ExecStart=/opt/coulobre/bin/coulobre-web-node job-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
# The receiver also terminates the website user's process on timeout.
CapabilityBoundingSet=CAP_SETUID CAP_SETGID CAP_DAC_READ_SEARCH CAP_KILL
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ProtectProc=invisible
ProtectControlGroups=true
ReadWritePaths=/srv/coulobre/web
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=true
RestrictSUIDSGID=true
MemoryMax=256M
TasksMax=32
CPUQuota=100%
RuntimeMaxSec=75s
TimeoutStopSec=5s
KillMode=control-group
@@ -0,0 +1,2 @@
# Remove abandoned transfer staging files. Keep the restore journal.
e /var/lib/coulobre/mail-archive-work - - - 1d
+1690 -26
View File
File diff suppressed because it is too large. Load diff
+176 -31
View File
@@ -41,7 +41,7 @@ operator applies a website quota from the account page.
Set optional PHP resource defaults on a hosting plan. Coulobre applies them
on first local activation and when an operator reapplies the plan on the
account page. See [website PHP settings](deployment.md#configure-php-per-website).
account page. See [website PHP settings](deployment.md#configure-php-pool-limits-per-website).
Changing or reassigning a plan preserves existing databases and mailboxes. If
the new limit is at or below current usage, the panel blocks additional
@@ -119,6 +119,25 @@ sessions**. In `/admin/`, users with **Can view customer impersonation
session** can review the administrator, customer, timestamps, and outcome
for each session. The audit records are read-only in Django admin.
### Make changes during a support session
Grant **Can start a support session with write access** in addition to the
two customer view permissions. Select **Support with write access** next
to the customer. The banner identifies the active customer, administrator,
and mode.
In a writable session, the administrator can request a database or mailbox
and manage SSH keys on the customer's hosting accounts. Each action also
requires the administrator's normal permission for that operation. The
customer's account scope and plan limits apply. Forms belong to the active
support session. Reopen the form after changing sessions or modes.
Grant **Can view customer impersonation action** to review these changes in
`/admin/`. Each entry records the session, administrator, customer, account
ID, operation, resource, and time. SSH key changes record fingerprints of
the keys added or removed. Queued changes still report their execution
status in the hosting account.
## Request a MariaDB database
Open a hosting account and select **Request database**. Choose a short suffix
@@ -292,7 +311,7 @@ notation for `responsible_name`, such as `hostmaster.example.net` for
by hand.
Render the zone file and validate it with the `named-checkzone` utility
provided by the Ubuntu `bind9-utils` package. The rendered zone is written to
provided by the `bind9-utils` package. The rendered zone is written to
standard output. See the [BIND9 command reference](https://bind9.readthedocs.io/en/stable/manpages.html#named-checkzone).
```sh
@@ -330,9 +349,27 @@ Supply TXT values as plain JSON strings. The renderer quotes the values and
splits long UTF-8 strings into DNS character strings. DKIM readers concatenate
the strings in the TXT record. [RFC 1035](https://www.rfc-editor.org/rfc/rfc1035.html) and [RFC 6376](https://www.rfc-editor.org/rfc/rfc6376.html)
### Include CNAME, SRV, and CAA records in a manifest
Version 3 adds an `extra_records` array and retains the two arrays from
version 2. The panel emits version 3 for zones that use an extra record type.
The node still accepts version 1 and 2 manifests.
```json
{
"name": "_sip._tcp.example.net",
"record_type": "SRV",
"value": "10 0 5060 sip.example.net."
}
```
Use fully qualified names for CNAME targets and SRV target hosts. Use `.`
as an SRV target for an unavailable service. A CNAME cannot share its owner
with any other record or form a loop within the zone.
### Apply a zone manifest
Install `bind9` and `bind9-utils` on an Ubuntu DNS node. Use BIND9's default
Install `bind9` and `bind9-utils` on the DNS node. Use BIND9's default
IN view and enable `allow-new-zones yes;` in the existing `options` block.
On an authoritative-only DNS node, set `recursion no;` and configure
`allow-transfer` to match your secondary servers. Set
@@ -367,7 +404,7 @@ sudo systemctl enable --now coulobre-dns-apply.socket
```
Grant the socket group only to the service identity responsible for publishing
zones. Send one version 1 or 2 zone manifest as UTF-8 JSON to
zones. Send one version 1, 2, or 3 zone manifest as UTF-8 JSON to
`/run/coulobre-dns-apply.sock`, with a limit of 1 MiB. Shut down the writing
half of the connection and read the JSON reply to EOF. For a valid manifest,
the reply identifies the domain and SOA serial. A `configured` reply means
@@ -396,11 +433,11 @@ coulobre-mail-node inspect coulobre-mailbox-1.json
### Apply a mailbox manifest
Use Ubuntu 24.04 with Dovecot 2.3 or Ubuntu 26.04 with Dovecot 2.4. Install
Postfix, `dovecot-imapd`, and `dovecot-lmtpd`. Install Coulobre in a root-owned
virtual environment on the node. Use a Postfix hostname outside the set of
hosted mail domains and keep those domains in Postfix's virtual mailbox
address class. See the [Postfix virtual domain guide](https://www.postfix.org/VIRTUAL_README.html).
Install Postfix, `dovecot-imapd`, and `dovecot-lmtpd`. Debian 13 and Ubuntu
26.04 use Dovecot 2.4. Ubuntu 24.04 uses Dovecot 2.3. Install Coulobre in a
root-owned virtual environment on the node. Use a Postfix hostname outside
the set of hosted mail domains and keep those domains in Postfix's virtual
mailbox address class. See the [Postfix virtual domain guide](https://www.postfix.org/VIRTUAL_README.html).
On a fresh mail node, create the virtual mail user and empty lookup files.
@@ -460,7 +497,7 @@ service lmtp {
}
```
#### Dovecot 2.4 on Ubuntu 26.04
#### Dovecot 2.4 on Debian 13 and Ubuntu 26.04
For a fresh, dedicated mail node, use the
[Dovecot 2.4 configuration example](../deploy/dovecot/coulobre-2.4.conf.example)
@@ -611,7 +648,7 @@ sudo systemctl enable --now coulobre-mail-apply.socket
Grant the socket group only to the service identity responsible for mailbox
provisioning. Send one version 1 or 2 mailbox manifest as UTF-8 JSON to
`/run/coulobre-mail-apply.sock`, with a limit of 4 KiB. Shut down the writing
`/run/coulobre-mail-apply.sock`, with a limit of 64 KiB. Shut down the writing
half of the connection and read the JSON reply to EOF. For a valid manifest,
the reply identifies the mailbox and reports `configured` or `failed`.
The generated password stays in a root-only credentials file on the mail node.
@@ -623,8 +660,19 @@ The reply includes both fields.
Use an account archive from DirectAdmin's Site Backup, Manage User Backups
or Admin Backup/Transfer feature. Coulobre reads plain tar and gzip archives
directly. Install the `zstd` package to read Zstandard archives. See the
[DirectAdmin backup guide](https://docs.directadmin.com/directadmin/backup-restore-migration/).
directly. Install the `zstd` package to read Zstandard archives. Include the
domains directory, database data, email accounts, and email data when taking
the source backup. The server-wide System Backup and CustomBuild database
backup are separate formats.
[DirectAdmin backup guide](https://docs.directadmin.com/directadmin/backup-restore-migration/)
| Resource | Source in the account archive | Destination |
| --- | --- | --- |
| Account | `backup/user.conf` and the domain inventory | One new hosting account with the selected primary domain |
| Website | `domains/DOMAIN/public_html` or `private_html` | Empty managed document root for the selected domain |
| Database | `backup/USERNAME_SUFFIX.sql` | Empty managed MariaDB database named `coulobre_ACCOUNTID_suffix` |
| Mailbox | `backup/DOMAIN/email/passwd` and a virtual mailbox Maildir | Fresh managed mailbox with the same address |
| DNS | `backup/DOMAIN/DOMAIN.db` | Unpublished primary-domain zone with apex SOA and NS, A, AAAA, MX, and TXT |
```sh
coulobre-directadmin inspect user.admin.customer.tar.zst
@@ -662,9 +710,9 @@ The command reads the panel database and reports `blocked` when the chosen
domain is already assigned to a hosting account, DNS zone or mail domain,
or when a domain still needs to be selected. The report lists database
requests using the suffix after the source username and mailbox requests
for the selected domain. The `manual_review` list identifies other domains,
database names that need a mapping, and data that needs a separate migration,
including website files, DNS zones, mail files and SQL dumps.
for the selected domain. `source_data` shows the selected domain's file counts
and DNS zone presence. `manual_review` lists resources that require a
separate restore step and source entries that need manual mapping.
### Import DirectAdmin account metadata
@@ -680,7 +728,8 @@ supported database requests and selected domain's mailbox requests in one
transaction. The JSON report includes the new account ID and the MariaDB
names derived from the database requests. Use the account page to download
deployment manifests for the nodes. The `manual_review` list records the
website, DNS, mail and SQL data that needs a separate migration.
website, DNS, mail and SQL data to review before completing the separate
restore steps below.
Replaying the same account and request selection reports `already_imported`
for the original account. A domain conflict or a change to the original
@@ -724,6 +773,84 @@ managed Apache configuration controls the restored site. Any restored
`.htaccess` files are available for review. See the
[Apache AllowOverride reference](https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride).
### Restore DirectAdmin database contents
Provision each database request using its Coulobre manifest. Copy the
same account archive and the manifest to the database node. Pass the
original database name from `database_requests` with its original casing.
```sh
sudo /opt/coulobre/bin/coulobre-database-node restore-directadmin \
coulobre-database-1.json user.admin.customer.tar.zst customer_site
```
The database must be empty. MariaDB reads the selected dump with the new
schema's managed login and client sandbox. Configure website applications
with the new database name and credentials. The account archive format
supplies a per-database logical SQL dump. Use a compatible single-schema
dump for objects that reference the old schema or have an explicit source
definer the managed login cannot use.
If MariaDB rejects the SQL, check the target before retrying. A failed dump
can leave partial data and a pending restore marker. Keep the destination
offline, review the source dump, and retry against an empty managed schema.
The restore refuses populated destinations.
### Restore DirectAdmin mailbox messages
Provision the mailbox on the destination and restore before users connect or
incoming mail reaches it. Run on the mail node with its mailbox manifest and
the same account archive.
```sh
sudo /opt/coulobre/bin/coulobre-mail-node restore-directadmin \
coulobre-mailbox-1.json user.admin.customer.tar.zst
```
The importer supports both `imap/DOMAIN/LOCALPART/Maildir` and
`backup/DOMAIN/email/data/imap/LOCALPART/Maildir`. It restores regular
messages in `cur` and `new`, including Maildir++ folders, and preserves their
timestamps and filename flags. A selected folder or message stored as a link
blocks the restore. Use a backup with regular files or migrate that mailbox
by IMAP. Dovecot rebuilds its indexes. The importer checks the selected
mailbox's quota and publishes only after the archive has been read. Both
an existing Maildir and an ambiguous source layout block publication.
[DirectAdmin's two IMAP backup layouts](https://docs.directadmin.com/changelog/version-1.50.0.html)
### Preview and save a DirectAdmin DNS zone
Use the imported account ID and run the first command without `--apply`.
Review the destination domain, addresses, nameservers, and mail records in
the resulting manifest.
```sh
python manage.py import_directadmin_zone user.admin.customer.tar.zst 1
python manage.py import_directadmin_zone user.admin.customer.tar.zst 1 --apply
```
Coulobre imports A, AAAA, MX, TXT, CNAME, SRV, and CAA with its own TTL and
SOA timers. Record types outside the mapping, such as delegated NS and DNSSEC
records, appear in the preview.
Use `--apply --skip-unsupported` only after deciding how the omitted records
will be served. A differing destination zone blocks the import. An identical
zone can be previewed or reapplied without creating another copy. Adjust
destination IP addresses, nameservers, and mail DNS before publishing from
the panel or updating your DNS provider. Saving the zone leaves deployment
and registrar delegation for the operator.
### Review remaining source data
Create a separate hosting account or model aliases explicitly for additional
web domains. Review mail forwarding, catch-all and vacation settings,
custom IMAP keywords and subscriptions, webmail preferences, scheduled
tasks, reseller assignments, FTP users, certificates, source credentials,
and the system mailbox in a nested home archive. Reissue TLS certificates
and rotate access using the provisioned Coulobre credentials. Verify the
website, database rows, mailbox folders, and published zone before cutover.
See [migration sources](migration-sources.md) for the assessment of cPanel
and Plesk account archives.
## Request an Apache configuration preview
Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development
@@ -766,20 +893,21 @@ coulobre-web-node render coulobre-web-plan-1.json apache > apache.conf
coulobre-web-node render coulobre-web-plan-1.json php-fpm > php-fpm.conf
```
The command reads the manifest and packaged templates locally. The isolated
Ubuntu check below demonstrates loading the configuration.
The command reads the manifest and packaged templates locally.
## Apply a manifest on an Ubuntu web node
## Apply a manifest on a web node
Use a dedicated Ubuntu 26.04 node with Apache and PHP 8.5 FPM installed from
the distribution packages. Enable FastCGI in Apache and start the native
services before applying a manifest.
Install Apache and PHP-FPM from the distribution packages. Use PHP 8.4 on
Debian 13 and PHP 8.5 on Ubuntu 26.04. Enable FastCGI in Apache and start the
services before applying a manifest. Each site's virtual host connects to its
own FPM socket.
```sh
sudo apt install apache2 php8.5-fpm
php_version=8.5 # Use 8.4 on Debian 13.
sudo apt install apache2 "php${php_version}-fpm"
sudo a2enmod proxy_fcgi
sudo service php8.5-fpm start
sudo service apache2 restart
sudo systemctl enable --now "php${php_version}-fpm"
sudo systemctl restart apache2
```
Install the matching Coulobre package in a root-owned virtual environment on
@@ -792,8 +920,11 @@ sudo /opt/coulobre/bin/coulobre-web-node apply coulobre-web-plan-1.json
The command reserves the account ID and domain on the node, creates a system
user and a document root under `/srv/coulobre/web/<account-id>/public`, and
installs Apache and PHP-FPM configuration. It validates both configurations,
reloads PHP-FPM, waits for the per-site socket, then reloads Apache.
installs Apache and PHP-FPM configuration. It selects the newest stable
installed series for a new site. Pass `--php-version 8.5` to select a
specific installed series at initial activation. It validates both
configurations, reloads PHP-FPM, waits for the per-site socket, then reloads
Apache. Reapplying the manifest preserves the active series.
Reapply the same manifest to retry or verify an existing installation. The
node checks the account registry for domain conflicts and protects existing
@@ -812,6 +943,7 @@ The JSON report includes the manifest identity and one of three states.
- `configured` means the reservation, Unix account, document root, service
configuration, running services, and PHP-FPM socket match the manifest.
The report includes the active `php_version`.
- `not_installed` means the node has no reservation for the account.
- `needs_attention` includes the first mismatch or service problem found.
@@ -819,7 +951,7 @@ The status command reads local state. It exits with code 0 for `configured`,
code 2 for the other report states, and code 1 if it cannot read the manifest
or inspect the node. Use an HTTP request to verify the site's response as well.
#Website aliases reuse the activation and HTTPS sockets. The web node stores
Website aliases reuse the activation and HTTPS sockets. The web node stores
alias reservations under `/var/lib/coulobre/web-node/aliases/` and creates
separate Apache virtual hosts that share the primary site's document root and
PHP-FPM socket. Existing website deployment manifests use the primary domain
@@ -911,6 +1043,14 @@ read the JSON reply to EOF. A `configured` reply includes the account ID and
domain. A `failed` reply includes a diagnostic in `problem`. Retry the same
manifest if the connection closes before a reply arrives.
The panel uses `activate_with_runtime` with a deployment manifest under
`site`, the PHP limits under `php_settings`, and an `allowed_versions`
array of PHP series. An empty array allows all installed stable series.
A successful reply includes the `applied_php_version` and
`applied_php_settings`. To change the active pool, send `set_php_version`
with the same `site` and a `php_version` series. Retry the same request
after an interrupted reply to confirm the applied series.
The socket also accepts a storage request with
`"operation": "measure_storage"` and the deployment manifest under `"site"`.
A successful reply includes the request identity and `used_bytes`.
@@ -1075,12 +1215,14 @@ time.
Use the [website backup command](#back-up-and-restore-hosted-website-files)
on the web node and the [database backup command](#back-up-and-restore-a-managed-database)
on each database node. Transfer the resulting files to a root-controlled
directory with mode `0600` on every archive. Name the website archive
directory with mode `0600` on every archive. Name the primary website archive
`website.tar.gz` and each SQL dump `database-<suffix>.sql.gz`, for example
`database-cms.sql.gz`. When the manifest includes mail, use the
[mailbox backup command](#back-up-and-restore-a-mailbox) on the mail node and
place each archive under `mailboxes/<domain>/<local-part>.tar.gz` within the
component directory. Assemble the ZIP with the same account manifest.
component directory. For a version 3 account manifest, use
`websites/s<site_id>.tar.gz` for each entry in `additional_websites`.
Assemble the ZIP with the same account manifest.
```sh
sudo /opt/coulobre/bin/coulobre-account-backup pack \
@@ -1104,6 +1246,8 @@ sudo /opt/coulobre/bin/coulobre-account-backup unpack \
```
Use the recovered `website.json` and `website.tar.gz` with `restore-site`.
For an independent website, use its `websites/s<site_id>.json` and
`websites/s<site_id>.tar.gz` pair with the same command.
Use each `database-<suffix>.json` and `database-<suffix>.sql.gz` pair with
`restore-database`. For mail, use the original manifest and archive recovered
as `mailboxes/<domain>/<local-part>.json` and
@@ -1168,5 +1312,6 @@ sh -n deploy/certbot/reload-apache.sh
python manage.py check
python manage.py makemigrations --check --dry-run
python manage.py test coulobre
python -m unittest discover -s tests -p test_panel_installer.py
git diff --check
```
+74
View File
@@ -0,0 +1,74 @@
# Migration sources
Coulobre v0.6 imports supported data from a DirectAdmin account archive.
The [DirectAdmin workflow](development.md#inspect-a-directadmin-backup)
describes the supported formats and destination checks. For cPanel and Plesk,
the mappings below are candidates based on vendor documentation. The next
test for each candidate needs an archive generated by the source product
from a disposable account populated with synthetic data.
## cPanel and WHM
Start with one full, unsplit Linux account archive produced by `pkgacct` or
the account's Full Backup interface. The archive can carry an account-specific
root directory. Create separate examples with and without website, mail, and
database contents to distinguish omitted components from empty components.
Incremental copies, split archives, PostgreSQL, and remote MySQL accounts
would need separate support.
[cPanel archive contents](https://docs.cpanel.net/knowledge-base/backup/backup-tarball-contents/)
· [pkgacct options](https://docs.cpanel.net/whm/scripts/the-pkgacct-script/124/)
| Resource | Candidate mapping |
| --- | --- |
| Account | Read `cp/USERNAME` for the primary domain and account metadata. Identify parked, addon, and subdomains separately before choosing any Coulobre aliases. |
| Website | Map `homedir/public_html` to the primary managed document root. Use the per-domain metadata to identify non-default roots. |
| Database | Restore account-scoped logical MySQL dumps from the MySQL component into fresh managed databases. Report omitted dumps, schema-only exports, and renamed databases. Generate new logins and grants. |
| Mail | Pair accounts in the domain mail settings with virtual Maildirs inside `homedir/mail`. Reuse the DirectAdmin Maildir destination checks and create fresh credentials. |
| DNS | Convert `dnszones/DOMAIN.db` through the same DNS record mapping and preview used for DirectAdmin. Treat signing keys and extra record types as manual work. |
**Decision.** Prioritize cPanel for a future importer when a maintainer or
pilot customer can supply genuine full backups for both packaging routes.
Start with inventory and dry-run mapping. Its file layout is close enough
to reuse the existing Coulobre destination logic.
## Plesk Obsidian on Linux
Start with a full single-subscription export from Backup Manager or
`plesk bin pleskbackup`. The export contains XML descriptors and nested
content archives. The storage tree uses separate pieces for configuration
and payloads. Incremental chains, password-protected or multivolume exports,
server or reseller backups, and Windows data add distinct cases.
[Plesk export options](https://docs.plesk.com/en-US/obsidian/cli-linux/using-command-line-utilities/pleskbackup-backing-up-content-and-configuration.74260/)
· [Plesk Linux backup structure](https://support.plesk.com/hc/en-us/articles/12377966554135-Local-backup-structure-in-Plesk-for-Linux)
| Resource | Candidate mapping |
| --- | --- |
| Account | Read the subscription info XML for the primary domain and site identities. Map subscriptions individually and review owner and plan assignments. |
| Website | Read the domain's user-data archive referenced in the descriptor. Use the documented domain and site hierarchy for paths other than the default `httpdocs`. |
| Database | Locate each database component through its descriptor and restore compatible logical MySQL dumps into new managed databases. |
| Mail | Map mailbox identities and message components from the subscription descriptor. Confirm the Linux payload format before treating it as Maildir data. |
| DNS | Convert subscription DNS information from the descriptor into a Coulobre zone preview. Confirm whether the export records DNS settings or uses a separate component for the selected Plesk version. |
**Decision.** Defer a Plesk importer until there is a migration request with
one or more genuine Linux exports. Confirm the descriptor and payload
mapping first. The XML references and nested compression need a source
adapter before the existing destination checks can be reused.
## Produce representative fixtures
Use a newly created account or subscription with an `example.net` domain,
a public page and a secondary domain, a small SQL database, an inbox and a
separate mail folder, and a DNS zone with A, AAAA, MX, TXT, and CNAME records.
Use synthetic file, row, and message contents, and record the source version
and backup options with the fixture. Generate the export with the vendor
tool and confirm its contents before using it in importer tests. Keep
credentials, keys, and customer archives out of the repository.
| Source | Fixture to request |
| --- | --- |
| cPanel | Full account backup from the account interface and an unsplit `pkgacct` backup of the same account. Include a custom document root and a database omitted by backup options in supplementary fixtures. |
| Plesk | Full Linux subscription export from Backup Manager plus a full CLI export of the same subscription. Include website content, mail, a MariaDB database, and a DNS configuration. |
Public documentation and documentation-derived examples describe the
expected layout. Compatibility checks will use source-generated exports
once a source installation is available.
+8 -1
View File
@@ -4,14 +4,17 @@ build-backend = "setuptools.build_meta"
[project]
name = "coulobre-panel"
version = "0.1.0.dev0"
version = "0.8.0rc1"
description = "A web hosting control panel for hosting providers and resellers."
readme = "README.md"
requires-python = ">=3.12"
license = "Apache-2.0"
dependencies = [
"Django>=5.2.8,<5.3",
"django-otp>=1.7.5,<2",
"celery>=5.6,<6",
"cryptography>=45",
"dnspython>=2.7,<3",
"idna>=3,<4",
]
@@ -20,8 +23,11 @@ coulobre-account-backup = "coulobre.account_backup:main"
coulobre-database-node = "coulobre.database_node:main"
coulobre-directadmin = "coulobre.directadmin:main"
coulobre-dns-node = "coulobre.dns_node:main"
coulobre-firewall = "coulobre.firewall:main"
coulobre-mail-node = "coulobre.mail_node:main"
coulobre-node-setup = "coulobre.node_setup:main"
coulobre-service-credentials = "coulobre.service_credentials:main"
coulobre-service-health = "coulobre.service_health:main"
coulobre-web-node = "coulobre.web_node:main"
[project.optional-dependencies]
@@ -37,6 +43,7 @@ server = ["gunicorn>=27.0.1,<28"]
"templates/hosting/*.conf",
"templates/hosting/*.html",
"templates/hosting/*.php",
"templates/hosting/*.txt",
]
[tool.ruff]
+93 -5
View File
@@ -9,6 +9,7 @@ from dataclasses import dataclass
from pathlib import Path
from shutil import copyfileobj
from tempfile import NamedTemporaryFile, TemporaryDirectory
from uuid import UUID
from zipfile import ZIP_STORED, BadZipFile, ZipFile
from .database_node import DEFAULT_SOCKET, DatabaseSpec
@@ -18,6 +19,7 @@ from .web_node import WebSite
BASE_MANIFEST_VERSION = 1
MAIL_MANIFEST_VERSION = 2
MULTI_SITE_MANIFEST_VERSION = 3
MANIFEST_KIND = "coulobre_account_backup"
MANIFEST_NAME = "manifest.json"
MAX_MANIFEST_BYTES = 1024 * 1024
@@ -29,8 +31,27 @@ class AccountBackup:
website: WebSite
databases: tuple[DatabaseSpec, ...]
mailboxes: tuple[MailboxSpec, ...] | None = None
additional_websites: tuple[WebSite, ...] = ()
def __post_init__(self):
if self.website.site_id is not None:
raise ValueError(
"The primary website must use its account identity."
)
sites = {self.website.domain}
site_ids = set()
for site in self.additional_websites:
if (
site.account_id != self.website.account_id
or site.site_id is None
):
raise ValueError(
"All websites must belong to the backup account."
)
if site.domain in sites or site.site_id in site_ids:
raise ValueError("The account backup lists a website twice.")
sites.add(site.domain)
site_ids.add(site.site_id)
names = set()
for database in self.databases:
if database.account_id != self.website.account_id:
@@ -41,7 +62,7 @@ class AccountBackup:
raise ValueError("The account backup lists a database twice.")
names.add(database.name)
if self.mailboxes is not None and len(self.mailboxes) != len(
set(self.mailboxes)
{mailbox.address for mailbox in self.mailboxes}
):
raise ValueError("The account backup lists a mailbox twice.")
@@ -57,6 +78,11 @@ class AccountBackup:
manifest["mailboxes"] = [
mailbox.manifest() for mailbox in self.mailboxes
]
if self.additional_websites:
manifest["version"] = MULTI_SITE_MANIFEST_VERSION
manifest["additional_websites"] = [
site.manifest() for site in self.additional_websites
]
return manifest
@classmethod
@@ -67,30 +93,44 @@ class AccountBackup:
if type(version) is not int or version not in (
BASE_MANIFEST_VERSION,
MAIL_MANIFEST_VERSION,
MULTI_SITE_MANIFEST_VERSION,
):
raise ValueError("Unsupported account backup manifest version.")
fields = {"version", "kind", "website", "databases"}
if version == MAIL_MANIFEST_VERSION:
if version == MULTI_SITE_MANIFEST_VERSION:
fields.add("additional_websites")
if version == MAIL_MANIFEST_VERSION or (
version == MULTI_SITE_MANIFEST_VERSION and "mailboxes" in data
):
fields.add("mailboxes")
if data.keys() != fields or not isinstance(data["databases"], list):
raise ValueError("Expected a Coulobre account backup manifest.")
mailboxes = None
if version == MAIL_MANIFEST_VERSION:
if "mailboxes" in fields:
if not isinstance(data["mailboxes"], list):
raise ValueError("Expected a list of mailbox manifests.")
mailboxes = tuple(
MailboxSpec.from_manifest(item) for item in data["mailboxes"]
)
sites = data.get("additional_websites", [])
if not isinstance(sites, list):
raise ValueError(
"Expected a list of additional website manifests."
)
return cls(
WebSite.from_manifest(data["website"]),
tuple(
DatabaseSpec.from_manifest(item) for item in data["databases"]
),
mailboxes,
tuple(WebSite.from_manifest(site) for site in sites),
)
def components(self):
yield self.website, "website.json", "website.tar.gz"
for site in self.additional_websites:
name = f"websites/{site.node_key}"
yield site, f"{name}.json", f"{name}.tar.gz"
for database in self.databases:
name = f"database-{database.suffix}"
yield database, f"{name}.json", f"{name}.sql.gz"
@@ -129,6 +169,20 @@ def main(argv=None):
commands.add_parser(
"restore-request", help="Restore a component for the panel worker."
)
commands.add_parser(
"offsite-request", help="Transfer a scheduled backup for the worker."
)
verify = commands.add_parser(
"verify-offsite", help="Check access to an off-site destination."
)
verify.add_argument("destination")
recover = commands.add_parser(
"recover-offsite", help="Retrieve and verify an off-site archive."
)
recover.add_argument("destination")
recover.add_argument("account_id", type=int)
recover.add_argument("backup_id", type=UUID)
recover.add_argument("output", type=Path)
args = parser.parse_args(argv)
if args.command == "restore-request":
@@ -146,7 +200,28 @@ def main(argv=None):
return serve_backup_request()
if args.command == "offsite-request":
from .offsite_node import serve_offsite_request
return serve_offsite_request()
try:
if args.command == "verify-offsite":
from .offsite_node import verify_destination
verify_destination(args.destination)
print("Off-site repository access verified.")
return 0
if args.command == "recover-offsite":
from .offsite_backup import OffsiteBackupRequest
from .offsite_node import recover_offsite_backup
request = OffsiteBackupRequest(
args.account_id, args.backup_id, args.destination
)
snapshot = recover_offsite_backup(request, args.output)
print(f"Verified archive recovered from snapshot {snapshot}.")
return 0
if args.command == "unpack":
backup = unpack_backup(args.archive, args.directory)
else:
@@ -180,14 +255,16 @@ def private_path(path, *, new=False):
return path
def create_backup(backup, archive, socket):
def create_backup(backup, archive, socket, *, remote_mail=False):
from .database_node_backup import backup_database
from .mail_archive_transport import download_mailbox_backup
from .mail_node_backup import backup_mailbox
from .web_node_backup import backup_website
archive = private_path(archive, new=True)
with TemporaryDirectory(dir=archive.parent) as directory:
directory = Path(directory)
captured = 0
for resource, _, filename in backup.components():
path = directory / filename
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
@@ -195,8 +272,19 @@ def create_backup(backup, archive, socket):
backup_website(resource, path)
elif isinstance(resource, DatabaseSpec):
backup_database(resource, socket, path)
else:
elif not remote_mail:
backup_mailbox(resource, path)
else:
try:
download_mailbox_backup(resource, path)
except (OSError, ValueError) as error:
raise ValueError(
f"Mail collection stopped at {resource.address} "
f"({captured} of {len(backup.mailboxes)} captured). "
"No account archive was published. "
f"{error}"
) from None
captured += 1
pack_backup(backup, directory, archive)
+33 -10
View File
@@ -16,6 +16,7 @@ from .node_files import check_root_file, locked_root_directory
from .node_requests import serve_apply_request
REQUEST_VERSION = 1
REMOTE_MAIL_VERSION = 2
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
BACKUP_TIMEOUT_SECONDS = 30 * 60
@@ -25,6 +26,7 @@ BACKUP_TIMEOUT_SECONDS = 30 * 60
class AccountBackupRequest:
backup_id: UUID
backup: AccountBackup
remote_mail: bool = False
@classmethod
def from_manifest(cls, data):
@@ -32,29 +34,39 @@ class AccountBackupRequest:
not isinstance(data, dict)
or data.keys() != {"version", "backup_id", "backup"}
or type(data["version"]) is not int
or data["version"] != REQUEST_VERSION
or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION)
or not isinstance(data["backup_id"], str)
):
raise ValueError("Expected a local account backup request.")
backup_id = UUID(data["backup_id"])
if str(backup_id) != data["backup_id"]:
raise ValueError("Expected a canonical backup ID.")
return cls(backup_id, AccountBackup.from_manifest(data["backup"]))
backup = AccountBackup.from_manifest(data["backup"])
remote_mail = data["version"] == REMOTE_MAIL_VERSION
if remote_mail and backup.mailboxes is None:
raise ValueError(
"Expected mailboxes in the remote backup request."
)
return cls(backup_id, backup, remote_mail)
def manifest(self):
return {
"version": REQUEST_VERSION,
"version": self.version,
"backup_id": str(self.backup_id),
"backup": self.backup.manifest(),
}
def identity(self):
return {
"version": REQUEST_VERSION,
"version": self.version,
"backup_id": str(self.backup_id),
"account_id": self.backup.website.account_id,
}
@property
def version(self):
return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION
def backup_archive(account_id, backup_id):
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
@@ -95,11 +107,17 @@ def serve_backup_request():
def create_requested_backup(request):
if os.geteuid() != 0:
raise ValueError("Run create-request as root on the backup node.")
if (
request.backup.mailboxes is not None
and os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") != "1"
):
raise ValueError("Enable mailbox backups on the local backup node.")
if request.backup.mailboxes is not None:
setting = (
"COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL"
if request.remote_mail
else "COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL"
)
if os.environ.get(setting) != "1":
location = "remote" if request.remote_mail else "local"
raise ValueError(
f"Enable mailbox backups on the {location} backup node."
)
with locked_root_directory(BACKUP_DIRECTORY):
archive = ensure_requested_archive(request)
return {"archive_bytes": archive.stat().st_size}
@@ -112,7 +130,12 @@ def ensure_requested_archive(request):
if os.path.lexists(expiration_marker(archive)):
raise ValueError("This account backup has expired.")
if not os.path.lexists(archive):
create_backup(request.backup, archive, DEFAULT_SOCKET)
if request.remote_mail:
create_backup(
request.backup, archive, DEFAULT_SOCKET, remote_mail=True
)
else:
create_backup(request.backup, archive, DEFAULT_SOCKET)
return archive
check_root_file(archive, mode=0o600)
+31 -7
View File
@@ -18,6 +18,7 @@ from .node_requests import serve_apply_request
from .web_node import WebSite
REQUEST_VERSION = 1
REMOTE_MAIL_VERSION = 2
RESTORE_DIRECTORY = Path("/var/lib/coulobre/account-restores")
RESTORE_SOCKET = "/run/coulobre-account-restore.sock"
RESTORE_TIMEOUT_SECONDS = BACKUP_TIMEOUT_SECONDS
@@ -94,6 +95,7 @@ class ComponentRestoreRequest:
backup_id: UUID
account_id: int
resource: DatabaseSpec | MailboxSpec
remote_mail: bool = False
def __post_init__(self):
if (
@@ -106,6 +108,8 @@ class ComponentRestoreRequest:
and self.resource.account_id != self.account_id
):
raise ValueError("The database must belong to the backup account.")
if self.remote_mail and not isinstance(self.resource, MailboxSpec):
raise ValueError("Remote mail restore requires a mailbox.")
@classmethod
def from_manifest(cls, data):
@@ -114,7 +118,7 @@ class ComponentRestoreRequest:
or data.keys()
!= {"version", "restore_id", "backup_id", "account_id", "resource"}
or type(data["version"]) is not int
or data["version"] != REQUEST_VERSION
or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION)
or not isinstance(data["resource"], dict)
):
raise ValueError("Expected a local component restore request.")
@@ -129,11 +133,14 @@ class ComponentRestoreRequest:
parse_uuid(data["backup_id"]),
data["account_id"],
spec,
data["version"] == REMOTE_MAIL_VERSION,
)
def manifest(self):
return {
"version": REQUEST_VERSION,
"version": REMOTE_MAIL_VERSION
if self.remote_mail
else REQUEST_VERSION,
"restore_id": str(self.restore_id),
"backup_id": str(self.backup_id),
"account_id": self.account_id,
@@ -193,7 +200,10 @@ def restore_requested_website(request):
def restore_requested_component(request):
if isinstance(request.resource, DatabaseSpec):
if request.remote_mail:
setting = "COULOBRE_REMOTE_MAILBOX_RESTORE"
feature = "remote mailbox"
elif isinstance(request.resource, DatabaseSpec):
setting = "COULOBRE_LOCAL_DATABASE_RESTORE"
feature = "database"
else:
@@ -203,14 +213,19 @@ def restore_requested_component(request):
raise ValueError(
f"Enable local {feature} restores on the backup node."
)
apply_restore_once(request, restore_component_from_bundle)
if request.remote_mail:
# The destination owns the restore claim across SSH disconnects.
restore_component_from_bundle(request)
else:
apply_restore_once(request, restore_component_from_bundle)
def apply_restore_once(request, restore):
def apply_restore_once(request, restore, *, journal=None):
if os.geteuid() != 0:
raise ValueError("Run the account restore as root on the backup node.")
with locked_root_directory(RESTORE_DIRECTORY) as directory:
claim = RESTORE_DIRECTORY / f"{request.restore_id}.json"
journal = RESTORE_DIRECTORY if journal is None else journal
with locked_root_directory(journal) as directory:
claim = journal / f"{request.restore_id}.json"
result = claim.with_suffix(".result")
manifest = json.dumps(request.manifest())
try:
@@ -259,6 +274,10 @@ def restore_website_from_bundle(request):
def restore_component_from_bundle(request):
from .database_node_backup import restore_database
from .mail_archive_transport import (
UNCONFIRMED_REMOTE_RESTORE,
upload_mailbox_restore,
)
from .mail_node_backup import restore_mailbox
resource = request.resource
@@ -270,6 +289,11 @@ def restore_component_from_bundle(request):
) as staged:
if isinstance(resource, DatabaseSpec):
restore_database(resource, DEFAULT_SOCKET, staged)
elif request.remote_mail:
try:
upload_mailbox_restore(resource, staged, request.restore_id)
except OSError:
raise ValueError(UNCONFIRMED_REMOTE_RESTORE) from None
else:
restore_mailbox(resource, staged)
+20
View File
@@ -8,6 +8,26 @@ class CoulobreAdminSite(AdminSite):
def has_permission(self, request):
return super().has_permission(request) and not is_tenant(request.user)
def login(self, request, extra_context=None):
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
destination = request.GET.get("next")
if not url_has_allowed_host_and_scheme(
destination,
{request.get_host()},
require_https=request.is_secure(),
):
destination = reverse("admin:index")
if request.user.is_authenticated:
if not self.has_permission(request):
raise PermissionDenied
return redirect(destination)
return redirect_to_login(destination, login_url="panel:login")
class CoulobreAdminConfig(AdminConfig):
default_site = "coulobre.admin.CoulobreAdminSite"
+95
View File
@@ -0,0 +1,95 @@
import json
import os
import re
import secrets
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import UUID
from .node_files import read_root_file, write_new_file
PASSWORD = re.compile(r"[A-Za-z0-9_-]{43}")
ROTATION_IN_PROGRESS = (
"Retry the current credential change before starting another."
)
def valid_generation(value):
if value is None:
return True
if not isinstance(value, str):
return False
try:
return str(UUID(value)) == value
except ValueError:
return False
def rotation_path(path):
return path.with_suffix(".rotation")
def load_pending_rotation(path):
try:
pending = json.loads(read_root_file(rotation_path(path), mode=0o600))
except FileNotFoundError:
return None
if (
not isinstance(pending, dict)
or not isinstance(pending.get("id"), str)
or not valid_generation(pending["id"])
or "previous" not in pending
or not valid_generation(pending["previous"])
or not isinstance(pending.get("password"), str)
or not PASSWORD.fullmatch(pending["password"])
):
raise ValueError("The pending credential record is invalid.")
return pending
def stage_rotation(path, request, generation, *, hash_password=None):
pending = load_pending_rotation(path)
if pending is not None and (
pending["id"] != request.rotation_id
or pending["previous"] != request.previous_id
):
raise ValueError(ROTATION_IN_PROGRESS)
if generation not in (request.previous_id, request.rotation_id):
raise ValueError(
"The credential changed after this request was opened."
)
if pending is not None or generation == request.rotation_id:
return pending
password = secrets.token_urlsafe(32)
pending = {
"id": request.rotation_id,
"previous": generation,
"password": password,
}
if hash_password is not None:
pending["password_hash"] = hash_password(password)
write_new_file(rotation_path(path), json.dumps(pending), mode=0o600)
sync_directory(path.parent)
return pending
def save_credential_record(path, record):
with TemporaryDirectory(dir=path.parent) as scratch:
staged = Path(scratch) / "credentials"
write_new_file(staged, json.dumps(record, indent=2) + "\n", mode=0o600)
os.replace(staged, path)
sync_directory(path.parent)
def finish_rotation(path):
rotation_path(path).unlink(missing_ok=True)
sync_directory(path.parent)
def sync_directory(path):
directory = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
+41 -3
View File
@@ -5,6 +5,8 @@ from dataclasses import dataclass
from pathlib import Path
from .node_requests import serve_apply_request
from .node_retirement import RetirementRequest, parse_retirement
from .service_access import ServiceAccessRequest, parse_service_request
MANIFEST_VERSION = 1
MANIFEST_KIND = "mariadb_database"
@@ -98,15 +100,44 @@ def main(argv=None):
restore.add_argument("manifest", type=Path)
restore.add_argument("archive", type=Path)
restore.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
directadmin = commands.add_parser(
"restore-directadmin", help="Restore a DirectAdmin account database."
)
directadmin.add_argument("manifest", type=Path)
directadmin.add_argument("backup", type=Path)
directadmin.add_argument("source_database")
directadmin.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
args = parser.parse_args(argv)
if args.command == "apply-request":
from .database_node_apply import apply_database
from .database_node_apply import (
apply_database,
retire_database,
set_database_access,
)
def parse(data):
return parse_retirement(
data,
DatabaseSpec.from_manifest,
lambda values: parse_service_request(
values, DatabaseSpec.from_manifest
),
)
def apply(request):
if isinstance(request, RetirementRequest):
return retire_database(request, DEFAULT_SOCKET)
if isinstance(request, ServiceAccessRequest):
return set_database_access(
request.resource, DEFAULT_SOCKET, request.suspended
)
return apply_database(request, DEFAULT_SOCKET)
return serve_apply_request(
MANIFEST_VERSION,
DatabaseSpec.from_manifest,
lambda database: apply_database(database, DEFAULT_SOCKET),
parse,
apply,
)
try:
@@ -134,6 +165,13 @@ def main(argv=None):
report = restore_database(database, args.socket, args.archive)
print(json.dumps(report, indent=2))
elif args.command == "restore-directadmin":
from .database_node_backup import restore_directadmin_database
report = restore_directadmin_database(
database, args.socket, args.backup, args.source_database
)
print(json.dumps(report, indent=2))
else:
print(
json.dumps(
+153 -4
View File
@@ -5,7 +5,13 @@ import secrets
from contextlib import closing, contextmanager, suppress
from pathlib import Path
from .credential_rotation import (
ROTATION_IN_PROGRESS,
rotation_path,
valid_generation,
)
from .node_files import read_root_file, require_root_directory, write_new_file
from .node_retirement import RetirementRecord
STATE_DIRECTORY = Path("/var/lib/coulobre/database-node")
MANAGED_COMMENT_PREFIX = "Coulobre managed database "
@@ -109,7 +115,15 @@ def check_database(driver, cursor, database, socket, record_path):
def checked_credentials(
driver, cursor, database, socket, record_path, *, restoring=False
driver,
cursor,
database,
socket,
record_path,
*,
restoring=False,
verify_login=True,
pending_password=None,
):
name = database.name
schema, users = read_resources(cursor, name)
@@ -129,7 +143,20 @@ def checked_credentials(
raise ValueError("The database installation is incomplete.")
if not restoring:
check_restore_complete(record_path)
password_hash = native_password_hash(record["password"])
if pending_password is None and os.path.lexists(
rotation_path(record_path)
):
raise ValueError(ROTATION_IN_PROGRESS)
password = record["password"]
if pending_password is not None and users == (
(
"localhost",
"mysql_native_password",
native_password_hash(pending_password),
),
):
password = pending_password
password_hash = native_password_hash(password)
check_resources(
schema,
users,
@@ -146,14 +173,23 @@ def checked_credentials(
),
(f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",),
}
if set(cursor.fetchall()) != expected_grants:
grants = {
(grant.removesuffix(" ACCOUNT LOCK"),)
for (grant,) in cursor.fetchall()
}
if grants != expected_grants:
raise ValueError("The MariaDB login has unexpected grants.")
if not verify_login or (
load_access_checkpoint(record_path, record) is not None
and login_is_locked(cursor, name)
):
return record
try:
with closing(
driver.connect(
host="localhost",
user=name,
passwd=record["password"],
passwd=password,
db=name,
unix_socket=str(socket),
connect_timeout=5,
@@ -177,6 +213,12 @@ def check_restore_complete(record_path):
def install_database(cursor, database, socket, record_path):
if os.path.lexists(record_path.with_suffix(".retired")):
raise ValueError(
"This database is retained for a retired hosting account."
)
if os.path.lexists(rotation_path(record_path)):
raise ValueError(ROTATION_IN_PROGRESS)
check_restore_complete(record_path)
name = database.name
schema, users = read_resources(cursor, name)
@@ -254,6 +296,7 @@ def load_credentials(database, socket, path):
or not isinstance(record.get("password"), str)
or not record["password"]
or not record["password"].isascii()
or not valid_generation(record.get("rotation_id"))
or not isinstance(record.get("ownership"), str)
or not record["ownership"]
):
@@ -311,3 +354,109 @@ def grant_scope(name):
def native_password_hash(password):
first = hashlib.sha1(password.encode("utf-8")).digest()
return "*" + hashlib.sha1(first).hexdigest().upper()
def login_is_locked(cursor, name):
cursor.execute(
"SELECT COALESCE("
"JSON_UNQUOTE(JSON_EXTRACT(Priv, '$.account_locked')), 'false') "
"FROM mysql.global_priv WHERE User = %s AND Host = 'localhost'",
(name,),
)
row = cursor.fetchone()
if row not in (("true",), ("false",)):
raise ValueError("MariaDB returned an invalid login lock state.")
return row == ("true",)
def load_access_checkpoint(record_path, record):
try:
checkpoint = json.loads(
read_root_file(record_path.with_suffix(".suspended"), mode=0o600)
)
except FileNotFoundError:
return None
if (
not isinstance(checkpoint, dict)
or checkpoint.get("ownership") != record["ownership"]
or type(checkpoint.get("was_locked")) is not bool
):
raise ValueError("The MariaDB suspension checkpoint is invalid.")
return checkpoint
def set_database_access(database, socket, suspended):
if os.geteuid() != 0:
raise ValueError(
"Run the service access request as root on the MariaDB node."
)
socket = socket.resolve()
record_path = STATE_DIRECTORY / f"{database.name}.json"
with locked_cursor(database, socket) as (driver, cursor):
record = checked_credentials(
driver, cursor, database, socket, record_path, verify_login=False
)
if record is None:
raise ValueError(
"Apply the database manifest before changing its access."
)
if not suspended and os.path.lexists(
record_path.with_suffix(".retired")
):
raise ValueError(
"This database is retained for a retired account."
)
checkpoint = load_access_checkpoint(record_path, record)
marker = record_path.with_suffix(".suspended")
if suspended and checkpoint is None:
checkpoint = {
"ownership": record["ownership"],
"was_locked": login_is_locked(cursor, database.name),
}
write_new_file(marker, json.dumps(checkpoint), mode=0o600)
directory = os.open(
record_path.parent, os.O_RDONLY | os.O_DIRECTORY
)
try:
os.fsync(directory)
finally:
os.close(directory)
if checkpoint is None:
return
lock_login = suspended or checkpoint["was_locked"]
action = "LOCK" if lock_login else "UNLOCK"
cursor.execute(
f"ALTER USER %s@'localhost' ACCOUNT {action}", (database.name,)
)
if login_is_locked(cursor, database.name) != lock_login:
raise ValueError(
"MariaDB did not apply the requested login state."
)
if not suspended:
marker.unlink()
def retire_database(request, socket):
database = request.resource
socket = socket.resolve()
record_path = STATE_DIRECTORY / f"{database.name}.json"
with locked_cursor(database, socket) as (driver, cursor):
retirement = RetirementRecord(STATE_DIRECTORY, request)
if retirement.is_complete:
return
record = checked_credentials(
driver, cursor, database, socket, record_path, verify_login=False
)
if record is None or not login_is_locked(cursor, database.name):
raise ValueError(
"Suspend the managed database login before retirement."
)
retirement.begin()
cursor.execute("KILL USER %s", (database.name,))
marker = record_path.with_suffix(".retired")
if not os.path.lexists(marker):
write_new_file(marker, retirement.document, mode=0o600)
elif read_root_file(marker, mode=0o600) != retirement.document:
raise ValueError("The database has a different retirement record.")
retirement.finish()
+40 -19
View File
@@ -72,25 +72,7 @@ def restore_database(database, socket, archive):
check_root_file(archive, mode=0o600)
with TemporaryFile(dir=archive.parent) as validated:
read_dump(database, archive, validated)
validated.seek(0)
with managed_database(database, socket, restoring=True) as (
cursor,
record,
record_path,
):
check_empty_database(cursor, database.name)
with client_options(record, record_path.parent) as options:
restore_marker = mark_restore_pending(record_path, record)
command = client_command("mariadb", options, record) + (
"--batch",
"--sandbox",
"--binary-mode",
"--local-infile=0",
"--skip-reconnect",
f"--database={database.name}",
)
import_dump(command, validated)
restore_marker.unlink()
restore_dump(database, socket, validated)
return database.manifest() | {
"kind": "coulobre_mariadb_restore",
@@ -99,6 +81,45 @@ def restore_database(database, socket, archive):
}
def restore_directadmin_database(database, socket, backup, source):
from .directadmin_payload import copy_database_dump
if os.geteuid() != 0:
raise ValueError(
"Run restore-directadmin as root on the MariaDB node."
)
with TemporaryFile() as validated:
copy_database_dump(database, backup, source, validated)
restore_dump(database, socket, validated)
return database.manifest() | {
"kind": "directadmin_database_restore",
"database": database.name,
"source_database": source,
}
def restore_dump(database, socket, validated):
validated.seek(0)
with managed_database(database, socket, restoring=True) as (
cursor,
record,
record_path,
):
check_empty_database(cursor, database.name)
with client_options(record, record_path.parent) as options:
restore_marker = mark_restore_pending(record_path, record)
command = client_command("mariadb", options, record) + (
"--batch",
"--sandbox",
"--binary-mode",
"--local-infile=0",
"--skip-reconnect",
f"--database={database.name}",
)
import_dump(command, validated)
restore_marker.unlink()
@contextmanager
def managed_database(database, socket, *, restoring=False):
socket = socket.resolve()
+81
View File
@@ -0,0 +1,81 @@
from contextlib import closing
from . import database_node_apply as db
from .credential_rotation import (
finish_rotation,
load_pending_rotation,
save_credential_record,
stage_rotation,
)
ACCESS_DENIED = 1045
def rotate_database_credentials(request, socket):
database = request.resource
socket = socket.resolve()
path = db.STATE_DIRECTORY / f"{database.name}.json"
with db.locked_cursor(database, socket) as (driver, cursor):
pending = load_pending_rotation(path)
record = db.checked_credentials(
driver,
cursor,
database,
socket,
path,
pending_password=pending["password"] if pending else None,
)
if record is None:
raise ValueError(
"Apply the database manifest before rotating its login."
)
if db.login_is_locked(cursor, database.name):
raise ValueError(
"Resume the database login before rotating its password."
)
generation = record.get("rotation_id")
pending = stage_rotation(path, request, generation)
if generation != request.rotation_id:
password = pending["password"]
cursor.execute(
"ALTER USER %s@'localhost' "
"IDENTIFIED VIA mysql_native_password USING %s",
(database.name, db.native_password_hash(password)),
)
db.checked_credentials(
driver,
cursor,
database,
socket,
path,
pending_password=password,
)
verify_old_password_rejected(driver, record)
record = record | {
"password": password,
"rotation_id": request.rotation_id,
}
save_credential_record(path, record)
finish_rotation(path)
return record
def verify_old_password_rejected(driver, record):
try:
with closing(
driver.connect(
host="localhost",
user=record["user"],
passwd=record["password"],
db=record["database"],
unix_socket=record["socket"],
connect_timeout=5,
charset="utf8mb4",
)
):
pass
except driver.Error as error:
if error.args and error.args[0] == ACCESS_DENIED:
return
raise
raise ValueError("MariaDB still accepts the previous password.")
+107
View File
@@ -0,0 +1,107 @@
import dns.exception
import dns.rdatatype
import dns.zone
from .directadmin import MAX_METADATA_SIZE
from .directadmin_payload import read_resource
from .dns_node import AddressRecord, DnsZone, ExtraRecord, MxRecord, TxtRecord
from .domain_names import canonical_domain
def read_zone_backup(backup, domain):
def matches(parts):
return (
len(parts) == 3
and parts[0] == "backup"
and parts[2] == f"{parts[1]}.db"
and canonical_domain(parts[1]) == domain
)
def read_zone(stream, size):
if size > MAX_METADATA_SIZE:
raise ValueError("The source DNS zone exceeds the size limit.")
return stream.read(size).decode("utf-8")
username, zone_text = read_resource(backup, matches, read_zone)
return username, *convert_zone(zone_text, domain)
def convert_zone(text, domain):
try:
source = dns.zone.from_text(
text,
origin=f"{domain}.",
relativize=False,
allow_include=False,
allow_directives=("$ORIGIN", "$TTL"),
)
except dns.exception.DNSException:
raise ValueError(
"Invalid source DNS zone or unsupported directive."
) from None
soa = source.get_soa()
nameservers = [
str(record.target)
for record in source.find_rdataset(source.origin, "NS")
]
master = str(soa.mname)
if master in nameservers:
nameservers.remove(master)
nameservers.insert(0, master)
addresses, mx_records, txt_records, extra_records = [], [], [], []
unsupported = []
for owner, records in source.iterate_rdatasets():
name = str(owner)
record_type = dns.rdatatype.to_text(records.rdtype)
if owner == source.origin and record_type in ("SOA", "NS"):
continue
for record in records:
try:
match record_type:
case "A" | "AAAA":
addresses.append(AddressRecord(name, record.address))
case "MX":
mx_records.append(
MxRecord(
name, record.preference, str(record.exchange)
)
)
case "TXT":
txt_records.append(
TxtRecord(
name, b"".join(record.strings).decode("utf-8")
)
)
case "CNAME" | "SRV" | "CAA":
extra_records.append(
ExtraRecord(name, record_type, record.to_text())
)
case _:
unsupported.append(
{
"name": name,
"type": record_type,
"reason": "record_type",
}
)
except ValueError:
unsupported.append(
{
"name": name,
"type": record_type,
"reason": "record_value",
}
)
zone = DnsZone(
domain,
soa.serial,
tuple(nameservers),
str(soa.rname),
tuple(addresses),
tuple(mx_records),
tuple(txt_records),
tuple(extra_records),
)
return zone, unsupported
+142
View File
@@ -0,0 +1,142 @@
import os
from pathlib import Path
from tempfile import TemporaryDirectory
from .directadmin import (
BackupInventory,
backup_members,
copy_member,
member_path,
open_backup,
)
from .domain_names import canonical_domain
from .mail_node_backup import (
MAILDIR,
MAILDIR_FOLDERS,
check_fresh_maildir,
managed_mailbox,
publish_maildir,
)
def restore_directadmin_mailbox(mailbox, backup):
if os.geteuid() != 0:
raise ValueError("Run restore-directadmin as root on the mail node.")
with managed_mailbox(mailbox) as (home, account):
destination = home / MAILDIR
check_fresh_maildir(destination)
with TemporaryDirectory(dir=home.parent) as directory:
staged = Path(directory) / MAILDIR
staged.mkdir(mode=0o700)
summary = copy_mailbox_messages(mailbox, backup, staged)
for root, _, files in staged.walk():
root.chmod(0o700)
os.chown(root, account.pw_uid, account.pw_gid)
for name in files:
os.chown(root / name, account.pw_uid, account.pw_gid)
publish_maildir(staged, destination)
return {
"kind": "directadmin_mailbox_restore",
"address": mailbox.address,
**summary,
}
def maildir_prefix(parts, mailbox):
match parts:
case ("imap", domain, local, "Maildir", *_):
prefix = parts[:4]
case ("backup", domain, "email", "data", "imap", local, "Maildir", *_):
prefix = parts[:7]
case _:
return None
if (
local.lower() == mailbox.local_part
and canonical_domain(domain) == mailbox.domain
):
return prefix
return None
def copy_mailbox_messages(mailbox, backup, destination):
inventory = BackupInventory()
source = None
messages = total_bytes = 0
folders = {destination}
with open_backup(backup) as archive:
for member in backup_members(archive):
parts = member_path(member)
if parts == ("backup", "user.conf") or (
len(parts) == 4
and parts[0] == "backup"
and parts[2:] == ("email", "passwd")
and canonical_domain(parts[1]) == mailbox.domain
):
inventory.visit(archive, member)
prefix = maildir_prefix(parts, mailbox)
if prefix is None:
continue
if source is not None and source != prefix:
raise ValueError(
"The backup contains multiple Maildirs for this mailbox."
)
source = prefix
relative = parts[len(prefix) :]
if (
relative
and relative[0].startswith(".")
and relative[0] not in (".", "..")
):
folder = destination / relative[0]
relative = relative[1:]
else:
folder = destination
if not relative or (
len(relative) == 1 and relative[0] in MAILDIR_FOLDERS
):
if not member.isdir():
raise ValueError(
"The source Maildir has an invalid folder."
)
folders.add(folder)
continue
if len(relative) != 2 or relative[0] not in ("cur", "new"):
continue
if not member.isreg():
raise ValueError(
"A selected mailbox message is a link or special file."
)
folders.add(folder)
total_bytes += member.size
if (
mailbox.quota_mib is not None
and total_bytes > mailbox.quota_mib * 1024**2
):
raise ValueError(
"Messages exceed the destination mailbox quota."
)
target = folder.joinpath(*relative)
copy_member(archive, member, target)
os.utime(target, (member.mtime, member.mtime))
messages += 1
if inventory.username is None:
raise ValueError(
"Expected a DirectAdmin account backup with backup/user.conf."
)
if mailbox.address not in inventory.domain(mailbox.domain).mailboxes:
raise ValueError(
"The destination mailbox is absent from the backup's mailbox list."
)
if source is None:
raise ValueError(
"The backup does not contain a supported Maildir for this mailbox."
)
for folder in folders:
for name in MAILDIR_FOLDERS:
(folder / name).mkdir(mode=0o700, parents=True, exist_ok=True)
return {
"source_username": inventory.username,
"messages": messages,
"bytes": total_bytes,
}
+68
View File
@@ -0,0 +1,68 @@
import re
from shutil import copyfileobj
from .database_node import DATABASE_SUFFIX_PATTERN
from .directadmin import (
BackupInventory,
backup_members,
member_path,
open_backup,
)
def database_suffix(username, source):
normalized = source.lower()
suffix = normalized.removeprefix(f"{username.lower()}_")
if suffix == normalized or not re.fullmatch(
DATABASE_SUFFIX_PATTERN, suffix
):
return None
return suffix
def read_resource(backup, matches, read):
account = BackupInventory()
resource = None
with open_backup(backup) as archive:
for member in backup_members(archive):
parts = member_path(member)
if parts == ("backup", "user.conf"):
account.visit(archive, member)
if not matches(parts):
continue
if resource is not None:
raise ValueError("The backup repeats the selected resource.")
if not member.isreg() or member.size <= 0:
raise ValueError(
"The selected resource must be a nonempty file."
)
with archive.extractfile(member) as stream:
resource = read(stream, member.size)
if account.username is None:
raise ValueError(
"Expected a DirectAdmin account backup with backup/user.conf."
)
if resource is None:
raise ValueError("The backup does not contain the selected resource.")
return account.username, resource
def copy_database_dump(database, backup, source, destination):
if not re.fullmatch(r"[a-zA-Z0-9_]{1,64}", source):
raise ValueError("Enter the original DirectAdmin database name.")
def copy_dump(stream, size):
copyfileobj(stream, destination, length=1024 * 1024)
if destination.tell() != size:
raise ValueError("The DirectAdmin database dump is incomplete.")
return size
username, _ = read_resource(
backup,
lambda parts: parts == ("backup", f"{source}.sql"),
copy_dump,
)
if database_suffix(username, source) != database.suffix:
raise ValueError(
"The source database does not match the destination suffix."
)
+130 -9
View File
@@ -6,13 +6,19 @@ import sys
from dataclasses import asdict, dataclass
from pathlib import Path
import dns.exception
import dns.name
import dns.rdata
import idna
from .domain_names import canonical_domain
from .node_requests import serve_apply_request
from .node_retirement import RetirementRequest, parse_retirement
BASE_MANIFEST_VERSION = 1
MAIL_RECORD_MANIFEST_VERSION = 2
EXTENDED_MANIFEST_VERSION = 3
EXTRA_RECORD_TYPES = ("CNAME", "SRV", "CAA")
MANIFEST_KIND = "bind9_zone"
MAX_SOA_SERIAL = 2**32 - 1
TXT_CHUNK_SIZE = 255
@@ -167,6 +173,62 @@ class TxtRecord:
return f"{self.name}. IN TXT {text}"
@dataclass(frozen=True)
class ExtraRecord:
name: str
record_type: str
value: str
def __post_init__(self):
name = txt_owner_name(self.name)
if (
self.record_type not in EXTRA_RECORD_TYPES
or not isinstance(self.value, str)
or not self.value
or not self.value.isprintable()
):
raise ValueError("Enter a CNAME, SRV, or CAA record value.")
if self.record_type == "SRV" and not re.match(
r"^_[a-z0-9-]+\._[a-z0-9-]+\.", name
):
raise ValueError("SRV names start with _service._protocol.")
try:
value = dns.rdata.from_text(
"IN",
self.record_type,
self.value,
origin=dns.name.root,
relativize=False,
)
except (dns.exception.DNSException, ValueError):
raise ValueError(
f"Invalid {self.record_type} record value."
) from None
if self.record_type == "CNAME":
target = txt_owner_name(value.target.to_text())
text = f"{target}."
elif self.record_type == "SRV" and value.target != dns.name.root:
target = dns_name(value.target.to_text())
text = f"{value.priority} {value.weight} {value.port} {target}."
else:
text = value.to_text()
object.__setattr__(self, "name", name)
object.__setattr__(self, "value", text)
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != {
"name",
"record_type",
"value",
}:
raise ValueError("Expected a DNS record name, type, and value.")
return cls(**data)
def render(self):
return f"{self.name}. IN {self.record_type} {self.value}"
def read_records(data, key, record_type):
records = data.get(key, [])
if not isinstance(records, list):
@@ -183,6 +245,7 @@ class DnsZone:
addresses: tuple[AddressRecord, ...] = ()
mx_records: tuple[MxRecord, ...] = ()
txt_records: tuple[TxtRecord, ...] = ()
extra_records: tuple[ExtraRecord, ...] = ()
def __post_init__(self):
object.__setattr__(self, "domain", dns_name(self.domain))
@@ -214,6 +277,37 @@ class DnsZone:
"Each in-zone nameserver needs an address record."
)
self.check_mail_records(address_names)
self.check_extra_records(address_names)
def check_extra_records(self, address_names):
ordinary = (
address_names
| {self.domain}
| {record.name for record in (*self.mx_records, *self.txt_records)}
)
aliases = {}
for record in self.extra_records:
if not in_zone(record.name, self.domain):
raise ValueError("DNS record names must belong to the zone.")
if record.record_type == "CNAME":
if record.name in aliases:
raise ValueError("A CNAME name may only have one target.")
aliases[record.name] = txt_owner_name(record.value)
else:
ordinary.add(record.name)
if ordinary.intersection(aliases):
raise ValueError(
"A CNAME cannot share its name with another record."
)
visited = set()
for name in aliases:
chain = set()
while name in aliases and name not in visited:
if name in chain:
raise ValueError("The CNAME records create a loop.")
chain.add(name)
name = aliases[name]
visited.update(chain)
def check_mail_records(self, address_names):
if any(
@@ -248,6 +342,7 @@ class DnsZone:
if type(version) is not int or version not in (
BASE_MANIFEST_VERSION,
MAIL_RECORD_MANIFEST_VERSION,
EXTENDED_MANIFEST_VERSION,
):
raise ValueError("Unsupported DNS zone manifest version.")
fields = {
@@ -259,8 +354,10 @@ class DnsZone:
"responsible_name",
"addresses",
}
if version == MAIL_RECORD_MANIFEST_VERSION:
if version >= MAIL_RECORD_MANIFEST_VERSION:
fields.update(("mx_records", "txt_records"))
if version == EXTENDED_MANIFEST_VERSION:
fields.add("extra_records")
if data.keys() != fields:
raise ValueError("Expected a BIND9 zone manifest.")
if not isinstance(data["nameservers"], list):
@@ -273,13 +370,18 @@ class DnsZone:
addresses=read_records(data, "addresses", AddressRecord),
mx_records=read_records(data, "mx_records", MxRecord),
txt_records=read_records(data, "txt_records", TxtRecord),
extra_records=read_records(data, "extra_records", ExtraRecord),
)
def manifest_identity(self):
version = (
MAIL_RECORD_MANIFEST_VERSION
if self.mx_records or self.txt_records
else BASE_MANIFEST_VERSION
EXTENDED_MANIFEST_VERSION
if self.extra_records
else (
MAIL_RECORD_MANIFEST_VERSION
if self.mx_records or self.txt_records
else BASE_MANIFEST_VERSION
)
)
return {
"version": version,
@@ -294,11 +396,15 @@ class DnsZone:
"responsible_name": self.responsible_name,
"addresses": [asdict(record) for record in self.addresses],
}
if manifest["version"] == MAIL_RECORD_MANIFEST_VERSION:
if manifest["version"] >= MAIL_RECORD_MANIFEST_VERSION:
manifest.update(
mx_records=[asdict(record) for record in self.mx_records],
txt_records=[asdict(record) for record in self.txt_records],
)
if self.extra_records:
manifest["extra_records"] = [
asdict(record) for record in self.extra_records
]
return manifest
def render(self):
@@ -315,6 +421,7 @@ class DnsZone:
)
lines.extend(record.render() for record in self.mx_records)
lines.extend(record.render() for record in self.txt_records)
lines.extend(record.render() for record in self.extra_records)
return "\n".join(lines) + "\n"
@@ -336,14 +443,28 @@ def main(argv=None):
args = parser.parse_args(argv)
if args.command == "apply-request":
from .dns_node_apply import apply_zone
from .dns_node_apply import apply_zone, retire_zone
def apply(request):
if isinstance(request, RetirementRequest):
retire_zone(request)
else:
apply_zone(request)
def identity(request):
if isinstance(request, RetirementRequest):
return request.identity()
return request.manifest_identity()
return serve_apply_request(
BASE_MANIFEST_VERSION,
DnsZone.from_manifest,
apply_zone,
lambda data: parse_retirement(
data, DnsZone.from_manifest, DnsZone.from_manifest
),
apply,
limit=DNS_REQUEST_LIMIT,
identity=DnsZone.manifest_identity,
identity=identity,
probe_role="dns",
)
try:
+35 -2
View File
@@ -8,7 +8,13 @@ from pathlib import Path
from tempfile import TemporaryDirectory
from .dns_node import MAX_SOA_SERIAL
from .node_files import read_root_file, require_root_directory, write_new_file
from .node_files import (
locked_root_directory,
read_root_file,
require_root_directory,
write_new_file,
)
from .node_retirement import RetirementRecord, archive_path
ZONE_DIRECTORY = Path("/etc/bind/coulobre")
RNDC = ("rndc", "-s", "127.0.0.1")
@@ -30,7 +36,7 @@ def apply_zone(zone):
def install_zone(zone, path, directory):
domain = zone.domain
config = f'{{ type primary; file "{path}"; allow-update {{ "none"; }}; }};'
config = zone_configuration(path)
registered = check_registration(domain, config)
wanted = zone_file(zone)
previous = (
@@ -78,6 +84,33 @@ def install_zone(zone, path, directory):
wait_for_serial(domain, zone.serial)
def zone_configuration(path):
return f'{{ type primary; file "{path}"; allow-update {{ "none"; }}; }};'
def retire_zone(request):
zone = request.resource
with locked_root_directory(ZONE_DIRECTORY):
record = RetirementRecord(ZONE_DIRECTORY, request)
if record.is_complete:
return
path = ZONE_DIRECTORY / zone.domain
managed = check_registration(zone.domain, zone_configuration(path))
if os.path.lexists(path):
contents = read_root_file(path, mode=0o644)
if contents != zone_file(zone):
raise ValueError("The managed zone changed since the preview.")
elif managed or not record.matches(record.started):
raise ValueError("The managed zone file is missing.")
record.begin()
if managed:
run(*RNDC, "delzone", zone.domain)
if check_registration(zone.domain, zone_configuration(path)):
raise ValueError("BIND9 still has the zone registered.")
archive_path(path, record.directory / "zone")
record.finish()
def check_registration(domain, config):
missing = (
"rndc: 'showzone' failed: not found\n"
+273
View File
@@ -0,0 +1,273 @@
import argparse
import json
import os
import subprocess
from pathlib import Path
from uuid import uuid4
from . import firewall_bans
from .firewall_policy import (
OWNER,
TABLE,
FirewallPolicy,
policy_comment,
render_rules,
)
from .node_files import (
locked_root_directory,
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
STATE = Path("/var/lib/coulobre/firewall")
ENTRY_POINT = "/opt/coulobre/bin/coulobre-firewall"
NFT = "/usr/sbin/nft"
MAX_POLICY_BYTES = 65536
def run(*command, content=None):
try:
result = subprocess.run(
command,
input=content,
capture_output=True,
text=True,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"},
timeout=15,
)
except subprocess.TimeoutExpired:
raise ValueError(f"{command[0]} did not respond.") from None
if result.returncode:
detail = result.stderr.strip() or result.stdout.strip()
raise ValueError(f"{command[0]} failed. {detail}".strip())
return result.stdout
def nftables(*command):
reply = json.loads(run(NFT, "--json", *command))
return reply["nftables"]
def active_table():
definitions = nftables("list", "tables")
if not any(
table.get("family") == "inet" and table.get("name") == TABLE
for item in definitions
if (table := item.get("table"))
):
return None
snapshot = nftables("list", "table", "inet", TABLE)
if not table_comment(snapshot).startswith(f"{OWNER} "):
raise ValueError(
f"The existing inet {TABLE} table is not owned by Coulobre."
)
return snapshot
def table_comment(snapshot):
return next(
(
table.get("comment", "")
for item in snapshot
if (table := item.get("table")) and table.get("name") == TABLE
),
"",
)
def policy_batch(policy):
existing = active_table()
prefix = f"delete table inet {TABLE}\n" if existing is not None else ""
return prefix + (render_rules(policy) if policy is not None else "")
def activate(content):
if content:
run(NFT, "--file", "-", content=content)
def read_policy(path):
with path.open("rb") as source:
body = source.read(MAX_POLICY_BYTES + 1)
if len(body) > MAX_POLICY_BYTES:
raise ValueError("Firewall profile exceeds 64 KiB.")
return FirewallPolicy.from_manifest(json.loads(body))
def load_state():
path = STATE / "state.json"
if not os.path.lexists(path):
return {"confirmed": None, "pending": None}
return json.loads(read_root_file(path, mode=0o600))
def save_state(state):
path = STATE / "state.json"
content = json.dumps(state, indent=2) + "\n"
if os.path.lexists(path):
replace_configuration(path, content, mode=0o600)
else:
write_new_file(path, content, mode=0o600)
def confirmed_policy(state):
data = state["confirmed"]
return FirewallPolicy.from_manifest(data) if data is not None else None
def arm_rollback(operation, seconds):
run(
"/usr/bin/systemd-run",
"--quiet",
"--collect",
f"--unit=coulobre-firewall-rollback-{operation}",
f"--on-active={seconds}s",
"--timer-property=AccuracySec=1s",
ENTRY_POINT,
"rollback",
operation,
)
def stage_policy(state, policy, seconds):
if state["pending"] is not None:
raise ValueError(
"Confirm or roll back the pending firewall change first."
)
content = policy_batch(policy)
run(NFT, "--check", "--file", "-", content=content)
operation = uuid4().hex
pending = {"id": operation, "policy": policy.manifest(), "applied": False}
save_state(state | {"pending": pending})
try:
arm_rollback(operation, seconds)
except (OSError, ValueError):
save_state(state)
raise
activate(content)
save_state(state | {"pending": pending | {"applied": True}})
return operation
def confirm(state, operation):
pending = state["pending"]
if pending is None or pending["id"] != operation or not pending["applied"]:
raise ValueError(
"No applied firewall change matches this confirmation ID."
)
snapshot = active_table()
policy = FirewallPolicy.from_manifest(pending["policy"])
if snapshot is None or table_comment(snapshot) != policy_comment(policy):
raise ValueError("The staged firewall table is no longer active.")
save_state({"confirmed": pending["policy"], "pending": None})
def restore(state, operation=None):
pending = state["pending"]
if operation is not None and (
pending is None or operation != pending["id"]
):
return
activate(policy_batch(confirmed_policy(state)))
if pending is not None:
save_state(state | {"pending": None})
def state_status(state):
try:
bans = firewall_bans.ban_status(run)
except (OSError, ValueError) as error:
bans = {"problem": str(error)}
return state | {"table": active_table(), "bans": bans}
def timeout_seconds(value):
seconds = int(value)
if not 15 <= seconds <= 600:
raise argparse.ArgumentTypeError("Enter 15 to 600 seconds.")
return seconds
def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-firewall")
commands = parser.add_subparsers(dest="command", required=True)
for name, help_text in (
("preview", "Render a policy as nftables rules."),
("apply", "Stage a policy with a scheduled rollback."),
):
action = commands.add_parser(name, help=help_text)
action.add_argument("policy", type=Path)
if name == "apply":
action.add_argument("--timeout", type=timeout_seconds, default=120)
commands.add_parser(
"confirm", help="Keep the staged policy."
).add_argument("id")
rollback = commands.add_parser(
"rollback", help="Restore the confirmed policy."
)
rollback.add_argument("id", nargs="?")
commands.add_parser(
"restore", help="Load the confirmed policy at startup."
)
commands.add_parser("clear", help="Remove the Coulobre host firewall.")
commands.add_parser("status", help="Report live rules and managed bans.")
commands.add_parser(
"prepare-bans", help="Write the managed Fail2ban configuration."
)
commands.add_parser("audit", help="Show manual unblock events.")
unblock = commands.add_parser(
"unblock", help="Remove one managed ban and log it."
)
unblock.add_argument("jail", choices=firewall_bans.JAILS)
unblock.add_argument("address")
unblock.add_argument("--reason", required=True)
args = parser.parse_args(argv)
try:
if args.command == "preview":
print(render_rules(read_policy(args.policy)), end="")
return 0
if os.geteuid() != 0:
raise ValueError("Run this command as root.")
require_root_directory(STATE.parent, create_mode=0o750)
require_root_directory(STATE, create_mode=0o700)
with locked_root_directory(STATE):
dispatch(args, load_state())
except (OSError, ValueError, KeyError, RecursionError) as error:
parser.exit(1, f"coulobre-firewall: {error}\n")
return 0
def dispatch(args, state):
action = args.command
audit = STATE / "unblock.jsonl"
if action == "apply":
operation = stage_policy(state, read_policy(args.policy), args.timeout)
print(
f"Confirmation ID {operation}. Rollback in {args.timeout} seconds."
)
elif action == "confirm":
confirm(state, args.id)
print("Confirmed the firewall policy.")
elif action == "rollback":
restore(state, args.id)
elif action == "restore":
restore(state)
elif action == "clear":
activate(policy_batch(None))
save_state({"confirmed": None, "pending": None})
elif action == "status":
print(json.dumps(state_status(state), indent=2))
elif action == "prepare-bans":
policy = confirmed_policy(state)
if policy is None:
raise ValueError(
"Confirm the host firewall before enabling managed bans."
)
firewall_bans.prepare_bans(policy, STATE)
elif action == "unblock":
firewall_bans.unblock(run, audit, args.jail, args.address, args.reason)
print("Recorded the unblock request and result.")
elif os.path.lexists(audit):
print(read_root_file(audit, mode=0o600), end="")
+163
View File
@@ -0,0 +1,163 @@
import ipaddress
import json
import os
import pwd
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
from .node_files import (
check_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
RUNTIME = Path("/run/coulobre-fail2ban")
CONFIG = RUNTIME / "config"
SOCKET = RUNTIME / "fail2ban.sock"
JAILS = ("coulobre-sshd", "coulobre-postfix", "coulobre-dovecot")
BAN_TABLE = "coulobre_bans"
def render_jails(policy):
sources = " ".join(map(str, policy.admin_sources))
defaults = (
"[DEFAULT]\n"
"backend = systemd\n"
"bantime = 600\n"
"findtime = 600\n"
"maxretry = 5\n"
"usedns = no\n"
f"ignoreip = 127.0.0.0/8 ::1 {sources}\n"
)
jails = [(JAILS[0], "sshd", str(policy.ssh_port))]
if "mail" in policy.services:
jails.extend(
(
(JAILS[1], "postfix[mode=auth]", "465,587"),
(JAILS[2], "dovecot", "143,993"),
)
)
return defaults + "".join(
f"\n[{name}]\nenabled = true\nfilter = {filter_name}\n"
f"action = nftables[type=multiport, table={BAN_TABLE}, "
f'name={name}, port="{destinations}", protocol=tcp, blocktype=drop]\n'
for name, filter_name, destinations in jails
)
def prepare_bans(policy, state_directory):
config = CONFIG
require_root_directory(config, create_mode=0o700)
for name in ("filter.d", "action.d"):
link = config / name
target = Path("/etc/fail2ban") / name
require_root_directory(target)
if not os.path.lexists(link):
link.symlink_to(target, target_is_directory=True)
elif not link.is_symlink() or link.readlink() != target:
raise ValueError(f"Unexpected Fail2ban configuration at {link}.")
server_config = (
"[Definition]\n"
"logtarget = STDOUT\n"
"loglevel = INFO\n"
f"socket = {SOCKET}\n"
f"pidfile = {RUNTIME / 'fail2ban.pid'}\n"
f"dbfile = {state_directory / 'fail2ban.sqlite3'}\n"
)
for name, content in (
("fail2ban.conf", server_config),
("jail.conf", render_jails(policy)),
):
path = config / name
if os.path.lexists(path):
check_root_file(path, mode=0o600)
replace_configuration(path, content, mode=0o600)
else:
write_new_file(path, content, mode=0o600)
def client(run, *arguments):
return run(
"/usr/bin/fail2ban-client",
"-c",
str(CONFIG),
"-s",
str(SOCKET),
*arguments,
)
def ban_status(run):
if not SOCKET.is_socket():
return {"running": False, "jails": {}}
summary = client(run, "status")
names = next(
(
line.split("Jail list:", 1)[1]
for line in summary.splitlines()
if "Jail list:" in line
),
"",
)
enabled = {name.strip() for name in names.split(",")}
return {
"running": True,
"jails": {
name: client(run, "get", name, "banip").split()
for name in JAILS
if name in enabled
},
}
def operator_name():
try:
uid = int(Path("/proc/self/loginuid").read_text())
except (OSError, ValueError):
uid = 4294967295
if uid == 4294967295:
uid = int(os.environ.get("SUDO_UID", "0"))
try:
return pwd.getpwuid(uid).pw_name
except KeyError:
return str(uid)
def record_unblock(path, event, result):
if os.path.lexists(path):
check_root_file(path, mode=0o600)
fd = os.open(
path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600
)
with os.fdopen(fd, "a", encoding="utf-8") as log:
event = event | {
"time": datetime.now(UTC).isoformat(),
"result": result,
}
log.write(json.dumps(event) + "\n")
log.flush()
os.fsync(log.fileno())
def unblock(run, path, jail, address, reason):
if "%" in address or not reason.strip() or len(reason) > 250:
raise ValueError(
"Enter an IP address and a reason of up to 250 characters."
)
address = str(ipaddress.ip_address(address))
event = {
"id": str(uuid4()),
"operator": operator_name(),
"jail": jail,
"address": address,
"reason": reason,
}
record_unblock(path, event, "requested")
try:
count = client(run, "set", jail, "unbanip", address).strip()
except (OSError, ValueError):
record_unblock(path, event, "failed")
raise
record_unblock(path, event | {"removed": count == "1"}, "completed")
+283
View File
@@ -0,0 +1,283 @@
import hashlib
import ipaddress
import json
from dataclasses import dataclass
TABLE = "coulobre_host"
OWNER = "Coulobre managed host firewall v1"
PROFILES = ("public", "lan", "proxy", "node")
SERVICE_PORTS = {
"web": (80, 443),
"mail": (25, 143, 465, 587, 993),
"dns": (53,),
"sftp": (),
}
DEFAULT_RATES = {"panel": 40, "web": 120, "mail": 30, "dns": 100, "ssh": 8}
POLICY_FIELDS = {
"version",
"profile",
"services",
"admin_sources",
"extra_tcp_ports",
"extra_udp_ports",
"panel_sources",
"ssh_port",
"panel_ports",
"rates",
}
def integer(value, minimum, maximum):
return type(value) is int and minimum <= value <= maximum
def ports(value):
if (
not isinstance(value, list)
or len(value) > 8
or any(not integer(port, 1, 65535) for port in value)
):
raise ValueError("Expected up to eight TCP ports from 1 to 65535.")
return tuple(sorted(set(value)))
def networks(value):
if (
not isinstance(value, list)
or len(value) > 64
or any(not isinstance(item, str) or "%" in item for item in value)
):
raise ValueError("Expected up to 64 IPv4 or IPv6 source networks.")
try:
subnets = [ipaddress.ip_network(item) for item in value]
except ValueError:
raise ValueError(
"Enter source IP addresses or CIDR networks."
) from None
collapsed = tuple(
subnet
for version in (4, 6)
for subnet in ipaddress.collapse_addresses(
item for item in subnets if item.version == version
)
)
if any(not subnet.prefixlen for subnet in collapsed):
raise ValueError("Use specific source networks for restricted access.")
return collapsed
@dataclass(frozen=True)
class FirewallPolicy:
profile: str
services: tuple
admin_sources: tuple
panel_sources: tuple
ssh_port: int
panel_ports: tuple
extra_tcp_ports: tuple
extra_udp_ports: tuple
rates: dict
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys() - POLICY_FIELDS
or type(data.get("version")) is not int
or data["version"] != 1
or data.get("profile") not in PROFILES
):
raise ValueError("Expected a version 1 firewall profile.")
profile = data["profile"]
services = data.get("services", [])
if not isinstance(services, list) or any(
not isinstance(service, str) or service not in SERVICE_PORTS
for service in services
):
raise ValueError("Choose web, mail, dns, or sftp services.")
services = tuple(sorted(set(services)))
admins = networks(data.get("admin_sources", []))
sources = networks(data.get("panel_sources", []))
if not admins:
raise ValueError(
"Enter at least one administrator source network."
)
if bool(sources) != (profile in ("lan", "proxy")):
raise ValueError("Set panel_sources for LAN and proxy profiles.")
default_ports = {"node": [], "proxy": [8080]}
panel = ports(
data.get("panel_ports", default_ports.get(profile, [80, 443]))
)
if bool(panel) == (profile == "node"):
raise ValueError(
"Panel ports are required for public, LAN and proxy profiles."
)
ssh = data.get("ssh_port", 22)
service_ports = {
port for service in services for port in SERVICE_PORTS[service]
}
if not integer(ssh, 1, 65535) or ssh in service_ports or ssh in panel:
raise ValueError(
"Set an SSH port distinct from panel and service ports."
)
shared_ports = service_ports.intersection(panel)
if shared_ports and not (
profile == "public" and shared_ports <= {80, 443}
):
raise ValueError(
"Use separate TCP listeners for panel and public services."
)
extra_tcp = ports(data.get("extra_tcp_ports", []))
extra_udp = ports(data.get("extra_udp_ports", []))
if set(extra_tcp) & (service_ports | set(panel) | {ssh}) or (
"dns" in services and 53 in extra_udp
):
raise ValueError(
"Extra ports must be distinct from managed ports."
)
overrides = data.get("rates", {})
if not isinstance(overrides, dict) or any(
service not in DEFAULT_RATES or not integer(rate, 0, 100000)
for service, rate in overrides.items()
):
raise ValueError(
"Set per-second rates from 0 to 100000 for known services."
)
return cls(
profile,
services,
admins,
sources,
ssh,
panel,
extra_tcp,
extra_udp,
DEFAULT_RATES | overrides,
)
def manifest(self):
return {
"version": 1,
"profile": self.profile,
"services": list(self.services),
"admin_sources": [str(item) for item in self.admin_sources],
"panel_sources": [str(item) for item in self.panel_sources],
"ssh_port": self.ssh_port,
"panel_ports": list(self.panel_ports),
"extra_tcp_ports": list(self.extra_tcp_ports),
"extra_udp_ports": list(self.extra_udp_ports),
"rates": self.rates,
}
def policy_comment(policy):
canonical = json.dumps(policy.manifest(), sort_keys=True).encode()
return f"{OWNER} {hashlib.sha256(canonical).hexdigest()}"
def nft_set(values):
return "{ " + ", ".join(map(str, values)) + " }"
def source_sets(name, sources):
return [
f" set {name}{version} {{ type {address_type}; flags interval; "
f"elements = {nft_set(subnets)}; }}"
for version, _, address_type in ADDRESS_FAMILIES
if (subnets := [item for item in sources if item.version == version])
]
ADDRESS_FAMILIES = ((4, "ip", "ipv4_addr"), (6, "ip6", "ipv6_addr"))
def render_rules(policy):
sets = source_sets("admins", policy.admin_sources)
sets.extend(source_sets("panel", policy.panel_sources))
chains = []
udp = []
incoming = [
" ct state established,related counter accept",
*(
f" {family} saddr @admins{version} tcp dport {policy.ssh_port}"
" counter accept"
for version, family, _ in ADDRESS_FAMILIES
if any(item.version == version for item in policy.admin_sources)
),
]
def add_service(name, protocol, allowed, *, sources=()):
if not allowed:
return
chain = f"{name}_{protocol}"
destination = f"{protocol} dport {nft_set(allowed)}"
rate = policy.rates[name]
verdict = f"jump {chain}" if rate else "counter accept"
rules = udp if protocol == "udp" else incoming
if sources:
rules.extend(
f" {family} saddr @panel{version} {destination} {verdict}"
for version, family, _ in ADDRESS_FAMILIES
if any(item.version == version for item in sources)
)
else:
rules.append(f" {destination} {verdict}")
if rate:
render_rate(chain, rate, sets, chains)
for name in policy.services:
if name == "sftp":
add_service("ssh", "tcp", (policy.ssh_port,))
else:
add_service(name, "tcp", SERVICE_PORTS[name])
if "dns" in policy.services:
add_service("dns", "udp", SERVICE_PORTS["dns"])
panel_ports = tuple(
port
for port in policy.panel_ports
if "web" not in policy.services or port not in SERVICE_PORTS["web"]
)
add_service("panel", "tcp", panel_ports, sources=policy.panel_sources)
for protocol, additional in (
("tcp", policy.extra_tcp_ports),
("udp", policy.extra_udp_ports),
):
if additional:
incoming.append(
f" {protocol} dport {nft_set(additional)} counter accept"
)
lines = [
f"table inet {TABLE} {{",
f' comment "{policy_comment(policy)}"',
*sets,
*chains,
" chain input {",
" type filter hook input priority 10; policy drop;",
' iifname "lo" counter accept',
" meta l4proto { icmp, ipv6-icmp } counter accept",
" udp sport 67 udp dport 68 counter accept",
" ip6 saddr fe80::/10 udp sport 547 udp dport 546 counter accept",
" ct state invalid counter drop",
*udp,
*incoming,
" counter drop",
" }",
"}",
]
return "\n".join(lines) + "\n"
def render_rate(chain, rate, sets, chains):
chains.append(f" chain {chain} {{")
for version, family, address_type in ADDRESS_FAMILIES:
name = f"{chain}{version}"
sets.append(
f" set {name} {{ type {address_type}; flags dynamic,timeout; "
"timeout 1m; size 16384; }"
)
chains.append(
f" update @{name} {{ {family} saddr limit rate {rate}/second "
f"burst {rate} packets }} counter accept"
)
chains.extend((" counter drop", " }"))
+30
View File
@@ -1,3 +1,18 @@
NAVIGATION_SECTIONS = {
"accounts": "accounts",
"retired-accounts": "accounts",
"databases": "accounts",
"dns-zones": "accounts",
"mailboxes": "accounts",
"mail-domains": "accounts",
"customers": "customers",
"resellers": "resellers",
"hosting-plans": "hosting_plans",
"plans": "plans",
"service-health": "service_health",
}
def customer_for_user(user):
if not user.is_authenticated or user.is_superuser:
return None
@@ -21,15 +36,30 @@ def is_tenant(user):
)
def manages_account(user, account):
customer = customer_for_user(user)
if customer is not None:
return account.customer_id == customer.pk
reseller = reseller_for_user(user)
return reseller is not None and account.reseller_id == reseller.pk
def panel_access(request):
customer = customer_for_user(request.user) is not None
reseller = not customer and reseller_for_user(request.user) is not None
match = request.resolver_match
section = None
if match is not None and match.namespace == "panel":
section = NAVIGATION_SECTIONS.get(
match.route.split("/", 1)[0], match.url_name
)
return {
"is_customer": customer,
"is_reseller": reseller,
"is_tenant": customer or reseller,
"is_operator": request.user.is_authenticated
and not (customer or reseller),
"panel_section": section,
}
@@ -1,6 +1,7 @@
from uuid import uuid4
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
@@ -18,6 +19,7 @@ SCHEDULE_FIELDS = (
"weekday",
"time",
"include_mailboxes",
"offsite_destination",
)
@@ -47,6 +49,15 @@ class AccountBackupScheduleForm(forms.Form):
self.allow_mail = allow_mail
if not allow_mail and not self.initial.get("include_mailboxes"):
del self.fields["include_mailboxes"]
destinations = settings.OFFSITE_BACKUP_DESTINATIONS
current = self.initial.get("offsite_destination")
if destinations or current:
choices = [("", "Local archive only"), *destinations.items()]
if current and current not in destinations:
choices.append((current, f"{current} (unavailable)"))
self.fields["offsite_destination"] = forms.ChoiceField(
choices=choices, required=False, label="Off-site destination"
)
def clean(self):
cleaned = super().clean()
@@ -91,6 +102,18 @@ class WebsiteRestoreForm(BackupRestoreForm):
label="Replace the existing file at this path", required=False
)
def __init__(self, *args, targets=None, **kwargs):
super().__init__(*args, **kwargs)
self.targets = targets or {}
if len(self.targets) > 1:
self.fields["site_key"] = forms.ChoiceField(
label="Website",
choices=[
(key, site.domain) for key, site in self.targets.items()
],
)
self.order_fields(["site_key", "scope", "filename", "replace"])
def clean_filename(self):
filename = self.cleaned_data["filename"]
if filename:
@@ -102,6 +125,8 @@ class WebsiteRestoreForm(BackupRestoreForm):
def clean(self):
cleaned = super().clean()
if len(self.targets) == 1:
cleaned["site_key"] = next(iter(self.targets))
if cleaned.get("scope") == "file" and cleaned.get("filename") == "":
self.add_error(
"filename", "Enter the path of the file to restore."
+37 -5
View File
@@ -1,18 +1,28 @@
from datetime import UTC, datetime, timedelta
from django.core.exceptions import PermissionDenied
from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.web_node import WebSite
from .independent_websites import active_websites
from .models import (
AccountBackupSchedule,
HostingAccount,
HostingMailbox,
OffsiteBackupTransfer,
)
from .resource_requests import lock_hosting_account
from .resource_requests import lock_hosting_account, require_open_account
def mail_backups_enabled():
return (
settings.LOCAL_ACCOUNT_BACKUP_MAIL
or settings.REMOTE_ACCOUNT_BACKUP_MAIL
)
def account_backup_manifest(account, *, include_mailboxes=False):
@@ -26,23 +36,33 @@ def account_backup_manifest(account, *, include_mailboxes=False):
WebSite(account.pk, account.primary_domain),
tuple(database.spec for database in account.databases.all()),
mailboxes,
tuple(site.spec for site in active_websites(account)),
).manifest()
@transaction.atomic
def queue_account_backup(account_id, *, include_mailboxes=False):
account = lock_hosting_account(account_id, customer_id=None)
require_open_account(account)
_enqueue_backup(account, include_mailboxes=include_mailboxes)
def _enqueue_backup(account, *, include_mailboxes, scheduled_for=None):
def _enqueue_backup(
account, *, include_mailboxes, scheduled_for=None, offsite_destination=""
):
if not account.backup_jobs.filter(finished_at__isnull=True).exists():
account.backup_jobs.create(
job = account.backup_jobs.create(
manifest=account_backup_manifest(
account, include_mailboxes=include_mailboxes
),
remote_mail=include_mailboxes
and settings.REMOTE_ACCOUNT_BACKUP_MAIL,
scheduled_for=scheduled_for,
)
if scheduled_for is not None and offsite_destination:
OffsiteBackupTransfer.objects.create(
backup=job, destination=offsite_destination
)
def _next_backup_run(schedule, now):
@@ -59,6 +79,7 @@ def _next_backup_run(schedule, now):
@transaction.atomic
def save_backup_schedule(account_id, *, can_manage_mail, schedule_fields):
account = lock_hosting_account(account_id, customer_id=None)
require_open_account(account)
schedule = getattr(account, "backup_schedule", None)
if schedule is None:
schedule = AccountBackupSchedule(account=account)
@@ -66,6 +87,15 @@ def save_backup_schedule(account_id, *, can_manage_mail, schedule_fields):
schedule.include_mailboxes or schedule_fields["include_mailboxes"]
):
raise PermissionDenied
destination = schedule_fields.get(
"offsite_destination", schedule.offsite_destination
)
if (
schedule_fields["enabled"]
and destination
and destination not in settings.OFFSITE_BACKUP_DESTINATIONS
):
raise ValidationError("Choose an available off-site destination.")
timing_changed = any(
getattr(schedule, field) != schedule_fields[field]
@@ -100,7 +130,8 @@ def _queue_scheduled_backup(account_id, now):
account = lock_hosting_account(account_id, customer_id=None)
schedule = getattr(account, "backup_schedule", None)
if (
schedule is None
account.retired_at is not None
or schedule is None
or not schedule.enabled
or schedule.next_run_at is None
or schedule.next_run_at > now
@@ -111,6 +142,7 @@ def _queue_scheduled_backup(account_id, now):
account,
include_mailboxes=schedule.include_mailboxes,
scheduled_for=schedule.next_run_at,
offsite_destination=schedule.offsite_destination,
)
schedule.next_run_at = _next_backup_run(schedule, now)
schedule.save(update_fields=["next_run_at"])
Loaded 100 of 294 files, more files were not shown because too many files have changed in this diff. Show more