212 lines
7.0 KiB
Go
212 lines
7.0 KiB
Go
package isolation
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"os/exec"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-sql-driver/mysql"
|
|
)
|
|
|
|
// Root credentials stay inside the root agent. The fixed, isolated Python
|
|
// program reads only aaPanel's local configuration; no shell or supplied code.
|
|
func (a Agent) mysqlConfig(ctx context.Context) (*mysql.Config, error) {
|
|
if a.databaseAdminDSN != "" {
|
|
return mysql.ParseDSN(a.databaseAdminDSN)
|
|
}
|
|
command := exec.CommandContext(ctx, "/www/server/panel/pyenv/bin/python3", "-I", "-c", `import os,sys,json,re
|
|
from pathlib import Path
|
|
os.chdir('/www/server/panel');sys.path.insert(0,'/www/server/panel/class');import public
|
|
password=public.M('config').where('id=?',(1,)).getField('mysql_root')
|
|
assert isinstance(password,str) and password
|
|
port=3306
|
|
socket='/tmp/mysql.sock'
|
|
p=Path('/etc/my.cnf')
|
|
if p.is_file():
|
|
text=p.read_text();section=False
|
|
for line in text.splitlines():
|
|
line=line.strip()
|
|
if line.startswith('['):section=line.lower()=='[mysqld]'
|
|
elif section:
|
|
m=re.fullmatch(r'port\s*=\s*(\d+)\s*(?:[#;].*)?',line)
|
|
if m:port=int(m.group(1))
|
|
m=re.fullmatch(r'socket\s*=\s*(/[^\s#;]+)\s*(?:[#;].*)?',line)
|
|
if m:socket=m.group(1)
|
|
assert 1<=port<=65535
|
|
print(json.dumps({'password':password,'port':port,'socket':socket}))`)
|
|
data, err := command.Output()
|
|
if err != nil || len(data) > 64<<10 {
|
|
return nil, errors.New("cannot read local MySQL administrator configuration")
|
|
}
|
|
var value struct {
|
|
Password string
|
|
Port int
|
|
Socket string
|
|
}
|
|
if json.Unmarshal(data, &value) != nil || value.Password == "" || value.Port < 1 || value.Port > 65535 {
|
|
return nil, errors.New("invalid local MySQL administrator configuration")
|
|
}
|
|
cfg := mysql.NewConfig()
|
|
cfg.User = "root"
|
|
cfg.Passwd = value.Password
|
|
cfg.Net = "unix"
|
|
cfg.Addr = value.Socket
|
|
if !strings.HasPrefix(cfg.Addr, "/") || strings.ContainsAny(cfg.Addr, "\r\n\x00") {
|
|
return nil, errors.New("invalid MySQL socket path")
|
|
}
|
|
if strings.HasPrefix(cfg.Addr, "/tmp/") {
|
|
cfg.Addr = "/etc/sea-vhost-mysql/host-tmp/" + strings.TrimPrefix(cfg.Addr, "/tmp/")
|
|
}
|
|
cfg.Timeout = 5 * time.Second
|
|
cfg.ReadTimeout = 30 * time.Second
|
|
cfg.WriteTimeout = 30 * time.Second
|
|
return cfg, nil
|
|
}
|
|
|
|
func (a Agent) openMySQL(ctx context.Context) (*sql.DB, error) {
|
|
cfg, err := a.mysqlConfig(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
db, err := sql.Open("mysql", cfg.FormatDSN())
|
|
if err != nil {
|
|
return nil, errors.New("cannot initialize local MySQL administrator connection")
|
|
}
|
|
db.SetMaxOpenConns(1)
|
|
if db.PingContext(ctx) != nil {
|
|
db.Close()
|
|
return nil, errors.New("cannot connect to local MySQL administrator")
|
|
}
|
|
return db, nil
|
|
}
|
|
|
|
func (a Agent) configureDatabaseAccess(w http.ResponseWriter, r *http.Request) {
|
|
var spec DatabaseAccessSpec
|
|
decoder := json.NewDecoder(r.Body)
|
|
decoder.DisallowUnknownFields()
|
|
if decoder.Decode(&spec) != nil || decoder.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(spec.Project.HostName) || spec.Database != spec.Project.HostName || spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 {
|
|
http.Error(w, "invalid managed database identity", 400)
|
|
return
|
|
}
|
|
root, err := a.projectPath(spec.Project)
|
|
if err != nil || requirePhysicalDirectory(root) != nil {
|
|
http.Error(w, "managed project root unavailable", 412)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
|
|
defer cancel()
|
|
db, err := a.openMySQL(ctx)
|
|
if err == nil {
|
|
defer db.Close()
|
|
err = setDatabaseAccess(ctx, db, spec.Database, spec.ReadOnly, spec.BlockCleanup)
|
|
}
|
|
if err != nil {
|
|
http.Error(w, "cannot enforce managed database access: "+err.Error(), 412)
|
|
return
|
|
}
|
|
w.WriteHeader(200)
|
|
}
|
|
|
|
func setDatabaseAccess(ctx context.Context, db *sql.DB, name string, readOnly, blockCleanup bool) error {
|
|
if !managedWebHostPattern.MatchString(name) {
|
|
return errors.New("invalid database name")
|
|
}
|
|
cleanupPrivilege := "Y"
|
|
if blockCleanup {
|
|
cleanupPrivilege = "N"
|
|
}
|
|
rows, err := db.QueryContext(ctx, `SELECT u.Host,COALESCE(d.Insert_priv,'N'),COALESCE(d.Select_priv='Y' AND d.Delete_priv=? AND d.Drop_priv=? AND d.Insert_priv='N' AND d.Update_priv='N' AND d.Create_priv='N' AND d.Grant_priv='N' AND d.References_priv='N' AND d.Index_priv='N' AND d.Alter_priv='N' AND d.Create_tmp_table_priv='N' AND d.Lock_tables_priv='N' AND d.Create_view_priv='N' AND d.Show_view_priv='N' AND d.Create_routine_priv='N' AND d.Alter_routine_priv='N' AND d.Execute_priv='N' AND d.Event_priv='N' AND d.Trigger_priv='N',FALSE) FROM mysql.user u LEFT JOIN mysql.db d ON d.User=u.User AND d.Host=u.Host AND d.Db=? WHERE u.User=?`, cleanupPrivilege, cleanupPrivilege, name, name)
|
|
if err != nil {
|
|
return errors.New("cannot inspect managed account")
|
|
}
|
|
type account struct {
|
|
host, insert string
|
|
readOnly bool
|
|
}
|
|
var accounts []account
|
|
for rows.Next() {
|
|
var item account
|
|
if err = rows.Scan(&item.host, &item.insert, &item.readOnly); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
if item.host != "localhost" && item.host != "127.0.0.1" && item.host != "::1" && item.host != "%" {
|
|
rows.Close()
|
|
return errors.New("unexpected managed account host")
|
|
}
|
|
accounts = append(accounts, item)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(accounts) == 0 {
|
|
return errors.New("managed account not found")
|
|
}
|
|
changed := false
|
|
for _, item := range accounts {
|
|
if (readOnly && item.readOnly) || (!readOnly && item.insert == "Y") {
|
|
continue
|
|
}
|
|
accountSQL := "'" + name + "'@'" + item.host + "'"
|
|
if _, err = db.ExecContext(ctx, "REVOKE ALL PRIVILEGES, GRANT OPTION FROM "+accountSQL); err != nil {
|
|
return errors.New("cannot revoke managed account privileges")
|
|
}
|
|
privileges := "ALL PRIVILEGES"
|
|
if readOnly {
|
|
privileges = "SELECT, DELETE, DROP"
|
|
if blockCleanup {
|
|
privileges = "SELECT"
|
|
}
|
|
}
|
|
if _, err = db.ExecContext(ctx, "GRANT "+privileges+" ON `"+name+"`.* TO "+accountSQL); err != nil {
|
|
return errors.New("cannot grant managed account recovery privileges")
|
|
}
|
|
changed = true
|
|
}
|
|
if !changed && !readOnly {
|
|
return nil
|
|
}
|
|
// Existing sessions cache database grants. Disconnect only this exact user,
|
|
// so pooled connections and transactions cannot retain the old write access.
|
|
sessions, err := db.QueryContext(ctx, "SELECT ID FROM information_schema.PROCESSLIST WHERE USER=?", name)
|
|
if err != nil {
|
|
return errors.New("cannot inspect managed database sessions")
|
|
}
|
|
var ids []uint64
|
|
for sessions.Next() {
|
|
var id uint64
|
|
if err = sessions.Scan(&id); err != nil {
|
|
sessions.Close()
|
|
return err
|
|
}
|
|
ids = append(ids, id)
|
|
}
|
|
err = sessions.Err()
|
|
sessions.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, id := range ids {
|
|
if _, err = db.ExecContext(ctx, "KILL CONNECTION "+strconv.FormatUint(id, 10)); err != nil {
|
|
var mysqlErr *mysql.MySQLError
|
|
if !errors.As(err, &mysqlErr) || mysqlErr.Number != 1094 {
|
|
return errors.New("cannot disconnect managed database session")
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func mysqlOptionValue(value string) string {
|
|
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`, "\r", `\r`).Replace(value) + `"`
|
|
}
|