Upload test 1

This commit is contained in:
Penguinehis
2026-09-29 10:05:43 -03:00
commit b4a8a70e54
96 changed files with 41273 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
/shell2.exe
/BOT_PLAN.md
/SECURITY_REVIEW.md
/DragonCoreSSH-NewWEB.zip
/dist/
/.tmp-bhttp-harness.exe
/Dockerfile.build
/tunnel_pipe_test.go
/docker-build.sh
+45
View File
@@ -0,0 +1,45 @@
# DragonCoreSSH CLI
DragonCoreSSH server with a terminal administration menu and HTTP API. Based on the supplied DragonCoreSSH-NewWEB source. The supplied SSHPlus archive informed the menu organization; its code and licensing mechanism are not included. The browser panel and static assets have been removed. SSH, Xray, DNSTT, BHTTP, BTUN, HCR, UDPGW, PostgreSQL accounting, and bot/API service code remain in the Go server.
## Install on a fresh Linux/systemd host
Extract this archive, then run `sudo bash install.sh` from the extracted `DragonCoreSSH-CLI` directory. The installer sets up the Go server, PostgreSQL, Xray, service, and the `menu` command. If `/usr/local/bin/menu` already exists, it is saved as `menu.backup.<timestamp>` before the DragonCoreSSH command is installed. It generates all credentials. It needs a compatible Linux distribution and access to its system packages, the Go toolchain download, and Xray release download. Run it only on a fresh server: like the original installer it generates new database and configuration credentials.
Run `menu` from a root shell, or `sudo menu` otherwise. The `dragoncore` command remains an alias. Other commands: `sudo menu status`, `sudo menu users`, `sudo menu logs`, `sudo menu api-password show`, `sudo menu api-password change`. The change command generates a new API password, restarts the service, verifies it, and restores the old one if verification fails. It never prompts for a password. Creating/resetting SSH users generates credentials and prints them once.
The menu detects the terminal width. On a phone it uses a compact status header and wraps menu labels and account details; on a wider terminal it uses the fuller layout. If an SSH app reports the wrong width, run `menu --mobile` to force 40 columns, or set `DRAGONCORE_COLUMNS=36` to choose another width. For editing advanced JSON from a phone SSH client, install `nano` or set `$EDITOR` to your preferred terminal editor.
## Migrate an existing DragonCoreSSH-NewWEB installation
Back up `/opt/sshpanel`, its PostgreSQL database, and `/etc/systemd/system/sshpanel.service` first. Extract this release on the server and run `sudo bash update.sh` from its directory. The updater builds the CLI version, preserves `.env`, `config.json`, Xray configuration, SSH keys, accounts, and database, then restarts the service. It reads this local release only; it does not fetch the NewWEB branch. The previous binary is saved as `/opt/sshpanel/sshpanel.bak`. The old `admin/` directory is no longer served. The existing `ADMIN_HTTP_ADDR` setting is preserved; set it to `127.0.0.1:9090` and restart if remote API access is unnecessary.
## API
The API defaults to `http://127.0.0.1:9090` on new installations. Administrative endpoints accept `Authorization: Bearer <API password>`; use the `api-password show` command as root to view the value. Existing session-based API clients still work, including managed-server integrations. The `/check` and payment webhook endpoints remain part of the API. If exposing the API remotely for integrations, use TLS and appropriate access controls. There is no browser UI; `/` returns 404.
Example: `curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:9090/api/users` (set `TOKEN` privately; avoid putting credentials in shell history).
## Menu areas
- The main menu shows live VPS OS, CPU, RAM, disk, uptime, clock, network speed, SSH online/expired/total, Xray online, and service status. The CLI falls back to local VPS metrics when the API is down.
- SSH users: list/live usage, create, create a 24-hour test account, renew/edit, change limits and quotas, generate a new SSH password, report usage/speed, reset traffic, delete expired or individual users.
- Xray: inbounds, clients, create UUID, edit/delete clients, reset traffic, status, edit JSON, start/stop/restart, and a guided shared-port setup.
- Connection modes: show SSH/TLS listeners and configured DNSTT/BHTTP/HCR/BTUN/UDPGW/Xray ports, live protocol statistics and logs, TLS certificates and issuance, DNSTT public key and key regeneration, and edit protocol settings.
- VPS and traffic: detailed network interface rates and byte totals, SSH/Xray account activity, daily/monthly traffic, system logs, build status.
- Configuration: banner, guided SSH listener ports and default limits, full server JSON, Xray JSON, bot settings display, managed servers display. The service validates settings through its API and applies server settings live.
- Reseller management remains in the Telegram bot; the CLI has no reseller menu.
- API password: view and rotate.
- Service status, logs, and restart.
Full configuration remains available through the server API. Use the JSON editor option for settings not covered by guided prompts. This uses the editor in `$EDITOR`, or `nano` if unset. The CLI never requests a login or password. Root access to `.env` is its local authentication boundary.
## Native Xray on the same SSH/TLS ports
In **Xray → Share SSH/TLS ports (WS/XHTTP)**, select an existing VLESS/VMess inbound or enter a new tag. Choose WebSocket or XHTTP, then enter a distinct URL path. Leaving the path blank generates `/c1`, `/c2`, and so on. New inbounds receive a generated UUID. The menu applies and starts/restarts the native emulator. Existing inbound clients are preserved, but switching an inbound's transport requires updating their client configurations.
Shared inbounds use `dragoncoreSharedPort: true` in the native Xray JSON. The path is required, must be more specific than `/`, and cannot overlap another shared path. The server rejects shared raw TCP and inbound TLS settings because the DragonCoreSSH public listener terminates TLS itself. Configure the client with **TLS security on the panel's TLS port** (for example 443), or no TLS on a public SSH/HTTP port (for example 80), and use the path printed by the menu. TLS XHTTP can negotiate HTTP/2; WebSocket uses HTTP/1.1. The same inbound is available on each configured public listener without a separate Xray socket. External Xray mode does not support this option. Ports owned by other processes, including a separate system sshd, cannot be shared through this router.
## Build and checks
Requires Go 1.25.4 and the dependencies in `go.mod`: `go build -o sshpanel .` and `go test ./...`. The CLI needs Python 3 with only the standard library. Run `python3 -m py_compile dragoncore_cli.py` and `bash -n install.sh update.sh` for syntax checks.
+921
View File
@@ -0,0 +1,921 @@
package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/crypto/bcrypt"
)
const (
RoleSuperAdmin = "superadmin"
RoleReseller = "reseller"
sessionTTL = 12 * time.Hour
adminBcryptCost = 12
)
var adminUsernamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
// ---------- AdminUser ----------
type AdminUser struct {
ID int
Username string
PasswordHash string
Role string
MaxUsers int
ExpiresAt *time.Time
IsActive bool
CreatedAt time.Time
}
// ---------- Session store (in-memory) ----------
type AdminSession struct {
Token string
UserID int
Username string
Role string
ExpiresAt time.Time
}
type sessionStoreT struct {
mu sync.RWMutex
m map[string]*AdminSession
}
var sessions = &sessionStoreT{m: make(map[string]*AdminSession)}
func (s *sessionStoreT) Create(userID int, username, role string) (*AdminSession, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return nil, fmt.Errorf("generate session token: %w", err)
}
tok := hex.EncodeToString(b)
sess := &AdminSession{
Token: tok,
UserID: userID,
Username: username,
Role: role,
ExpiresAt: time.Now().Add(sessionTTL),
}
s.mu.Lock()
s.m[tok] = sess
s.mu.Unlock()
return sess, nil
}
func (s *sessionStoreT) Get(token string) *AdminSession {
if token == "" {
return nil
}
s.mu.RLock()
sess := s.m[token]
s.mu.RUnlock()
if sess == nil || time.Now().After(sess.ExpiresAt) {
return nil
}
return sess
}
func (s *sessionStoreT) Delete(token string) {
s.mu.Lock()
delete(s.m, token)
s.mu.Unlock()
}
func (s *sessionStoreT) DeleteUser(userID int) {
s.mu.Lock()
defer s.mu.Unlock()
for token, sess := range s.m {
if sess.UserID == userID {
delete(s.m, token)
}
}
}
func (s *sessionStoreT) cleanup() {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
for tok, sess := range s.m {
if now.After(sess.ExpiresAt) {
delete(s.m, tok)
}
}
}
// ---------- In-memory AdminUser cache ----------
type adminUserMgrT struct {
mu sync.RWMutex
m map[string]*AdminUser
}
var adminUsers = &adminUserMgrT{m: make(map[string]*AdminUser)}
func (m *adminUserMgrT) set(u *AdminUser) {
m.mu.Lock()
m.m[u.Username] = u
m.mu.Unlock()
}
func (m *adminUserMgrT) get(username string) (*AdminUser, bool) {
m.mu.RLock()
u, ok := m.m[username]
m.mu.RUnlock()
return u, ok
}
func (m *adminUserMgrT) delete(username string) {
m.mu.Lock()
delete(m.m, username)
m.mu.Unlock()
}
func (m *adminUserMgrT) list() []*AdminUser {
m.mu.RLock()
defer m.mu.RUnlock()
out := make([]*AdminUser, 0, len(m.m))
for _, u := range m.m {
cp := *u
out = append(out, &cp)
}
return out
}
func (m *adminUserMgrT) replaceAll(users []*AdminUser) {
m.mu.Lock()
m.m = make(map[string]*AdminUser, len(users))
for _, u := range users {
cp := *u
m.m[u.Username] = &cp
}
m.mu.Unlock()
}
// ---------- Context helpers ----------
type ctxKeyAdmin struct{}
func withSession(ctx context.Context, s *AdminSession) context.Context {
return context.WithValue(ctx, ctxKeyAdmin{}, s)
}
func sessionFromCtx(ctx context.Context) *AdminSession {
s, _ := ctx.Value(ctxKeyAdmin{}).(*AdminSession)
return s
}
// ---------- Middleware ----------
// sessionMiddleware accepts the local CLI/API token or a reseller session.
// The bearer token is intentionally loaded on process start; rotating it in
// .env requires a service restart, which also revokes previous sessions.
func sessionMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") {
provided := strings.TrimPrefix(h, "Bearer ")
secret := os.Getenv("ADMIN_TOKEN")
if len(secret) >= 32 && len(provided) == len(secret) &&
subtle.ConstantTimeCompare([]byte(provided), []byte(secret)) == 1 {
next.ServeHTTP(w, r.WithContext(withSession(r.Context(), &AdminSession{
Username: "admin", Role: RoleSuperAdmin,
})))
return
}
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
token := r.Header.Get("X-Session-Token")
s := sessions.Get(token)
if s == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
// Re-check the account on every request. This immediately revokes sessions
// after an account is suspended, expired, deleted, or has its role changed.
u, ok := adminUsers.get(s.Username)
if !ok || u.ID != s.UserID || !u.IsActive || u.Role != s.Role ||
(u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt)) {
sessions.Delete(token)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r.WithContext(withSession(r.Context(), s)))
})
}
// superAdminOnly wraps a handler to require role == superadmin.
// Must be used AFTER sessionMiddleware (session must be in context).
func superAdminOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := sessionFromCtx(r.Context())
if s == nil || s.Role != RoleSuperAdmin {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// saSession chains sessionMiddleware + superAdminOnly.
func saSession(next http.Handler) http.Handler {
return sessionMiddleware(superAdminOnly(next))
}
// ---------- Password hashing ----------
func legacyAdminPasswordHash(pw string) string {
h := sha256.Sum256([]byte(pw))
return hex.EncodeToString(h[:])
}
func hashAdminPassword(pw string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(pw), adminBcryptCost)
if err != nil {
return "", fmt.Errorf("hash admin password: %w", err)
}
return string(hash), nil
}
// verifyAdminPassword accepts bcrypt and the legacy unsalted SHA-256 format.
// Legacy hashes are upgraded immediately after a successful login.
func verifyAdminPassword(storedHash, password string) (valid bool, needsUpgrade bool) {
if strings.HasPrefix(storedHash, "$2a$") || strings.HasPrefix(storedHash, "$2b$") || strings.HasPrefix(storedHash, "$2y$") {
if bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(password)) != nil {
return false, false
}
cost, err := bcrypt.Cost([]byte(storedHash))
return true, err != nil || cost < adminBcryptCost
}
if len(storedHash) != sha256.Size*2 {
return false, false
}
expected := legacyAdminPasswordHash(password)
return subtle.ConstantTimeCompare([]byte(storedHash), []byte(expected)) == 1, true
}
func validateAdminPassword(password string) error {
if len(password) < 10 {
return fmt.Errorf("password must contain at least 10 characters")
}
if len(password) > 1024 {
return fmt.Errorf("password is too long")
}
return nil
}
func validateAdminUsername(username string) error {
if !adminUsernamePattern.MatchString(username) {
return fmt.Errorf("username must be 1-64 characters using letters, numbers, dot, underscore, or hyphen")
}
return nil
}
// ---------- Login throttling ----------
type loginAttempt struct {
Failures int
FirstSeen time.Time
BlockedTo time.Time
}
type loginThrottleT struct {
mu sync.Mutex
attempts map[string]loginAttempt
}
var loginThrottle = &loginThrottleT{attempts: make(map[string]loginAttempt)}
func loginAttemptKey(r *http.Request, username string) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
return host + "\x00" + strings.ToLower(username)
}
func (l *loginThrottleT) retryAfter(key string, now time.Time) time.Duration {
l.mu.Lock()
defer l.mu.Unlock()
a, ok := l.attempts[key]
if !ok {
return 0
}
if !a.BlockedTo.IsZero() && now.Before(a.BlockedTo) {
return time.Until(a.BlockedTo)
}
if now.Sub(a.FirstSeen) > 15*time.Minute {
delete(l.attempts, key)
}
return 0
}
func (l *loginThrottleT) fail(key string, now time.Time) {
l.mu.Lock()
defer l.mu.Unlock()
a := l.attempts[key]
if a.FirstSeen.IsZero() || now.Sub(a.FirstSeen) > 15*time.Minute {
a = loginAttempt{FirstSeen: now}
}
a.Failures++
if a.Failures >= 5 {
a.BlockedTo = now.Add(15 * time.Minute)
}
l.attempts[key] = a
}
func (l *loginThrottleT) success(key string) {
l.mu.Lock()
delete(l.attempts, key)
l.mu.Unlock()
}
// ---------- DB methods on Store ----------
func (s *Store) EnsureAdminUsersSchema(ctx context.Context) error {
stmts := []string{
`CREATE TABLE IF NOT EXISTS admin_users (
id SERIAL PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'reseller',
max_users INT NOT NULL DEFAULT 30,
expires_at TIMESTAMPTZ,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS owner_username TEXT NOT NULL DEFAULT ''`,
}
for _, stmt := range stmts {
if _, err := s.db.ExecContext(ctx, stmt); err != nil {
return fmt.Errorf("EnsureAdminUsersSchema: %w", err)
}
}
return nil
}
func (s *Store) GetAdminUserByUsername(ctx context.Context, username string) (*AdminUser, error) {
u := &AdminUser{}
var expiresAt sql.NullTime
err := s.db.QueryRowContext(ctx,
`SELECT id, username, password_hash, role, max_users, expires_at, is_active, created_at
FROM admin_users WHERE username = $1`, username,
).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role, &u.MaxUsers,
&expiresAt, &u.IsActive, &u.CreatedAt)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
if expiresAt.Valid {
u.ExpiresAt = &expiresAt.Time
}
return u, nil
}
func (s *Store) ListAdminUsers(ctx context.Context) ([]*AdminUser, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT id, username, password_hash, role, max_users, expires_at, is_active, created_at
FROM admin_users ORDER BY role, username`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*AdminUser
for rows.Next() {
u := &AdminUser{}
var expiresAt sql.NullTime
if err := rows.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role,
&u.MaxUsers, &expiresAt, &u.IsActive, &u.CreatedAt); err != nil {
return nil, err
}
if expiresAt.Valid {
u.ExpiresAt = &expiresAt.Time
}
out = append(out, u)
}
return out, rows.Err()
}
func (s *Store) UpsertAdminUser(ctx context.Context, u *AdminUser) error {
var expiresAt interface{}
if u.ExpiresAt != nil {
expiresAt = *u.ExpiresAt
}
if u.ID == 0 {
return s.db.QueryRowContext(ctx,
`INSERT INTO admin_users (username, password_hash, role, max_users, expires_at, is_active)
VALUES ($1,$2,$3,$4,$5,$6) RETURNING id`,
u.Username, u.PasswordHash, u.Role, u.MaxUsers, expiresAt, u.IsActive,
).Scan(&u.ID)
}
_, err := s.db.ExecContext(ctx,
`UPDATE admin_users SET password_hash=$2, role=$3, max_users=$4,
expires_at=$5, is_active=$6 WHERE id=$1`,
u.ID, u.PasswordHash, u.Role, u.MaxUsers, expiresAt, u.IsActive)
return err
}
func (s *Store) UpdateAdminPasswordHash(ctx context.Context, id int, passwordHash string) error {
_, err := s.db.ExecContext(ctx, `UPDATE admin_users SET password_hash=$2 WHERE id=$1`, id, passwordHash)
return err
}
func (s *Store) DeleteAdminUser(ctx context.Context, username string) error {
_, err := s.db.ExecContext(ctx, `DELETE FROM admin_users WHERE username=$1`, username)
return err
}
func (s *Store) SetAdminUserActive(ctx context.Context, username string, active bool) error {
_, err := s.db.ExecContext(ctx, `UPDATE admin_users SET is_active=$1 WHERE username=$2`, active, username)
return err
}
func (s *Store) ListExpiredResellers(ctx context.Context) ([]*AdminUser, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT id, username, password_hash, role, max_users, expires_at, is_active, created_at
FROM admin_users
WHERE role=$1 AND is_active=TRUE AND expires_at IS NOT NULL AND expires_at < NOW()`,
RoleReseller)
if err != nil {
return nil, err
}
defer rows.Close()
return scanAdminUsers(rows)
}
func (s *Store) ListInactiveButRenewedResellers(ctx context.Context) ([]*AdminUser, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT id, username, password_hash, role, max_users, expires_at, is_active, created_at
FROM admin_users
WHERE role=$1 AND is_active=FALSE AND (expires_at IS NULL OR expires_at > NOW())`,
RoleReseller)
if err != nil {
return nil, err
}
defer rows.Close()
return scanAdminUsers(rows)
}
func scanAdminUsers(rows *sql.Rows) ([]*AdminUser, error) {
var out []*AdminUser
for rows.Next() {
u := &AdminUser{}
var expiresAt sql.NullTime
if err := rows.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role,
&u.MaxUsers, &expiresAt, &u.IsActive, &u.CreatedAt); err != nil {
return nil, err
}
if expiresAt.Valid {
u.ExpiresAt = &expiresAt.Time
}
out = append(out, u)
}
return out, rows.Err()
}
// BootstrapSuperAdmin creates a default "admin" superadmin if none exists.
// Returns the generated password, or "" if a superadmin already existed.
func (s *Store) BootstrapSuperAdmin(ctx context.Context) (string, error) {
var count int
if err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM admin_users WHERE role=$1`, RoleSuperAdmin,
).Scan(&count); err != nil {
return "", err
}
if count > 0 {
return "", nil
}
b := make([]byte, 10)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generate bootstrap password: %w", err)
}
pw := hex.EncodeToString(b)
passwordHash, err := hashAdminPassword(pw)
if err != nil {
return "", err
}
u := &AdminUser{
Username: "admin",
PasswordHash: passwordHash,
Role: RoleSuperAdmin,
MaxUsers: 0,
IsActive: true,
}
if err := s.UpsertAdminUser(ctx, u); err != nil {
return "", err
}
return pw, nil
}
// loadAdminUsersIntoCache reloads all admin_users rows into the in-memory cache.
func loadAdminUsersIntoCache(ctx context.Context, store *Store) error {
users, err := store.ListAdminUsers(ctx)
if err != nil {
return err
}
adminUsers.replaceAll(users)
return nil
}
// ---------- Owner check (called from SSH auth callbacks) ----------
// ownerIsActive returns nil if an SSH user's reseller owner is active, or an error if suspended/expired.
func ownerIsActive(ownerUsername string) error {
if ownerUsername == "" {
return nil
}
u, ok := adminUsers.get(ownerUsername)
if !ok {
return fmt.Errorf("reseller account not found")
}
if !u.IsActive {
return fmt.Errorf("reseller account suspended")
}
if u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt) {
return fmt.Errorf("reseller account expired")
}
return nil
}
// disconnectOwnerUsers forcibly closes all active SSH connections for users owned by owner.
func disconnectOwnerUsers(ownerUsername string) {
for _, u := range userMgr.List() {
if u.Cfg.OwnerUsername == ownerUsername {
userMgr.DisconnectUser(u.Cfg.Username)
}
}
}
// countOwnedUsers counts SSH users in memory that belong to owner.
func countOwnedUsers(ownerUsername string) int {
n := 0
for _, u := range userMgr.List() {
if u.Cfg.OwnerUsername == ownerUsername {
n++
}
}
return n
}
// ---------- Reseller expiry background checker ----------
func startResellerExpiryChecker(store *Store) {
if store == nil {
return
}
go func() {
ticker := time.NewTicker(60 * time.Second)
defer ticker.Stop()
for range ticker.C {
ctx := context.Background()
// Expire active resellers past their deadline
expired, err := store.ListExpiredResellers(ctx)
if err != nil {
log.Printf("reseller expiry check: %v", err)
}
for _, u := range expired {
log.Printf("reseller %s expired — suspending", u.Username)
if err := store.SetAdminUserActive(ctx, u.Username, false); err != nil {
log.Printf("reseller expiry: %v", err)
continue
}
u.IsActive = false
adminUsers.set(u)
disconnectOwnerUsers(u.Username)
suspendOwnerXrayClients(ctx, store, u.Username)
}
// Reactivate resellers that have been renewed (inactive but expiry now in future/nil)
renewed, err := store.ListInactiveButRenewedResellers(ctx)
if err != nil {
log.Printf("reseller renewal check: %v", err)
}
for _, u := range renewed {
log.Printf("reseller %s renewed — reactivating", u.Username)
if err := store.SetAdminUserActive(ctx, u.Username, true); err != nil {
log.Printf("reseller renewal: %v", err)
continue
}
u.IsActive = true
adminUsers.set(u)
restoreOwnerXrayClients(ctx, store, u.Username)
}
sessions.cleanup()
}
}()
}
// ---------- HTTP handlers ----------
func handleLogin(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if store == nil {
http.Error(w, "database not configured", http.StatusServiceUnavailable)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
var req struct {
Username string `json:"username"`
Password string `json:"password"`
}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&req); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
req.Username = strings.TrimSpace(req.Username)
if req.Username == "" || req.Password == "" {
http.Error(w, "username and password required", http.StatusBadRequest)
return
}
key := loginAttemptKey(r, req.Username)
now := time.Now()
if retry := loginThrottle.retryAfter(key, now); retry > 0 {
w.Header().Set("Retry-After", strconv.Itoa(max(1, int(retry.Seconds()))))
http.Error(w, "too many login attempts", http.StatusTooManyRequests)
return
}
u, err := store.GetAdminUserByUsername(r.Context(), req.Username)
if err != nil {
log.Printf("login db: %v", err)
http.Error(w, "server error", http.StatusInternalServerError)
return
}
valid := false
needsUpgrade := false
if u != nil {
valid, needsUpgrade = verifyAdminPassword(u.PasswordHash, req.Password)
} else {
// Keep roughly the same CPU cost for unknown users to reduce account probing.
_, _ = hashAdminPassword(req.Password)
}
if !valid {
loginThrottle.fail(key, now)
http.Error(w, "invalid credentials", http.StatusUnauthorized)
return
}
if !u.IsActive {
http.Error(w, "account suspended", http.StatusForbidden)
return
}
if u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt) {
http.Error(w, "account expired", http.StatusForbidden)
return
}
if needsUpgrade {
if upgradedHash, hashErr := hashAdminPassword(req.Password); hashErr == nil {
if updateErr := store.UpdateAdminPasswordHash(r.Context(), u.ID, upgradedHash); updateErr != nil {
log.Printf("upgrade admin password hash for %s: %v", u.Username, updateErr)
} else {
u.PasswordHash = upgradedHash
adminUsers.set(u)
}
}
}
loginThrottle.success(key)
sess, err := sessions.Create(u.ID, u.Username, u.Role)
if err != nil {
log.Printf("create admin session: %v", err)
http.Error(w, "server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"token": sess.Token,
"username": u.Username,
"role": u.Role,
})
}
}
func handleLogout(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
sessions.Delete(r.Header.Get("X-Session-Token"))
w.WriteHeader(http.StatusOK)
}
func handleMe(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
s := sessionFromCtx(r.Context())
resp := map[string]interface{}{
"username": s.Username,
"role": s.Role,
}
if s.Role == RoleReseller {
if u, ok := adminUsers.get(s.Username); ok {
resp["max_users"] = u.MaxUsers
resp["used_users"] = countOwnedQuota(r.Context(), statsStore, s.Username)
resp["used_ssh_users"] = countOwnedUsers(s.Username)
resp["used_xray_users"] = countOwnedXrayClients(r.Context(), statsStore, s.Username)
resp["expires_at"] = u.ExpiresAt
resp["is_active"] = u.IsActive
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
// ---------- Reseller management (superadmin only) ----------
type ResellerDTO struct {
ID int `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
MaxUsers int `json:"max_users"`
UsedUsers int `json:"used_users"`
UsedSSH int `json:"used_ssh_users"`
UsedXray int `json:"used_xray_users"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
IsActive bool `json:"is_active"`
CreatedAt time.Time `json:"created_at"`
}
func handleListResellers(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
users, err := store.ListAdminUsers(r.Context())
if err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
out := make([]ResellerDTO, 0, len(users))
for _, u := range users {
out = append(out, ResellerDTO{
ID: u.ID,
Username: u.Username,
Role: u.Role,
MaxUsers: u.MaxUsers,
UsedUsers: countOwnedQuota(r.Context(), store, u.Username),
UsedSSH: countOwnedUsers(u.Username),
UsedXray: countOwnedXrayClients(r.Context(), store, u.Username),
ExpiresAt: u.ExpiresAt,
IsActive: u.IsActive,
CreatedAt: u.CreatedAt,
})
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(out)
}
}
type ResellerPayload struct {
Username string `json:"username"`
Password string `json:"password,omitempty"`
MaxUsers int `json:"max_users"`
ExpiresAt string `json:"expires_at"`
IsActive bool `json:"is_active"`
}
func handleCreateReseller(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var p ResellerPayload
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
p.Username = strings.TrimSpace(p.Username)
if err := validateAdminUsername(p.Username); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if p.MaxUsers < 0 || p.MaxUsers > 1000000 {
http.Error(w, "max_users must be between 0 and 1000000", http.StatusBadRequest)
return
}
ctx := r.Context()
existing, err := store.GetAdminUserByUsername(ctx, p.Username)
if err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
var u *AdminUser
if existing != nil {
u = existing
} else {
if p.Password == "" {
http.Error(w, "password required for new account", http.StatusBadRequest)
return
}
u = &AdminUser{Username: p.Username, Role: RoleReseller}
}
if p.Password != "" {
if err := validateAdminPassword(p.Password); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
passwordHash, err := hashAdminPassword(p.Password)
if err != nil {
http.Error(w, "failed to hash password", http.StatusInternalServerError)
return
}
u.PasswordHash = passwordHash
}
u.MaxUsers = p.MaxUsers
u.IsActive = p.IsActive
u.ExpiresAt = nil
if p.ExpiresAt != "" {
t, err := time.Parse(time.RFC3339, p.ExpiresAt)
if err != nil {
http.Error(w, "invalid expires_at (RFC3339 required)", http.StatusBadRequest)
return
}
u.ExpiresAt = &t
}
if err := store.UpsertAdminUser(ctx, u); err != nil {
log.Printf("upsert reseller: %v", err)
http.Error(w, "db error", http.StatusInternalServerError)
return
}
adminUsers.set(u)
if p.Password != "" && existing != nil {
sessions.DeleteUser(u.ID)
}
if u.Role == RoleReseller {
if !u.IsActive || (u.ExpiresAt != nil && time.Now().After(*u.ExpiresAt)) {
disconnectOwnerUsers(u.Username)
suspendOwnerXrayClients(ctx, store, u.Username)
} else {
restoreOwnerXrayClients(ctx, store, u.Username)
}
}
w.WriteHeader(http.StatusCreated)
}
}
func handleDeleteReseller(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
username := strings.TrimSpace(r.URL.Query().Get("username"))
if err := validateAdminUsername(username); err != nil {
http.Error(w, "invalid username", http.StatusBadRequest)
return
}
ctx := r.Context()
u, _ := store.GetAdminUserByUsername(ctx, username)
if u != nil && u.Role == RoleSuperAdmin {
http.Error(w, "superadmin accounts cannot be deleted from the reseller endpoint", http.StatusForbidden)
return
}
if err := store.DeleteAdminUser(ctx, username); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
disconnectOwnerUsers(username)
removeOwnerXrayClients(ctx, store, username)
adminUsers.delete(username)
if u != nil {
sessions.DeleteUser(u.ID)
}
w.WriteHeader(http.StatusNoContent)
}
}
+231
View File
@@ -0,0 +1,231 @@
package main
// Live per-account bandwidth. The panel already keeps cumulative uploaded and
// downloaded byte counters for every SSH user and Xray client; this file turns
// those counters into a current speed so the UI can show "↑ 12 Mbps ↓ 40 Mbps"
// for the whole account instead of only lifetime totals. Speeds are always the
// sum of every connection the account has open, because the counters they are
// derived from are per account, not per connection.
import (
"math"
"strings"
"sync"
"sync/atomic"
"time"
)
// bandwidthRate is a smoothed instantaneous speed in bytes per second.
type bandwidthRate struct {
UpBytesPerSec float64
DownBytesPerSec float64
}
func (r bandwidthRate) isZero() bool {
return r.UpBytesPerSec == 0 && r.DownBytesPerSec == 0
}
type bandwidthSample struct {
up int64
down int64
at time.Time
rate bandwidthRate
}
// bandwidthSampler converts monotonically increasing byte counters into a
// speed. Deltas smaller than minSampleInterval are ignored so a double sample
// cannot divide by an almost-zero interval, and a counter that moves backwards
// (traffic reset, account recreated) re-baselines instead of reporting a
// nonsensical negative or huge rate.
type bandwidthSampler struct {
mu sync.Mutex
samples map[string]bandwidthSample
// tau is the exponential smoothing time constant. Larger values give a
// calmer number; zero disables smoothing.
tau time.Duration
// staleAfter makes Rate report zero for accounts that stopped being
// sampled (idle Xray clients dropped by the stats poller, for example),
// instead of freezing the last speed on screen forever.
staleAfter time.Duration
}
const minBandwidthSampleInterval = 250 * time.Millisecond
func newBandwidthSampler(tau, staleAfter time.Duration) *bandwidthSampler {
return &bandwidthSampler{
samples: make(map[string]bandwidthSample),
tau: tau,
staleAfter: staleAfter,
}
}
// Observe records the current cumulative counters for key. The first
// observation only establishes a baseline; the rate stays zero until a second
// one arrives.
func (s *bandwidthSampler) Observe(key string, up, down int64, now time.Time) {
if s == nil {
return
}
key = strings.TrimSpace(key)
if key == "" {
return
}
if up < 0 {
up = 0
}
if down < 0 {
down = 0
}
s.mu.Lock()
defer s.mu.Unlock()
prev, ok := s.samples[key]
if !ok {
s.samples[key] = bandwidthSample{up: up, down: down, at: now}
return
}
// Counters went backwards: the account's traffic was reset or the entry was
// recycled. Start over from this value.
if up < prev.up || down < prev.down {
s.samples[key] = bandwidthSample{up: up, down: down, at: now}
return
}
dt := now.Sub(prev.at)
if dt < minBandwidthSampleInterval {
return
}
seconds := dt.Seconds()
instant := bandwidthRate{
UpBytesPerSec: float64(up-prev.up) / seconds,
DownBytesPerSec: float64(down-prev.down) / seconds,
}
next := instant
if s.tau > 0 && !prev.rate.isZero() {
// alpha derived from the real interval so an irregular sampling
// cadence still converges on the true average.
alpha := 1 - math.Exp(-seconds/s.tau.Seconds())
if alpha > 1 {
alpha = 1
}
next = bandwidthRate{
UpBytesPerSec: prev.rate.UpBytesPerSec + alpha*(instant.UpBytesPerSec-prev.rate.UpBytesPerSec),
DownBytesPerSec: prev.rate.DownBytesPerSec + alpha*(instant.DownBytesPerSec-prev.rate.DownBytesPerSec),
}
}
if next.UpBytesPerSec < 0 {
next.UpBytesPerSec = 0
}
if next.DownBytesPerSec < 0 {
next.DownBytesPerSec = 0
}
s.samples[key] = bandwidthSample{up: up, down: down, at: now, rate: next}
}
// Rate returns the last known speed for key. Stale entries report zero.
func (s *bandwidthSampler) Rate(key string) (bandwidthRate, bool) {
if s == nil {
return bandwidthRate{}, false
}
key = strings.TrimSpace(key)
if key == "" {
return bandwidthRate{}, false
}
s.mu.Lock()
defer s.mu.Unlock()
return s.rateLocked(key)
}
// RateForKeys returns the first known speed among keys. Xray clients are
// tracked under their UUID in native mode and under their email in external
// mode, so callers pass every identifier the client may be stored under.
func (s *bandwidthSampler) RateForKeys(keys ...string) (bandwidthRate, bool) {
if s == nil {
return bandwidthRate{}, false
}
s.mu.Lock()
defer s.mu.Unlock()
for _, key := range keys {
key = strings.TrimSpace(key)
if key == "" {
continue
}
if rate, ok := s.rateLocked(key); ok {
return rate, true
}
}
return bandwidthRate{}, false
}
func (s *bandwidthSampler) rateLocked(key string) (bandwidthRate, bool) {
sample, ok := s.samples[key]
if !ok {
return bandwidthRate{}, false
}
if s.staleAfter > 0 && !sample.at.IsZero() && time.Since(sample.at) > s.staleAfter {
return bandwidthRate{}, true
}
return sample.rate, true
}
// Retain drops every tracked key that is not in keep, so the map cannot grow
// forever as accounts are deleted or recreated.
func (s *bandwidthSampler) Retain(keep map[string]struct{}) {
if s == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
for key := range s.samples {
if _, ok := keep[key]; !ok {
delete(s.samples, key)
}
}
}
// ---- SSH accounts ----
const sshBandwidthSampleInterval = 2 * time.Second
var sshBandwidth = newBandwidthSampler(5*time.Second, 20*time.Second)
func startSSHUserRateSampler() {
go func() {
ticker := time.NewTicker(sshBandwidthSampleInterval)
defer ticker.Stop()
for range ticker.C {
sampleSSHUserRates(time.Now())
}
}()
}
func sampleSSHUserRates(now time.Time) {
if userMgr == nil {
return
}
states := userMgr.List()
active := make(map[string]struct{}, len(states))
for _, u := range states {
if u == nil {
continue
}
u.mu.Lock()
username := strings.TrimSpace(u.Cfg.Username)
u.mu.Unlock()
if username == "" {
continue
}
sshBandwidth.Observe(
username,
atomic.LoadInt64(&u.TotalUplinkBytes),
atomic.LoadInt64(&u.TotalDownlinkBytes),
now,
)
active[username] = struct{}{}
}
sshBandwidth.Retain(active)
}
func sshUserRate(username string) bandwidthRate {
rate, _ := sshBandwidth.Rate(username)
return rate
}
+121
View File
@@ -0,0 +1,121 @@
package main
import (
"testing"
"time"
)
func TestBandwidthSamplerFirstObservationIsBaselineOnly(t *testing.T) {
s := newBandwidthSampler(0, time.Minute)
now := time.Now()
s.Observe("bob", 10_000, 20_000, now)
rate, ok := s.Rate("bob")
if !ok {
t.Fatal("expected the account to be tracked after the first observation")
}
if !rate.isZero() {
t.Fatalf("first observation must not report a speed, got %+v", rate)
}
}
func TestBandwidthSamplerComputesBytesPerSecond(t *testing.T) {
s := newBandwidthSampler(0, time.Minute) // no smoothing: exact delta/dt
now := time.Now()
s.Observe("bob", 0, 0, now)
// 2 MB up and 10 MB down over 2 seconds.
s.Observe("bob", 2<<20, 10<<20, now.Add(2*time.Second))
rate, _ := s.Rate("bob")
if wantUp := float64(1 << 20); rate.UpBytesPerSec != wantUp {
t.Fatalf("up = %v, want %v", rate.UpBytesPerSec, wantUp)
}
if wantDown := float64(5 << 20); rate.DownBytesPerSec != wantDown {
t.Fatalf("down = %v, want %v", rate.DownBytesPerSec, wantDown)
}
}
func TestBandwidthSamplerIgnoresSamplesTakenTooCloseTogether(t *testing.T) {
s := newBandwidthSampler(0, time.Minute)
now := time.Now()
s.Observe("bob", 0, 0, now)
s.Observe("bob", 5<<20, 5<<20, now.Add(10*time.Millisecond))
rate, _ := s.Rate("bob")
if !rate.isZero() {
t.Fatalf("a 10ms interval must not produce a speed, got %+v", rate)
}
}
func TestBandwidthSamplerRebaselinesAfterTrafficReset(t *testing.T) {
s := newBandwidthSampler(0, time.Minute)
now := time.Now()
s.Observe("bob", 0, 0, now)
s.Observe("bob", 4<<20, 4<<20, now.Add(2*time.Second))
// Panel reset the account's traffic: counters go back to zero.
s.Observe("bob", 0, 0, now.Add(4*time.Second))
rate, _ := s.Rate("bob")
if !rate.isZero() {
t.Fatalf("counters moving backwards must reset the speed, got %+v", rate)
}
s.Observe("bob", 2<<20, 0, now.Add(6*time.Second))
rate, _ = s.Rate("bob")
if wantUp := float64(1 << 20); rate.UpBytesPerSec != wantUp {
t.Fatalf("up after reset = %v, want %v", rate.UpBytesPerSec, wantUp)
}
}
func TestBandwidthSamplerReportsZeroWhenIdle(t *testing.T) {
s := newBandwidthSampler(0, time.Minute)
now := time.Now()
s.Observe("bob", 0, 0, now)
s.Observe("bob", 4<<20, 4<<20, now.Add(2*time.Second))
s.Observe("bob", 4<<20, 4<<20, now.Add(4*time.Second))
rate, _ := s.Rate("bob")
if !rate.isZero() {
t.Fatalf("unchanged counters must report an idle account, got %+v", rate)
}
}
func TestBandwidthSamplerDropsStaleSpeeds(t *testing.T) {
s := newBandwidthSampler(0, time.Second)
now := time.Now().Add(-time.Hour)
s.Observe("bob", 0, 0, now)
s.Observe("bob", 4<<20, 4<<20, now.Add(2*time.Second))
rate, ok := s.Rate("bob")
if !ok {
t.Fatal("expected the account to still be tracked")
}
if !rate.isZero() {
t.Fatalf("an hour-old sample must not still report a speed, got %+v", rate)
}
}
func TestBandwidthSamplerSmoothsWithTimeConstant(t *testing.T) {
s := newBandwidthSampler(5*time.Second, time.Minute)
now := time.Now()
s.Observe("bob", 0, 0, now)
// First real sample has no previous rate to blend with, so it lands exactly.
s.Observe("bob", 2<<20, 0, now.Add(2*time.Second))
first, _ := s.Rate("bob")
if first.UpBytesPerSec != float64(1<<20) {
t.Fatalf("first speed = %v, want %v", first.UpBytesPerSec, float64(1<<20))
}
// Traffic stops: the smoothed value has to fall without jumping to zero.
s.Observe("bob", 2<<20, 0, now.Add(4*time.Second))
second, _ := s.Rate("bob")
if second.UpBytesPerSec <= 0 || second.UpBytesPerSec >= first.UpBytesPerSec {
t.Fatalf("smoothed speed = %v, want a value between 0 and %v", second.UpBytesPerSec, first.UpBytesPerSec)
}
}
func TestBandwidthSamplerRateForKeysAndRetain(t *testing.T) {
s := newBandwidthSampler(0, time.Minute)
now := time.Now()
s.Observe("uuid-1", 0, 0, now)
s.Observe("uuid-1", 1<<20, 0, now.Add(1*time.Second))
if _, ok := s.RateForKeys("", "unknown@example", "uuid-1"); !ok {
t.Fatal("RateForKeys must find the client under any of its identifiers")
}
s.Retain(map[string]struct{}{"uuid-2": {}})
if _, ok := s.Rate("uuid-1"); ok {
t.Fatal("Retain must drop accounts that no longer exist")
}
}
File diff suppressed because it is too large Load Diff
+532
View File
@@ -0,0 +1,532 @@
package main
// This file embeds the BHTTP (BHP1/BHP2) transport into the panel. BHTTP is the
// obfuscated TCP transport used by the DTunnel-family clients: a client opens a
// plain TCP socket, optionally sends an HTTP request as cover, then speaks the
// 29-byte-header BHTTP framing (probe, upload, download, batch, ACK and — in
// v2 — persistent lanes with resume and cumulative ACKs).
//
// The transport does NOT talk to the system's OpenSSH daemon. Exactly like the
// DNSTT integration, every BHTTP session is handed to this process's own SSH
// server through handleConn, so panel accounts, expiry, TOTP, per-user
// bandwidth limits, data quotas and connection counters all apply unchanged.
// There is no dependency on sshd, PAM or /etc/shadow anywhere in this path.
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"sync"
"time"
"shell2/internal/bhttp"
)
// BHTTPConfig defines the settings for the integrated BHTTP transport. A nil
// *BHTTPConfig in the main config disables it entirely.
type BHTTPConfig struct {
// Listen lists the TCP addresses to bind. IPv6 addresses must use bracket
// form, for example "[::]:8880". Empty uses the default 0.0.0.0:8880.
// Ports 80/8080 normally belong to the HTTP+SSH proxy listeners, so BHTTP
// defaults to a separate port instead of fighting them for the socket.
Listen []string `json:"listen"`
// SharedPorts also accepts BHTTP on the ports the panel already owns: the
// HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080)
// and every TLS forwarder (normally 443). Those listeners read the first
// bytes of each connection and hand it here only when it is unmistakably a
// BHTTP frame, so SSH and HTTP-injection clients on the same port are
// unaffected.
//
// The one behaviour this changes for other clients: the proxy listener
// normally answers with "HTTP/1.1 101" the moment a socket opens, and with
// sharing on it waits for the client's first bytes instead (up to
// bhttpSniffTimeout). Every known client sends immediately on connect, but
// turn this off if a client of yours waits for that 101 before speaking.
SharedPorts bool `json:"shared_ports,omitempty"`
// SessionTimeout is how long a BHTTP session may sit with no traffic before
// it is dropped and its SSH connection closed. Empty defaults to "2m".
// BHTTP v2 clients reconnect lanes into an existing session, so this value
// also bounds how long a resume stays possible.
SessionTimeout string `json:"session_timeout,omitempty"`
// MaxV2Lanes caps the combined number of BHTTP v2 lanes a single session
// may keep attached. Zero uses the protocol default (128).
MaxV2Lanes int `json:"max_v2_lanes,omitempty"`
// MaxSessions caps concurrently tracked BHTTP sessions. Once reached, new
// session IDs are refused while existing sessions keep working. Zero uses a
// safe default; negative disables the cap.
MaxSessions int `json:"max_sessions,omitempty"`
// MaxConnections caps concurrently accepted client sockets across every
// BHTTP listener. Sockets past the cap are closed before any protocol work.
// Zero uses a safe default; negative disables the cap.
MaxConnections int `json:"max_connections,omitempty"`
// DisableConsoleLog keeps BHTTP log lines out of stderr. They are still
// captured in memory and served by /api/bhttp/logs for the panel.
DisableConsoleLog bool `json:"disable_console_log,omitempty"`
// LogConnections enables one log line per accepted socket. Leave it off on
// servers with thousands of users; connection logging can become the
// bottleneck.
LogConnections bool `json:"log_connections,omitempty"`
// AutoRestartInterval controls a watchdog that periodically hard-restarts
// only the BHTTP listeners and drops their sessions. Empty, "0s", "off" or
// "disabled" turns it off. Minimum accepted value is 1m.
AutoRestartInterval string `json:"auto_restart_interval,omitempty"`
// AutoRestartGrace is the delay between closing the old listeners and
// binding them again during an auto restart. Empty defaults to "2s".
AutoRestartGrace string `json:"auto_restart_grace,omitempty"`
}
const (
defaultBHTTPListen = "0.0.0.0:8880"
defaultBHTTPSessionTimeout = 2 * time.Minute
defaultBHTTPMaxSessions = 10000
defaultBHTTPMaxConnections = 10000
// bhttpTargetLabel is the "address" handed to the dialer. BHTTP never dials
// a TCP target, so this is only what shows up in logs.
bhttpTargetLabel = "bhttp"
)
var (
bhttpMu sync.Mutex
bhttpServer *bhttp.Server
bhttpListeners []net.Listener
bhttpAddrs []string
// bhttpSharedPorts mirrors BHTTPConfig.SharedPorts for the running
// instance, so the proxy and TLS listeners can check it without reading the
// whole config on every connection.
bhttpSharedPorts bool
bhttpAutoMu sync.Mutex
bhttpAutoCancel context.CancelFunc
bhttpLog = log.New(os.Stderr, "bhttp: ", log.LstdFlags|log.Lmicroseconds)
bhttpLogBuf *ringLogBuffer
)
// ---------- Log buffer shared by the embedded transports ----------
// ringLogBuffer keeps the most recent log lines in memory so the admin panel
// can show them even when console logging is disabled.
type ringLogBuffer struct {
mu sync.Mutex
lines []string
maxLines int
partial string
}
func newRingLogBuffer(maxLines int) *ringLogBuffer {
if maxLines <= 0 {
maxLines = 100
}
return &ringLogBuffer{lines: make([]string, 0, maxLines), maxLines: maxLines}
}
func (b *ringLogBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
text := b.partial + string(p)
b.partial = ""
for {
index := strings.IndexByte(text, '\n')
if index < 0 {
b.partial = text
break
}
line := strings.TrimRight(text[:index], "\r")
text = text[index+1:]
if line == "" {
continue
}
if len(b.lines) >= b.maxLines {
copy(b.lines, b.lines[1:])
b.lines = b.lines[:len(b.lines)-1]
}
b.lines = append(b.lines, line)
}
return len(p), nil
}
func (b *ringLogBuffer) GetLines() []string {
if b == nil {
return nil
}
b.mu.Lock()
defer b.mu.Unlock()
out := make([]string, len(b.lines))
copy(out, b.lines)
return out
}
func getBHTTPLogLines() []string { return bhttpLogBuf.GetLines() }
// ---------- Handing a tunnelled stream to the built-in SSH server ----------
// transportAddr is a stable net.Addr placeholder for in-process tunnel streams,
// mirroring how the DNSTT integration labels its streams.
type transportAddr string
func (a transportAddr) Network() string { return string(a) }
func (a transportAddr) String() string { return string(a) }
// dialInternalSSH returns a net.Conn whose other end is being served by this
// process's own SSH server. Nothing leaves the process: no loopback socket, no
// system sshd, no PAM. label only affects log output.
//
// The pair is buffered in both directions (see tunnel_pipe.go), so neither
// side has to be reading for the other to make progress. That keeps the SSH
// server's handshake, which writes and reads in the same goroutine, from
// depending on the transport happening to be draining at that moment.
func dialInternalSSH(label string) (net.Conn, error) {
sshConf := getSSHConfig()
if sshConf == nil {
return nil, fmt.Errorf("%s: internal SSH server is not ready", label)
}
clientSide, serverSide := newTunnelConnPair(label, tunnelPipeBuffer)
go func() {
defer func() {
if r := recover(); r != nil {
log.Printf("%s: recovered panic in SSH handler: %v", label, r)
}
}()
defer serverSide.Close()
handleConn(serverSide, sshConf)
}()
return clientSide, nil
}
// ---------- Lifecycle ----------
// stopBHTTP closes the BHTTP listeners, drops every session and stops the
// optional auto-restart watchdog. It is a no-op if BHTTP is not running.
func stopBHTTP() {
stopBHTTPAutoRestart()
stopBHTTPInstance()
}
// stopBHTTPInstance closes only the listeners and sessions. The auto-restart
// watchdog uses this so it can cycle BHTTP without disabling itself.
func stopBHTTPInstance() {
bhttpMu.Lock()
listeners := bhttpListeners
server := bhttpServer
bhttpListeners = nil
bhttpAddrs = nil
bhttpServer = nil
bhttpSharedPorts = false
bhttpMu.Unlock()
for _, listener := range listeners {
if listener != nil {
_ = listener.Close()
}
}
if server != nil {
server.Close()
}
}
func stopBHTTPAutoRestart() {
bhttpAutoMu.Lock()
defer bhttpAutoMu.Unlock()
if bhttpAutoCancel != nil {
bhttpAutoCancel()
bhttpAutoCancel = nil
}
}
func bhttpRunning() bool {
bhttpMu.Lock()
defer bhttpMu.Unlock()
// The server can legitimately run with no listener of its own when it only
// serves connections handed over from the shared proxy and TLS ports.
return bhttpServer != nil
}
// bhttpListenList describes where BHTTP is reachable, for the panel.
func bhttpListenList() string {
bhttpMu.Lock()
addrs := append([]string(nil), bhttpAddrs...)
shared := bhttpSharedPorts
bhttpMu.Unlock()
if shared {
addrs = append(addrs, "shared proxy/TLS ports")
}
return strings.Join(addrs, ", ")
}
// bhttpShareEnabled reports whether a running BHTTP server wants the shared
// proxy and TLS ports.
func bhttpShareEnabled() bool {
bhttpMu.Lock()
defer bhttpMu.Unlock()
return bhttpServer != nil && bhttpSharedPorts
}
func bhttpEnabledInCurrentConfig() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.BHTTP != nil
}
// startBHTTP starts the integrated BHTTP transport if cfg is non-nil. Startup
// errors are returned so the admin panel can report them, but they never crash
// the panel.
func startBHTTP(cfg *BHTTPConfig) error {
if cfg == nil {
return nil
}
stopBHTTPAutoRestart()
if err := startBHTTPInstance(cfg); err != nil {
return err
}
startBHTTPAutoRestart(cfg)
return nil
}
func startBHTTPInstance(cfg *BHTTPConfig) error {
if cfg == nil {
return nil
}
if bhttpLogBuf == nil {
bhttpLogBuf = newRingLogBuffer(200)
}
if cfg.DisableConsoleLog {
bhttpLog.SetOutput(bhttpLogBuf)
} else {
bhttpLog.SetOutput(io.MultiWriter(bhttpLogBuf, os.Stderr))
}
addrs := normalizeBHTTPListenList(cfg.Listen)
cfg.Listen = addrs
if len(addrs) == 0 && !cfg.SharedPorts {
msg := errors.New("bhttp: needs either a listen address or shared_ports")
bhttpLog.Print(msg.Error())
return msg
}
sessionTimeout := bhttpSessionTimeout(cfg)
maxSessions := cfg.MaxSessions
if maxSessions == 0 {
maxSessions = defaultBHTTPMaxSessions
} else if maxSessions < 0 {
maxSessions = 0 // unlimited
}
maxConnections := cfg.MaxConnections
if maxConnections == 0 {
maxConnections = defaultBHTTPMaxConnections
} else if maxConnections < 0 {
maxConnections = 0 // unlimited
}
server := bhttp.NewServer(bhttp.Config{
TargetAddress: bhttpTargetLabel,
SessionTimeout: sessionTimeout,
MaxV2Lanes: cfg.MaxV2Lanes,
MaxSessions: maxSessions,
MaxConnections: maxConnections,
LogConnections: cfg.LogConnections,
Logger: bhttpLog,
DialTarget: dialInternalSSH,
})
// Release the previous instance first: rebinding the same address while the
// old socket is still open would fail with "address already in use".
stopBHTTPInstance()
// Bind synchronously so the panel immediately knows whether BHTTP really
// started or failed on a busy port.
listeners := make([]net.Listener, 0, len(addrs))
bound := make([]string, 0, len(addrs))
for _, addr := range addrs {
listener, err := net.Listen("tcp", addr)
if err != nil {
for _, opened := range listeners {
_ = opened.Close()
}
server.Close()
msg := fmt.Errorf("bhttp: listen failed on %s: %w", addr, err)
bhttpLog.Print(msg.Error())
return msg
}
listeners = append(listeners, listener)
bound = append(bound, addr)
}
bhttpMu.Lock()
bhttpServer = server
bhttpListeners = listeners
bhttpAddrs = bound
bhttpSharedPorts = cfg.SharedPorts
bhttpMu.Unlock()
bhttpLog.Printf("starting: listen=%q shared_ports=%v session_timeout=%s max_v2_lanes=%d max_sessions=%d max_connections=%d log_connections=%v -> built-in SSH server",
bound, cfg.SharedPorts, sessionTimeout, cfg.MaxV2Lanes, maxSessions, maxConnections, cfg.LogConnections)
for _, listener := range listeners {
go func(current net.Listener) {
defer func() {
if r := recover(); r != nil {
bhttpLog.Printf("recovered panic in accept loop: %v", r)
}
}()
if err := server.Serve(current); err != nil && !isListenerClosed(err) {
bhttpLog.Printf("listener %s stopped: %v", current.Addr(), err)
}
}(listener)
}
return nil
}
func startBHTTPAutoRestart(cfg *BHTTPConfig) {
interval := bhttpAutoRestartInterval(cfg)
if interval <= 0 {
return
}
grace := bhttpAutoRestartGrace(cfg)
cfgCopy := *cfg
cfgCopy.Listen = append([]string(nil), cfg.Listen...)
ctx, cancel := context.WithCancel(context.Background())
bhttpAutoMu.Lock()
if bhttpAutoCancel != nil {
bhttpAutoCancel()
}
bhttpAutoCancel = cancel
bhttpAutoMu.Unlock()
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
bhttpLog.Printf("auto restart enabled: interval=%s grace=%s mode=hard", interval, grace)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
bhttpLog.Print("auto restart: stopping listeners and sessions")
stopBHTTPInstance()
if !sleepOrContextDone(ctx, grace) {
return
}
for attempt := 1; ; attempt++ {
if err := startBHTTPInstance(&cfgCopy); err != nil {
bhttpLog.Printf("auto restart: start attempt %d failed: %v", attempt, err)
if !sleepOrContextDone(ctx, 10*time.Second) {
return
}
continue
}
bhttpLog.Print("auto restart: listeners rebound")
break
}
}
}
}()
}
func bhttpSessionTimeout(cfg *BHTTPConfig) time.Duration {
if cfg == nil {
return defaultBHTTPSessionTimeout
}
raw := strings.TrimSpace(cfg.SessionTimeout)
if raw == "" {
return defaultBHTTPSessionTimeout
}
d, err := time.ParseDuration(raw)
if err != nil || d <= 0 {
bhttpLog.Printf("invalid session_timeout %q; using default %s", raw, defaultBHTTPSessionTimeout)
return defaultBHTTPSessionTimeout
}
return d
}
func bhttpAutoRestartInterval(cfg *BHTTPConfig) time.Duration {
if cfg == nil {
return 0
}
raw := strings.TrimSpace(cfg.AutoRestartInterval)
if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") {
return 0
}
d, err := time.ParseDuration(raw)
if err != nil {
bhttpLog.Printf("auto restart disabled: invalid interval %q: %v", raw, err)
return 0
}
if d < time.Minute {
bhttpLog.Printf("auto restart disabled: interval %q is below minimum 1m", raw)
return 0
}
return d
}
func bhttpAutoRestartGrace(cfg *BHTTPConfig) time.Duration {
if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" {
return 2 * time.Second
}
d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace))
if err != nil || d < 0 {
bhttpLog.Printf("auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace)
return 2 * time.Second
}
if d > time.Minute {
return time.Minute
}
return d
}
// normalizeBHTTPListenList trims, de-duplicates and preserves the order of the
// configured listen addresses.
func normalizeBHTTPListenList(addrs []string) []string {
seen := make(map[string]bool, len(addrs))
out := make([]string, 0, len(addrs))
for _, addr := range addrs {
addr = strings.TrimSpace(addr)
if addr == "" || seen[addr] {
continue
}
seen[addr] = true
out = append(out, addr)
}
return out
}
// ---------- Stats ----------
// BHTTPStatsSnapshot is what /api/bhttp returns.
type BHTTPStatsSnapshot struct {
Enabled bool `json:"enabled"`
Running bool `json:"running"`
Listen string `json:"listen,omitempty"`
bhttp.StatsSnapshot
}
// GetBHTTPStatsSnapshot returns the current BHTTP counters. It is safe for
// concurrent use and always returns a copy.
func GetBHTTPStatsSnapshot() BHTTPStatsSnapshot {
snapshot := BHTTPStatsSnapshot{
Enabled: bhttpEnabledInCurrentConfig(),
Running: bhttpRunning(),
Listen: bhttpListenList(),
}
bhttpMu.Lock()
server := bhttpServer
bhttpMu.Unlock()
if server != nil {
snapshot.StatsSnapshot = server.Stats()
}
return snapshot
}
+583
View File
@@ -0,0 +1,583 @@
package main
// bot_api.go — /api/bot/* admin endpoints (superadmin).
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode"
)
var botSettingKeys = map[string]int{
"welcome_text": 4096,
"contact_text": 4096,
"app_text": 4096,
"app_url": 2048,
}
func botHasControlCharacters(value string) bool {
return strings.IndexFunc(value, func(r rune) bool {
return unicode.IsControl(r) && r != '\n' && r != '\r' && r != '\t'
}) >= 0
}
func botHasAnyControlCharacters(value string) bool {
return strings.IndexFunc(value, unicode.IsControl) >= 0
}
func validateBotPlan(p *BotPlan) error {
p.Name = strings.TrimSpace(p.Name)
p.Kind = strings.ToLower(strings.TrimSpace(p.Kind))
p.XrayProtocol = strings.ToLower(strings.TrimSpace(p.XrayProtocol))
p.XrayInboundTag = strings.TrimSpace(p.XrayInboundTag)
p.ServerID = strings.TrimSpace(p.ServerID)
if p.Name == "" || len(p.Name) > 120 || botHasControlCharacters(p.Name) {
return fmt.Errorf("plan name must contain 1-120 safe characters")
}
if p.Kind != "ssh" && p.Kind != "xray" {
return fmt.Errorf("plan kind must be ssh or xray")
}
if p.Days < 1 || p.Days > 3650 || p.MaxConnections < 0 || p.MaxConnections > 10000 {
return fmt.Errorf("invalid plan duration or connection limit")
}
if p.LimitMbpsUp < 0 || p.LimitMbpsUp > 1000000 || p.LimitMbpsDown < 0 || p.LimitMbpsDown > 1000000 {
return fmt.Errorf("invalid bandwidth limit")
}
if p.PriceCents < 0 || p.PriceCents > 1000000000 || p.CreditCost < 0 || p.CreditCost > 1000000000 {
return fmt.Errorf("invalid plan price or credit cost")
}
if p.Kind == "xray" && p.XrayProtocol != "" && p.XrayProtocol != "vless" && p.XrayProtocol != "vmess" && p.XrayProtocol != "trojan" {
return fmt.Errorf("invalid Xray protocol")
}
if len(p.XrayInboundTag) > 128 || len(p.ServerID) > 128 {
return fmt.Errorf("inbound tag or server id is too long")
}
return nil
}
func validateBotPackage(p *BotCreditPackage) error {
p.Name = strings.TrimSpace(p.Name)
if p.Name == "" || len(p.Name) > 120 || botHasControlCharacters(p.Name) {
return fmt.Errorf("package name must contain 1-120 safe characters")
}
if p.Credits < 1 || p.Credits > 1000000000 || p.PriceCents < 0 || p.PriceCents > 1000000000 {
return fmt.Errorf("invalid package credits or price")
}
return nil
}
func botWriteJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}
func botStoreReady(w http.ResponseWriter, store *Store) bool {
if store == nil {
http.Error(w, "database not configured", http.StatusServiceUnavailable)
return false
}
return true
}
// ---------- Config ----------
type botConfigDTO struct {
Enabled bool `json:"enabled"`
MPConfirmMode string `json:"mp_confirm_mode"`
MPPollInterval string `json:"mp_poll_interval"`
PixExpirationMinutes int `json:"pix_expiration_minutes"`
TrialEnabled bool `json:"trial_enabled"`
TrialHours int `json:"trial_hours"`
TrialMaxConnections int `json:"trial_max_connections"`
TrialKind string `json:"trial_kind"`
TrialInboundTag string `json:"trial_inbound_tag"`
AdminTelegramIDs []int64 `json:"admin_telegram_ids"`
Currency string `json:"currency"`
PublicHost string `json:"public_host"`
XrayPublicHost string `json:"xray_public_host"`
HasTelegramToken bool `json:"has_telegram_token"`
HasMPAccessToken bool `json:"has_mp_access_token"`
HasMPWebhookSecret bool `json:"has_mp_webhook_secret"`
// Write-only secret fields (empty on GET; empty on POST = keep existing).
TelegramToken string `json:"telegram_token"`
MPAccessToken string `json:"mp_access_token"`
MPWebhookSecret string `json:"mp_webhook_secret"`
}
func handleBotConfig(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !botStoreReady(w, store) {
return
}
ctx := r.Context()
switch r.Method {
case http.MethodGet:
cfg, err := LoadBotConfig(ctx, store)
if err != nil {
http.Error(w, "load config: "+err.Error(), http.StatusInternalServerError)
return
}
botWriteJSON(w, botConfigDTO{
Enabled: cfg.Enabled,
MPConfirmMode: cfg.MPConfirmMode,
MPPollInterval: cfg.MPPollInterval,
PixExpirationMinutes: cfg.PixExpirationMinutes,
TrialEnabled: cfg.TrialEnabled,
TrialHours: cfg.TrialHours,
TrialMaxConnections: cfg.TrialMaxConnections,
TrialKind: cfg.TrialKind,
TrialInboundTag: cfg.TrialInboundTag,
AdminTelegramIDs: cfg.AdminTelegramIDs,
Currency: cfg.Currency,
PublicHost: cfg.PublicHost,
XrayPublicHost: cfg.XrayPublicHost,
HasTelegramToken: cfg.TelegramToken != "",
HasMPAccessToken: cfg.MPAccessToken != "",
HasMPWebhookSecret: cfg.MPWebhookSecret != "",
})
case http.MethodPost:
var dto botConfigDTO
r.Body = http.MaxBytesReader(w, r.Body, 64*1024)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&dto); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
dto.MPConfirmMode = strings.ToLower(strings.TrimSpace(dto.MPConfirmMode))
if dto.MPConfirmMode != "polling" && dto.MPConfirmMode != "webhook" {
http.Error(w, "confirmation mode must be polling or webhook", http.StatusBadRequest)
return
}
pollInterval, err := time.ParseDuration(strings.TrimSpace(dto.MPPollInterval))
if err != nil || pollInterval < 5*time.Second || pollInterval > 5*time.Minute {
http.Error(w, "poll interval must be between 5s and 5m", http.StatusBadRequest)
return
}
if dto.PixExpirationMinutes < 5 || dto.PixExpirationMinutes > 1440 || dto.TrialHours < 1 || dto.TrialHours > 720 || dto.TrialMaxConnections < 1 || dto.TrialMaxConnections > 1000 {
http.Error(w, "invalid PIX expiration or trial limits", http.StatusBadRequest)
return
}
dto.TrialKind = strings.ToLower(strings.TrimSpace(dto.TrialKind))
if dto.TrialKind != "ssh" && dto.TrialKind != "xray" {
http.Error(w, "trial kind must be ssh or xray", http.StatusBadRequest)
return
}
if len(dto.AdminTelegramIDs) > 100 {
http.Error(w, "too many admin Telegram IDs", http.StatusBadRequest)
return
}
for _, id := range dto.AdminTelegramIDs {
if id <= 0 {
http.Error(w, "admin Telegram IDs must be positive", http.StatusBadRequest)
return
}
}
for _, value := range []string{dto.TelegramToken, dto.MPAccessToken, dto.MPWebhookSecret, dto.PublicHost, dto.XrayPublicHost, dto.TrialInboundTag} {
if len(value) > 2048 || botHasAnyControlCharacters(value) {
http.Error(w, "configuration contains an invalid value", http.StatusBadRequest)
return
}
}
existing, err := LoadBotConfig(ctx, store)
if err != nil {
http.Error(w, "load existing config", http.StatusInternalServerError)
return
}
effectiveTelegramToken := strings.TrimSpace(dto.TelegramToken)
if effectiveTelegramToken == "" {
effectiveTelegramToken = existing.TelegramToken
}
if dto.Enabled && effectiveTelegramToken == "" {
http.Error(w, "Telegram token is required before enabling the bot", http.StatusBadRequest)
return
}
effectiveWebhookSecret := strings.TrimSpace(dto.MPWebhookSecret)
if effectiveWebhookSecret == "" {
effectiveWebhookSecret = existing.MPWebhookSecret
}
if dto.MPConfirmMode == "webhook" && len(effectiveWebhookSecret) < 16 {
http.Error(w, "a webhook secret of at least 16 characters is required", http.StatusBadRequest)
return
}
cfg := &BotConfig{
Enabled: dto.Enabled,
TelegramToken: strings.TrimSpace(dto.TelegramToken),
MPAccessToken: strings.TrimSpace(dto.MPAccessToken),
MPConfirmMode: dto.MPConfirmMode,
MPWebhookSecret: strings.TrimSpace(dto.MPWebhookSecret),
MPPollInterval: dto.MPPollInterval,
PixExpirationMinutes: dto.PixExpirationMinutes,
TrialEnabled: dto.TrialEnabled,
TrialHours: dto.TrialHours,
TrialMaxConnections: dto.TrialMaxConnections,
TrialKind: dto.TrialKind,
TrialInboundTag: strings.TrimSpace(dto.TrialInboundTag),
AdminTelegramIDs: dto.AdminTelegramIDs,
Currency: dto.Currency,
PublicHost: strings.TrimSpace(dto.PublicHost),
XrayPublicHost: strings.TrimSpace(dto.XrayPublicHost),
}
if err := SaveBotConfig(ctx, store, cfg); err != nil {
http.Error(w, "save config: "+err.Error(), http.StatusInternalServerError)
return
}
reloadBotService(store)
botWriteJSON(w, map[string]bool{"ok": true})
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
// ---------- Plans ----------
func handleBotPlans(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !botStoreReady(w, store) {
return
}
ctx := r.Context()
switch r.Method {
case http.MethodGet:
plans, err := store.ListPlans(ctx, false)
if err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
botWriteJSON(w, plans)
case http.MethodPost:
var p BotPlan
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
if p.Kind == "" {
p.Kind = "ssh"
}
if err := validateBotPlan(&p); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := store.UpsertPlan(ctx, &p); err != nil {
http.Error(w, "db error: "+err.Error(), http.StatusInternalServerError)
return
}
botWriteJSON(w, p)
case http.MethodDelete:
id, _ := strconv.Atoi(r.URL.Query().Get("id"))
if id <= 0 {
http.Error(w, "invalid id", http.StatusBadRequest)
return
}
if err := store.DeletePlan(ctx, id); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
// ---------- Credit packages ----------
func handleBotCreditPackages(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !botStoreReady(w, store) {
return
}
ctx := r.Context()
switch r.Method {
case http.MethodGet:
pkgs, err := store.ListCreditPackages(ctx, false)
if err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
botWriteJSON(w, pkgs)
case http.MethodPost:
var p BotCreditPackage
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
if err := validateBotPackage(&p); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := store.UpsertCreditPackage(ctx, &p); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
botWriteJSON(w, p)
case http.MethodDelete:
id, _ := strconv.Atoi(r.URL.Query().Get("id"))
if id <= 0 {
http.Error(w, "invalid id", http.StatusBadRequest)
return
}
if err := store.DeleteCreditPackage(ctx, id); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
// ---------- Bot users ----------
func handleBotUsers(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !botStoreReady(w, store) {
return
}
ctx := r.Context()
switch r.Method {
case http.MethodGet:
users, err := store.ListBotUsers(ctx)
if err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
botWriteJSON(w, users)
case http.MethodPost:
var req struct {
TelegramID int64 `json:"telegram_id"`
Action string `json:"action"`
Role string `json:"role"`
LinkedAdminUsername string `json:"linked_admin_username"`
Credits int `json:"credits"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.TelegramID == 0 {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
switch req.Action {
case "set_role":
if req.Role == "" {
req.Role = "customer"
}
req.Role = strings.ToLower(strings.TrimSpace(req.Role))
if req.Role != "customer" && req.Role != "reseller" && req.Role != "blocked" {
http.Error(w, "role must be customer, reseller, or blocked", http.StatusBadRequest)
return
}
req.LinkedAdminUsername = strings.TrimSpace(req.LinkedAdminUsername)
if req.Role == "reseller" {
linked, err := store.GetAdminUserByUsername(ctx, req.LinkedAdminUsername)
if err != nil || linked == nil || linked.Role != RoleReseller {
http.Error(w, "linked reseller account not found", http.StatusBadRequest)
return
}
} else {
req.LinkedAdminUsername = ""
}
if err := store.SetBotUserRole(ctx, req.TelegramID, req.Role, req.LinkedAdminUsername); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
case "block":
if err := store.SetBotUserRole(ctx, req.TelegramID, "blocked", ""); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
case "unblock":
if err := store.SetBotUserRole(ctx, req.TelegramID, "customer", ""); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
case "adjust_credits":
if req.Credits == 0 || req.Credits < -1000000000 || req.Credits > 1000000000 {
http.Error(w, "invalid credit adjustment", http.StatusBadRequest)
return
}
if _, err := store.AdjustCredits(ctx, req.TelegramID, req.Credits, "admin_adjust", nil); err != nil {
http.Error(w, "adjust: "+err.Error(), http.StatusBadRequest)
return
}
default:
http.Error(w, "unknown action", http.StatusBadRequest)
return
}
botWriteJSON(w, map[string]bool{"ok": true})
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
// ---------- Transactions ----------
func handleBotTransactions(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !botStoreReady(w, store) {
return
}
ctx := r.Context()
switch r.Method {
case http.MethodGet:
status := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("status")))
if status != "" && status != "pending" && status != "approved" && status != "expired" && status != "refunded" && status != "error" {
http.Error(w, "invalid status", http.StatusBadRequest)
return
}
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
if limit <= 0 {
limit = 200
}
if limit > 500 {
limit = 500
}
txns, err := store.ListTransactions(ctx, status, limit)
if err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
botWriteJSON(w, txns)
case http.MethodPost:
var req struct {
ID int `json:"id"`
Action string `json:"action"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ID == 0 {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
switch req.Action {
case "refund":
if err := store.SetTransactionStatus(ctx, req.ID, "refunded"); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
case "reprocess":
if b := currentBot(); b != nil {
go b.tryFulfill(req.ID)
} else {
http.Error(w, "bot not running", http.StatusServiceUnavailable)
return
}
default:
http.Error(w, "unknown action", http.StatusBadRequest)
return
}
botWriteJSON(w, map[string]bool{"ok": true})
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
// ---------- Settings (bot texts) ----------
func handleBotSettings(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !botStoreReady(w, store) {
return
}
ctx := r.Context()
switch r.Method {
case http.MethodGet:
all, err := store.AllSettings(ctx)
if err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
botWriteJSON(w, all)
case http.MethodPost:
var kv map[string]string
if err := json.NewDecoder(r.Body).Decode(&kv); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
for k, v := range kv {
maxLen, ok := botSettingKeys[k]
if !ok || len(v) > maxLen || botHasControlCharacters(v) {
http.Error(w, "invalid bot setting", http.StatusBadRequest)
return
}
if k == "app_url" && strings.TrimSpace(v) != "" {
u, err := url.ParseRequestURI(strings.TrimSpace(v))
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
http.Error(w, "app_url must be an http or https URL", http.StatusBadRequest)
return
}
}
if err := store.SetSetting(ctx, k, v); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
}
botWriteJSON(w, map[string]bool{"ok": true})
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
// ---------- Connectivity test ----------
func handleBotTest(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !botStoreReady(w, store) {
return
}
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
ctx := r.Context()
var req struct {
TelegramToken string `json:"telegram_token"`
MPAccessToken string `json:"mp_access_token"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
cfg, _ := LoadBotConfig(ctx, store)
tgToken := strings.TrimSpace(req.TelegramToken)
mpToken := strings.TrimSpace(req.MPAccessToken)
if cfg != nil {
if tgToken == "" {
tgToken = cfg.TelegramToken
}
if mpToken == "" {
mpToken = cfg.MPAccessToken
}
}
out := map[string]interface{}{}
if tgToken != "" {
name, err := newTGClient(tgToken).getMe(ctx)
if err != nil {
out["telegram_ok"] = false
out["telegram_error"] = err.Error()
} else {
out["telegram_ok"] = true
out["telegram_bot"] = "@" + name
}
} else {
out["telegram_ok"] = false
out["telegram_error"] = "no token configured"
}
if mpToken != "" {
_, err := newMPClient(mpToken).do(ctx, http.MethodGet, "/v1/payment_methods", nil, "")
if err != nil {
out["mp_ok"] = false
out["mp_error"] = err.Error()
} else {
out["mp_ok"] = true
}
} else {
out["mp_ok"] = false
out["mp_error"] = "no token configured"
}
botWriteJSON(w, out)
}
}
+152
View File
@@ -0,0 +1,152 @@
package main
// bot_config.go — in-memory bot configuration loaded from the bot_config table.
// Secrets are decrypted here and never persisted in plaintext.
import (
"context"
"errors"
"strconv"
)
var errInsufficientCredits = errors.New("insufficient credits")
func botItoa(n int) string { return strconv.Itoa(n) }
// BotConfig is the decrypted, ready-to-use bot configuration.
// Telegram always uses long-polling (no webhook). The webhook/polling toggle
// applies only to Mercado Pago payment confirmation (MPConfirmMode).
type BotConfig struct {
Enabled bool
TelegramToken string
MPAccessToken string
MPConfirmMode string // webhook | polling
MPWebhookSecret string
MPPollInterval string
PixExpirationMinutes int
TrialEnabled bool
TrialHours int
TrialMaxConnections int
TrialKind string // ssh | xray
TrialInboundTag string
AdminTelegramIDs []int64
Currency string
PublicHost string // SSH connection host shown to buyers
XrayPublicHost string // host used to build vless/vmess links
}
// LoadBotConfig reads the config row and decrypts secrets into a BotConfig.
func LoadBotConfig(ctx context.Context, store *Store) (*BotConfig, error) {
r, err := store.getBotConfigRow(ctx)
if err != nil {
return nil, err
}
tok, err := decryptSecret(r.TelegramTokenEnc)
if err != nil {
return nil, err
}
mp, err := decryptSecret(r.MPAccessTokenEnc)
if err != nil {
return nil, err
}
mpSec, err := decryptSecret(r.MPWebhookSecretEnc)
if err != nil {
return nil, err
}
cfg := &BotConfig{
Enabled: r.Enabled,
TelegramToken: tok,
MPAccessToken: mp,
MPConfirmMode: r.MPConfirmMode,
MPWebhookSecret: mpSec,
MPPollInterval: r.MPPollInterval,
PixExpirationMinutes: r.PixExpirationMinutes,
TrialEnabled: r.TrialEnabled,
TrialHours: r.TrialHours,
TrialMaxConnections: r.TrialMaxConnections,
TrialKind: r.TrialKind,
TrialInboundTag: r.TrialInboundTag,
AdminTelegramIDs: r.AdminTelegramIDs,
Currency: r.Currency,
PublicHost: r.PublicHost,
XrayPublicHost: r.XrayPublicHost,
}
cfg.applyDefaults()
return cfg, nil
}
func (c *BotConfig) applyDefaults() {
if c.MPConfirmMode == "" {
c.MPConfirmMode = "polling"
}
if c.MPPollInterval == "" {
c.MPPollInterval = "20s"
}
if c.PixExpirationMinutes <= 0 {
c.PixExpirationMinutes = 30
}
if c.TrialHours <= 0 {
c.TrialHours = 1
}
if c.TrialMaxConnections <= 0 {
c.TrialMaxConnections = 1
}
if c.TrialKind == "" {
c.TrialKind = "ssh"
}
if c.Currency == "" {
c.Currency = "BRL"
}
}
func (c *BotConfig) isAdmin(telegramID int64) bool {
for _, id := range c.AdminTelegramIDs {
if id == telegramID {
return true
}
}
return false
}
// SaveBotConfig persists a BotConfig. Empty secret fields preserve the stored
// value (nil blob → column left unchanged).
func SaveBotConfig(ctx context.Context, store *Store, cfg *BotConfig) error {
cfg.applyDefaults()
row := &botConfigRow{
Enabled: cfg.Enabled,
TelegramMode: "polling", // Telegram is always long-polling
TelegramWebhookURL: "",
MPConfirmMode: cfg.MPConfirmMode,
MPPollInterval: cfg.MPPollInterval,
PixExpirationMinutes: cfg.PixExpirationMinutes,
TrialEnabled: cfg.TrialEnabled,
TrialHours: cfg.TrialHours,
TrialMaxConnections: cfg.TrialMaxConnections,
TrialKind: cfg.TrialKind,
TrialInboundTag: cfg.TrialInboundTag,
AdminTelegramIDs: cfg.AdminTelegramIDs,
Currency: cfg.Currency,
PublicHost: cfg.PublicHost,
XrayPublicHost: cfg.XrayPublicHost,
}
var tokEnc, mpEnc, mpSecEnc []byte
var err error
if cfg.TelegramToken != "" {
if tokEnc, err = encryptSecret(cfg.TelegramToken); err != nil {
return err
}
}
if cfg.MPAccessToken != "" {
if mpEnc, err = encryptSecret(cfg.MPAccessToken); err != nil {
return err
}
}
if cfg.MPWebhookSecret != "" {
if mpSecEnc, err = encryptSecret(cfg.MPWebhookSecret); err != nil {
return err
}
}
// tgSecEnc is always nil now (no Telegram webhook secret).
return store.saveBotConfigRow(ctx, row, tokEnc, nil, mpEnc, mpSecEnc)
}
+267
View File
@@ -0,0 +1,267 @@
package main
// bot_core.go — Bot lifecycle, Telegram update dispatch, and shared helpers.
import (
"context"
"log"
"strings"
"sync"
"time"
)
// Global bot instance (nil when disabled). Guarded by botMgrMu.
var (
botMgr *Bot
botMgrMu sync.Mutex
)
func currentBot() *Bot {
botMgrMu.Lock()
defer botMgrMu.Unlock()
return botMgr
}
type Bot struct {
store *Store
cfg *BotConfig
tg *tgClient
mp *mpClient
ctx context.Context
cancel context.CancelFunc
}
func newBot(store *Store, cfg *BotConfig) *Bot {
ctx, cancel := context.WithCancel(context.Background())
b := &Bot{
store: store,
cfg: cfg,
tg: newTGClient(cfg.TelegramToken),
ctx: ctx,
cancel: cancel,
}
if cfg.MPAccessToken != "" {
b.mp = newMPClient(cfg.MPAccessToken)
}
return b
}
// ---------- Lifecycle (called from main.go boot and bot_api.go on save) ----------
// startBotService loads config from the DB and starts the bot if enabled.
func startBotService(store *Store) {
if store == nil {
return
}
cfg, err := LoadBotConfig(context.Background(), store)
if err != nil {
log.Printf("[bot] load config: %v", err)
return
}
botMgrMu.Lock()
defer botMgrMu.Unlock()
if botMgr != nil {
botMgr.cancel()
botMgr = nil
}
if !cfg.Enabled {
log.Printf("[bot] disabled")
return
}
if cfg.TelegramToken == "" {
log.Printf("[bot] enabled but no telegram token configured; not starting")
return
}
b := newBot(store, cfg)
botMgr = b
b.start()
}
// reloadBotService restarts the bot after a config change.
func reloadBotService(store *Store) { startBotService(store) }
func (b *Bot) start() {
log.Printf("[bot] starting (telegram=long-polling, mp_confirm=%s)", b.cfg.MPConfirmMode)
// Telegram uses long-polling only. Clearing any stale webhook + polling both
// hit the network, so run off the goroutine that holds botMgrMu.
go func() {
_ = b.tg.deleteWebhook(b.ctx)
b.runPolling()
}()
if b.mp != nil && b.cfg.MPConfirmMode == "polling" {
go b.runPaymentPoller()
}
}
func (b *Bot) stop() { b.cancel() }
// ---------- Update polling ----------
func (b *Bot) runPolling() {
var offset int64
log.Printf("[bot] long-polling started")
for {
select {
case <-b.ctx.Done():
log.Printf("[bot] polling stopped")
return
default:
}
ups, err := b.tg.getUpdates(b.ctx, offset, 50)
if err != nil {
if b.ctx.Err() != nil {
return
}
log.Printf("[bot] getUpdates: %v", err)
time.Sleep(3 * time.Second)
continue
}
for i := range ups {
u := ups[i]
if u.UpdateID >= offset {
offset = u.UpdateID + 1
}
b.handleUpdate(&u)
}
}
}
// ---------- Dispatch ----------
func (b *Bot) handleUpdate(u *tgUpdate) {
defer func() {
if r := recover(); r != nil {
log.Printf("[bot] panic handling update: %v", r)
}
}()
switch {
case u.CallbackQuery != nil:
b.handleCallback(u.CallbackQuery)
case u.Message != nil && u.Message.From != nil:
b.handleMessage(u.Message)
}
}
func (b *Bot) handleMessage(m *tgMessage) {
b.touchUser(m.From)
text := strings.TrimSpace(m.Text)
switch {
case text == "/start" || text == "/menu" || text == "start":
b.showMainMenu(m.Chat.ID, m.From, 0)
case strings.HasPrefix(text, "/stats") && b.cfg.isAdmin(m.From.ID):
b.cmdAdminStats(m.Chat.ID)
case strings.HasPrefix(text, "/addcredit") && b.cfg.isAdmin(m.From.ID):
b.cmdAdminAddCredit(m.Chat.ID, text)
default:
b.showMainMenu(m.Chat.ID, m.From, 0)
}
}
func (b *Bot) handleCallback(cb *tgCallbackQuery) {
b.touchUser(&cb.From)
_ = b.tg.answerCallback(b.ctx, cb.ID, "")
if cb.Message == nil {
return
}
chatID := cb.Message.Chat.ID
msgID := cb.Message.MessageID
data := cb.Data
switch {
case data == "menu:main":
b.showMainMenu(chatID, &cb.From, msgID)
case data == "buy":
b.showPlanList(chatID, msgID, "ssh_or_xray", "buy")
case strings.HasPrefix(data, "buy:"):
b.startPlanPurchase(chatID, &cb.From, data[len("buy:"):], false)
case data == "renew":
b.showRenewList(chatID, &cb.From, msgID)
case strings.HasPrefix(data, "renew:"):
b.startRenew(chatID, &cb.From, msgID, data[len("renew:"):])
case strings.HasPrefix(data, "rnw:"):
b.startRenewPayment(chatID, &cb.From, data[len("rnw:"):])
case data == "trial":
b.handleTrial(chatID, &cb.From)
case data == "purchases":
b.showPurchases(chatID, &cb.From, msgID)
case data == "app":
b.showText(chatID, msgID, "app_text", "📥 App: (configure em bot_settings)")
case data == "contact":
b.showText(chatID, msgID, "contact_text", "👤 Contato: (configure em bot_settings)")
case data == "res:menu":
b.showResellerMenu(chatID, &cb.From, msgID)
case data == "res:topup":
b.showCreditPackages(chatID, msgID)
case strings.HasPrefix(data, "res:topup:"):
b.startTopup(chatID, &cb.From, data[len("res:topup:"):])
case data == "res:create":
b.showPlanList(chatID, msgID, "ssh_or_xray", "res:create")
case strings.HasPrefix(data, "res:create:"):
b.resellerCreateAccount(chatID, &cb.From, data[len("res:create:"):])
case data == "res:clients":
b.showResellerClients(chatID, &cb.From, msgID)
case strings.HasPrefix(data, "pay:check:"):
b.checkPaymentButton(chatID, &cb.From, data[len("pay:check:"):])
default:
// unknown — refresh menu
b.showMainMenu(chatID, &cb.From, msgID)
}
}
// ---------- User helpers ----------
func (b *Bot) touchUser(u *tgUser) {
if u == nil {
return
}
_ = b.store.UpsertBotUser(b.ctx, &BotUser{
TelegramID: u.ID,
Username: u.Username,
FirstName: u.FirstName,
})
}
func (b *Bot) botUser(telegramID int64) *BotUser {
u, err := b.store.GetBotUser(b.ctx, telegramID)
if err != nil {
return &BotUser{TelegramID: telegramID, Role: "customer"}
}
return u
}
// ---------- Message helpers ----------
func (b *Bot) send(chatID int64, text string, kb *tgInlineKeyboard) {
if _, err := b.tg.sendMessage(b.ctx, chatID, text, kb); err != nil {
log.Printf("[bot] sendMessage: %v", err)
}
}
// sendOrEdit edits an existing message if msgID>0, else sends a new one.
func (b *Bot) sendOrEdit(chatID, msgID int64, text string, kb *tgInlineKeyboard) {
if msgID > 0 {
if err := b.tg.editMessageText(b.ctx, chatID, msgID, text, kb); err == nil {
return
}
}
b.send(chatID, text, kb)
}
func (b *Bot) showText(chatID, msgID int64, key, def string) {
txt := b.store.GetSetting(b.ctx, key, def)
b.sendOrEdit(chatID, msgID, txt, backKeyboard())
}
// ---------- Keyboard builders ----------
func kb(rows ...[]tgInlineButton) *tgInlineKeyboard {
return &tgInlineKeyboard{InlineKeyboard: rows}
}
func btn(text, data string) tgInlineButton { return tgInlineButton{Text: text, CallbackData: data} }
func urlBtn(text, u string) tgInlineButton { return tgInlineButton{Text: text, URL: u} }
func backKeyboard() *tgInlineKeyboard {
return kb([]tgInlineButton{btn("⬅️ Voltar", "menu:main")})
}
+151
View File
@@ -0,0 +1,151 @@
package main
// bot_crypto.go — secret encryption for the Telegram/Mercado Pago bot.
//
// Bot tokens (Telegram bot token, Mercado Pago access token, webhook secrets)
// are stored in PostgreSQL encrypted with AES-256-GCM. The 32-byte master key
// lives OUTSIDE the database, so a DB dump alone never reveals the secrets:
// 1) env BOT_MASTER_KEY (64 hex chars), if set; otherwise
// 2) a 0600 key file next to config.json (bot_master.key); otherwise
// 3) generated with crypto/rand on first use and written to that key file.
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
)
var (
botKeyOnce sync.Once
botKey []byte
botKeyErr error
)
// botMasterKeyPath returns the on-disk location of the AES master key.
func botMasterKeyPath() string {
if globalCfgPath != "" {
return filepath.Join(filepath.Dir(globalCfgPath), "bot_master.key")
}
return "/opt/sshpanel/bot_master.key"
}
// loadBotMasterKey resolves the 32-byte master key (env → file → generate).
func loadBotMasterKey() ([]byte, error) {
botKeyOnce.Do(func() {
if env := strings.TrimSpace(os.Getenv("BOT_MASTER_KEY")); env != "" {
k, err := hex.DecodeString(env)
if err != nil {
botKeyErr = fmt.Errorf("BOT_MASTER_KEY invalid hex: %w", err)
return
}
if len(k) != 32 {
botKeyErr = fmt.Errorf("BOT_MASTER_KEY must be 32 bytes (64 hex chars), got %d", len(k))
return
}
botKey = k
return
}
path := botMasterKeyPath()
data, err := os.ReadFile(path)
if err == nil {
k, derr := hex.DecodeString(strings.TrimSpace(string(data)))
if derr == nil && len(k) == 32 {
botKey = k
return
}
// Refuse to overwrite a bad key file — overwriting would make
// existing ciphertext undecryptable and silently lose secrets.
botKeyErr = fmt.Errorf("bot master key file %s is invalid; refusing to overwrite", path)
return
}
if !errors.Is(err, os.ErrNotExist) {
botKeyErr = fmt.Errorf("read bot master key: %w", err)
return
}
k := make([]byte, 32)
if _, e := rand.Read(k); e != nil {
botKeyErr = fmt.Errorf("generate bot master key: %w", e)
return
}
if e := os.WriteFile(path, []byte(hex.EncodeToString(k)), 0o600); e != nil {
botKeyErr = fmt.Errorf("write bot master key %s: %w", path, e)
return
}
botKey = k
})
return botKey, botKeyErr
}
// encryptSecret encrypts a plaintext secret. Empty input returns nil (no blob).
func encryptSecret(plain string) ([]byte, error) {
if plain == "" {
return nil, nil
}
key, err := loadBotMasterKey()
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
// Output is nonce || ciphertext(+tag).
return gcm.Seal(nonce, nonce, []byte(plain), nil), nil
}
// decryptSecret reverses encryptSecret. Empty/nil input returns "".
func decryptSecret(enc []byte) (string, error) {
if len(enc) == 0 {
return "", nil
}
key, err := loadBotMasterKey()
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
if len(enc) < gcm.NonceSize() {
return "", fmt.Errorf("ciphertext too short")
}
nonce, ct := enc[:gcm.NonceSize()], enc[gcm.NonceSize():]
pt, err := gcm.Open(nil, nonce, ct, nil)
if err != nil {
return "", fmt.Errorf("decrypt secret: %w", err)
}
return string(pt), nil
}
// maskSecret returns a log-safe representation of a secret.
func maskSecret(s string) string {
if s == "" {
return "(empty)"
}
if len(s) <= 6 {
return "***"
}
return s[:3] + "***" + s[len(s)-2:]
}
+511
View File
@@ -0,0 +1,511 @@
package main
// bot_flows.go — customer + reseller conversation flows and admin commands.
import (
"encoding/base64"
"fmt"
"log"
"strconv"
"strings"
"time"
)
// ---------- Main menu ----------
func (b *Bot) showMainMenu(chatID int64, from *tgUser, msgID int64) {
bu := b.botUser(from.ID)
if bu.Role == "blocked" {
b.sendOrEdit(chatID, msgID, "🚫 Seu acesso foi bloqueado.", nil)
return
}
welcome := b.store.GetSetting(b.ctx, "welcome_text", "")
var text string
if welcome != "" {
text = strings.ReplaceAll(welcome, "{name}", htmlEscape(from.FirstName))
} else {
text = fmt.Sprintf("😉 Olá <b>%s</b>, seja bem-vindo!\n\n🚀 Aqui você encontra os melhores planos <b>SSH</b> e <b>Xray</b> Premium.\nSelecione uma das opções abaixo:", htmlEscape(from.FirstName))
}
var rows [][]tgInlineButton
if b.cfg.TrialEnabled {
rows = append(rows, []tgInlineButton{btn("⏳ Teste Grátis", "trial"), btn("🛍️ Minhas Compras", "purchases")})
} else {
rows = append(rows, []tgInlineButton{btn("🛍️ Minhas Compras", "purchases")})
}
rows = append(rows, []tgInlineButton{btn("💎 Comprar Premium", "buy")})
rows = append(rows, []tgInlineButton{btn("🔄 Renovar", "renew")})
appURL := b.store.GetSetting(b.ctx, "app_url", "")
appRow := []tgInlineButton{}
if appURL != "" {
appRow = append(appRow, urlBtn("📥 Baixar APP", appURL))
} else {
appRow = append(appRow, btn("📥 Baixar APP", "app"))
}
appRow = append(appRow, btn("👤 Contato", "contact"))
rows = append(rows, appRow)
if bu.Role == "reseller" {
rows = append(rows, []tgInlineButton{btn("👑 Área do Revendedor", "res:menu")})
}
b.sendOrEdit(chatID, msgID, text, kb(rows...))
}
// ---------- Plan list (buy / reseller create) ----------
func (b *Bot) showPlanList(chatID, msgID int64, _ string, action string) {
plans, err := b.store.ListPlans(b.ctx, true)
if err != nil || len(plans) == 0 {
b.sendOrEdit(chatID, msgID, "Nenhum plano disponível no momento.", backKeyboard())
return
}
isReseller := action == "res:create"
var rows [][]tgInlineButton
for _, p := range plans {
icon := "🔒"
if p.Kind == "xray" {
icon = "⚡"
}
var label string
if isReseller {
label = fmt.Sprintf("%s %s — %d créd.", icon, p.Name, p.CreditCost)
} else {
label = fmt.Sprintf("%s %s — %s", icon, p.Name, centsToBRL(p.PriceCents))
}
rows = append(rows, []tgInlineButton{btn(label, action+":"+botItoa(p.ID))})
}
rows = append(rows, []tgInlineButton{btn("⬅️ Voltar", backTarget(action))})
title := "💎 Escolha um plano:"
if isReseller {
title = "➕ Escolha um plano para criar (custo em créditos):"
}
b.sendOrEdit(chatID, msgID, title, kb(rows...))
}
func backTarget(action string) string {
if strings.HasPrefix(action, "res:") {
return "res:menu"
}
return "menu:main"
}
// ---------- Buy ----------
func (b *Bot) startPlanPurchase(chatID int64, from *tgUser, planIDStr string, _ bool) {
id, _ := strconv.Atoi(planIDStr)
p, err := b.store.GetPlan(b.ctx, id)
if err != nil {
b.send(chatID, "Plano não encontrado.", backKeyboard())
return
}
pid := p.ID
b.createAndSendPix(chatID, from, "plan_purchase", "Compra: "+p.Name, p.PriceCents, &pid, nil, 0, "")
}
// ---------- Renew ----------
func (b *Bot) showRenewList(chatID int64, from *tgUser, msgID int64) {
txns, _ := b.store.ListUserTransactions(b.ctx, from.ID, 100)
seen := map[string]bool{}
var rows [][]tgInlineButton
for _, t := range txns {
if t.Status != "approved" || t.TargetUsername == "" || t.PlanID == nil {
continue
}
p, err := b.store.GetPlan(b.ctx, *t.PlanID)
if err != nil {
continue
}
key := p.Kind + ":" + t.TargetUsername
if seen[key] {
continue
}
seen[key] = true
short := "s"
if p.Kind == "xray" {
short = "x"
}
disp := t.TargetUsername
if len(disp) > 16 {
disp = disp[:8] + "…"
}
rows = append(rows, []tgInlineButton{btn("🔄 "+disp+" ("+p.Kind+")", "renew:"+short+":"+t.TargetUsername)})
}
if len(rows) == 0 {
b.sendOrEdit(chatID, msgID, "Você não tem contas para renovar.", backKeyboard())
return
}
rows = append(rows, []tgInlineButton{btn("⬅️ Voltar", "menu:main")})
b.sendOrEdit(chatID, msgID, "🔄 Selecione a conta para renovar:", kb(rows...))
}
func (b *Bot) startRenew(chatID int64, from *tgUser, msgID int64, target string) {
kind := "ssh"
if strings.HasPrefix(target, "x:") {
kind = "xray"
}
plans, _ := b.store.ListPlans(b.ctx, true)
var rows [][]tgInlineButton
for _, p := range plans {
if p.Kind != kind {
continue
}
label := fmt.Sprintf("%s — %s", p.Name, centsToBRL(p.PriceCents))
rows = append(rows, []tgInlineButton{btn(label, "rnw:"+botItoa(p.ID)+":"+target)})
}
if len(rows) == 0 {
b.sendOrEdit(chatID, msgID, "Nenhum plano de renovação disponível.", backKeyboard())
return
}
rows = append(rows, []tgInlineButton{btn("⬅️ Voltar", "renew")})
b.sendOrEdit(chatID, msgID, "🔄 Escolha a duração da renovação:", kb(rows...))
}
func (b *Bot) startRenewPayment(chatID int64, from *tgUser, payload string) {
parts := strings.SplitN(payload, ":", 3)
if len(parts) < 3 {
b.send(chatID, "Renovação inválida.", backKeyboard())
return
}
id, _ := strconv.Atoi(parts[0])
renewTarget := parts[1] + ":" + parts[2] // "s:username" or "x:uuid"
p, err := b.store.GetPlan(b.ctx, id)
if err != nil {
b.send(chatID, "Plano não encontrado.", backKeyboard())
return
}
pid := p.ID
b.createAndSendPix(chatID, from, "plan_renewal", "Renovação: "+p.Name, p.PriceCents, &pid, nil, 0, renewTarget)
}
// ---------- Trial ----------
func (b *Bot) handleTrial(chatID int64, from *tgUser) {
if !b.cfg.TrialEnabled {
b.send(chatID, "Teste grátis indisponível.", backKeyboard())
return
}
bu := b.botUser(from.ID)
if bu.TrialUsed {
b.send(chatID, "⚠️ Você já utilizou seu teste grátis.", backKeyboard())
return
}
exp := time.Now().Add(time.Duration(b.cfg.TrialHours) * time.Hour)
if b.cfg.TrialKind == "xray" {
uuid, link, err := createXrayClient(b.ctx, b.store, b.cfg.TrialInboundTag, "", exp, b.cfg.TrialMaxConnections, "", b.cfg.XrayPublicHost)
if err != nil {
log.Printf("[bot] trial xray: %v", err)
b.send(chatID, "❌ Falha ao criar teste. Tente mais tarde.", backKeyboard())
return
}
_ = b.store.SetBotUserTrialUsed(b.ctx, from.ID)
b.send(chatID, b.formatXrayDelivery("Teste Grátis", uuid, link, exp), backKeyboard())
return
}
user := genUsername("test")
pass := genPassword()
if err := createSSHUser(b.ctx, b.store, user, pass, exp, b.cfg.TrialMaxConnections, 0, 0, ""); err != nil {
log.Printf("[bot] trial ssh: %v", err)
b.send(chatID, "❌ Falha ao criar teste. Tente mais tarde.", backKeyboard())
return
}
_ = b.store.SetBotUserTrialUsed(b.ctx, from.ID)
b.send(chatID, b.formatSSHDelivery("Teste Grátis", user, pass, exp), backKeyboard())
}
// ---------- Purchases ----------
func (b *Bot) showPurchases(chatID int64, from *tgUser, msgID int64) {
txns, _ := b.store.ListUserTransactions(b.ctx, from.ID, 20)
var sb strings.Builder
sb.WriteString("🛍️ <b>Suas Compras</b>\n\n")
count := 0
for _, t := range txns {
if t.Status == "pending" {
continue
}
count++
sb.WriteString(fmt.Sprintf("• #%d %s — %s — %s\n", t.ID, txnTypeLabel(t.Type), centsToBRL(t.AmountCents), statusLabel(t.Status)))
if t.TargetUsername != "" && t.Status == "approved" {
sb.WriteString(" conta: <code>" + htmlEscape(t.TargetUsername) + "</code>\n")
}
}
if count == 0 {
sb.WriteString("Nenhuma compra ainda.")
}
b.sendOrEdit(chatID, msgID, sb.String(), backKeyboard())
}
// ---------- Reseller ----------
func (b *Bot) showResellerMenu(chatID int64, from *tgUser, msgID int64) {
bu := b.botUser(from.ID)
if bu.Role != "reseller" {
b.sendOrEdit(chatID, msgID, "Você não é um revendedor.", backKeyboard())
return
}
text := fmt.Sprintf("👑 <b>Área do Revendedor</b>\n\n💳 Saldo: <b>%d créditos</b>", bu.CreditBalance)
rows := [][]tgInlineButton{
{btn("💳 Recarregar Créditos", "res:topup")},
{btn("➕ Criar Conta", "res:create")},
{btn("👥 Meus Clientes", "res:clients")},
{btn("⬅️ Voltar", "menu:main")},
}
b.sendOrEdit(chatID, msgID, text, kb(rows...))
}
func (b *Bot) showCreditPackages(chatID, msgID int64) {
pkgs, _ := b.store.ListCreditPackages(b.ctx, true)
if len(pkgs) == 0 {
b.sendOrEdit(chatID, msgID, "Nenhum pacote de créditos disponível.", kb([]tgInlineButton{btn("⬅️ Voltar", "res:menu")}))
return
}
var rows [][]tgInlineButton
for _, p := range pkgs {
rows = append(rows, []tgInlineButton{btn(fmt.Sprintf("%s — %d créd. — %s", p.Name, p.Credits, centsToBRL(p.PriceCents)), "res:topup:"+botItoa(p.ID))})
}
rows = append(rows, []tgInlineButton{btn("⬅️ Voltar", "res:menu")})
b.sendOrEdit(chatID, msgID, "💳 Escolha um pacote de créditos:", kb(rows...))
}
func (b *Bot) startTopup(chatID int64, from *tgUser, pkgIDStr string) {
id, _ := strconv.Atoi(pkgIDStr)
p, err := b.store.GetCreditPackage(b.ctx, id)
if err != nil {
b.send(chatID, "Pacote não encontrado.", backKeyboard())
return
}
pid := p.ID
b.createAndSendPix(chatID, from, "credit_topup", "Recarga: "+p.Name, p.PriceCents, nil, &pid, p.Credits, "")
}
func (b *Bot) resellerCreateAccount(chatID int64, from *tgUser, planIDStr string) {
bu := b.botUser(from.ID)
if bu.Role != "reseller" || bu.LinkedAdminUsername == "" {
b.send(chatID, "Conta de revendedor não configurada.", backKeyboard())
return
}
id, _ := strconv.Atoi(planIDStr)
p, err := b.store.GetPlan(b.ctx, id)
if err != nil {
b.send(chatID, "Plano não encontrado.", backKeyboard())
return
}
if bu.CreditBalance < p.CreditCost {
b.send(chatID, fmt.Sprintf("❌ Saldo insuficiente. Necessário %d créditos, você tem %d.", p.CreditCost, bu.CreditBalance),
kb([]tgInlineButton{btn("💳 Recarregar", "res:topup"), btn("⬅️ Voltar", "res:menu")}))
return
}
if owner, ok := adminUsers.get(bu.LinkedAdminUsername); ok && owner.MaxUsers > 0 &&
countOwnedQuota(b.ctx, b.store, bu.LinkedAdminUsername) >= owner.MaxUsers {
b.send(chatID, fmt.Sprintf("❌ Limite de contas atingido (%d).", owner.MaxUsers), backKeyboard())
return
}
// Debit first; refund if provisioning fails.
if _, err := b.store.AdjustCredits(b.ctx, from.ID, -p.CreditCost, "account_create", nil); err != nil {
b.send(chatID, "❌ Não foi possível debitar créditos.", backKeyboard())
return
}
exp := time.Now().Add(time.Duration(p.Days) * 24 * time.Hour)
var deliver string
if p.Kind == "xray" {
uuid, link, err := createXrayClient(b.ctx, b.store, p.XrayInboundTag, p.XrayProtocol, exp, p.MaxConnections, bu.LinkedAdminUsername, b.cfg.XrayPublicHost)
if err != nil {
_, _ = b.store.AdjustCredits(b.ctx, from.ID, p.CreditCost, "refund", nil)
b.send(chatID, "❌ Falha ao criar conta Xray. Créditos devolvidos.", backKeyboard())
return
}
deliver = b.formatXrayDelivery(p.Name, uuid, link, exp)
} else {
user := genUsername("r")
pass := genPassword()
if err := createSSHUser(b.ctx, b.store, user, pass, exp, p.MaxConnections, p.LimitMbpsUp, p.LimitMbpsDown, bu.LinkedAdminUsername); err != nil {
_, _ = b.store.AdjustCredits(b.ctx, from.ID, p.CreditCost, "refund", nil)
b.send(chatID, "❌ Falha ao criar conta SSH. Créditos devolvidos.", backKeyboard())
return
}
deliver = b.formatSSHDelivery(p.Name, user, pass, exp)
}
b.send(chatID, deliver+fmt.Sprintf("\n\n💳 Saldo restante: %d créditos", bu.CreditBalance-p.CreditCost),
kb([]tgInlineButton{btn("➕ Criar outra", "res:create"), btn("⬅️ Voltar", "res:menu")}))
}
func (b *Bot) showResellerClients(chatID int64, from *tgUser, msgID int64) {
bu := b.botUser(from.ID)
if bu.Role != "reseller" || bu.LinkedAdminUsername == "" {
b.sendOrEdit(chatID, msgID, "Conta de revendedor não configurada.", backKeyboard())
return
}
var sb strings.Builder
sb.WriteString("👥 <b>Seus Clientes</b>\n\n")
n := 0
for _, u := range userMgr.List() {
if u.Cfg.OwnerUsername == bu.LinkedAdminUsername {
n++
exp := "sem validade"
if u.ExpiresAt != nil {
exp = u.ExpiresAt.Format("02/01/2006")
}
sb.WriteString(fmt.Sprintf("• SSH <code>%s</code> — %s\n", htmlEscape(u.Cfg.Username), exp))
if n >= 40 {
break
}
}
}
xs, _ := b.store.ListXrayClientsByOwner(b.ctx, bu.LinkedAdminUsername)
for _, x := range xs {
n++
exp := "sem validade"
if x.ExpiresAt != nil {
exp = x.ExpiresAt.Format("02/01/2006")
}
sb.WriteString(fmt.Sprintf("• Xray <code>%s</code> — %s\n", htmlEscape(x.UUID), exp))
if n >= 80 {
break
}
}
if n == 0 {
sb.WriteString("Nenhum cliente ainda.")
}
b.sendOrEdit(chatID, msgID, sb.String(), kb([]tgInlineButton{btn("⬅️ Voltar", "res:menu")}))
}
// ---------- PIX charge creation + delivery formatting ----------
func (b *Bot) createAndSendPix(chatID int64, from *tgUser, ttype, description string, amountCents int, planID, pkgID *int, credits int, renewTarget string) {
if amountCents <= 0 {
b.send(chatID, "❌ Este item não tem preço configurado. Fale com o suporte.", backKeyboard())
return
}
if b.mp == nil {
b.send(chatID, "❌ Pagamento não configurado no momento. Fale com o suporte.", backKeyboard())
return
}
exp := time.Now().Add(time.Duration(b.cfg.PixExpirationMinutes) * time.Minute)
pix, err := b.mp.CreatePixPayment(b.ctx, amountCents, description, "", strconv.FormatInt(from.ID, 10), exp, uuidV4())
if err != nil {
log.Printf("[bot] create pix: %v", err)
b.send(chatID, "❌ Falha ao gerar o pagamento PIX. Tente novamente em instantes.", backKeyboard())
return
}
txn := &BotTransaction{
TelegramID: from.ID,
Type: ttype,
PlanID: planID,
PackageID: pkgID,
Credits: credits,
AmountCents: amountCents,
MPPaymentID: pix.PaymentID,
MPQRCode: pix.QRCode,
MPQRBase64: pix.QRBase64,
Status: "pending",
RenewTarget: renewTarget,
ExpiresAt: &exp,
}
if err := b.store.CreateTransaction(b.ctx, txn); err != nil {
log.Printf("[bot] create txn: %v", err)
b.send(chatID, "❌ Erro interno ao registrar o pagamento.", backKeyboard())
return
}
b.sendPixMessage(chatID, txn, description)
}
func (b *Bot) sendPixMessage(chatID int64, txn *BotTransaction, description string) {
caption := fmt.Sprintf("💳 <b>Pagamento PIX</b>\n%s\nValor: <b>%s</b>\n⏱ Validade: %d min\n\nEscaneie o QR acima ou use o código copia-e-cola abaixo. A liberação é automática após o pagamento.",
htmlEscape(description), centsToBRL(txn.AmountCents), b.cfg.PixExpirationMinutes)
kbd := kb(
[]tgInlineButton{btn("✅ Já paguei / Verificar", "pay:check:"+botItoa(txn.ID))},
[]tgInlineButton{btn("⬅️ Voltar", "menu:main")},
)
sent := false
if txn.MPQRBase64 != "" {
if raw, err := base64.StdEncoding.DecodeString(txn.MPQRBase64); err == nil {
if _, err := b.tg.sendPhotoBytes(b.ctx, chatID, raw, "pix.png", caption, kbd); err == nil {
sent = true
}
}
}
if !sent {
b.send(chatID, caption, kbd)
}
if txn.MPQRCode != "" {
b.send(chatID, "📋 <b>PIX Copia e Cola:</b>\n<code>"+htmlEscape(txn.MPQRCode)+"</code>", nil)
}
}
func (b *Bot) formatSSHDelivery(planName, user, pass string, exp time.Time) string {
host := b.cfg.PublicHost
if host == "" {
host = "(configure o host no painel)"
}
return fmt.Sprintf("✅ <b>%s</b>\n\n🔒 <b>Conta SSH</b>\nHost: <code>%s</code>\nUsuário: <code>%s</code>\nSenha: <code>%s</code>\nValidade: %s",
htmlEscape(planName), htmlEscape(host), htmlEscape(user), htmlEscape(pass), exp.Format("02/01/2006 15:04"))
}
func (b *Bot) formatXrayDelivery(planName, uuid, link string, exp time.Time) string {
return fmt.Sprintf("✅ <b>%s</b>\n\n⚡ <b>Conta Xray</b>\nUUID: <code>%s</code>\nValidade: %s\n\n🔗 Link de conexão:\n<code>%s</code>",
htmlEscape(planName), htmlEscape(uuid), exp.Format("02/01/2006 15:04"), htmlEscape(link))
}
// ---------- Admin commands (in-chat convenience) ----------
func (b *Bot) cmdAdminStats(chatID int64) {
users, _ := b.store.ListBotUsers(b.ctx)
pend, _ := b.store.ListPendingTransactions(b.ctx)
b.send(chatID, fmt.Sprintf("📊 <b>Estatísticas</b>\nUsuários do bot: %d\nPagamentos pendentes: %d\nContas SSH ativas: %d",
len(users), len(pend), len(userMgr.List())), nil)
}
func (b *Bot) cmdAdminAddCredit(chatID int64, text string) {
f := strings.Fields(text)
if len(f) < 3 {
b.send(chatID, "Uso: /addcredit &lt;telegram_id&gt; &lt;quantidade&gt;", nil)
return
}
tid, _ := strconv.ParseInt(f[1], 10, 64)
amt, _ := strconv.Atoi(f[2])
bal, err := b.store.AdjustCredits(b.ctx, tid, amt, "admin_adjust", nil)
if err != nil {
b.send(chatID, "Erro: "+err.Error(), nil)
return
}
b.send(chatID, fmt.Sprintf("✅ Ajuste aplicado. Novo saldo de %d: %d créditos", tid, bal), nil)
b.notify(tid, fmt.Sprintf("💳 Seu saldo foi ajustado em %+d créditos. Saldo atual: %d", amt, bal))
}
func (b *Bot) notify(telegramID int64, text string) {
if _, err := b.tg.sendMessage(b.ctx, telegramID, text, nil); err != nil {
log.Printf("[bot] notify %d: %v", telegramID, err)
}
}
// ---------- labels ----------
func txnTypeLabel(t string) string {
switch t {
case "plan_purchase":
return "Compra"
case "plan_renewal":
return "Renovação"
case "credit_topup":
return "Recarga"
}
return t
}
func statusLabel(s string) string {
switch s {
case "approved":
return "✅ pago"
case "pending":
return "⏳ pendente"
case "expired":
return "⌛ expirado"
case "refunded":
return "↩️ estornado"
case "error":
return "❌ erro"
}
return s
}
+242
View File
@@ -0,0 +1,242 @@
package main
// bot_mercadopago.go — Mercado Pago PIX client + inbound webhook handler.
// Built on net/http; no third-party dependency.
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strconv"
"strings"
"time"
)
const mpAPIBase = "https://api.mercadopago.com"
type mpClient struct {
accessToken string
hc *http.Client
}
func newMPClient(accessToken string) *mpClient {
return &mpClient{accessToken: accessToken, hc: &http.Client{Timeout: 25 * time.Second}}
}
// mpPixResult holds what the bot needs to show the buyer.
type mpPixResult struct {
PaymentID string
QRCode string // copy-and-paste PIX string
QRBase64 string // PNG image, base64 (no data: prefix)
Status string
}
// CreatePixPayment creates a PIX charge and returns the QR data.
// amountCents is BRL cents; expiresAt bounds the QR validity.
func (c *mpClient) CreatePixPayment(ctx context.Context, amountCents int, description, payerEmail, externalRef string, expiresAt time.Time, idempotencyKey string) (*mpPixResult, error) {
if payerEmail == "" {
payerEmail = "comprador@example.com"
}
body := map[string]interface{}{
"transaction_amount": float64(amountCents) / 100.0,
"description": description,
"payment_method_id": "pix",
"payer": map[string]interface{}{"email": payerEmail},
"date_of_expiration": expiresAt.Format("2006-01-02T15:04:05.000-07:00"),
"external_reference": externalRef,
}
raw, err := c.do(ctx, http.MethodPost, "/v1/payments", body, idempotencyKey)
if err != nil {
return nil, err
}
var resp struct {
ID json.Number `json:"id"`
Status string `json:"status"`
PointOfInteraction struct {
TransactionData struct {
QRCode string `json:"qr_code"`
QRCodeBase64 string `json:"qr_code_base64"`
} `json:"transaction_data"`
} `json:"point_of_interaction"`
}
if err := json.Unmarshal(raw, &resp); err != nil {
return nil, fmt.Errorf("mp create payment: parse: %w", err)
}
if resp.ID.String() == "" {
return nil, fmt.Errorf("mp create payment: no id in response: %s", string(raw))
}
return &mpPixResult{
PaymentID: resp.ID.String(),
QRCode: resp.PointOfInteraction.TransactionData.QRCode,
QRBase64: resp.PointOfInteraction.TransactionData.QRCodeBase64,
Status: resp.Status,
}, nil
}
// GetPaymentStatus returns the current status of a payment (e.g. "approved").
func (c *mpClient) GetPaymentStatus(ctx context.Context, paymentID string) (string, error) {
raw, err := c.do(ctx, http.MethodGet, "/v1/payments/"+paymentID, nil, "")
if err != nil {
return "", err
}
var resp struct {
Status string `json:"status"`
}
if err := json.Unmarshal(raw, &resp); err != nil {
return "", err
}
return resp.Status, nil
}
func (c *mpClient) do(ctx context.Context, method, path string, body interface{}, idempotencyKey string) ([]byte, error) {
var rdr io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
rdr = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, mpAPIBase+path, rdr)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
req.Header.Set("Content-Type", "application/json")
if idempotencyKey != "" {
req.Header.Set("X-Idempotency-Key", idempotencyKey)
}
resp, err := c.hc.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if resp.StatusCode >= 300 {
return nil, fmt.Errorf("mercado pago %s %s: http %d: %s", method, path, resp.StatusCode, string(data))
}
return data, nil
}
// verifyMPSignature validates the x-signature header per Mercado Pago's spec.
// Manifest: "id:<dataID>;request-id:<x-request-id>;ts:<ts>;" HMAC-SHA256(secret).
func verifyMPSignature(xSignature, xRequestID, dataID, secret string) bool {
if secret == "" {
return false
}
var ts, v1 string
for _, part := range strings.Split(xSignature, ",") {
kv := strings.SplitN(strings.TrimSpace(part), "=", 2)
if len(kv) != 2 {
continue
}
switch strings.TrimSpace(kv[0]) {
case "ts":
ts = strings.TrimSpace(kv[1])
case "v1":
v1 = strings.TrimSpace(kv[1])
}
}
if ts == "" || v1 == "" {
return false
}
if timestamp, err := strconv.ParseInt(ts, 10, 64); err != nil || timestamp <= 0 {
return false
}
parts := make([]string, 0, 3)
if dataID != "" {
parts = append(parts, "id:"+strings.ToLower(dataID))
}
if xRequestID != "" {
parts = append(parts, "request-id:"+xRequestID)
}
parts = append(parts, "ts:"+ts)
manifest := strings.Join(parts, ";") + ";"
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(manifest))
expected := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(expected), []byte(v1))
}
// handleMPWebhook is the public endpoint Mercado Pago calls on payment events.
// It never trusts the body: it re-fetches the payment and fulfills idempotently.
func handleMPWebhook(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
b := currentBot()
if b == nil {
w.WriteHeader(http.StatusOK) // bot disabled; acknowledge to stop retries
return
}
// Only honor webhooks when confirmation mode is "webhook". In polling mode
// the poller drives fulfillment; ignore unsolicited posts to this endpoint.
if b.cfg.MPConfirmMode != "webhook" {
w.WriteHeader(http.StatusOK)
return
}
// Extract the payment id from body or query.
dataID := r.URL.Query().Get("data.id")
if dataID == "" {
dataID = r.URL.Query().Get("id")
}
signatureDataID := dataID
var payload struct {
Type string `json:"type"`
Action string `json:"action"`
Data struct {
ID json.Number `json:"id"`
} `json:"data"`
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "invalid webhook body", http.StatusRequestEntityTooLarge)
return
}
if len(body) > 0 {
_ = json.Unmarshal(body, &payload)
if dataID == "" {
dataID = payload.Data.ID.String()
}
}
if dataID == "" {
w.WriteHeader(http.StatusOK)
return
}
if len(dataID) > 32 {
w.WriteHeader(http.StatusBadRequest)
return
}
for _, char := range dataID {
if char < '0' || char > '9' {
w.WriteHeader(http.StatusBadRequest)
return
}
}
if !verifyMPSignature(r.Header.Get("x-signature"), r.Header.Get("x-request-id"), signatureDataID, b.cfg.MPWebhookSecret) {
log.Printf("[bot] MP webhook: invalid signature for payment %s", dataID)
w.WriteHeader(http.StatusUnauthorized)
return
}
// Acknowledge immediately; process in the background so MP doesn't time out.
go b.processPaymentByMPID(dataID)
w.WriteHeader(http.StatusOK)
}
// centsToBRL formats cents as "R$ 12,34".
func centsToBRL(cents int) string {
reais := cents / 100
cent := cents % 100
return "R$ " + strconv.Itoa(reais) + "," + fmt.Sprintf("%02d", cent)
}
+237
View File
@@ -0,0 +1,237 @@
package main
// bot_payments.go — payment polling, webhook processing, and idempotent delivery.
import (
"fmt"
"log"
"strconv"
"strings"
"time"
)
// ---------- Polling mode ----------
func (b *Bot) runPaymentPoller() {
d, err := time.ParseDuration(b.cfg.MPPollInterval)
if err != nil || d < 5*time.Second {
d = 20 * time.Second
}
t := time.NewTicker(d)
defer t.Stop()
log.Printf("[bot] payment poller started (interval=%s)", d)
for {
select {
case <-b.ctx.Done():
log.Printf("[bot] payment poller stopped")
return
case <-t.C:
b.pollPending()
}
}
}
func (b *Bot) pollPending() {
txns, err := b.store.ListPendingTransactions(b.ctx)
if err != nil {
log.Printf("[bot] poll list: %v", err)
return
}
now := time.Now()
for _, txn := range txns {
if txn.ExpiresAt != nil && now.After(*txn.ExpiresAt) {
_ = b.store.SetTransactionStatus(b.ctx, txn.ID, "expired")
b.notify(txn.TelegramID, fmt.Sprintf("⌛ O PIX do pedido #%d expirou. Gere um novo pagamento se ainda quiser.", txn.ID))
continue
}
if b.mp == nil {
continue
}
status, err := b.mp.GetPaymentStatus(b.ctx, txn.MPPaymentID)
if err != nil {
continue
}
if status == "approved" {
b.tryFulfill(txn.ID)
}
}
}
// ---------- Webhook mode ----------
// processPaymentByMPID is invoked from the Mercado Pago webhook handler.
func (b *Bot) processPaymentByMPID(mpID string) {
txn, err := b.store.GetTransactionByMPID(b.ctx, mpID)
if err != nil {
log.Printf("[bot] webhook: no txn for mp payment %s: %v", mpID, err)
return
}
if b.mp == nil {
return
}
status, err := b.mp.GetPaymentStatus(b.ctx, mpID)
if err != nil {
log.Printf("[bot] webhook: get status %s: %v", mpID, err)
return
}
if status == "approved" {
b.tryFulfill(txn.ID)
}
}
// ---------- Idempotent fulfillment ----------
// tryFulfill flips the txn to approved exactly once, then delivers.
func (b *Bot) tryFulfill(txnID int) {
ok, err := b.store.MarkTransactionApproved(b.ctx, txnID)
if err != nil {
log.Printf("[bot] mark approved %d: %v", txnID, err)
return
}
if !ok {
return // already fulfilled by another path
}
txn, err := b.store.GetTransaction(b.ctx, txnID)
if err != nil {
log.Printf("[bot] fulfill get txn %d: %v", txnID, err)
return
}
b.fulfillTransaction(txn)
}
func (b *Bot) fulfillTransaction(txn *BotTransaction) {
switch txn.Type {
case "credit_topup":
bal, err := b.store.AdjustCredits(b.ctx, txn.TelegramID, txn.Credits, "topup", &txn.ID)
if err != nil {
log.Printf("[bot] topup credit %d: %v", txn.ID, err)
b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao creditar. Contate o suporte.")
return
}
b.notify(txn.TelegramID, fmt.Sprintf("✅ Recarga aprovada! +%d créditos.\n💳 Saldo atual: %d créditos.", txn.Credits, bal))
case "plan_renewal":
b.fulfillRenewal(txn)
default:
b.fulfillPurchase(txn)
}
}
func (b *Bot) fulfillPurchase(txn *BotTransaction) {
if txn.PlanID == nil {
return
}
p, err := b.store.GetPlan(b.ctx, *txn.PlanID)
if err != nil {
log.Printf("[bot] fulfill purchase: plan %v: %v", txn.PlanID, err)
b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas o plano não foi encontrado. Contate o suporte.")
return
}
exp := time.Now().Add(time.Duration(p.Days) * 24 * time.Hour)
if p.Kind == "xray" {
uuid, link, err := createXrayClient(b.ctx, b.store, p.XrayInboundTag, p.XrayProtocol, exp, p.MaxConnections, "", b.cfg.XrayPublicHost)
if err != nil {
log.Printf("[bot] fulfill xray: %v", err)
b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao criar a conta Xray. Contate o suporte.")
return
}
_ = b.store.SetTransactionTarget(b.ctx, txn.ID, uuid)
b.notify(txn.TelegramID, b.formatXrayDelivery(p.Name, uuid, link, exp))
return
}
user := genUsername("ssh")
pass := genPassword()
if err := createSSHUser(b.ctx, b.store, user, pass, exp, p.MaxConnections, p.LimitMbpsUp, p.LimitMbpsDown, ""); err != nil {
log.Printf("[bot] fulfill ssh: %v", err)
b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao criar a conta SSH. Contate o suporte.")
return
}
_ = b.store.SetTransactionTarget(b.ctx, txn.ID, user)
b.notify(txn.TelegramID, b.formatSSHDelivery(p.Name, user, pass, exp))
}
func (b *Bot) fulfillRenewal(txn *BotTransaction) {
if txn.PlanID == nil || txn.RenewTarget == "" {
return
}
p, err := b.store.GetPlan(b.ctx, *txn.PlanID)
if err != nil {
return
}
parts := strings.SplitN(txn.RenewTarget, ":", 2)
if len(parts) < 2 {
return
}
kind, id := parts[0], parts[1]
base := time.Now()
add := time.Duration(p.Days) * 24 * time.Hour
if kind == "x" {
newExp := base.Add(add)
if meta, err := b.store.GetXrayClientMeta(b.ctx, id); err == nil && meta.ExpiresAt != nil && meta.ExpiresAt.After(base) {
newExp = meta.ExpiresAt.Add(add)
}
if err := renewXrayClient(b.ctx, b.store, id, newExp); err != nil {
log.Printf("[bot] renew xray %s: %v", id, err)
b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao renovar. Contate o suporte.")
return
}
_ = b.store.SetTransactionTarget(b.ctx, txn.ID, id)
b.notify(txn.TelegramID, fmt.Sprintf("✅ <b>%s</b> renovado!\n⚡ Xray <code>%s</code>\nNova validade: %s",
htmlEscape(p.Name), htmlEscape(id), newExp.Format("02/01/2006 15:04")))
return
}
newExp := base.Add(add)
if u, ok := userMgr.Get(id); ok && u.ExpiresAt != nil && u.ExpiresAt.After(base) {
newExp = u.ExpiresAt.Add(add)
}
if err := renewSSHUser(b.ctx, b.store, id, newExp); err != nil {
log.Printf("[bot] renew ssh %s: %v", id, err)
b.notify(txn.TelegramID, "❌ Pagamento aprovado, mas houve um erro ao renovar. Contate o suporte.")
return
}
_ = b.store.SetTransactionTarget(b.ctx, txn.ID, id)
b.notify(txn.TelegramID, fmt.Sprintf("✅ <b>%s</b> renovado!\n🔒 SSH <code>%s</code>\nNova validade: %s",
htmlEscape(p.Name), htmlEscape(id), newExp.Format("02/01/2006 15:04")))
}
// ---------- "Verificar" button ----------
func (b *Bot) checkPaymentButton(chatID int64, from *tgUser, txnIDStr string) {
id, _ := strconv.Atoi(txnIDStr)
txn, err := b.store.GetTransaction(b.ctx, id)
if err != nil {
b.send(chatID, "Pagamento não encontrado.", backKeyboard())
return
}
if txn.TelegramID != from.ID {
b.send(chatID, "Pagamento inválido.", backKeyboard())
return
}
switch txn.Status {
case "approved":
b.send(chatID, "✅ Pagamento já confirmado! Veja em 🛍️ Minhas Compras.", backKeyboard())
return
case "expired":
b.send(chatID, "⌛ Este PIX expirou. Gere um novo pagamento.", backKeyboard())
return
case "refunded":
b.send(chatID, "Este pagamento foi estornado.", backKeyboard())
return
}
if b.mp == nil {
b.send(chatID, "Pagamento não configurado.", backKeyboard())
return
}
status, err := b.mp.GetPaymentStatus(b.ctx, txn.MPPaymentID)
if err != nil {
b.send(chatID, "Não foi possível verificar agora. Tente novamente em instantes.", backKeyboard())
return
}
if status == "approved" {
b.tryFulfill(txn.ID) // delivers via notify
return
}
b.send(chatID, "⏱ Pagamento ainda não identificado. Assim que cair, a liberação é automática.",
kb([]tgInlineButton{btn("🔄 Verificar novamente", "pay:check:"+botItoa(txn.ID)), btn("⬅️ Voltar", "menu:main")}))
}
+292
View File
@@ -0,0 +1,292 @@
package main
// bot_provision.go — bridges the bot to the panel's account creation.
// SSH: Store.UpsertUser. Xray: xrayMgr.AddXrayClient + UpsertXrayClientMeta.
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net"
"net/url"
"strconv"
"strings"
"time"
)
// ---------- credential generation ----------
const credAlphabet = "abcdefghijkmnpqrstuvwxyz23456789"
func randString(n int) string {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
// extremely unlikely; fall back to a fixed-length timestamp-free filler
for i := range b {
b[i] = credAlphabet[0]
}
return string(b)
}
for i := range b {
b[i] = credAlphabet[int(b[i])%len(credAlphabet)]
}
return string(b)
}
func genUsername(prefix string) string {
if prefix == "" {
prefix = "ssh"
}
return prefix + randString(6)
}
func genPassword() string { return randString(10) }
func uuidV4() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}
// ---------- SSH ----------
func createSSHUser(ctx context.Context, store *Store, username, password string, expiresAt time.Time, maxConns, upMbps, downMbps int, owner string) error {
cfg := UserConfig{
Username: username,
Password: password,
MaxConnections: maxConns,
ExpiresAt: expiresAt.UTC().Format(time.RFC3339),
LimitMbpsUp: upMbps,
LimitMbpsDown: downMbps,
OwnerUsername: owner,
}
if err := store.UpsertUser(ctx, cfg); err != nil {
return err
}
reloadUsersFromDB(ctx, store)
return nil
}
// renewSSHUser extends an existing SSH account's expiry, preserving credentials.
func renewSSHUser(ctx context.Context, store *Store, username string, newExpiry time.Time) error {
u, ok := userMgr.Get(username)
if !ok {
return fmt.Errorf("conta SSH %q não encontrada", username)
}
cfg := u.Cfg
cfg.ExpiresAt = newExpiry.UTC().Format(time.RFC3339)
if err := store.UpsertUser(ctx, cfg); err != nil {
return err
}
reloadUsersFromDB(ctx, store)
return nil
}
// ---------- Xray ----------
func createXrayClient(ctx context.Context, store *Store, inboundTag, protocol string, expiresAt time.Time, maxConns int, owner, publicHost string) (uuid, link string, err error) {
if inboundTag == "" {
return "", "", fmt.Errorf("plano Xray sem inbound configurado")
}
uuid = uuidV4()
email := "bot-" + uuid[:8]
if err = xrayMgr.AddXrayClient(inboundTag, uuid, email); err != nil {
return "", "", err
}
exp := expiresAt
meta := XrayClientMeta{
UUID: uuid,
Name: email,
Email: email,
InboundTag: inboundTag,
OwnerUsername: owner,
MaxConns: maxConns,
ExpiresAt: &exp,
}
if e := store.UpsertXrayClientMeta(ctx, meta); e != nil {
// The client is already live in Xray; a metadata failure must not
// abort delivery. Log and continue.
log.Printf("[bot] xray meta save for %s: %v", uuid, e)
}
xrayMgr.restartIfExternalRunning()
link = buildXrayLink(inboundTag, protocol, uuid, publicHost, email)
return uuid, link, nil
}
func renewXrayClient(ctx context.Context, store *Store, uuid string, newExpiry time.Time) error {
meta, err := store.GetXrayClientMeta(ctx, uuid)
if err != nil {
return fmt.Errorf("cliente Xray não encontrado: %w", err)
}
exp := newExpiry
meta.ExpiresAt = &exp
return store.UpsertXrayClientMeta(ctx, *meta)
}
// ---------- Xray connection link ----------
type xrayInboundDetail struct {
Protocol string
Port int
Network string
Security string
Path string
Host string
SNI string
ServiceName string
}
// inboundDetail reads streamSettings for an inbound from the raw Xray config.
func (m *XrayManager) inboundDetail(tag string) (*xrayInboundDetail, error) {
m.mu.Lock()
defer m.mu.Unlock()
data, err := m.readConfigLocked()
if err != nil {
return nil, err
}
var cfg struct {
Inbounds []json.RawMessage `json:"inbounds"`
}
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, err
}
for _, raw := range cfg.Inbounds {
var ib struct {
Tag string `json:"tag"`
Protocol string `json:"protocol"`
Port json.RawMessage `json:"port"`
SharedPort bool `json:"dragoncoreSharedPort"`
StreamSettings map[string]interface{} `json:"streamSettings"`
}
if err := json.Unmarshal(raw, &ib); err != nil {
continue
}
if ib.Tag != tag {
continue
}
d := &xrayInboundDetail{Protocol: strings.ToLower(ib.Protocol)}
var pnum int
if json.Unmarshal(ib.Port, &pnum) == nil {
d.Port = pnum
} else {
var pstr string
if json.Unmarshal(ib.Port, &pstr) == nil {
d.Port, _ = strconv.Atoi(pstr)
}
}
if ss := ib.StreamSettings; ss != nil {
d.Network, _ = ss["network"].(string)
d.Security, _ = ss["security"].(string)
d.Path, d.Host, d.ServiceName = extractStreamParams(ss, d.Network)
if tls, ok := ss["tlsSettings"].(map[string]interface{}); ok {
d.SNI, _ = tls["serverName"].(string)
}
if rl, ok := ss["realitySettings"].(map[string]interface{}); ok {
if sn, _ := rl["serverNames"].([]interface{}); len(sn) > 0 {
d.SNI, _ = sn[0].(string)
}
}
}
if ib.SharedPort {
// The public listener terminates TLS before the native emulator.
// Connection links describe the client-facing socket instead of the
// internal streamSettings security (which must remain "none").
if panel := getGlobalCfg(); panel != nil {
if len(panel.TLSForwarders) > 0 {
selected := panel.TLSForwarders[0].Listen
for _, fwd := range panel.TLSForwarders {
if strings.HasSuffix(fwd.Listen, ":443") { selected = fwd.Listen; break }
}
if _, port, err := net.SplitHostPort(selected); err == nil {
if value, err := strconv.Atoi(port); err == nil { d.Port = value; d.Security = "tls" }
}
} else if _, port, err := net.SplitHostPort(panel.Listen); err == nil {
if value, err := strconv.Atoi(port); err == nil { d.Port = value; d.Security = "none" }
}
}
}
return d, nil
}
return nil, fmt.Errorf("inbound %q não encontrado", tag)
}
func extractStreamParams(ss map[string]interface{}, network string) (path, host, serviceName string) {
get := func(key, field string) string {
if sub, ok := ss[key].(map[string]interface{}); ok {
v, _ := sub[field].(string)
return v
}
return ""
}
switch network {
case "ws":
return get("wsSettings", "path"), get("wsSettings", "host"), ""
case "xhttp":
return get("xhttpSettings", "path"), get("xhttpSettings", "host"), ""
case "httpupgrade":
return get("httpupgradeSettings", "path"), get("httpupgradeSettings", "host"), ""
case "grpc":
return "", "", get("grpcSettings", "serviceName")
case "http", "h2":
return get("httpSettings", "path"), get("httpSettings", "host"), ""
}
return "", "", ""
}
// buildXrayLink assembles a shareable connection URI. Best-effort: if the config
// can't be read it still returns a minimal link with host/port/uuid.
func buildXrayLink(inboundTag, protocol, uuid, publicHost, label string) string {
d, err := xrayMgr.inboundDetail(inboundTag)
if err != nil || d == nil {
if protocol == "" {
protocol = "vless"
}
return fmt.Sprintf("%s://%s@%s#%s", protocol, uuid, publicHost, url.QueryEscape(label))
}
if protocol == "" {
protocol = d.Protocol
}
host := publicHost
if host == "" {
host = d.SNI
}
addr := fmt.Sprintf("%s:%d", host, d.Port)
q := url.Values{}
if d.Network != "" {
q.Set("type", d.Network)
}
if d.Security != "" {
q.Set("security", d.Security)
}
if d.Path != "" {
q.Set("path", d.Path)
}
if d.Host != "" {
q.Set("host", d.Host)
}
if d.SNI != "" {
q.Set("sni", d.SNI)
}
if d.ServiceName != "" {
q.Set("serviceName", d.ServiceName)
}
switch protocol {
case "vmess":
conf := map[string]interface{}{
"v": "2", "ps": label, "add": host, "port": strconv.Itoa(d.Port),
"id": uuid, "aid": "0", "scy": "auto", "net": d.Network,
"type": "none", "host": d.Host, "path": d.Path, "tls": d.Security, "sni": d.SNI,
}
b, _ := json.Marshal(conf)
return "vmess://" + base64.StdEncoding.EncodeToString(b)
default: // vless, trojan
return fmt.Sprintf("%s://%s@%s?%s#%s", protocol, uuid, addr, q.Encode(), url.QueryEscape(label))
}
}
+672
View File
@@ -0,0 +1,672 @@
package main
// bot_store.go — PostgreSQL persistence for the Telegram sales bot.
//
// Tables (all created idempotently by EnsureBotSchema):
// bot_users — Telegram customers/resellers
// bot_plans — sellable SSH/Xray plans
// bot_credit_packages — reseller credit top-up packages
// bot_transactions — PIX payments (Mercado Pago)
// bot_credits_ledger — auditable credit movements
// bot_settings — editable bot texts (key/value)
// bot_config — single-row bot config with encrypted secrets
import (
"context"
"database/sql"
"time"
"github.com/lib/pq"
)
// ---------- Models ----------
type BotUser struct {
TelegramID int64
Username string
FirstName string
Role string // customer | reseller | blocked
LinkedAdminUsername string
CreditBalance int
TrialUsed bool
CreatedAt time.Time
LastSeenAt time.Time
}
type BotPlan struct {
ID int
Name string
Kind string // ssh | xray
Days int
MaxConnections int
LimitMbpsUp int
LimitMbpsDown int
XrayInboundTag string
XrayProtocol string
PriceCents int
CreditCost int
ServerID string
IsActive bool
SortOrder int
}
type BotCreditPackage struct {
ID int
Name string
Credits int
PriceCents int
IsActive bool
SortOrder int
}
type BotTransaction struct {
ID int
TelegramID int64
Type string // plan_purchase | plan_renewal | credit_topup
PlanID *int
PackageID *int
Credits int
AmountCents int
MPPaymentID string
MPQRCode string
MPQRBase64 string
Status string // pending | approved | expired | refunded | error
TargetUsername string // account/uuid created or renewed
RenewTarget string // for renewals: existing account/uuid to extend
CreatedAt time.Time
PaidAt *time.Time
ExpiresAt *time.Time
}
type BotLedgerEntry struct {
ID int
TelegramID int64
Delta int
Reason string
RefTxnID *int
BalanceAfter int
CreatedAt time.Time
}
// ---------- Schema ----------
func (s *Store) EnsureBotSchema(ctx context.Context) error {
stmts := []string{
`CREATE TABLE IF NOT EXISTS bot_users (
telegram_id BIGINT PRIMARY KEY,
username TEXT NOT NULL DEFAULT '',
first_name TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT 'customer',
linked_admin_username TEXT NOT NULL DEFAULT '',
credit_balance INT NOT NULL DEFAULT 0,
trial_used BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE TABLE IF NOT EXISTS bot_plans (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
kind TEXT NOT NULL DEFAULT 'ssh',
days INT NOT NULL DEFAULT 30,
max_connections INT NOT NULL DEFAULT 1,
limit_mbps_up INT NOT NULL DEFAULT 0,
limit_mbps_down INT NOT NULL DEFAULT 0,
xray_inbound_tag TEXT NOT NULL DEFAULT '',
xray_protocol TEXT NOT NULL DEFAULT '',
price_cents INT NOT NULL DEFAULT 0,
credit_cost INT NOT NULL DEFAULT 1,
server_id TEXT NOT NULL DEFAULT '',
is_active BOOLEAN NOT NULL DEFAULT true,
sort_order INT NOT NULL DEFAULT 0
)`,
`CREATE TABLE IF NOT EXISTS bot_credit_packages (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
credits INT NOT NULL DEFAULT 0,
price_cents INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT true,
sort_order INT NOT NULL DEFAULT 0
)`,
`CREATE TABLE IF NOT EXISTS bot_transactions (
id SERIAL PRIMARY KEY,
telegram_id BIGINT NOT NULL,
type TEXT NOT NULL,
plan_id INT,
package_id INT,
credits INT NOT NULL DEFAULT 0,
amount_cents INT NOT NULL DEFAULT 0,
mp_payment_id TEXT NOT NULL DEFAULT '',
mp_qr_code TEXT NOT NULL DEFAULT '',
mp_qr_base64 TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending',
target_username TEXT NOT NULL DEFAULT '',
renew_target TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
paid_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS bot_transactions_mp_payment_id_uidx
ON bot_transactions (mp_payment_id) WHERE mp_payment_id <> ''`,
`CREATE TABLE IF NOT EXISTS bot_credits_ledger (
id SERIAL PRIMARY KEY,
telegram_id BIGINT NOT NULL,
delta INT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
ref_transaction_id INT,
balance_after INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`CREATE TABLE IF NOT EXISTS bot_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL DEFAULT ''
)`,
`CREATE TABLE IF NOT EXISTS bot_config (
id INT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
enabled BOOLEAN NOT NULL DEFAULT false,
telegram_mode TEXT NOT NULL DEFAULT 'polling',
telegram_webhook_url TEXT NOT NULL DEFAULT '',
mp_confirm_mode TEXT NOT NULL DEFAULT 'polling',
mp_poll_interval TEXT NOT NULL DEFAULT '20s',
pix_expiration_minutes INT NOT NULL DEFAULT 30,
trial_enabled BOOLEAN NOT NULL DEFAULT true,
trial_hours INT NOT NULL DEFAULT 1,
trial_max_connections INT NOT NULL DEFAULT 1,
trial_kind TEXT NOT NULL DEFAULT 'ssh',
trial_inbound_tag TEXT NOT NULL DEFAULT '',
admin_telegram_ids BIGINT[] NOT NULL DEFAULT '{}',
currency TEXT NOT NULL DEFAULT 'BRL',
public_host TEXT NOT NULL DEFAULT '',
xray_public_host TEXT NOT NULL DEFAULT '',
telegram_token_enc BYTEA,
telegram_webhook_secret_enc BYTEA,
mp_access_token_enc BYTEA,
mp_webhook_secret_enc BYTEA,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`INSERT INTO bot_config (id) VALUES (1) ON CONFLICT (id) DO NOTHING`,
}
for _, stmt := range stmts {
if _, err := s.db.ExecContext(ctx, stmt); err != nil {
return err
}
}
return nil
}
// ---------- bot_users ----------
// UpsertBotUser inserts a user or refreshes username/first_name/last_seen.
// Role, credits, linkage and trial_used are preserved on update.
func (s *Store) UpsertBotUser(ctx context.Context, u *BotUser) error {
_, err := s.db.ExecContext(ctx, `
INSERT INTO bot_users (telegram_id, username, first_name, last_seen_at)
VALUES ($1, $2, $3, NOW())
ON CONFLICT (telegram_id) DO UPDATE
SET username = EXCLUDED.username,
first_name = EXCLUDED.first_name,
last_seen_at = NOW()`,
u.TelegramID, u.Username, u.FirstName)
return err
}
func scanBotUser(row interface{ Scan(...interface{}) error }) (*BotUser, error) {
var u BotUser
err := row.Scan(&u.TelegramID, &u.Username, &u.FirstName, &u.Role,
&u.LinkedAdminUsername, &u.CreditBalance, &u.TrialUsed, &u.CreatedAt, &u.LastSeenAt)
if err != nil {
return nil, err
}
return &u, nil
}
const botUserCols = `telegram_id, username, first_name, role, linked_admin_username, credit_balance, trial_used, created_at, last_seen_at`
func (s *Store) GetBotUser(ctx context.Context, telegramID int64) (*BotUser, error) {
row := s.db.QueryRowContext(ctx, `SELECT `+botUserCols+` FROM bot_users WHERE telegram_id=$1`, telegramID)
return scanBotUser(row)
}
func (s *Store) ListBotUsers(ctx context.Context) ([]*BotUser, error) {
rows, err := s.db.QueryContext(ctx, `SELECT `+botUserCols+` FROM bot_users ORDER BY last_seen_at DESC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BotUser
for rows.Next() {
u, err := scanBotUser(rows)
if err != nil {
return nil, err
}
out = append(out, u)
}
return out, rows.Err()
}
// SetBotUserRole updates role and reseller linkage.
func (s *Store) SetBotUserRole(ctx context.Context, telegramID int64, role, linkedAdmin string) error {
_, err := s.db.ExecContext(ctx,
`UPDATE bot_users SET role=$2, linked_admin_username=$3 WHERE telegram_id=$1`,
telegramID, role, linkedAdmin)
return err
}
func (s *Store) SetBotUserTrialUsed(ctx context.Context, telegramID int64) error {
_, err := s.db.ExecContext(ctx, `UPDATE bot_users SET trial_used=true WHERE telegram_id=$1`, telegramID)
return err
}
// AdjustCredits changes a reseller's balance atomically and writes a ledger row.
// Returns the resulting balance. Fails (rolls back) if the balance would go negative.
func (s *Store) AdjustCredits(ctx context.Context, telegramID int64, delta int, reason string, refTxn *int) (int, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
var balance int
if err := tx.QueryRowContext(ctx,
`UPDATE bot_users SET credit_balance = credit_balance + $2
WHERE telegram_id=$1 RETURNING credit_balance`,
telegramID, delta).Scan(&balance); err != nil {
return 0, err
}
if balance < 0 {
return 0, errInsufficientCredits
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO bot_credits_ledger (telegram_id, delta, reason, ref_transaction_id, balance_after)
VALUES ($1,$2,$3,$4,$5)`,
telegramID, delta, reason, refTxn, balance); err != nil {
return 0, err
}
if err := tx.Commit(); err != nil {
return 0, err
}
return balance, nil
}
func (s *Store) ListLedger(ctx context.Context, telegramID int64, limit int) ([]*BotLedgerEntry, error) {
if limit <= 0 {
limit = 100
}
rows, err := s.db.QueryContext(ctx,
`SELECT id, telegram_id, delta, reason, ref_transaction_id, balance_after, created_at
FROM bot_credits_ledger WHERE telegram_id=$1 ORDER BY id DESC LIMIT $2`, telegramID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BotLedgerEntry
for rows.Next() {
var e BotLedgerEntry
if err := rows.Scan(&e.ID, &e.TelegramID, &e.Delta, &e.Reason, &e.RefTxnID, &e.BalanceAfter, &e.CreatedAt); err != nil {
return nil, err
}
out = append(out, &e)
}
return out, rows.Err()
}
// ---------- bot_plans ----------
const botPlanCols = `id, name, kind, days, max_connections, limit_mbps_up, limit_mbps_down, xray_inbound_tag, xray_protocol, price_cents, credit_cost, server_id, is_active, sort_order`
func scanBotPlan(row interface{ Scan(...interface{}) error }) (*BotPlan, error) {
var p BotPlan
err := row.Scan(&p.ID, &p.Name, &p.Kind, &p.Days, &p.MaxConnections, &p.LimitMbpsUp, &p.LimitMbpsDown,
&p.XrayInboundTag, &p.XrayProtocol, &p.PriceCents, &p.CreditCost, &p.ServerID, &p.IsActive, &p.SortOrder)
if err != nil {
return nil, err
}
return &p, nil
}
func (s *Store) ListPlans(ctx context.Context, onlyActive bool) ([]*BotPlan, error) {
q := `SELECT ` + botPlanCols + ` FROM bot_plans`
if onlyActive {
q += ` WHERE is_active=true`
}
q += ` ORDER BY sort_order, id`
rows, err := s.db.QueryContext(ctx, q)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BotPlan
for rows.Next() {
p, err := scanBotPlan(rows)
if err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
func (s *Store) GetPlan(ctx context.Context, id int) (*BotPlan, error) {
row := s.db.QueryRowContext(ctx, `SELECT `+botPlanCols+` FROM bot_plans WHERE id=$1`, id)
return scanBotPlan(row)
}
func (s *Store) UpsertPlan(ctx context.Context, p *BotPlan) error {
if p.ID == 0 {
return s.db.QueryRowContext(ctx, `
INSERT INTO bot_plans (name, kind, days, max_connections, limit_mbps_up, limit_mbps_down,
xray_inbound_tag, xray_protocol, price_cents, credit_cost, server_id, is_active, sort_order)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) RETURNING id`,
p.Name, p.Kind, p.Days, p.MaxConnections, p.LimitMbpsUp, p.LimitMbpsDown,
p.XrayInboundTag, p.XrayProtocol, p.PriceCents, p.CreditCost, p.ServerID, p.IsActive, p.SortOrder,
).Scan(&p.ID)
}
_, err := s.db.ExecContext(ctx, `
UPDATE bot_plans SET name=$2, kind=$3, days=$4, max_connections=$5, limit_mbps_up=$6, limit_mbps_down=$7,
xray_inbound_tag=$8, xray_protocol=$9, price_cents=$10, credit_cost=$11, server_id=$12, is_active=$13, sort_order=$14
WHERE id=$1`,
p.ID, p.Name, p.Kind, p.Days, p.MaxConnections, p.LimitMbpsUp, p.LimitMbpsDown,
p.XrayInboundTag, p.XrayProtocol, p.PriceCents, p.CreditCost, p.ServerID, p.IsActive, p.SortOrder)
return err
}
func (s *Store) DeletePlan(ctx context.Context, id int) error {
_, err := s.db.ExecContext(ctx, `DELETE FROM bot_plans WHERE id=$1`, id)
return err
}
// ---------- bot_credit_packages ----------
const botPkgCols = `id, name, credits, price_cents, is_active, sort_order`
func scanBotPkg(row interface{ Scan(...interface{}) error }) (*BotCreditPackage, error) {
var p BotCreditPackage
if err := row.Scan(&p.ID, &p.Name, &p.Credits, &p.PriceCents, &p.IsActive, &p.SortOrder); err != nil {
return nil, err
}
return &p, nil
}
func (s *Store) ListCreditPackages(ctx context.Context, onlyActive bool) ([]*BotCreditPackage, error) {
q := `SELECT ` + botPkgCols + ` FROM bot_credit_packages`
if onlyActive {
q += ` WHERE is_active=true`
}
q += ` ORDER BY sort_order, id`
rows, err := s.db.QueryContext(ctx, q)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BotCreditPackage
for rows.Next() {
p, err := scanBotPkg(rows)
if err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
func (s *Store) GetCreditPackage(ctx context.Context, id int) (*BotCreditPackage, error) {
row := s.db.QueryRowContext(ctx, `SELECT `+botPkgCols+` FROM bot_credit_packages WHERE id=$1`, id)
return scanBotPkg(row)
}
func (s *Store) UpsertCreditPackage(ctx context.Context, p *BotCreditPackage) error {
if p.ID == 0 {
return s.db.QueryRowContext(ctx,
`INSERT INTO bot_credit_packages (name, credits, price_cents, is_active, sort_order)
VALUES ($1,$2,$3,$4,$5) RETURNING id`,
p.Name, p.Credits, p.PriceCents, p.IsActive, p.SortOrder).Scan(&p.ID)
}
_, err := s.db.ExecContext(ctx,
`UPDATE bot_credit_packages SET name=$2, credits=$3, price_cents=$4, is_active=$5, sort_order=$6 WHERE id=$1`,
p.ID, p.Name, p.Credits, p.PriceCents, p.IsActive, p.SortOrder)
return err
}
func (s *Store) DeleteCreditPackage(ctx context.Context, id int) error {
_, err := s.db.ExecContext(ctx, `DELETE FROM bot_credit_packages WHERE id=$1`, id)
return err
}
// ---------- bot_transactions ----------
const botTxnCols = `id, telegram_id, type, plan_id, package_id, credits, amount_cents, mp_payment_id, mp_qr_code, mp_qr_base64, status, target_username, renew_target, created_at, paid_at, expires_at`
func scanBotTxn(row interface{ Scan(...interface{}) error }) (*BotTransaction, error) {
var t BotTransaction
err := row.Scan(&t.ID, &t.TelegramID, &t.Type, &t.PlanID, &t.PackageID, &t.Credits, &t.AmountCents,
&t.MPPaymentID, &t.MPQRCode, &t.MPQRBase64, &t.Status, &t.TargetUsername, &t.RenewTarget,
&t.CreatedAt, &t.PaidAt, &t.ExpiresAt)
if err != nil {
return nil, err
}
return &t, nil
}
func (s *Store) CreateTransaction(ctx context.Context, t *BotTransaction) error {
return s.db.QueryRowContext(ctx, `
INSERT INTO bot_transactions (telegram_id, type, plan_id, package_id, credits, amount_cents,
mp_payment_id, mp_qr_code, mp_qr_base64, status, target_username, renew_target, expires_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) RETURNING id, created_at`,
t.TelegramID, t.Type, t.PlanID, t.PackageID, t.Credits, t.AmountCents,
t.MPPaymentID, t.MPQRCode, t.MPQRBase64, t.Status, t.TargetUsername, t.RenewTarget, t.ExpiresAt,
).Scan(&t.ID, &t.CreatedAt)
}
func (s *Store) GetTransaction(ctx context.Context, id int) (*BotTransaction, error) {
row := s.db.QueryRowContext(ctx, `SELECT `+botTxnCols+` FROM bot_transactions WHERE id=$1`, id)
return scanBotTxn(row)
}
func (s *Store) GetTransactionByMPID(ctx context.Context, mpID string) (*BotTransaction, error) {
row := s.db.QueryRowContext(ctx, `SELECT `+botTxnCols+` FROM bot_transactions WHERE mp_payment_id=$1`, mpID)
return scanBotTxn(row)
}
func (s *Store) ListPendingTransactions(ctx context.Context) ([]*BotTransaction, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT `+botTxnCols+` FROM bot_transactions WHERE status='pending' AND mp_payment_id <> '' ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BotTransaction
for rows.Next() {
t, err := scanBotTxn(rows)
if err != nil {
return nil, err
}
out = append(out, t)
}
return out, rows.Err()
}
func (s *Store) ListUserTransactions(ctx context.Context, telegramID int64, limit int) ([]*BotTransaction, error) {
if limit <= 0 {
limit = 50
}
rows, err := s.db.QueryContext(ctx,
`SELECT `+botTxnCols+` FROM bot_transactions WHERE telegram_id=$1 ORDER BY id DESC LIMIT $2`, telegramID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BotTransaction
for rows.Next() {
t, err := scanBotTxn(rows)
if err != nil {
return nil, err
}
out = append(out, t)
}
return out, rows.Err()
}
func (s *Store) ListTransactions(ctx context.Context, status string, limit int) ([]*BotTransaction, error) {
if limit <= 0 {
limit = 200
}
var rows *sql.Rows
var err error
if status != "" {
rows, err = s.db.QueryContext(ctx, `SELECT `+botTxnCols+` FROM bot_transactions WHERE status=$1 ORDER BY id DESC LIMIT $2`, status, limit)
} else {
rows, err = s.db.QueryContext(ctx, `SELECT `+botTxnCols+` FROM bot_transactions ORDER BY id DESC LIMIT $1`, limit)
}
if err != nil {
return nil, err
}
defer rows.Close()
var out []*BotTransaction
for rows.Next() {
t, err := scanBotTxn(rows)
if err != nil {
return nil, err
}
out = append(out, t)
}
return out, rows.Err()
}
// MarkTransactionApproved atomically flips a pending txn to approved. It returns
// true only for the caller that actually performed the transition, giving
// idempotent delivery even if webhook and poller race.
func (s *Store) MarkTransactionApproved(ctx context.Context, id int) (bool, error) {
res, err := s.db.ExecContext(ctx,
`UPDATE bot_transactions SET status='approved', paid_at=NOW() WHERE id=$1 AND status='pending'`, id)
if err != nil {
return false, err
}
n, _ := res.RowsAffected()
return n == 1, nil
}
func (s *Store) SetTransactionStatus(ctx context.Context, id int, status string) error {
_, err := s.db.ExecContext(ctx, `UPDATE bot_transactions SET status=$2 WHERE id=$1`, id, status)
return err
}
func (s *Store) SetTransactionTarget(ctx context.Context, id int, target string) error {
_, err := s.db.ExecContext(ctx, `UPDATE bot_transactions SET target_username=$2 WHERE id=$1`, id, target)
return err
}
// ---------- bot_settings ----------
func (s *Store) GetSetting(ctx context.Context, key, def string) string {
var v string
err := s.db.QueryRowContext(ctx, `SELECT value FROM bot_settings WHERE key=$1`, key).Scan(&v)
if err != nil {
return def
}
return v
}
func (s *Store) SetSetting(ctx context.Context, key, value string) error {
_, err := s.db.ExecContext(ctx,
`INSERT INTO bot_settings (key, value) VALUES ($1,$2)
ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value`, key, value)
return err
}
func (s *Store) AllSettings(ctx context.Context) (map[string]string, error) {
rows, err := s.db.QueryContext(ctx, `SELECT key, value FROM bot_settings`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]string{}
for rows.Next() {
var k, v string
if err := rows.Scan(&k, &v); err != nil {
return nil, err
}
out[k] = v
}
return out, rows.Err()
}
// ---------- bot_config (row) ----------
// botConfigRow mirrors the DB row; secrets stay encrypted here.
type botConfigRow struct {
Enabled bool
TelegramMode string
TelegramWebhookURL string
MPConfirmMode string
MPPollInterval string
PixExpirationMinutes int
TrialEnabled bool
TrialHours int
TrialMaxConnections int
TrialKind string
TrialInboundTag string
AdminTelegramIDs []int64
Currency string
PublicHost string
XrayPublicHost string
TelegramTokenEnc []byte
TelegramWebhookSecretEnc []byte
MPAccessTokenEnc []byte
MPWebhookSecretEnc []byte
}
func (s *Store) getBotConfigRow(ctx context.Context) (*botConfigRow, error) {
var r botConfigRow
var ids pq.Int64Array
err := s.db.QueryRowContext(ctx, `
SELECT enabled, telegram_mode, telegram_webhook_url, mp_confirm_mode, mp_poll_interval,
pix_expiration_minutes, trial_enabled, trial_hours, trial_max_connections, trial_kind,
trial_inbound_tag, admin_telegram_ids, currency, public_host, xray_public_host,
telegram_token_enc, telegram_webhook_secret_enc, mp_access_token_enc, mp_webhook_secret_enc
FROM bot_config WHERE id=1`).Scan(
&r.Enabled, &r.TelegramMode, &r.TelegramWebhookURL, &r.MPConfirmMode, &r.MPPollInterval,
&r.PixExpirationMinutes, &r.TrialEnabled, &r.TrialHours, &r.TrialMaxConnections, &r.TrialKind,
&r.TrialInboundTag, &ids, &r.Currency, &r.PublicHost, &r.XrayPublicHost,
&r.TelegramTokenEnc, &r.TelegramWebhookSecretEnc, &r.MPAccessTokenEnc, &r.MPWebhookSecretEnc)
if err != nil {
return nil, err
}
r.AdminTelegramIDs = []int64(ids)
return &r, nil
}
// saveBotConfigRow writes the non-secret fields plus any encrypted blobs that
// are non-nil (nil blob = keep existing secret).
func (s *Store) saveBotConfigRow(ctx context.Context, r *botConfigRow, tokEnc, tgSecEnc, mpEnc, mpSecEnc []byte) error {
set := `enabled=$1, telegram_mode=$2, telegram_webhook_url=$3, mp_confirm_mode=$4, mp_poll_interval=$5,
pix_expiration_minutes=$6, trial_enabled=$7, trial_hours=$8, trial_max_connections=$9, trial_kind=$10,
trial_inbound_tag=$11, admin_telegram_ids=$12, currency=$13, public_host=$14, xray_public_host=$15,
updated_at=NOW()`
args := []interface{}{
r.Enabled, r.TelegramMode, r.TelegramWebhookURL, r.MPConfirmMode, r.MPPollInterval,
r.PixExpirationMinutes, r.TrialEnabled, r.TrialHours, r.TrialMaxConnections, r.TrialKind,
r.TrialInboundTag, pq.Array(r.AdminTelegramIDs), r.Currency, r.PublicHost, r.XrayPublicHost,
}
n := len(args)
if tokEnc != nil {
n++
set += `, telegram_token_enc=$` + botItoa(n)
args = append(args, tokEnc)
}
if tgSecEnc != nil {
n++
set += `, telegram_webhook_secret_enc=$` + botItoa(n)
args = append(args, tgSecEnc)
}
if mpEnc != nil {
n++
set += `, mp_access_token_enc=$` + botItoa(n)
args = append(args, mpEnc)
}
if mpSecEnc != nil {
n++
set += `, mp_webhook_secret_enc=$` + botItoa(n)
args = append(args, mpSecEnc)
}
_, err := s.db.ExecContext(ctx, `UPDATE bot_config SET `+set+` WHERE id=1`, args...)
return err
}
+232
View File
@@ -0,0 +1,232 @@
package main
// bot_telegram.go — minimal Telegram Bot API client built on net/http.
// No third-party dependency.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"strconv"
"strings"
"time"
)
const tgAPIBase = "https://api.telegram.org/bot"
// ---------- Wire types (subset) ----------
type tgUpdate struct {
UpdateID int64 `json:"update_id"`
Message *tgMessage `json:"message"`
CallbackQuery *tgCallbackQuery `json:"callback_query"`
}
type tgMessage struct {
MessageID int64 `json:"message_id"`
From *tgUser `json:"from"`
Chat tgChat `json:"chat"`
Text string `json:"text"`
}
type tgCallbackQuery struct {
ID string `json:"id"`
From tgUser `json:"from"`
Message *tgMessage `json:"message"`
Data string `json:"data"`
}
type tgUser struct {
ID int64 `json:"id"`
FirstName string `json:"first_name"`
Username string `json:"username"`
}
type tgChat struct {
ID int64 `json:"id"`
}
type tgInlineKeyboard struct {
InlineKeyboard [][]tgInlineButton `json:"inline_keyboard"`
}
type tgInlineButton struct {
Text string `json:"text"`
CallbackData string `json:"callback_data,omitempty"`
URL string `json:"url,omitempty"`
}
// ---------- Client ----------
type tgClient struct {
token string
hc *http.Client
}
func newTGClient(token string) *tgClient {
return &tgClient{token: token, hc: &http.Client{Timeout: 65 * time.Second}}
}
type tgResponse struct {
OK bool `json:"ok"`
Description string `json:"description"`
Result json.RawMessage `json:"result"`
}
func (c *tgClient) call(ctx context.Context, method string, payload interface{}) (json.RawMessage, error) {
body, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tgAPIBase+c.token+"/"+method, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.hc.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
var tr tgResponse
if err := json.Unmarshal(data, &tr); err != nil {
return nil, fmt.Errorf("telegram %s: bad response: %s", method, string(data))
}
if !tr.OK {
return nil, fmt.Errorf("telegram %s: %s", method, tr.Description)
}
return tr.Result, nil
}
// getUpdates long-polls. offset is the next update_id to fetch.
func (c *tgClient) getUpdates(ctx context.Context, offset int64, timeoutSec int) ([]tgUpdate, error) {
payload := map[string]interface{}{
"offset": offset,
"timeout": timeoutSec,
"allowed_updates": []string{"message", "callback_query"},
}
raw, err := c.call(ctx, "getUpdates", payload)
if err != nil {
return nil, err
}
var ups []tgUpdate
if err := json.Unmarshal(raw, &ups); err != nil {
return nil, err
}
return ups, nil
}
func (c *tgClient) sendMessage(ctx context.Context, chatID int64, text string, kb *tgInlineKeyboard) (int64, error) {
payload := map[string]interface{}{
"chat_id": chatID,
"text": text,
"parse_mode": "HTML",
"disable_web_page_preview": true,
}
if kb != nil {
payload["reply_markup"] = kb
}
raw, err := c.call(ctx, "sendMessage", payload)
if err != nil {
return 0, err
}
var m tgMessage
_ = json.Unmarshal(raw, &m)
return m.MessageID, nil
}
func (c *tgClient) editMessageText(ctx context.Context, chatID, messageID int64, text string, kb *tgInlineKeyboard) error {
payload := map[string]interface{}{
"chat_id": chatID,
"message_id": messageID,
"text": text,
"parse_mode": "HTML",
"disable_web_page_preview": true,
}
if kb != nil {
payload["reply_markup"] = kb
}
_, err := c.call(ctx, "editMessageText", payload)
return err
}
func (c *tgClient) answerCallback(ctx context.Context, callbackID, text string) error {
payload := map[string]interface{}{"callback_query_id": callbackID}
if text != "" {
payload["text"] = text
}
_, err := c.call(ctx, "answerCallbackQuery", payload)
return err
}
// sendPhotoBytes uploads a photo (e.g. a PIX QR PNG) via multipart.
func (c *tgClient) sendPhotoBytes(ctx context.Context, chatID int64, photo []byte, filename, caption string, kb *tgInlineKeyboard) (int64, error) {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
_ = w.WriteField("chat_id", strconv.FormatInt(chatID, 10))
if caption != "" {
_ = w.WriteField("caption", caption)
_ = w.WriteField("parse_mode", "HTML")
}
if kb != nil {
kbJSON, _ := json.Marshal(kb)
_ = w.WriteField("reply_markup", string(kbJSON))
}
fw, err := w.CreateFormFile("photo", filename)
if err != nil {
return 0, err
}
if _, err := fw.Write(photo); err != nil {
return 0, err
}
_ = w.Close()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tgAPIBase+c.token+"/sendPhoto", &buf)
if err != nil {
return 0, err
}
req.Header.Set("Content-Type", w.FormDataContentType())
resp, err := c.hc.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
var tr tgResponse
if err := json.Unmarshal(data, &tr); err != nil || !tr.OK {
return 0, fmt.Errorf("telegram sendPhoto: %s", string(data))
}
var m tgMessage
_ = json.Unmarshal(tr.Result, &m)
return m.MessageID, nil
}
func (c *tgClient) deleteWebhook(ctx context.Context) error {
_, err := c.call(ctx, "deleteWebhook", map[string]interface{}{"drop_pending_updates": false})
return err
}
// getMe validates the token and returns the bot username.
func (c *tgClient) getMe(ctx context.Context) (string, error) {
raw, err := c.call(ctx, "getMe", map[string]interface{}{})
if err != nil {
return "", err
}
var me tgUser
_ = json.Unmarshal(raw, &me)
return me.Username, nil
}
// ---------- helpers ----------
func htmlEscape(s string) string {
s = strings.ReplaceAll(s, "&", "&amp;")
s = strings.ReplaceAll(s, "<", "&lt;")
s = strings.ReplaceAll(s, ">", "&gt;")
return s
}
+994
View File
@@ -0,0 +1,994 @@
package main
// This file embeds the BTUN protocol server into the panel. BTUN is the native
// DTunnel VPN transport: a client speaks a "DTUNNEL/1.1 CLIENT_HELLO" handshake
// over TCP or UDP, authenticates, is handed an IPv4 address from a private
// subnet, and then exchanges raw IPv4 packets with a TUN interface owned by
// this process.
//
// Unlike BHTTP or DNSTT, BTUN is not an SSH carrier — it moves IP packets, not
// an SSH stream. Authentication therefore cannot be delegated to handleConn, so
// it is delegated to the panel's own account database instead: the same
// username/password (or TOTP), the same expiry, reseller-owner, data-quota and
// max_connections rules that passwordCallback enforces for SSH. PAM,
// /etc/shadow and password files are deliberately unreachable from this path;
// a BTUN login is a panel login and nothing else.
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
"shell2/internal/btun"
)
// BTUNConfig defines the settings for the integrated BTUN server. A nil
// *BTUNConfig in the main config disables it entirely.
type BTUNConfig struct {
// TCPListen is the TCP address for BTUN clients. Empty disables the TCP
// transport. IPv6 addresses must use bracket form, e.g. "[::]:7300".
TCPListen string `json:"tcp_listen"`
// UDPListen is the UDP address for BTUN clients. Empty disables the UDP
// transport. At least one of TCPListen/UDPListen must be set.
UDPListen string `json:"udp_listen"`
// SharedPorts also accepts BTUN on the ports the panel already owns: the
// HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080)
// and every TLS forwarder (normally 443). Those listeners read the first
// bytes of each connection and hand it here only on the fixed
// "DTUNNEL/1.1 CLIENT_HELLO" marker, so SSH and HTTP-injection clients on
// the same port are unaffected.
//
// This covers the TCP transport only: the panel owns no shared UDP port, so
// UDP clients still need UDPListen. A TCP client that prepends cover bytes
// is matched when that cover is an HTTP request (the panel's own HTTP
// cleanup consumes it first); other cover shapes need TCPListen, because a
// shared port cannot buffer an unbounded prefix while SSH waits behind it.
SharedPorts bool `json:"shared_ports,omitempty"`
// TUNName is the TUN interface this server creates and owns. Default
// "btun0". It must not collide with an interface another service owns.
TUNName string `json:"tun_name,omitempty"`
// Subnet is the private IPv4 range handed out to clients, in CIDR form.
// Default "10.77.0.0/16". It must have room for at least four addresses.
Subnet string `json:"subnet,omitempty"`
// Gateway is the address configured on the TUN interface itself, in CIDR
// form, and is the first usable address of Subnet by convention. Empty
// derives it from Subnet (for 10.77.0.0/16 that is 10.77.0.1/16).
Gateway string `json:"gateway,omitempty"`
// MTU is set on the TUN interface. Default 1400, which leaves headroom for
// the BTUN framing plus an outer TCP/UDP header on a 1500-byte path.
MTU int `json:"mtu,omitempty"`
// ManageRouting lets the panel configure the interface address, MTU,
// net.ipv4.ip_forward and the NAT/forward rules for Subnet itself. Turn it
// off only when an external script (or an existing btun-routing unit)
// already owns those rules.
ManageRouting bool `json:"manage_routing,omitempty"`
// WANInterface is the uplink used for NAT. Empty auto-detects it from the
// default IPv4 route, which is correct on a single-uplink VPS.
WANInterface string `json:"wan_interface,omitempty"`
// HandshakeTimeout bounds the hello + authentication exchange. Empty
// defaults to "15s".
HandshakeTimeout string `json:"handshake_timeout,omitempty"`
// IdleTimeout drops a session that sends nothing for this long. Empty
// defaults to "2m". Clients send keep-alives, so this only reaps dead peers.
IdleTimeout string `json:"idle_timeout,omitempty"`
// MaxPacketSize limits a single BTUN frame payload in bytes. Zero uses the
// protocol default (64 KiB); the hard ceiling is 4 MiB.
MaxPacketSize int `json:"max_packet_size,omitempty"`
// MaxCoverBytes is how much junk a TCP client may send before its
// CLIENT_HELLO, which is what lets BTUN hide behind an HTTP-looking
// preamble. Zero uses the default (64 KiB).
MaxCoverBytes int `json:"max_cover_bytes,omitempty"`
// MaxSessions caps concurrent BTUN sessions across both transports. Zero
// uses a safe default; negative disables the cap. Per-account limits still
// come from each user's max_connections.
MaxSessions int `json:"max_sessions,omitempty"`
// DisableConsoleLog keeps BTUN log lines out of stderr. They are still
// captured in memory and served by /api/btun/logs for the panel.
DisableConsoleLog bool `json:"disable_console_log,omitempty"`
// LogConnections enables one log line per session start/stop.
LogConnections bool `json:"log_connections,omitempty"`
// AutoRestartInterval controls a watchdog that periodically hard-restarts
// only the BTUN listeners and TUN device. Empty, "0s", "off" or "disabled"
// turns it off. Minimum accepted value is 1m.
AutoRestartInterval string `json:"auto_restart_interval,omitempty"`
// AutoRestartGrace is the delay between tearing the old instance down and
// bringing a new one up during an auto restart. Empty defaults to "2s".
AutoRestartGrace string `json:"auto_restart_grace,omitempty"`
}
const (
defaultBTUNTCPListen = "0.0.0.0:7300"
defaultBTUNUDPListen = "0.0.0.0:7300"
defaultBTUNName = "btun0"
defaultBTUNSubnet = "10.77.0.0/16"
defaultBTUNMTU = 1400
defaultBTUNHandshakeTimeout = 15 * time.Second
defaultBTUNIdleTimeout = 2 * time.Minute
defaultBTUNMaxSessions = 10000
btunMaxPacketCeiling = 4 * 1024 * 1024
btunRouteCommandTimeout = 10 * time.Second
)
var (
btunMu sync.Mutex
btunServer *btun.Server
btunDevice btun.PacketDevice
btunTCP net.Listener
btunUDP net.PacketConn
btunListenTCP string
btunListenUDP string
// btunSharedPorts mirrors BTUNConfig.SharedPorts for the running instance,
// so the proxy and TLS listeners can check it without reading the whole
// config on every connection.
btunSharedPorts bool
// btunRoutingApplied records the settings used to add routing rules, so the
// exact same rules can be removed on shutdown even after the config changed.
btunRoutingApplied *btunRoutingSpec
btunAutoMu sync.Mutex
btunAutoCancel context.CancelFunc
btunLog = log.New(os.Stderr, "btun: ", log.LstdFlags|log.Lmicroseconds)
btunLogBuf *ringLogBuffer
// btunSessionsMu guards the per-account session registry used for
// max_connections and for forced disconnects from the panel.
btunSessionsMu sync.Mutex
btunSessions = make(map[string]map[*btunLedger]struct{})
)
func getBTUNLogLines() []string { return btunLogBuf.GetLines() }
// ---------- Panel-backed authentication ----------
// btunPanelAuthenticator verifies a BTUN credential against the panel's own
// account database. It is intentionally the only authenticator wired into the
// BTUN server: there is no PAM, /etc/shadow or password-file path here, and
// pam_auth_enabled does not apply to BTUN.
type btunPanelAuthenticator struct{}
func (btunPanelAuthenticator) Name() string { return "panel" }
func (btunPanelAuthenticator) Authenticate(username, password string) error {
// Mirrors passwordCallback's panel-credential branch. Kept as a separate
// implementation because passwordCallback is bound to ssh.ConnMetadata and
// also owns the (unrelated) system-login path.
u, ok := userMgr.Get(username)
if !ok {
return errors.New("invalid username or password")
}
now := time.Now()
if u.ExpiresAt != nil && now.After(*u.ExpiresAt) {
return errors.New("account expired")
}
if sshUserQuotaBlocked(u) {
return errDataQuotaExceeded
}
if err := ownerIsActive(u.Cfg.OwnerUsername); err != nil {
return errors.New("invalid username or password")
}
u.mu.Lock()
cfg := u.Cfg
u.mu.Unlock()
if strings.TrimSpace(cfg.TOTPSecret) != "" {
if matchTOTPPassword(u, password, now) {
return nil
}
if cfg.AllowStaticPassword && cfg.Password == password {
return nil
}
return errors.New("invalid username or password")
}
if cfg.Password != password {
return errors.New("invalid username or password")
}
return nil
}
// ---------- Panel-backed accounting ----------
// btunPanelAccountant admits authenticated BTUN sessions and meters their
// traffic against the same per-user counters the SSH path uses, so a user's
// bandwidth limits, data quota and connection count cover both transports.
type btunPanelAccountant struct{}
func (btunPanelAccountant) Admit(username, remote string, closer io.Closer) (btun.Ledger, error) {
u, ok := userMgr.Get(username)
if !ok {
return nil, errors.New("account not found")
}
u.mu.Lock()
cfg := u.Cfg
// max_connections is shared with SSH: BTUN sessions and SSH connections
// count against the same allowance, so a user cannot double their limit by
// mixing transports.
active := len(u.conns) + u.btunConns
if cfg.MaxConnections > 0 && active >= cfg.MaxConnections {
u.mu.Unlock()
return nil, fmt.Errorf("connection limit reached (%d)", cfg.MaxConnections)
}
u.btunConns++
u.ActiveConns = len(u.conns) + u.btunConns
u.mu.Unlock()
limitUp, limitDown := cfg.LimitMbpsUp, cfg.LimitMbpsDown
if limitUp == 0 || limitDown == 0 {
defUp, defDown := getDefaultLimits()
if limitUp == 0 {
limitUp = defUp
}
if limitDown == 0 {
limitDown = defDown
}
}
ledger := &btunLedger{
user: u,
username: username,
remote: remote,
closer: closer,
up: btunRateLimiter(limitUp),
down: btunRateLimiter(limitDown),
}
btunSessionsMu.Lock()
if btunSessions[username] == nil {
btunSessions[username] = make(map[*btunLedger]struct{})
}
btunSessions[username][ledger] = struct{}{}
btunSessionsMu.Unlock()
updateUserDisplay()
return ledger, nil
}
// btunRateLimiter builds a per-session limiter for an Mbps value. The burst is
// never smaller than one maximum-size IP packet, otherwise WaitN would reject
// a legitimate packet outright instead of pacing it.
func btunRateLimiter(mbps int) *rate.Limiter {
if mbps <= 0 {
return nil
}
bps := mbpsToBytesPerSec(mbps)
burst := int(bps)
if burst < 64*1024 {
burst = 64 * 1024
}
return rate.NewLimiter(rate.Limit(bps), burst)
}
// btunLedger meters one BTUN session against its panel account.
type btunLedger struct {
user *UserState
username string
remote string
closer io.Closer
up *rate.Limiter
down *rate.Limiter
once sync.Once
}
func (l *btunLedger) Uplink(ctx context.Context, n int) error {
return l.meter(ctx, true, l.up, n)
}
func (l *btunLedger) Downlink(ctx context.Context, n int) error {
return l.meter(ctx, false, l.down, n)
}
// meter reserves quota for one IP packet, paces it, and commits the bytes.
// BTUN forwards whole packets, so a partial quota allowance cannot be honoured:
// the reservation is released and the session ends instead of sending a
// truncated packet.
func (l *btunLedger) meter(ctx context.Context, uplink bool, limiter *rate.Limiter, n int) error {
if l.user == nil || n <= 0 {
return nil
}
// Held for the same reason sshQuotaWriter holds it: a traffic reset must not
// interleave with a reservation.
l.user.trafficMu.RLock()
defer l.user.trafficMu.RUnlock()
allowed, quotaLimiter, stopAfter := reserveSSHUserBytes(l.user, n)
if allowed <= 0 {
return errDataQuotaExceeded
}
if allowed < n {
finishSSHUserReservation(l.user, uplink, allowed, 0)
return errDataQuotaExceeded
}
if limiter != nil {
if err := limiter.WaitN(ctx, n); err != nil {
finishSSHUserReservation(l.user, uplink, allowed, 0)
return err
}
}
if quotaLimiter != nil {
if err := quotaLimiter.WaitN(ctx, allowed); err != nil {
finishSSHUserReservation(l.user, uplink, allowed, 0)
return err
}
}
finishSSHUserReservation(l.user, uplink, allowed, allowed)
if stopAfter {
return errDataQuotaExceeded
}
return nil
}
func (l *btunLedger) Close() {
l.once.Do(func() {
btunSessionsMu.Lock()
if set := btunSessions[l.username]; set != nil {
delete(set, l)
if len(set) == 0 {
delete(btunSessions, l.username)
}
}
btunSessionsMu.Unlock()
if l.user != nil {
l.user.mu.Lock()
if l.user.btunConns > 0 {
l.user.btunConns--
}
l.user.ActiveConns = len(l.user.conns) + l.user.btunConns
l.user.mu.Unlock()
}
updateUserDisplay()
})
}
// btunDisconnectUser closes every BTUN session belonging to username. It is
// called from UserManager.DisconnectUser so panel actions (delete, edit,
// expire) drop BTUN sessions the same way they drop SSH connections.
func btunDisconnectUser(username string) int {
btunSessionsMu.Lock()
ledgers := make([]*btunLedger, 0, len(btunSessions[username]))
for ledger := range btunSessions[username] {
ledgers = append(ledgers, ledger)
}
btunSessionsMu.Unlock()
for _, ledger := range ledgers {
if ledger.closer != nil {
_ = ledger.closer.Close()
}
}
return len(ledgers)
}
// btunDisconnectAll closes every tracked BTUN session.
func btunDisconnectAll() int {
btunSessionsMu.Lock()
ledgers := make([]*btunLedger, 0, len(btunSessions))
for _, set := range btunSessions {
for ledger := range set {
ledgers = append(ledgers, ledger)
}
}
btunSessionsMu.Unlock()
for _, ledger := range ledgers {
if ledger.closer != nil {
_ = ledger.closer.Close()
}
}
return len(ledgers)
}
// ---------- Lifecycle ----------
// stopBTUN tears down the BTUN listeners, TUN device, routing rules and the
// optional auto-restart watchdog. It is a no-op if BTUN is not running.
func stopBTUN() {
stopBTUNAutoRestart()
stopBTUNInstance()
}
// stopBTUNInstance closes only the running instance. The auto-restart watchdog
// uses this so it can cycle BTUN without disabling itself.
func stopBTUNInstance() {
btunMu.Lock()
server := btunServer
device := btunDevice
tcpListener := btunTCP
udpConn := btunUDP
routing := btunRoutingApplied
btunServer = nil
btunDevice = nil
btunTCP = nil
btunUDP = nil
btunListenTCP = ""
btunListenUDP = ""
btunSharedPorts = false
btunRoutingApplied = nil
btunMu.Unlock()
if tcpListener != nil {
_ = tcpListener.Close()
}
if udpConn != nil {
_ = udpConn.Close()
}
if server != nil {
// Server.Close also closes the TUN device it was given.
if err := server.Close(); err != nil {
btunLog.Printf("shutdown: %v", err)
}
server.Wait()
} else if device != nil {
_ = device.Close()
}
if routing != nil {
removeBTUNRouting(*routing)
}
}
func stopBTUNAutoRestart() {
btunAutoMu.Lock()
defer btunAutoMu.Unlock()
if btunAutoCancel != nil {
btunAutoCancel()
btunAutoCancel = nil
}
}
func btunRunning() bool {
btunMu.Lock()
defer btunMu.Unlock()
return btunServer != nil
}
// btunListenList reports the addresses currently bound, for the panel.
func btunListenList() string {
btunMu.Lock()
defer btunMu.Unlock()
parts := make([]string, 0, 3)
if btunListenTCP != "" {
parts = append(parts, "tcp "+btunListenTCP)
}
if btunListenUDP != "" {
parts = append(parts, "udp "+btunListenUDP)
}
if btunSharedPorts {
parts = append(parts, "shared proxy/TLS ports")
}
return strings.Join(parts, ", ")
}
// btunShareEnabled reports whether a running BTUN server wants the shared proxy
// and TLS ports.
func btunShareEnabled() bool {
btunMu.Lock()
defer btunMu.Unlock()
return btunServer != nil && btunSharedPorts
}
// btunConfiguredListen describes the addresses a config asks for, used in
// status reports when the server failed to bind them.
func btunConfiguredListen(cfg *BTUNConfig) string {
if cfg == nil {
return ""
}
parts := make([]string, 0, 3)
if addr := strings.TrimSpace(cfg.TCPListen); addr != "" {
parts = append(parts, "tcp "+addr)
}
if addr := strings.TrimSpace(cfg.UDPListen); addr != "" {
parts = append(parts, "udp "+addr)
}
if cfg.SharedPorts {
parts = append(parts, "shared proxy/TLS ports")
}
return strings.Join(parts, ", ")
}
func btunEnabledInCurrentConfig() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.BTUN != nil
}
// startBTUN starts the integrated BTUN server if cfg is non-nil. Startup errors
// are returned so the admin panel can report them, but they never crash the
// panel.
func startBTUN(cfg *BTUNConfig) error {
if cfg == nil {
return nil
}
stopBTUNAutoRestart()
if err := startBTUNInstance(cfg); err != nil {
return err
}
startBTUNAutoRestart(cfg)
return nil
}
func startBTUNInstance(cfg *BTUNConfig) error {
if cfg == nil {
return nil
}
if btunLogBuf == nil {
btunLogBuf = newRingLogBuffer(200)
}
if cfg.DisableConsoleLog {
btunLog.SetOutput(btunLogBuf)
} else {
btunLog.SetOutput(io.MultiWriter(btunLogBuf, os.Stderr))
}
normalizeBTUNConfig(cfg)
if cfg.TCPListen == "" && cfg.UDPListen == "" && !cfg.SharedPorts {
msg := errors.New("btun: needs tcp_listen, udp_listen or shared_ports")
btunLog.Print(msg.Error())
return msg
}
// Release the previous instance first: the TUN interface name and the
// listen addresses cannot be held twice.
stopBTUNInstance()
device, err := btun.OpenTUN(cfg.TUNName)
if err != nil {
msg := fmt.Errorf("btun: open TUN %s: %w", cfg.TUNName, err)
btunLog.Print(msg.Error())
return msg
}
maxSessions := cfg.MaxSessions
if maxSessions == 0 {
maxSessions = defaultBTUNMaxSessions
} else if maxSessions < 0 {
maxSessions = 0 // unlimited
}
server, err := btun.NewServer(btun.Config{
Subnet: cfg.Subnet,
Authenticator: btunPanelAuthenticator{},
Accountant: btunPanelAccountant{},
Logger: btunLog,
HandshakeTimeout: btunDurationOrDefault(cfg.HandshakeTimeout, defaultBTUNHandshakeTimeout, "handshake_timeout"),
IdleTimeout: btunDurationOrDefault(cfg.IdleTimeout, defaultBTUNIdleTimeout, "idle_timeout"),
MaxPacketSize: cfg.MaxPacketSize,
MaxCoverBytes: cfg.MaxCoverBytes,
MaxSessions: maxSessions,
LogConnections: cfg.LogConnections,
}, device)
if err != nil {
_ = device.Close()
msg := fmt.Errorf("btun: %w", err)
btunLog.Print(msg.Error())
return msg
}
var tcpListener net.Listener
if cfg.TCPListen != "" {
tcpListener, err = net.Listen("tcp", cfg.TCPListen)
if err != nil {
_ = server.Close()
msg := fmt.Errorf("btun: listen TCP %s: %w", cfg.TCPListen, err)
btunLog.Print(msg.Error())
return msg
}
}
var udpConn net.PacketConn
if cfg.UDPListen != "" {
udpConn, err = net.ListenPacket("udp", cfg.UDPListen)
if err != nil {
if tcpListener != nil {
_ = tcpListener.Close()
}
_ = server.Close()
msg := fmt.Errorf("btun: listen UDP %s: %w", cfg.UDPListen, err)
btunLog.Print(msg.Error())
return msg
}
}
var routing *btunRoutingSpec
if cfg.ManageRouting {
spec, routeErr := applyBTUNRouting(cfg, device.Name())
if routeErr != nil {
// Routing is a host-configuration concern: the tunnel itself is up,
// so keep serving and surface the problem instead of refusing to
// start. Without NAT clients reach the server but not the internet.
btunLog.Printf("routing not fully applied: %v", routeErr)
}
routing = &spec
}
btunMu.Lock()
btunServer = server
btunDevice = device
btunTCP = tcpListener
btunUDP = udpConn
btunListenTCP = cfg.TCPListen
btunListenUDP = cfg.UDPListen
btunSharedPorts = cfg.SharedPorts
btunRoutingApplied = routing
btunMu.Unlock()
btunLog.Printf("starting: tun=%s subnet=%s gateway=%s mtu=%d tcp=%q udp=%q shared_ports=%v auth=panel manage_routing=%v max_sessions=%d log_connections=%v",
device.Name(), cfg.Subnet, cfg.Gateway, cfg.MTU, cfg.TCPListen, cfg.UDPListen,
cfg.SharedPorts, cfg.ManageRouting, maxSessions, cfg.LogConnections)
if tcpListener != nil {
go func() {
defer btunRecover("ServeTCP")
if err := server.ServeTCP(tcpListener); err != nil && !isListenerClosed(err) {
btunLog.Printf("TCP listener stopped: %v", err)
}
}()
}
if udpConn != nil {
go func() {
defer btunRecover("ServeUDP")
if err := server.ServeUDP(udpConn); err != nil && !isListenerClosed(err) {
btunLog.Printf("UDP listener stopped: %v", err)
}
}()
}
return nil
}
func btunRecover(where string) {
if r := recover(); r != nil {
btunLog.Printf("recovered panic in %s: %v", where, r)
}
}
func startBTUNAutoRestart(cfg *BTUNConfig) {
interval := btunAutoRestartInterval(cfg)
if interval <= 0 {
return
}
grace := btunAutoRestartGrace(cfg)
cfgCopy := *cfg
ctx, cancel := context.WithCancel(context.Background())
btunAutoMu.Lock()
if btunAutoCancel != nil {
btunAutoCancel()
}
btunAutoCancel = cancel
btunAutoMu.Unlock()
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
btunLog.Printf("auto restart enabled: interval=%s grace=%s mode=hard", interval, grace)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
btunLog.Print("auto restart: stopping listeners, sessions and TUN device")
stopBTUNInstance()
if !sleepOrContextDone(ctx, grace) {
return
}
for attempt := 1; ; attempt++ {
if err := startBTUNInstance(&cfgCopy); err != nil {
btunLog.Printf("auto restart: start attempt %d failed: %v", attempt, err)
if !sleepOrContextDone(ctx, 10*time.Second) {
return
}
continue
}
btunLog.Print("auto restart: server restarted")
break
}
}
}
}()
}
func btunAutoRestartInterval(cfg *BTUNConfig) time.Duration {
if cfg == nil {
return 0
}
raw := strings.TrimSpace(cfg.AutoRestartInterval)
if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") {
return 0
}
d, err := time.ParseDuration(raw)
if err != nil {
btunLog.Printf("auto restart disabled: invalid interval %q: %v", raw, err)
return 0
}
if d < time.Minute {
btunLog.Printf("auto restart disabled: interval %q is below minimum 1m", raw)
return 0
}
return d
}
func btunAutoRestartGrace(cfg *BTUNConfig) time.Duration {
if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" {
return 2 * time.Second
}
d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace))
if err != nil || d < 0 {
btunLog.Printf("auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace)
return 2 * time.Second
}
if d > time.Minute {
return time.Minute
}
return d
}
func btunDurationOrDefault(raw string, fallback time.Duration, field string) time.Duration {
raw = strings.TrimSpace(raw)
if raw == "" {
return fallback
}
d, err := time.ParseDuration(raw)
if err != nil || d <= 0 {
btunLog.Printf("invalid %s %q; using default %s", field, raw, fallback)
return fallback
}
return d
}
// normalizeBTUNConfig fills in defaults and derives the gateway address. It
// mutates cfg so the value persisted by the admin API matches what runs.
func normalizeBTUNConfig(cfg *BTUNConfig) {
cfg.TCPListen = strings.TrimSpace(cfg.TCPListen)
cfg.UDPListen = strings.TrimSpace(cfg.UDPListen)
cfg.TUNName = strings.TrimSpace(cfg.TUNName)
if cfg.TUNName == "" {
cfg.TUNName = defaultBTUNName
}
cfg.Subnet = strings.TrimSpace(cfg.Subnet)
if cfg.Subnet == "" {
cfg.Subnet = defaultBTUNSubnet
}
cfg.Gateway = strings.TrimSpace(cfg.Gateway)
if cfg.Gateway == "" {
if derived, err := btunGatewayForSubnet(cfg.Subnet); err == nil {
cfg.Gateway = derived
}
}
if cfg.MTU <= 0 {
cfg.MTU = defaultBTUNMTU
}
if cfg.MaxPacketSize > btunMaxPacketCeiling {
btunLog.Printf("max_packet_size %d exceeds the %d ceiling; clamping",
cfg.MaxPacketSize, btunMaxPacketCeiling)
cfg.MaxPacketSize = btunMaxPacketCeiling
}
cfg.WANInterface = strings.TrimSpace(cfg.WANInterface)
}
// btunGatewayForSubnet returns the first usable address of subnet in CIDR form,
// which is the address the TUN interface takes. For 10.77.0.0/16 that is
// 10.77.0.1/16.
func btunGatewayForSubnet(subnet string) (string, error) {
ip, network, err := net.ParseCIDR(subnet)
if err != nil {
return "", err
}
if ip.To4() == nil {
return "", errors.New("BTUN subnet must be IPv4")
}
ones, bits := network.Mask.Size()
if bits != 32 || ones > 30 {
return "", errors.New("BTUN subnet must contain at least four IPv4 addresses")
}
base := network.IP.To4()
gateway := net.IPv4(base[0], base[1], base[2], base[3]).To4()
gateway[3] |= 1
return fmt.Sprintf("%s/%d", gateway.String(), ones), nil
}
// ---------- Host routing ----------
// btunRoutingSpec records exactly which rules were installed, so the same ones
// can be removed later even if the configuration changed in between.
type btunRoutingSpec struct {
TUNName string
Subnet string
Gateway string
MTU int
WAN string
}
// applyBTUNRouting configures the TUN interface and the NAT/forward rules that
// let BTUN clients reach the internet. It mirrors deploy/btun/btun-routing from
// the standalone deployment, but runs in-process so the panel owns the state.
func applyBTUNRouting(cfg *BTUNConfig, tunName string) (btunRoutingSpec, error) {
spec := btunRoutingSpec{
TUNName: tunName,
Subnet: cfg.Subnet,
Gateway: cfg.Gateway,
MTU: cfg.MTU,
WAN: cfg.WANInterface,
}
if spec.WAN == "" {
detected, err := detectDefaultWANInterface()
if err != nil {
return spec, fmt.Errorf("detect WAN interface: %w (set wan_interface explicitly)", err)
}
spec.WAN = detected
btunLog.Printf("routing: detected WAN interface %s", detected)
}
var problems []string
run := func(name string, args ...string) {
if out, err := runBTUNCommand(name, args...); err != nil {
problems = append(problems, fmt.Sprintf("%s %s: %v%s", name, strings.Join(args, " "), err, out))
}
}
if spec.Gateway != "" {
run("ip", "address", "replace", spec.Gateway, "dev", spec.TUNName)
}
run("ip", "link", "set", "dev", spec.TUNName, "mtu", strconv.Itoa(spec.MTU), "up")
// Only write the sysctl when forwarding is actually off. On most hosts it
// is already on, and the write is denied in restricted environments
// (containers, hardened kernels) where forwarding nonetheless works, which
// would otherwise report a failure for something already correct.
if !ipForwardingEnabled() {
run("sysctl", "-w", "net.ipv4.ip_forward=1")
}
// Each rule is added only when an identical one is not already present, so
// repeated restarts do not stack duplicates in the tables.
ensure := func(check, add []string) {
if _, err := runBTUNCommand("iptables", check...); err == nil {
return
}
if out, err := runBTUNCommand("iptables", add...); err != nil {
problems = append(problems, fmt.Sprintf("iptables %s: %v%s", strings.Join(add, " "), err, out))
}
}
ensure(
[]string{"-t", "nat", "-C", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"},
[]string{"-t", "nat", "-A", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"},
)
ensure(
[]string{"-C", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"},
[]string{"-A", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"},
)
ensure(
[]string{"-C", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"},
[]string{"-A", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"},
)
if len(problems) > 0 {
return spec, errors.New(strings.Join(problems, "; "))
}
btunLog.Printf("routing: %s %s up, NAT via %s", spec.TUNName, spec.Gateway, spec.WAN)
return spec, nil
}
// removeBTUNRouting deletes the rules applyBTUNRouting installed. Failures are
// logged and ignored: the rules may already be gone, or the interface may have
// disappeared with the TUN device.
func removeBTUNRouting(spec btunRoutingSpec) {
if spec.WAN == "" || spec.TUNName == "" {
return
}
deletes := [][]string{
{"-t", "nat", "-D", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"},
{"-D", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"},
{"-D", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"},
}
for _, args := range deletes {
if _, err := runBTUNCommand("iptables", args...); err != nil {
btunLog.Printf("routing cleanup: iptables %s: %v", strings.Join(args, " "), err)
}
}
}
// ipForwardingEnabled reports whether the kernel already forwards IPv4. A read
// error is treated as "not enabled" so the caller still attempts the write.
func ipForwardingEnabled() bool {
data, err := os.ReadFile("/proc/sys/net/ipv4/ip_forward")
if err != nil {
return false
}
return strings.TrimSpace(string(data)) == "1"
}
// detectDefaultWANInterface reads the uplink from the default IPv4 route, the
// same way the standalone btun-routing script does.
func detectDefaultWANInterface() (string, error) {
out, err := runBTUNCommand("ip", "-4", "route", "show", "default")
if err != nil {
return "", err
}
for _, line := range strings.Split(out, "\n") {
fields := strings.Fields(line)
for index := 0; index+1 < len(fields); index++ {
if fields[index] == "dev" {
return fields[index+1], nil
}
}
}
return "", errors.New("no default IPv4 route")
}
// runBTUNCommand runs a short host command with a timeout and returns its
// combined output. The output is included in error strings so a failing
// iptables rule is diagnosable from the panel.
func runBTUNCommand(name string, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), btunRouteCommandTimeout)
defer cancel()
var output bytes.Buffer
command := exec.CommandContext(ctx, name, args...)
command.Stdout = &output
command.Stderr = &output
err := command.Run()
text := strings.TrimSpace(output.String())
if text != "" {
text = ": " + text
}
return text, err
}
// ---------- Stats ----------
// BTUNStatsSnapshot is what /api/btun returns.
type BTUNStatsSnapshot struct {
Enabled bool `json:"enabled"`
Running bool `json:"running"`
Listen string `json:"listen,omitempty"`
TUNName string `json:"tunName,omitempty"`
Subnet string `json:"subnet,omitempty"`
btun.StatsSnapshot
}
// GetBTUNStatsSnapshot returns the current BTUN counters. It is safe for
// concurrent use and always returns a copy.
func GetBTUNStatsSnapshot() BTUNStatsSnapshot {
snapshot := BTUNStatsSnapshot{
Enabled: btunEnabledInCurrentConfig(),
Running: btunRunning(),
Listen: btunListenList(),
}
btunMu.Lock()
server := btunServer
device := btunDevice
btunMu.Unlock()
if device != nil {
snapshot.TUNName = device.Name()
}
if server != nil {
snapshot.StatsSnapshot = server.Stats()
}
globalCfgMu.RLock()
if globalCfg != nil && globalCfg.BTUN != nil {
snapshot.Subnet = globalCfg.BTUN.Subnet
}
globalCfgMu.RUnlock()
return snapshot
}
+184
View File
@@ -0,0 +1,184 @@
//go:build linux
package main
// These tests exercise the parts of BTUN that only exist on Linux and need real
// privileges: creating the TUN interface, and installing and removing the
// NAT/forward rules that let clients reach the internet. Nothing else in the
// suite can reach that code, so without these it ships unexecuted.
//
// They are opt-in because they need NET_ADMIN and /dev/net/tun. Run them with:
//
// docker run --rm --cap-add NET_ADMIN --device /dev/net/tun \
// -v "$PWD:/src" dragoncore-build tun
import (
"os"
"os/exec"
"strings"
"testing"
"time"
"shell2/internal/btun"
)
// requireTUN skips unless the environment can actually create a TUN device.
func requireTUN(t *testing.T) {
t.Helper()
if os.Getenv("BTUN_TUN_TESTS") == "" {
t.Skip("set BTUN_TUN_TESTS=1 and grant NET_ADMIN + /dev/net/tun to run this")
}
if _, err := os.Stat("/dev/net/tun"); err != nil {
t.Skipf("/dev/net/tun is unavailable: %v", err)
}
}
// OpenTUN is the call that fails on a container without /dev/net/tun and is the
// single most common reason BTUN does not start. This checks that it really
// creates the interface it names, and really releases it on Close.
func TestBTUNOpenTUNCreatesAndReleasesTheInterface(t *testing.T) {
requireTUN(t)
const name = "btuntest0"
device, err := btun.OpenTUN(name)
if err != nil {
t.Fatalf("OpenTUN(%q): %v", name, err)
}
if device.Name() != name {
t.Fatalf("device name = %q, want %q", device.Name(), name)
}
if !interfaceExists(t, name) {
t.Fatalf("interface %s was not created in the kernel", name)
}
if err := device.Close(); err != nil {
t.Fatalf("close: %v", err)
}
// The kernel removes the interface once the last handle is gone, which may
// take a moment.
deadline := time.Now().Add(5 * time.Second)
for interfaceExists(t, name) {
if time.Now().After(deadline) {
t.Fatalf("interface %s survived the device being closed", name)
}
time.Sleep(50 * time.Millisecond)
}
}
// An interface name the kernel cannot accept has to fail cleanly rather than
// leaving a half-open device behind.
func TestBTUNOpenTUNRejectsInvalidNames(t *testing.T) {
requireTUN(t)
for _, name := range []string{"", "this-name-is-far-too-long"} {
if device, err := btun.OpenTUN(name); err == nil {
_ = device.Close()
t.Fatalf("OpenTUN(%q) succeeded, want an error", name)
}
}
}
// The managed-routing path configures the interface and installs NAT. This runs
// it for real and then checks the rules it claims to have added are present,
// and that removing them leaves the tables as they were.
func TestBTUNManagedRoutingInstallsAndRemovesItsRules(t *testing.T) {
requireTUN(t)
if _, err := exec.LookPath("iptables"); err != nil {
t.Skip("iptables is not installed")
}
const name = "btuntest1"
const subnet = "10.79.0.0/24"
device, err := btun.OpenTUN(name)
if err != nil {
t.Fatalf("OpenTUN: %v", err)
}
defer device.Close()
cfg := &BTUNConfig{
TCPListen: "127.0.0.1:0",
Subnet: subnet,
TUNName: name,
MTU: 1400,
ManageRouting: true,
WANInterface: "eth0",
}
normalizeBTUNConfig(cfg)
if cfg.Gateway != "10.79.0.1/24" {
t.Fatalf("derived gateway = %q, want 10.79.0.1/24", cfg.Gateway)
}
spec, err := applyBTUNRouting(cfg, device.Name())
if err != nil {
t.Fatalf("applyBTUNRouting: %v", err)
}
t.Cleanup(func() { removeBTUNRouting(spec) })
if !interfaceHasAddress(t, name, "10.79.0.1") {
t.Fatalf("gateway address was not configured on %s", name)
}
if !natRuleExists(t, subnet) {
t.Fatalf("MASQUERADE rule for %s was not installed", subnet)
}
if got := readSysctl(t, "net.ipv4.ip_forward"); got != "1" {
t.Fatalf("net.ipv4.ip_forward = %q, want 1", got)
}
// Re-applying must not stack duplicates, which is what would happen on
// every panel restart if the rules were added unconditionally.
if _, err := applyBTUNRouting(cfg, device.Name()); err != nil {
t.Fatalf("second applyBTUNRouting: %v", err)
}
if count := natRuleCount(t, subnet); count != 1 {
t.Fatalf("MASQUERADE rule appears %d times after re-applying, want 1", count)
}
removeBTUNRouting(spec)
if natRuleExists(t, subnet) {
t.Fatalf("MASQUERADE rule for %s survived removal", subnet)
}
}
func interfaceExists(t *testing.T, name string) bool {
t.Helper()
return exec.Command("ip", "link", "show", name).Run() == nil
}
func interfaceHasAddress(t *testing.T, name, address string) bool {
t.Helper()
out, err := exec.Command("ip", "-4", "addr", "show", "dev", name).CombinedOutput()
if err != nil {
t.Fatalf("ip addr show %s: %v (%s)", name, err, out)
}
return strings.Contains(string(out), address)
}
func natRuleCount(t *testing.T, subnet string) int {
t.Helper()
out, err := exec.Command("iptables", "-t", "nat", "-S", "POSTROUTING").CombinedOutput()
if err != nil {
t.Fatalf("iptables -S POSTROUTING: %v (%s)", err, out)
}
count := 0
for _, line := range strings.Split(string(out), "\n") {
if strings.Contains(line, subnet) && strings.Contains(line, "MASQUERADE") {
count++
}
}
return count
}
func natRuleExists(t *testing.T, subnet string) bool {
t.Helper()
return natRuleCount(t, subnet) > 0
}
func readSysctl(t *testing.T, key string) string {
t.Helper()
path := "/proc/sys/" + strings.ReplaceAll(key, ".", "/")
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return strings.TrimSpace(string(data))
}
+122
View File
@@ -0,0 +1,122 @@
package main
import (
"database/sql"
"encoding/json"
"net/http"
"time"
)
// CheckResponse is returned by the public /check endpoint.
type CheckResponse struct {
Username string `json:"username"`
CountConnections int `json:"count_connections"`
ExpirationDate string `json:"expiration_date"`
ExpirationDays int `json:"expiration_days"`
LimitConnections int `json:"limit_connections"`
}
// handleCheck is the public user-check API. No authentication required.
// Accepts ?user=<ssh-username> or ?uuid=<xray-uuid> (or both; user takes priority).
// Returns JSON matching CheckResponse.
func handleCheck(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
q := r.URL.Query()
username := q.Get("user")
uuid := q.Get("uuid")
if username == "" && uuid == "" {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"user or uuid parameter required"}`))
return
}
if username != "" {
checkSSHUser(w, username)
return
}
checkXrayUUID(w, r, uuid)
}
func checkSSHUser(w http.ResponseWriter, username string) {
u, ok := userMgr.Get(username)
if !ok {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":"user not found"}`))
return
}
u.mu.Lock()
activeConns := len(u.conns) + u.btunConns
u.ActiveConns = activeConns
maxConns := u.Cfg.MaxConnections
expiresAt := u.ExpiresAt
u.mu.Unlock()
resp := CheckResponse{
Username: username,
CountConnections: activeConns,
LimitConnections: maxConns,
}
fillExpiry(&resp, expiresAt)
_ = json.NewEncoder(w).Encode(resp)
}
func checkXrayUUID(w http.ResponseWriter, r *http.Request, uuid string) {
if statsStore == nil {
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(`{"error":"database not configured"}`))
return
}
meta, err := statsStore.GetXrayClientMeta(r.Context(), uuid)
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":"uuid not found"}`))
return
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error":"database error"}`))
return
}
displayName := meta.Name
if displayName == "" {
displayName = meta.UUID
}
resp := CheckResponse{
Username: displayName,
CountConnections: 0,
LimitConnections: meta.MaxConns,
}
fillExpiry(&resp, meta.ExpiresAt)
_ = json.NewEncoder(w).Encode(resp)
}
func fillExpiry(resp *CheckResponse, expiresAt *time.Time) {
if expiresAt == nil {
resp.ExpirationDate = "Unlimited"
resp.ExpirationDays = -1
return
}
resp.ExpirationDate = expiresAt.Local().Format("02/01/2006")
days := int(time.Until(*expiresAt).Hours() / 24)
if days < 0 {
days = 0
}
resp.ExpirationDays = days
}
+40
View File
@@ -0,0 +1,40 @@
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestCLIAdminBearerToken(t *testing.T) {
secret := strings.Repeat("a", 48)
t.Setenv("ADMIN_TOKEN", secret)
h := saSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if sessionFromCtx(r.Context()).Role != RoleSuperAdmin {
t.Fatal("bearer token did not receive admin role")
}
w.WriteHeader(http.StatusNoContent)
}))
for _, tc := range []struct {
name, header string
want int
}{
{"valid", "Bearer " + secret, http.StatusNoContent},
{"wrong", "Bearer " + strings.Repeat("b", 48), http.StatusUnauthorized},
{"short", "Bearer a", http.StatusUnauthorized},
{"empty", "", http.StatusUnauthorized},
} {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/users", nil)
if tc.header != "" {
req.Header.Set("Authorization", tc.header)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Code != tc.want {
t.Fatalf("got status %d, want %d", w.Code, tc.want)
}
})
}
}
+647
View File
@@ -0,0 +1,647 @@
package main
import (
"fmt"
"log"
"net"
"strconv"
"strings"
"time"
)
const (
defaultMainListen = "0.0.0.0:80"
defaultExtraListen = "0.0.0.0:8080"
defaultLocalSSHListen = "127.0.0.1:2222"
defaultDNSTTListen = "0.0.0.0:5300"
defaultUDPGWListen = "0.0.0.0:7400"
)
// normalizeDurationField validates one optional duration setting in place. An
// invalid value is cleared so the service falls back to its own default rather
// than starting with a nonsense timeout.
func normalizeDurationField(value *string, label string, minimum, maximum time.Duration, warn func(string, ...interface{})) {
*value = strings.TrimSpace(*value)
if *value == "" {
return
}
d, err := time.ParseDuration(*value)
if err != nil || d <= 0 {
warn("%s %q is invalid; using the service default", label, *value)
*value = ""
return
}
if minimum > 0 && d < minimum {
warn("%s %q is below the minimum %s; clamping", label, *value, minimum)
*value = minimum.String()
return
}
if maximum > 0 && d > maximum {
warn("%s %q is above the maximum %s; clamping", label, *value, maximum)
*value = maximum.String()
}
}
// normalizeAutoRestartFields applies the shared auto-restart rules used by
// every embedded service: an interval below 1m disables the watchdog, and the
// grace delay is capped at 1m.
func normalizeAutoRestartFields(interval, grace *string, label string, warn func(string, ...interface{})) {
*interval = strings.TrimSpace(*interval)
if *interval != "" && *interval != "0" && *interval != "0s" &&
!strings.EqualFold(*interval, "off") && !strings.EqualFold(*interval, "disabled") {
if d, err := time.ParseDuration(*interval); err != nil {
warn("%s auto restart interval %q is invalid; disabling auto restart", label, *interval)
*interval = ""
} else if d < time.Minute {
warn("%s auto restart interval %q is below minimum 1m; disabling auto restart", label, *interval)
*interval = ""
}
}
*grace = strings.TrimSpace(*grace)
if *grace != "" {
if d, err := time.ParseDuration(*grace); err != nil || d < 0 {
warn("%s auto restart grace %q is invalid; using default 2s", label, *grace)
*grace = ""
} else if d > time.Minute {
warn("%s auto restart grace %q is above 1m; clamping to 1m", label, *grace)
*grace = "1m"
}
}
}
func normalizeRuntimePorts(cfg *Config) []string {
var warnings []string
warn := func(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
warnings = append(warnings, msg)
log.Printf("config safety: %s", msg)
}
cfg.Listen = strings.TrimSpace(cfg.Listen)
if cfg.Listen == "" {
cfg.Listen = defaultMainListen
}
if err := tcpAddrAvailableForPool(cfg.Listen, publicPool); err != nil {
old := cfg.Listen
cfg.Listen = defaultMainListen
warn("main listener %s is unavailable (%v); using default %s", old, err, cfg.Listen)
if err2 := tcpAddrAvailableForPool(cfg.Listen, publicPool); err2 != nil {
warn("default main listener %s is also unavailable: %v", cfg.Listen, err2)
}
}
seen := map[string]bool{cfg.Listen: true}
extra := make([]string, 0, len(cfg.ExtraListen))
for _, addr := range cfg.ExtraListen {
addr = strings.TrimSpace(addr)
if addr == "" || seen[addr] {
continue
}
if err := tcpAddrAvailableForPool(addr, publicPool); err != nil {
warn("extra listener %s is unavailable (%v)", addr, err)
fallback := defaultExtraListen
if !seen[fallback] {
if err2 := tcpAddrAvailableForPool(fallback, publicPool); err2 == nil {
extra = append(extra, fallback)
seen[fallback] = true
warn("extra listener fell back to default %s", fallback)
} else {
warn("default extra listener %s is also unavailable: %v", fallback, err2)
}
}
continue
}
extra = append(extra, addr)
seen[addr] = true
}
cfg.ExtraListen = extra
oldLocalSSHListen := strings.TrimSpace(cfg.LocalSSHListen)
normalizedLocalSSHListen, localSSHErr := normalizeLocalSSHListen(oldLocalSSHListen)
cfg.LocalSSHListen = normalizedLocalSSHListen
if localSSHErr != nil {
warn("internal SSH listener %q is invalid (%v); using safe default %s", oldLocalSSHListen, localSSHErr, cfg.LocalSSHListen)
}
if err := tcpAddrAvailableForPool(cfg.LocalSSHListen, localPool); err != nil {
old := cfg.LocalSSHListen
cfg.LocalSSHListen = defaultLocalSSHListen
if old != defaultLocalSSHListen {
warn("internal SSH listener %s is unavailable (%v); using default %s", old, err, cfg.LocalSSHListen)
}
if err2 := tcpAddrAvailableForPool(cfg.LocalSSHListen, localPool); err2 != nil {
warn("default internal SSH listener %s is unavailable: %v", cfg.LocalSSHListen, err2)
}
}
cfg.ProxyAutoRestartInterval = strings.TrimSpace(cfg.ProxyAutoRestartInterval)
if cfg.ProxyAutoRestartInterval != "" && cfg.ProxyAutoRestartInterval != "0" && cfg.ProxyAutoRestartInterval != "0s" && !strings.EqualFold(cfg.ProxyAutoRestartInterval, "off") && !strings.EqualFold(cfg.ProxyAutoRestartInterval, "disabled") {
if d, err := time.ParseDuration(cfg.ProxyAutoRestartInterval); err != nil {
warn("proxy auto restart interval %q is invalid; disabling auto restart", cfg.ProxyAutoRestartInterval)
cfg.ProxyAutoRestartInterval = ""
} else if d < time.Minute {
warn("proxy auto restart interval %q is below 1m; disabling auto restart", cfg.ProxyAutoRestartInterval)
cfg.ProxyAutoRestartInterval = ""
}
}
cfg.ProxyAutoRestartGrace = strings.TrimSpace(cfg.ProxyAutoRestartGrace)
if cfg.ProxyAutoRestartGrace != "" {
if d, err := time.ParseDuration(cfg.ProxyAutoRestartGrace); err != nil || d < 0 {
warn("proxy auto restart grace %q is invalid; using default 2s", cfg.ProxyAutoRestartGrace)
cfg.ProxyAutoRestartGrace = ""
} else if d > time.Minute {
warn("proxy auto restart grace %q is above 1m; clamping to 1m", cfg.ProxyAutoRestartGrace)
cfg.ProxyAutoRestartGrace = "1m"
}
}
if cfg.DNSTT != nil {
cfg.DNSTT.FakeDNSDomain = strings.TrimSpace(cfg.DNSTT.FakeDNSDomain)
if cfg.DNSTT.FakeDNSEnabled {
if cfg.DNSTT.FakeDNSDomain == "" {
cfg.DNSTT.FakeDNSDomain = "t.local.lan"
}
// Automatically add the local/fake test zone to the accepted DNSTT
// domains so the tunnel handler can decode traffic for it.
cfg.DNSTT.Domains = append(cfg.DNSTT.Domains, cfg.DNSTT.FakeDNSDomain)
}
cfg.DNSTT.Domains = normalizeDNSTTDomainList(cfg.DNSTT.Domain, cfg.DNSTT.Domains)
if len(cfg.DNSTT.Domains) > 0 {
cfg.DNSTT.Domain = cfg.DNSTT.Domains[0]
} else {
cfg.DNSTT.Domain = strings.TrimSpace(cfg.DNSTT.Domain)
}
if cfg.DNSTT.FakeDNSEnabled {
localDomains := normalizeDNSTTDomainList(cfg.DNSTT.FakeDNSDomain, nil)
if len(localDomains) > 0 {
cfg.DNSTT.FakeDNSDomain = localDomains[0]
}
}
var migratedLegacyDNSTTWildcard bool
cfg.DNSTT.UDPListen, migratedLegacyDNSTTWildcard = normalizeDNSTTListenDefault(cfg.DNSTT.UDPListen)
if migratedLegacyDNSTTWildcard {
warn("DNSTT legacy default [::]:5300 is IPv6-only; using IPv4 default %s", cfg.DNSTT.UDPListen)
}
if err := udpAddrAvailableForDNSTT(cfg.DNSTT.UDPListen); err != nil {
old := cfg.DNSTT.UDPListen
cfg.DNSTT.UDPListen = defaultDNSTTListen
warn("DNSTT UDP listener %s is unavailable (%v); using default %s", old, err, cfg.DNSTT.UDPListen)
if err2 := udpAddrAvailableForDNSTT(cfg.DNSTT.UDPListen); err2 != nil {
warn("default DNSTT UDP listener %s is also unavailable: %v", cfg.DNSTT.UDPListen, err2)
}
}
if cfg.DNSTT.FakeDNSEnabled {
cfg.DNSTT.FakeDNSListen = strings.TrimSpace(cfg.DNSTT.FakeDNSListen)
if cfg.DNSTT.FakeDNSListen == "" {
cfg.DNSTT.FakeDNSListen = "[::]:53"
}
if !sameUDPListenAddress(cfg.DNSTT.FakeDNSListen, cfg.DNSTT.UDPListen) {
if err := udpAddrAvailableForDNSTT(cfg.DNSTT.FakeDNSListen); err != nil {
warn("built-in DNSTT local DNS listener %s is unavailable: %v", cfg.DNSTT.FakeDNSListen, err)
}
}
}
cfg.DNSTT.AutoRestartInterval = strings.TrimSpace(cfg.DNSTT.AutoRestartInterval)
if cfg.DNSTT.AutoRestartInterval != "" && cfg.DNSTT.AutoRestartInterval != "0" && cfg.DNSTT.AutoRestartInterval != "0s" && !strings.EqualFold(cfg.DNSTT.AutoRestartInterval, "off") && !strings.EqualFold(cfg.DNSTT.AutoRestartInterval, "disabled") {
if d, err := time.ParseDuration(cfg.DNSTT.AutoRestartInterval); err != nil {
warn("DNSTT auto restart interval %q is invalid; disabling auto restart", cfg.DNSTT.AutoRestartInterval)
cfg.DNSTT.AutoRestartInterval = ""
} else if d < time.Minute {
warn("DNSTT auto restart interval %q is below 1m; disabling auto restart", cfg.DNSTT.AutoRestartInterval)
cfg.DNSTT.AutoRestartInterval = ""
}
}
cfg.DNSTT.AutoRestartGrace = strings.TrimSpace(cfg.DNSTT.AutoRestartGrace)
if cfg.DNSTT.AutoRestartGrace != "" {
if d, err := time.ParseDuration(cfg.DNSTT.AutoRestartGrace); err != nil || d < 0 {
warn("DNSTT auto restart grace %q is invalid; using default 2s", cfg.DNSTT.AutoRestartGrace)
cfg.DNSTT.AutoRestartGrace = ""
} else if d > time.Minute {
warn("DNSTT auto restart grace %q is above 1m; clamping to 1m", cfg.DNSTT.AutoRestartGrace)
cfg.DNSTT.AutoRestartGrace = "1m"
}
}
if cfg.DNSTT.MaxSessions < -1 {
warn("DNSTT max_sessions %d is invalid; using unlimited (-1)", cfg.DNSTT.MaxSessions)
cfg.DNSTT.MaxSessions = -1
}
if cfg.DNSTT.MaxStreams < -1 {
warn("DNSTT max_streams %d is invalid; using unlimited (-1)", cfg.DNSTT.MaxStreams)
cfg.DNSTT.MaxStreams = -1
}
if cfg.DNSTT.PendingResponses > 0 {
if cfg.DNSTT.PendingResponses < minDNSTTPendingResponses {
warn("DNSTT pending_responses %d is too low; clamping to %d", cfg.DNSTT.PendingResponses, minDNSTTPendingResponses)
cfg.DNSTT.PendingResponses = minDNSTTPendingResponses
} else if cfg.DNSTT.PendingResponses > maxDNSTTPendingResponses {
warn("DNSTT pending_responses %d is too high; clamping to %d", cfg.DNSTT.PendingResponses, maxDNSTTPendingResponses)
cfg.DNSTT.PendingResponses = maxDNSTTPendingResponses
}
}
if cfg.DNSTT.StreamBuffer > 0 {
if cfg.DNSTT.StreamBuffer < minDNSTTStreamBuffer {
warn("DNSTT stream_buffer %d is too low; clamping to %d", cfg.DNSTT.StreamBuffer, minDNSTTStreamBuffer)
cfg.DNSTT.StreamBuffer = minDNSTTStreamBuffer
} else if cfg.DNSTT.StreamBuffer > maxDNSTTStreamBuffer {
warn("DNSTT stream_buffer %d is too high; clamping to %d", cfg.DNSTT.StreamBuffer, maxDNSTTStreamBuffer)
cfg.DNSTT.StreamBuffer = maxDNSTTStreamBuffer
}
}
if cfg.DNSTT.UDPReadBuffer < 0 {
warn("DNSTT udp_read_buffer %d is invalid; using default", cfg.DNSTT.UDPReadBuffer)
cfg.DNSTT.UDPReadBuffer = 0
}
if cfg.DNSTT.UDPWriteBuffer < 0 {
warn("DNSTT udp_write_buffer %d is invalid; using default", cfg.DNSTT.UDPWriteBuffer)
cfg.DNSTT.UDPWriteBuffer = 0
}
if cfg.DNSTT.FakeDNSWorkers < 0 {
warn("DNSTT fake_dns_workers %d is invalid; using automatic default", cfg.DNSTT.FakeDNSWorkers)
cfg.DNSTT.FakeDNSWorkers = 0
} else if cfg.DNSTT.FakeDNSWorkers > maxDNSTTFakeDNSWorkers {
warn("DNSTT fake_dns_workers %d is too high; clamping to %d", cfg.DNSTT.FakeDNSWorkers, maxDNSTTFakeDNSWorkers)
cfg.DNSTT.FakeDNSWorkers = maxDNSTTFakeDNSWorkers
}
if cfg.DNSTT.DNSResponseWorkers < 0 {
warn("DNSTT dns_response_workers %d is invalid; using default", cfg.DNSTT.DNSResponseWorkers)
cfg.DNSTT.DNSResponseWorkers = 0
} else if cfg.DNSTT.DNSResponseWorkers > maxDNSTTResponseWorkers {
warn("DNSTT dns_response_workers %d is too high; clamping to %d", cfg.DNSTT.DNSResponseWorkers, maxDNSTTResponseWorkers)
cfg.DNSTT.DNSResponseWorkers = maxDNSTTResponseWorkers
}
}
if cfg.UDPGW != nil {
cfg.UDPGW.Listen = strings.TrimSpace(cfg.UDPGW.Listen)
if cfg.UDPGW.Listen == "" {
cfg.UDPGW.Listen = defaultUDPGWListen
}
if err := tcpAddrAvailableForUDPGW(cfg.UDPGW.Listen); err != nil {
old := cfg.UDPGW.Listen
cfg.UDPGW.Listen = defaultUDPGWListen
warn("UDPGW listener %s is unavailable (%v); using default %s", old, err, cfg.UDPGW.Listen)
if err2 := tcpAddrAvailableForUDPGW(cfg.UDPGW.Listen); err2 != nil {
warn("default UDPGW listener %s is also unavailable: %v", cfg.UDPGW.Listen, err2)
}
}
cfg.UDPGW.AutoRestartInterval = strings.TrimSpace(cfg.UDPGW.AutoRestartInterval)
if cfg.UDPGW.AutoRestartInterval != "" && cfg.UDPGW.AutoRestartInterval != "0" && cfg.UDPGW.AutoRestartInterval != "0s" && !strings.EqualFold(cfg.UDPGW.AutoRestartInterval, "off") && !strings.EqualFold(cfg.UDPGW.AutoRestartInterval, "disabled") {
if d, err := time.ParseDuration(cfg.UDPGW.AutoRestartInterval); err != nil {
warn("UDPGW auto restart interval %q is invalid; disabling auto restart", cfg.UDPGW.AutoRestartInterval)
cfg.UDPGW.AutoRestartInterval = ""
} else if d < time.Minute {
warn("UDPGW auto restart interval %q is below 1m; disabling auto restart", cfg.UDPGW.AutoRestartInterval)
cfg.UDPGW.AutoRestartInterval = ""
}
}
cfg.UDPGW.AutoRestartGrace = strings.TrimSpace(cfg.UDPGW.AutoRestartGrace)
if cfg.UDPGW.AutoRestartGrace != "" {
if d, err := time.ParseDuration(cfg.UDPGW.AutoRestartGrace); err != nil || d < 0 {
warn("UDPGW auto restart grace %q is invalid; using default 2s", cfg.UDPGW.AutoRestartGrace)
cfg.UDPGW.AutoRestartGrace = ""
} else if d > time.Minute {
warn("UDPGW auto restart grace %q is above 1m; clamping to 1m", cfg.UDPGW.AutoRestartGrace)
cfg.UDPGW.AutoRestartGrace = "1m"
}
}
}
if cfg.BHTTP != nil {
addrs := normalizeBHTTPListenList(cfg.BHTTP.Listen)
if len(addrs) == 0 && !cfg.BHTTP.SharedPorts {
// With no dedicated listener and no shared ports nothing would
// serve BHTTP at all, so fall back to a port of its own.
addrs = []string{defaultBHTTPListen}
warn("BHTTP has no listen address and shared ports are off; using default %s", defaultBHTTPListen)
}
kept := make([]string, 0, len(addrs))
for _, addr := range addrs {
if err := tcpAddrAvailableForBHTTP(addr); err != nil {
warn("BHTTP listener %s is unavailable (%v)", addr, err)
continue
}
kept = append(kept, addr)
}
if len(addrs) > 0 && len(kept) == 0 {
warn("no BHTTP listener could be opened; keeping the configured addresses so the panel reports the failure")
kept = addrs
}
cfg.BHTTP.Listen = kept
normalizeDurationField(&cfg.BHTTP.SessionTimeout, "BHTTP session_timeout", 10*time.Second, time.Hour, warn)
if cfg.BHTTP.MaxV2Lanes < 0 {
warn("BHTTP max_v2_lanes %d is invalid; using the protocol default", cfg.BHTTP.MaxV2Lanes)
cfg.BHTTP.MaxV2Lanes = 0
}
if cfg.BHTTP.MaxSessions < -1 {
warn("BHTTP max_sessions %d is invalid; using unlimited (-1)", cfg.BHTTP.MaxSessions)
cfg.BHTTP.MaxSessions = -1
}
if cfg.BHTTP.MaxConnections < -1 {
warn("BHTTP max_connections %d is invalid; using unlimited (-1)", cfg.BHTTP.MaxConnections)
cfg.BHTTP.MaxConnections = -1
}
normalizeAutoRestartFields(&cfg.BHTTP.AutoRestartInterval, &cfg.BHTTP.AutoRestartGrace, "BHTTP", warn)
}
if cfg.BTUN != nil {
normalizeBTUNConfig(cfg.BTUN)
if cfg.BTUN.TCPListen == "" && cfg.BTUN.UDPListen == "" && !cfg.BTUN.SharedPorts {
// With no listener and no shared ports nothing would serve BTUN at
// all, so fall back to ports of its own.
cfg.BTUN.TCPListen = defaultBTUNTCPListen
cfg.BTUN.UDPListen = defaultBTUNUDPListen
warn("BTUN has no listener and shared ports are off; using defaults tcp/udp %s", defaultBTUNTCPListen)
}
if cfg.BTUN.TCPListen != "" {
if err := tcpAddrAvailableForBTUN(cfg.BTUN.TCPListen); err != nil {
warn("BTUN TCP listener %s is unavailable (%v)", cfg.BTUN.TCPListen, err)
}
}
if cfg.BTUN.UDPListen != "" {
if err := udpAddrAvailableForBTUN(cfg.BTUN.UDPListen); err != nil {
warn("BTUN UDP listener %s is unavailable (%v)", cfg.BTUN.UDPListen, err)
}
}
if _, _, err := net.ParseCIDR(cfg.BTUN.Subnet); err != nil {
warn("BTUN subnet %q is invalid (%v); using default %s", cfg.BTUN.Subnet, err, defaultBTUNSubnet)
cfg.BTUN.Subnet = defaultBTUNSubnet
cfg.BTUN.Gateway = ""
}
if gateway, err := btunGatewayForSubnet(cfg.BTUN.Subnet); err != nil {
warn("BTUN subnet %q cannot host clients (%v); using default %s", cfg.BTUN.Subnet, err, defaultBTUNSubnet)
cfg.BTUN.Subnet = defaultBTUNSubnet
cfg.BTUN.Gateway, _ = btunGatewayForSubnet(defaultBTUNSubnet)
} else if cfg.BTUN.Gateway == "" {
cfg.BTUN.Gateway = gateway
} else if _, _, err := net.ParseCIDR(cfg.BTUN.Gateway); err != nil {
warn("BTUN gateway %q is invalid (%v); deriving %s from the subnet", cfg.BTUN.Gateway, err, gateway)
cfg.BTUN.Gateway = gateway
}
if cfg.BTUN.MTU < 576 || cfg.BTUN.MTU > 9000 {
warn("BTUN mtu %d is out of the 576..9000 range; using default %d", cfg.BTUN.MTU, defaultBTUNMTU)
cfg.BTUN.MTU = defaultBTUNMTU
}
normalizeDurationField(&cfg.BTUN.HandshakeTimeout, "BTUN handshake_timeout", time.Second, 5*time.Minute, warn)
normalizeDurationField(&cfg.BTUN.IdleTimeout, "BTUN idle_timeout", 10*time.Second, time.Hour, warn)
if cfg.BTUN.MaxPacketSize < 0 {
warn("BTUN max_packet_size %d is invalid; using the protocol default", cfg.BTUN.MaxPacketSize)
cfg.BTUN.MaxPacketSize = 0
}
if cfg.BTUN.MaxCoverBytes < 0 {
warn("BTUN max_cover_bytes %d is invalid; using the protocol default", cfg.BTUN.MaxCoverBytes)
cfg.BTUN.MaxCoverBytes = 0
}
if cfg.BTUN.MaxSessions < -1 {
warn("BTUN max_sessions %d is invalid; using unlimited (-1)", cfg.BTUN.MaxSessions)
cfg.BTUN.MaxSessions = -1
}
normalizeAutoRestartFields(&cfg.BTUN.AutoRestartInterval, &cfg.BTUN.AutoRestartGrace, "BTUN", warn)
}
if cfg.HCR != nil {
addrs := normalizeHCRListenList(cfg.HCR.Listen)
if len(addrs) == 0 && !cfg.HCR.SharedPorts {
addrs = []string{defaultHCRListen}
warn("HCR has no listen address and shared ports are off; using default %s", defaultHCRListen)
}
kept := make([]string, 0, len(addrs))
for _, addr := range addrs {
if err := tcpAddrAvailableForHCR(addr); err != nil {
warn("HCR listener %s is unavailable (%v)", addr, err)
continue
}
kept = append(kept, addr)
}
if len(addrs) > 0 && len(kept) == 0 {
warn("no HCR listener could be opened; keeping the configured addresses so the panel reports the failure")
kept = addrs
}
cfg.HCR.Listen = kept
normalizeDurationField(&cfg.HCR.DownloadPollTimeout, "HCR download_poll_timeout", time.Second, time.Minute, warn)
normalizeDurationField(&cfg.HCR.IdleSessionTimeout, "HCR idle_session_timeout", 10*time.Second, time.Hour, warn)
if cfg.HCR.MaxSessions < -1 {
warn("HCR max_sessions %d is invalid; using unlimited (-1)", cfg.HCR.MaxSessions)
cfg.HCR.MaxSessions = -1
}
if cfg.HCR.MaxConnections < -1 {
warn("HCR max_connections %d is invalid; using unlimited (-1)", cfg.HCR.MaxConnections)
cfg.HCR.MaxConnections = -1
}
if cfg.HCR.MaxSourceSessions < 0 {
warn("HCR max_source_sessions %d is invalid; using 0 (unlimited)", cfg.HCR.MaxSourceSessions)
cfg.HCR.MaxSourceSessions = 0
}
if cfg.HCR.MaxDownloadFrame < 0 {
warn("HCR max_download_frame %d is invalid; using the default", cfg.HCR.MaxDownloadFrame)
cfg.HCR.MaxDownloadFrame = 0
}
normalizeAutoRestartFields(&cfg.HCR.AutoRestartInterval, &cfg.HCR.AutoRestartGrace, "HCR", warn)
}
return warnings
}
// tcpAddrAvailableForHCR reports whether an HCR listen address can be bound. An
// address this process already serves for HCR is treated as available.
func tcpAddrAvailableForHCR(addr string) error {
if addr == "" {
return nil
}
if hcrRunning() {
for _, current := range strings.Split(hcrListenList(), ", ") {
if strings.TrimSpace(current) == addr {
return nil
}
}
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return ln.Close()
}
// tcpAddrAvailableForBHTTP reports whether a BHTTP listen address can be bound.
// An address this process already serves for BHTTP is treated as available, so
// saving an unchanged config does not report a false conflict.
func tcpAddrAvailableForBHTTP(addr string) error {
if addr == "" {
return nil
}
if bhttpRunning() {
for _, current := range strings.Split(bhttpListenList(), ", ") {
if strings.TrimSpace(current) == addr {
return nil
}
}
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return ln.Close()
}
func tcpAddrAvailableForBTUN(addr string) error {
if addr == "" {
return nil
}
btunMu.Lock()
current := btunListenTCP
running := btunServer != nil
btunMu.Unlock()
if running && current == addr {
return nil
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return ln.Close()
}
func udpAddrAvailableForBTUN(addr string) error {
if addr == "" {
return nil
}
btunMu.Lock()
current := btunListenUDP
running := btunServer != nil
btunMu.Unlock()
if running && current == addr {
return nil
}
pc, err := net.ListenPacket("udp", addr)
if err != nil {
return err
}
return pc.Close()
}
// normalizeLocalSSHListen guarantees that the raw integration endpoint can
// only bind to this machine. Hostnames and wildcard/non-loopback addresses are
// deliberately rejected: a changed hosts file must not turn an internal SSH
// port into a remotely reachable service.
func normalizeLocalSSHListen(addr string) (string, error) {
addr = strings.TrimSpace(addr)
if addr == "" {
return defaultLocalSSHListen, nil
}
host, portText, err := net.SplitHostPort(addr)
if err != nil {
return defaultLocalSSHListen, fmt.Errorf("expected loopback host:port: %w", err)
}
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
return defaultLocalSSHListen, fmt.Errorf("host must be a numeric loopback IP")
}
port, err := strconv.Atoi(portText)
if err != nil || port < 1 || port > 65535 {
return defaultLocalSSHListen, fmt.Errorf("port must be between 1 and 65535")
}
if ipv4 := ip.To4(); ipv4 != nil {
ip = ipv4
}
return net.JoinHostPort(ip.String(), strconv.Itoa(port)), nil
}
func tcpAddrAvailableForPool(addr string, pool *listenerPool) error {
if addr == "" {
return nil
}
if pool != nil && pool.Has(addr) {
return nil
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return ln.Close()
}
func tcpAddrAvailableForUDPGW(addr string) error {
if addr == "" {
return nil
}
globalCfgMu.RLock()
current := globalCfg != nil && globalCfg.UDPGW != nil && globalCfg.UDPGW.Listen == addr && udpgwRunning()
globalCfgMu.RUnlock()
if current {
return nil
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return ln.Close()
}
func normalizeDNSTTDomainList(primary string, domains []string) []string {
seen := make(map[string]bool, len(domains)+1)
out := make([]string, 0, len(domains)+1)
add := func(v string) {
v = strings.TrimSpace(v)
v = strings.TrimSuffix(v, ".")
v = strings.ToLower(v)
if v == "" || seen[v] {
return
}
seen[v] = true
out = append(out, v)
}
add(primary)
for _, d := range domains {
add(d)
}
return out
}
// normalizeDNSTTListenDefault keeps explicit IPv4 and concrete IPv6 listeners,
// but migrates the old wildcard IPv6 default. listenDNSTTPacket deliberately
// opens IPv6 addresses with udp6, so [::]:5300 never receives IPv4 queries.
// Existing installations commonly inherited that value from the old default;
// moving only that wildcard/default-port combination makes them work after an
// update without changing intentionally selected IPv6 interface addresses.
func normalizeDNSTTListenDefault(addr string) (string, bool) {
addr = strings.TrimSpace(addr)
if addr == "" {
return defaultDNSTTListen, false
}
host, port, err := net.SplitHostPort(addr)
if err != nil || port != "5300" {
return addr, false
}
ip := net.ParseIP(strings.Trim(host, "[]"))
if ip != nil && ip.To4() == nil && ip.IsUnspecified() {
return defaultDNSTTListen, true
}
return addr, false
}
func udpAddrAvailableForDNSTT(addr string) error {
if addr == "" {
return nil
}
globalCfgMu.RLock()
current := false
if globalCfg != nil && globalCfg.DNSTT != nil && dnsttRunning() {
current = sameUDPListenAddress(globalCfg.DNSTT.UDPListen, addr) || sameUDPListenAddress(globalCfg.DNSTT.FakeDNSListen, addr)
}
globalCfgMu.RUnlock()
if current {
return nil
}
pc, err := listenDNSTTPacket(addr)
if err != nil {
return err
}
return pc.Close()
}
+64
View File
@@ -0,0 +1,64 @@
package main
import "testing"
func TestNormalizeLocalSSHListen(t *testing.T) {
tests := []struct {
name string
input string
want string
wantErr bool
}{
{name: "empty uses safe default", input: "", want: defaultLocalSSHListen},
{name: "whitespace uses safe default", input: " ", want: defaultLocalSSHListen},
{name: "IPv4 loopback", input: "127.0.0.1:2200", want: "127.0.0.1:2200"},
{name: "other IPv4 loopback", input: "127.10.20.30:2222", want: "127.10.20.30:2222"},
{name: "IPv6 loopback", input: "[::1]:2222", want: "[::1]:2222"},
{name: "wildcard IPv4 rejected", input: "0.0.0.0:2222", want: defaultLocalSSHListen, wantErr: true},
{name: "wildcard IPv6 rejected", input: "[::]:2222", want: defaultLocalSSHListen, wantErr: true},
{name: "public address rejected", input: "192.0.2.10:2222", want: defaultLocalSSHListen, wantErr: true},
{name: "hostname rejected", input: "localhost:2222", want: defaultLocalSSHListen, wantErr: true},
{name: "missing port rejected", input: "127.0.0.1", want: defaultLocalSSHListen, wantErr: true},
{name: "zero port rejected", input: "127.0.0.1:0", want: defaultLocalSSHListen, wantErr: true},
{name: "large port rejected", input: "127.0.0.1:65536", want: defaultLocalSSHListen, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := normalizeLocalSSHListen(tt.input)
if got != tt.want {
t.Fatalf("normalizeLocalSSHListen(%q) address = %q, want %q", tt.input, got, tt.want)
}
if (err != nil) != tt.wantErr {
t.Fatalf("normalizeLocalSSHListen(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
}
})
}
}
func TestNormalizeDNSTTListenDefault(t *testing.T) {
tests := []struct {
name string
input string
want string
migrated bool
}{
{name: "empty uses IPv4 default", input: "", want: "0.0.0.0:5300"},
{name: "whitespace uses IPv4 default", input: " ", want: "0.0.0.0:5300"},
{name: "legacy IPv6 wildcard migrates", input: "[::]:5300", want: "0.0.0.0:5300", migrated: true},
{name: "expanded legacy wildcard migrates", input: "[0:0:0:0:0:0:0:0]:5300", want: "0.0.0.0:5300", migrated: true},
{name: "explicit IPv4 remains", input: "192.0.2.10:53", want: "192.0.2.10:53"},
{name: "IPv4 wildcard remains", input: "0.0.0.0:5300", want: "0.0.0.0:5300"},
{name: "concrete IPv6 remains", input: "[2001:db8::10]:53", want: "[2001:db8::10]:53"},
{name: "IPv6 wildcard on custom port remains", input: "[::]:5301", want: "[::]:5301"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, migrated := normalizeDNSTTListenDefault(tt.input)
if got != tt.want || migrated != tt.migrated {
t.Fatalf("normalizeDNSTTListenDefault(%q) = (%q, %v), want (%q, %v)", tt.input, got, migrated, tt.want, tt.migrated)
}
})
}
}
+35
View File
@@ -0,0 +1,35 @@
package main
import (
"testing"
"time"
)
func TestSSHIdleTimeoutDisabledByDefault(t *testing.T) {
for _, raw := range []string{"", "0", "0s", "off", "disabled"} {
if got := parseSSHIdleTimeout(raw); got != 0 {
t.Fatalf("parseSSHIdleTimeout(%q) = %s, want disabled", raw, got)
}
}
}
func TestSSHIdleTimeoutExplicitValue(t *testing.T) {
if got := parseSSHIdleTimeout("30m"); got != 30*time.Minute {
t.Fatalf("got %s, want 30m", got)
}
}
// The connected-session sweeper is the backstop that reaps XHTTP->SSH sessions
// whose stream-down GET context never fires (silent client drop behind a CDN).
// Without it those sessions leak fds/goroutines until a process restart, which
// is what produced the recurring reboot-only XHTTP 502s. It must stay enabled;
// the window is generous so only zero-traffic (dead) sessions are reaped.
func TestNativeXHTTPConnectedIdleSweepEnabled(t *testing.T) {
got := nativeXHTTPIdleTimeout()
if got <= 0 {
t.Fatalf("native XHTTP idle timeout = %s, want a positive backstop window", got)
}
if got != 20*time.Minute {
t.Fatalf("native XHTTP idle timeout = %s, want 20m backstop", got)
}
}
+29
View File
@@ -0,0 +1,29 @@
package main
import (
"encoding/base64"
"fmt"
"strings"
)
func sealCredential(prefix, plain string) (string, error) {
if plain == "" || strings.HasPrefix(plain, prefix) {
return plain, nil
}
enc, err := encryptSecret(plain)
if err != nil {
return "", err
}
return prefix + base64.RawStdEncoding.EncodeToString(enc), nil
}
func openCredential(prefix, stored string) (string, error) {
if !strings.HasPrefix(stored, prefix) {
return stored, nil
}
raw, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(stored, prefix))
if err != nil {
return "", fmt.Errorf("decode encrypted credential: %w", err)
}
return decryptSecret(raw)
}
+232
View File
@@ -0,0 +1,232 @@
package main
import (
"errors"
"strings"
)
// Traditional DES-based crypt(3) — the 13-character, no-"$"-prefix hash used by
// old Linux/UNIX systems (e.g. accounts created with perl's crypt() or legacy
// SSH-account scripts). Pure Go; no dependency on libcrypt.
//
// Verified against the canonical vector crypt("rasmuslerdorf","rl") ==
// "rl.3StKT.4T8M" (see descrypt_test.go).
const cryptAlphabet = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
func crypt64Decode(c byte) int {
return strings.IndexByte(cryptAlphabet, c)
}
// ---- Standard DES permutation tables (1-indexed, MSB-first) ----
var ipTable = []int{
58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7,
}
var fpTable = []int{
40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25,
}
var eTable = []int{
32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1,
}
var pTable = []int{
16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25,
}
var pc1Table = []int{
57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4,
}
var pc2Table = []int{
14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32,
}
var shiftTable = []int{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}
var sBoxes = [8][64]int{
{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13},
{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9},
{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12},
{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14},
{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3},
{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13},
{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12},
{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11},
}
// permute selects bits from in (each element 0/1, MSB-first) per a 1-indexed table.
func permute(in []byte, table []int) []byte {
out := make([]byte, len(table))
for i, pos := range table {
out[i] = in[pos-1]
}
return out
}
func keySchedule(key64 []byte) [][]byte {
cd := permute(key64, pc1Table) // 56 bits
c := cd[:28]
d := cd[28:]
subkeys := make([][]byte, 16)
for i := 0; i < 16; i++ {
c = rotl(c, shiftTable[i])
d = rotl(d, shiftTable[i])
combined := append(append([]byte{}, c...), d...)
subkeys[i] = permute(combined, pc2Table) // 48 bits
}
return subkeys
}
func rotl(b []byte, n int) []byte {
out := make([]byte, len(b))
for i := range b {
out[i] = b[(i+n)%len(b)]
}
return out
}
// feistel computes f(R, K) with the salt-perturbed E expansion.
func feistel(r []byte, k []byte, saltMask [24]bool) []byte {
e := permute(r, eTable) // 48 bits
// Salt: for i in 0..23, if saltMask[i] swap E-output bits i and i+24.
for i := 0; i < 24; i++ {
if saltMask[i] {
e[i], e[i+24] = e[i+24], e[i]
}
}
x := make([]byte, 48)
for i := range x {
x[i] = e[i] ^ k[i]
}
out := make([]byte, 32)
for box := 0; box < 8; box++ {
off := box * 6
row := int(x[off])<<1 | int(x[off+5])
col := int(x[off+1])<<3 | int(x[off+2])<<2 | int(x[off+3])<<1 | int(x[off+4])
val := sBoxes[box][row*16+col]
for bit := 0; bit < 4; bit++ {
out[box*4+bit] = byte((val >> (3 - bit)) & 1)
}
}
return permute(out, pTable)
}
func desEncryptBlock(block []byte, subkeys [][]byte, saltMask [24]bool) []byte {
ip := permute(block, ipTable)
l := ip[:32]
r := ip[32:]
for i := 0; i < 16; i++ {
f := feistel(r, subkeys[i], saltMask)
newR := make([]byte, 32)
for j := 0; j < 32; j++ {
newR[j] = l[j] ^ f[j]
}
l = r
r = newR
}
pre := append(append([]byte{}, r...), l...) // R16 L16
return permute(pre, fpTable)
}
// desCrypt implements the traditional 13-char DES crypt. setting supplies the
// 2-char salt (its first two characters).
func desCrypt(password, setting string) (string, error) {
if len(setting) < 2 {
return "", errors.New("descrypt: salt too short")
}
s0 := crypt64Decode(setting[0])
s1 := crypt64Decode(setting[1])
if s0 < 0 || s1 < 0 {
return "", errors.New("descrypt: bad salt characters")
}
salt := s0 | (s1 << 6)
var saltMask [24]bool
for i := 0; i < 24; i++ {
if (salt>>i)&1 == 1 {
saltMask[i] = true
}
}
// Key: first 8 bytes of the password, each char<<1 forms a key byte.
key64 := make([]byte, 64)
for i := 0; i < 8; i++ {
var c byte
if i < len(password) {
c = password[i]
}
kb := c << 1
for bit := 0; bit < 8; bit++ {
key64[i*8+bit] = (kb >> (7 - bit)) & 1
}
}
subkeys := keySchedule(key64)
block := make([]byte, 64) // all zeros
for iter := 0; iter < 25; iter++ {
block = desEncryptBlock(block, subkeys, saltMask)
}
return string(setting[0]) + string(setting[1]) + encodeDESOutput(block), nil
}
// encodeDESOutput packs the 64-bit result (MSB-first bit array) into 11
// crypt-base64 characters: eleven 6-bit groups read most-significant-bit first,
// the last group zero-padded to 6 bits.
func encodeDESOutput(block []byte) string {
out := make([]byte, 0, 11)
for j := 0; j < 11; j++ {
v := 0
for k := 0; k < 6; k++ {
idx := j*6 + k
bit := 0
if idx < len(block) {
bit = int(block[idx])
}
v = (v << 1) | bit
}
out = append(out, cryptAlphabet[v])
}
return string(out)
}
+15
View File
@@ -0,0 +1,15 @@
package main
import "testing"
func TestDESCryptCanonical(t *testing.T) {
got, err := desCrypt("rasmuslerdorf", "rl")
if err != nil {
t.Fatal(err)
}
want := "rl.3StKT.4T8M"
t.Logf("got=%q want=%q", got, want)
if got != want {
t.Errorf("desCrypt mismatch: got %q want %q", got, want)
}
}
+1893
View File
File diff suppressed because it is too large Load Diff
+947
View File
@@ -0,0 +1,947 @@
#!/usr/bin/env python3
"""DragonCoreSSH terminal administration. Python 3 standard library only.
Root access to /opt/sshpanel/.env acts as local administrator authentication.
Passwords are generated; no password input or interactive login is requested.
"""
import argparse
import datetime as dt
import json
import os
from pathlib import Path
import secrets
import shlex
import shutil
import stat
import subprocess
import sys
import tempfile
import textwrap
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
INSTALL_DIR = Path(os.environ.get("DRAGONCORE_DIR", "/opt/sshpanel"))
ENV_FILE = INSTALL_DIR / ".env"
SERVICE = os.environ.get("DRAGONCORE_SERVICE", "sshpanel")
class CLIError(Exception):
pass
def require_root():
if os.geteuid() != 0:
raise CLIError("Run from a root shell (or use sudo menu).")
def read_env():
try:
fd = os.open(ENV_FILE, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
with os.fdopen(fd, encoding="utf-8") as handle:
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
raise CLIError(".env must be a regular file")
lines = handle.readlines()
except OSError as exc:
raise CLIError(f"Cannot read {ENV_FILE}: {exc}") from exc
values = {}
for line in lines:
if "=" in line and not line.lstrip().startswith("#"):
key, value = line.rstrip("\n").split("=", 1)
values[key.strip()] = value.strip().strip('"')
return lines, values
def api_password():
token = read_env()[1].get("ADMIN_TOKEN", "")
if len(token) < 32:
raise CLIError("ADMIN_TOKEN is missing or too short in .env")
return token
def api_base():
address = read_env()[1].get("ADMIN_HTTP_ADDR", "127.0.0.1:9090")
try:
parsed = urllib.parse.urlsplit("http://" + address)
port = parsed.port
if not port or not 1 <= port <= 65535:
raise ValueError("invalid port")
except ValueError as exc:
raise CLIError(f"Invalid ADMIN_HTTP_ADDR: {exc}") from exc
# Always connect locally, including when the API is explicitly exposed
# for managed-server integrations.
host = "[::1]" if parsed.hostname in ("::", "::1") else "127.0.0.1"
return f"http://{host}:{port}"
def request(method, path, data=None, timeout=25):
if not path.startswith("/") or path.startswith("//"):
raise CLIError("Invalid API path")
body = None if data is None else json.dumps(data).encode("utf-8")
req = urllib.request.Request(
api_base() + path, data=body, method=method,
headers={"Authorization": "Bearer " + api_password(),
"Content-Type": "application/json", "Accept": "application/json"},
)
try:
# Do not send the bearer credential through an inherited HTTP proxy.
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(req, timeout=timeout) as response:
raw = response.read(2 * 1024 * 1024)
return json.loads(raw) if raw.strip() else None
except urllib.error.HTTPError as exc:
detail = exc.read(2048).decode("utf-8", "replace").strip()
raise CLIError(f"API {exc.code}: {detail}") from exc
except (urllib.error.URLError, TimeoutError) as exc:
raise CLIError(f"API unavailable at {api_base()}: {exc}") from exc
def write_env_token(token):
if len(token) < 32 or not all(ch.isalnum() or ch in "-_" for ch in token):
raise CLIError("API password must have 32+ letters, digits, - or _")
lines, _ = read_env()
replaced = False
out = []
for line in lines:
if line.startswith("ADMIN_TOKEN="):
if not replaced:
out.append("ADMIN_TOKEN=" + token + "\n")
replaced = True
else:
out.append(line)
if not replaced:
out.append("ADMIN_TOKEN=" + token + "\n")
old = os.stat(ENV_FILE, follow_symlinks=False)
fd, tmp = tempfile.mkstemp(prefix=".env.dragoncore-", dir=ENV_FILE.parent)
try:
os.fchmod(fd, 0o600)
os.fchown(fd, old.st_uid, old.st_gid)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.writelines(out)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp, ENV_FILE)
dirfd = os.open(ENV_FILE.parent, os.O_RDONLY)
try:
os.fsync(dirfd)
finally:
os.close(dirfd)
finally:
if os.path.exists(tmp):
os.unlink(tmp)
def service_action(action):
proc = subprocess.run(["systemctl", action, SERVICE], capture_output=True, text=True)
if proc.returncode:
raise CLIError((proc.stderr or proc.stdout).strip() or f"systemctl {action} failed")
def rotate_api_password():
old = api_password()
new = secrets.token_urlsafe(36)
write_env_token(new)
try:
service_action("restart")
last_error = None
for _ in range(12):
try:
request("GET", "/api/users") # Verify the new token is active.
last_error = None
break
except CLIError as exc:
last_error = exc
time.sleep(1)
if last_error:
raise last_error
except CLIError as exc:
write_env_token(old)
try:
service_action("restart")
except CLIError:
pass
raise CLIError(f"Rotation failed; previous password restored: {exc}") from exc
print("New API password:", new)
def ask(label, default=""):
suffix = f" [{default}]" if default != "" else ""
result = input(f"{label}{suffix}: ").strip()
return result or str(default)
def number(label, default, minimum=0, maximum=1000000):
raw = ask(label, default)
try:
value = int(raw)
except ValueError as exc:
raise CLIError(f"{label} must be a number") from exc
if not minimum <= value <= maximum:
raise CLIError(f"{label} must be between {minimum} and {maximum}")
return value
def expiry(default=""):
raw = ask("Expiry (YYYY-MM-DD, days from now, or 'never')", default or "never")
if raw.lower() in ("never", "none", "0"):
return ""
try:
day = dt.date.today() + dt.timedelta(days=int(raw)) if raw.isdecimal() else dt.date.fromisoformat(raw)
return day.isoformat() + "T23:59:59Z"
except ValueError as exc:
raise CLIError("Enter YYYY-MM-DD, number of days, or never") from exc
def confirm(label):
return input(label + " Type YES: ").strip() == "YES"
def size(n):
n = float(n or 0)
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
if abs(n) < 1024 or unit == "TiB":
return f"{n:.1f} {unit}"
n /= 1024
def terminal_columns():
override = os.environ.get("DRAGONCORE_COLUMNS", "")
if override.isdecimal() and 24 <= int(override) <= 240:
return int(override)
return max(24, shutil.get_terminal_size(fallback=(80, 24)).columns)
def print_wrapped(value, indent=""):
width = max(20, terminal_columns() - len(indent) - 1)
for part in textwrap.wrap(str(value), width=width, break_long_words=True) or [""]:
print(indent + part)
def parse_expiry(value):
if not value:
return None
try:
parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
return parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.timezone.utc)
except (TypeError, ValueError):
return None
def local_meminfo():
try:
lines = Path("/proc/meminfo").read_text().splitlines()
values = {k.rstrip(":"): int(v.split()[0]) * 1024 for k, v in (line.split(":", 1) for line in lines)}
total = values["MemTotal"]
return total, max(0, total - values["MemAvailable"])
except (OSError, KeyError, ValueError):
return 0, 0
def collect_vps_status():
"""Read live host and DragonCore data; degraded API data never blocks the menu."""
try:
os_name = next((line.split("=", 1)[1].strip().strip('"')
for line in Path("/etc/os-release").read_text().splitlines()
if line.startswith("PRETTY_NAME=")), "Linux")
except OSError:
os_name = "Linux"
try:
seconds = int(float(Path("/proc/uptime").read_text().split()[0]))
uptime = f"{seconds // 86400}d {(seconds % 86400) // 3600}h"
except (OSError, ValueError, IndexError):
uptime = "--"
try:
service = subprocess.run(["systemctl", "is-active", SERVICE], capture_output=True, text=True)
state = service.stdout.strip()
if state not in ("active", "inactive", "failed", "activating", "deactivating"):
state = "unknown"
except OSError:
state = "unknown"
stats = users = xray = None
for path, key in (("/api/stats", "stats"), ("/api/users", "users"),
("/api/xray/status", "xray")):
try:
value = request("GET", path, timeout=2)
except (CLIError, ValueError):
value = None
if key == "stats":
stats = value if isinstance(value, dict) else None
elif key == "users":
users = value if isinstance(value, list) else None
else:
xray = value if isinstance(value, dict) else None
total_mem, used_mem = local_meminfo()
if stats and stats.get("mem_total_bytes"):
total_mem = stats["mem_total_bytes"]
used_mem = stats.get("mem_used_bytes", 0)
now = dt.datetime.now(dt.timezone.utc)
expired = sum(1 for u in users or [] if (e := parse_expiry(u.get("expires_at"))) and e <= now)
interfaces = (stats or {}).get("interfaces") or []
try:
disk = shutil.disk_usage("/")
disk_pct = 100 * disk.used / disk.total if disk.total else 0
except OSError:
disk_pct = 0
return {
"host": os.uname().nodename, "os": os_name, "uptime": uptime,
"time": dt.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M"),
"cores": os.cpu_count() or 1, "cpu": (stats or {}).get("cpu_percent"),
"mem_total": total_mem, "mem_used": used_mem,
"disk_pct": disk_pct,
"ssh_total": len(users) if users is not None else None,
"ssh_online": sum(1 for u in users or [] if u.get("active_conns", 0) > 0) if users is not None else None,
"ssh_expired": expired if users is not None else None,
"xray_online": xray.get("online_users") if xray else None,
"down_mbps": max((item.get("rx_mbps", 0) for item in interfaces), default=0),
"up_mbps": max((item.get("tx_mbps", 0) for item in interfaces), default=0),
"service": state, "api_online": stats is not None and users is not None,
}
def render_vps_status(s, columns=None):
"""Render VPS status within the terminal width, including narrow phones."""
cols = columns or terminal_columns()
width = min(74, max(20, cols - 4))
def field(value):
return "--" if value is None else str(value)
def line(value):
return "┃ " + value.ljust(width) + " ┃"
cpu = "--" if s["cpu"] is None else f"{s['cpu']:.1f}%"
ram = (f"{size(s['mem_used'])}/{size(s['mem_total'])}"
if s["mem_total"] else "--")
if cols < 60:
rows = [
"DRAGONCORESSH • VPS",
f"OS: {s['os']}",
f"Host: {s['host']} {s['time'][-5:]}",
f"CPU: {cpu} / {s['cores']} cores",
f"RAM: {ram} Disk: {s['disk_pct']:.0f}%",
f"Uptime: {s['uptime']} Service: {s['service']}",
f"SSH: {field(s['ssh_online'])} on / {field(s['ssh_total'])} total",
f"Expired: {field(s['ssh_expired'])} Xray: {field(s['xray_online'])} on",
f"Net: ↓ {s['down_mbps']:.1f} ↑ {s['up_mbps']:.1f} Mbps"
if s["api_online"] else "API offline; VPS data local",
]
else:
rows = [
"DRAGONCORESSH • VPS STATUS",
f"OS: {s['os']} Host: {s['host']}",
f"Time: {s['time']} Uptime: {s['uptime']} Service: {s['service']}",
f"CPU: {cpu} ({s['cores']} cores) RAM: {ram} Disk: {s['disk_pct']:.0f}%",
f"SSH: {field(s['ssh_online'])} online | {field(s['ssh_expired'])} expired | "
f"{field(s['ssh_total'])} total Xray: {field(s['xray_online'])} online",
f"Network: ↓ {s['down_mbps']:.2f} Mbps ↑ {s['up_mbps']:.2f} Mbps"
if s["api_online"] else "API: unavailable; local VPS metrics shown above",
]
wrapped = (piece for row in rows for piece in textwrap.wrap(row, width=width, break_long_words=True))
return "\n".join(["┏" + "━" * (width + 2) + "┓", *(line(part) for part in wrapped),
"┗" + "━" * (width + 2) + "┛"])
def list_users():
users = request("GET", "/api/users") or []
if terminal_columns() < 72:
for u in sorted(users, key=lambda row: row["username"]):
print_wrapped(f"{u['username']} {u.get('active_conns', 0)}/{u.get('max_connections', 0)} online")
print_wrapped(f"Usage {size(u.get('total_bytes', 0))} "
f"Expires {str(u.get('expires_at') or 'never')[:10]}", " ")
else:
print(f"{'USER':<24} {'ONLINE':>6} {'LIMIT':>6} {'USAGE':>12} EXPIRES")
for u in sorted(users, key=lambda row: row["username"]):
print(f"{u['username']:<24} {u.get('active_conns', 0):>6} "
f"{u.get('max_connections', 0):>6} {size(u.get('total_bytes', 0)):>12} "
f"{str(u.get('expires_at') or 'never')[:10]}")
print(f"Total: {len(users)}")
return users
def user_payload(u):
fields = ("username", "max_connections", "limit_mbps_up", "limit_mbps_down",
"data_quota_bytes", "quota_action", "quota_throttle_mbps", "totp_secret",
"totp_period", "totp_window", "totp_digits", "allow_static_password",
"use_pam", "owner_username")
p = {field: u[field] for field in fields if field in u}
p["expires_at"] = u.get("expires_at") or ""
return p
def get_user(name):
return next((u for u in request("GET", "/api/users") or [] if u["username"] == name), None)
def create_user(default_days=30, test_hours=None):
name = ask("SSH username").lower()
if not name:
raise CLIError("Username required")
if get_user(name):
raise CLIError("User exists; choose Edit SSH user")
password = secrets.token_urlsafe(18)
expires_at = ((dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=test_hours)).isoformat(timespec="seconds")
if test_hours else expiry(str(default_days)))
p = {"username": name, "password": password, "max_connections": number("Max connections", 1, 0, 10000),
"expires_at": expires_at, "limit_mbps_up": 0, "limit_mbps_down": 0,
"data_quota_bytes": 0, "quota_action": "throttle", "quota_throttle_mbps": 10}
request("POST", "/api/users/create", p)
print(f"SSH user: {name}\nGenerated SSH password: {password}")
def edit_user():
name = ask("SSH username").lower()
u = get_user(name)
if not u:
raise CLIError("User not found")
p = user_payload(u)
print("1 Expiry 2 Connections 3 Bandwidth 4 Quota 5 Generate new password")
choice = ask("Option")
if choice == "1":
p["expires_at"] = expiry(str(u.get("expires_at") or "")[:10])
elif choice == "2":
p["max_connections"] = number("Max connections", u.get("max_connections", 1), 0, 10000)
elif choice == "3":
p["limit_mbps_up"] = number("Upload Mbps (0 = default)", u.get("limit_mbps_up", 0))
p["limit_mbps_down"] = number("Download Mbps (0 = default)", u.get("limit_mbps_down", 0))
elif choice == "4":
gib = number("Quota GiB (0 = unlimited)", round(u.get("data_quota_bytes", 0) / 1024**3))
p["data_quota_bytes"] = gib * 1024**3
p["quota_action"] = ask("On quota: throttle/block", u.get("quota_action") or "throttle")
p["quota_throttle_mbps"] = number("Throttle Mbps", u.get("quota_throttle_mbps") or 10)
elif choice == "5":
p["password"] = secrets.token_urlsafe(18)
else:
return
request("POST", "/api/users/create", p)
print("Saved.")
if choice == "5":
print("Generated SSH password:", p["password"])
def delete_user():
name = ask("SSH username").lower()
if confirm(f"Delete SSH user {name}?"):
request("DELETE", "/api/users/delete?" + urllib.parse.urlencode({"username": name}))
print("Deleted.")
def reset_traffic():
name = ask("SSH username").lower()
if confirm(f"Reset usage for {name}?"):
request("POST", "/api/users/reset-traffic", {"username": name})
print("Traffic reset.")
def delete_expired_users():
now = dt.datetime.now(dt.timezone.utc)
expired = [u["username"] for u in request("GET", "/api/users") or []
if (end := parse_expiry(u.get("expires_at"))) and end <= now]
if not expired:
print("No expired SSH users.")
return
print("Expired SSH users:", ", ".join(expired))
if confirm(f"Delete all {len(expired)} expired SSH users?"):
for name in expired:
request("DELETE", "/api/users/delete?" + urllib.parse.urlencode({"username": name}))
print(f"Deleted {len(expired)} SSH users.")
def user_report():
for u in request("GET", "/api/users") or []:
print()
print_wrapped(f"{u['username']} | connections {u.get('active_conns', 0)}/{u.get('max_connections', 0)}"
f" | expires {str(u.get('expires_at') or 'never')[:10]}")
quota = u.get("data_quota_bytes", 0)
print_wrapped(f"Usage {size(u.get('total_bytes', 0))}/{size(quota) if quota else 'unlimited'}"
f" | speed ↑ {size(u.get('up_bytes_per_sec', 0))}/s"
f" ↓ {size(u.get('down_bytes_per_sec', 0))}/s", " ")
def xray_inbounds():
inbounds = request("GET", "/api/xray/inbounds") or []
for inbound in inbounds:
endpoint = ("shared SSH/TLS ports" if inbound.get("shared_port") else
f"port {inbound.get('port')}")
print_wrapped(f"{inbound.get('tag')} ({inbound.get('protocol')}/{inbound.get('network') or 'tcp'}, "
f"{endpoint}, path {inbound.get('path') or '-'})")
for c in inbound.get("clients") or []:
print_wrapped(f"{c.get('name') or c.get('email') or c.get('uuid')} "
f"online={c.get('online', False)} "
f"usage={size(c.get('total_bytes', 0))}", " ")
print_wrapped(str(c.get('uuid')), " ")
return inbounds
def xray_shared_port():
"""Configure an HTTP transport on the panel's existing public ports."""
server = request("GET", "/api/server/config")
xray = server.get("xray") or {}
if xray.get("mode", "native") == "external":
raise CLIError("Shared ports require native Xray emulator mode")
listeners = [server.get("listen") or "0.0.0.0:80", *(server.get("extra_listen") or [])]
tls_listeners = [entry.get("listen") for entry in server.get("tls_forwarders") or []]
print_wrapped("Public SSH/HTTP: " + ", ".join(listeners))
if tls_listeners:
print_wrapped("Public TLS: " + ", ".join(tls_listeners))
config = request("GET", "/api/xray/config")
inbounds = config.setdefault("inbounds", [])
candidates = [ib for ib in inbounds if ib.get("protocol") in ("vless", "vmess")]
for ib in candidates:
print_wrapped(f"{ib.get('tag')} ({ib.get('protocol')})"
+ (" [shared]" if ib.get("dragoncoreSharedPort") else ""), " ")
tag = ask("Inbound tag (new or listed)")
if not tag or any(ch.isspace() for ch in tag):
raise CLIError("Enter a tag without spaces")
inbound = next((ib for ib in candidates if ib.get("tag") == tag), None)
if inbound is None and any(ib.get("tag") == tag for ib in inbounds):
raise CLIError("That tag belongs to an unsupported inbound")
transport = ask("Transport (ws/xhttp)",
((inbound or {}).get("streamSettings") or {}).get("network", "ws")).lower()
transport = {"websocket": "ws", "splithttp": "xhttp"}.get(transport, transport)
if transport not in ("ws", "xhttp"):
raise CLIError("Shared port requires ws or xhttp")
existing_paths = set()
for ib in inbounds:
if ib is inbound or not ib.get("dragoncoreSharedPort"):
continue
stream = ib.get("streamSettings") or {}
settings = stream.get("wsSettings") if stream.get("network") in ("ws", "websocket") else stream.get("xhttpSettings")
path = (settings or {}).get("path", "").rstrip("/")
existing_paths.add(path)
def overlaps_shared(path):
return any(path == old or path.startswith(old + "/") or old.startswith(path + "/")
for old in existing_paths)
auto = next(f"/c{i}" for i in range(1, 10000) if not overlaps_shared(f"/c{i}"))
old_stream = (inbound or {}).get("streamSettings") or {}
old_settings = old_stream.get("wsSettings" if transport == "ws" else "xhttpSettings") or {}
entered = ask("Path (blank generates one)", old_settings.get("path", ""))
path = entered or auto
if not path.startswith("/"):
path = "/" + path
path = path.rstrip("/")
if path in ("", "/") or any(ch in path for ch in "?#%\\ \t\r\n") or "//" in path or any(
segment in (".", "..") for segment in path.split("/")):
raise CLIError("Use a distinct URL path like /c1")
if overlaps_shared(path):
raise CLIError("Path overlaps another shared Xray inbound")
if inbound is None:
protocol = ask("Protocol (vless/vmess)", "vless").lower()
if protocol not in ("vless", "vmess"):
raise CLIError("Protocol must be vless or vmess")
client_uuid = str(uuid.uuid4())
inbound = {"tag": tag, "protocol": protocol,
"settings": {"clients": [{"id": client_uuid, "email": tag + "@dragoncore.local"}]}}
inbounds.append(inbound)
print("Generated client UUID:", client_uuid)
else:
print_wrapped("The existing inbound transport will change; its clients are preserved.")
# Port is informational for shared inbounds: the panel already owns all
# public sockets. Clients use the port of whichever SSH/TLS listener they choose.
inbound["port"] = int(listeners[0].rsplit(":", 1)[-1])
inbound["dragoncoreSharedPort"] = True
stream = inbound.setdefault("streamSettings", {})
stream["network"] = transport
stream["security"] = "none" # the panel's TLS forwarder terminates TLS
stream.pop("tlsSettings", None)
stream.pop("wsSettings", None)
stream.pop("xhttpSettings", None)
stream.pop("splithttpSettings", None)
stream["wsSettings" if transport == "ws" else "xhttpSettings"] = {"path": path}
print_wrapped(f"Shared {transport.upper()} path: {path}")
if not confirm("Save and apply this Xray inbound?"):
return
request("POST", "/api/xray/config", config)
status = request("GET", "/api/xray/status") or {}
action = "restart" if status.get("running") else "start"
request("POST", f"/api/xray/{action}", {})
print_wrapped("Active on the public SSH/HTTP ports and configured TLS ports."
" Set the client path above; use TLS security in the client when using a TLS port.")
def xray_create():
inbounds = xray_inbounds()
tag = ask("Inbound tag")
if not any(x.get("tag") == tag for x in inbounds):
raise CLIError("Choose an inbound tag from the list")
name = ask("Client name")
if not name:
raise CLIError("Client name required")
client_uuid = str(uuid.uuid4())
data = {"inbound_tag": tag, "uuid": client_uuid,
"name": name, "email": name.lower().replace(" ", "-") + "@dragoncore.local",
"expires_at": expiry("30"), "max_connections": 0,
"data_quota_bytes": 0, "quota_action": "block", "quota_throttle_mbps": 1}
request("POST", "/api/xray/clients/add", data)
print("Created Xray client UUID:", client_uuid)
def xray_delete():
tag = ask("Inbound tag")
client_uuid = ask("Client UUID")
if confirm(f"Delete Xray client {client_uuid}?"):
query = urllib.parse.urlencode({"inbound_tag": tag, "uuid": client_uuid})
request("DELETE", "/api/xray/clients/remove?" + query)
print("Deleted.")
def xray_edit():
client_uuid = ask("Client UUID")
client = next((c for inbound in request("GET", "/api/xray/inbounds") or []
for c in inbound.get("clients") or [] if c.get("uuid") == client_uuid), None)
if not client:
raise CLIError("Xray client not found")
p = {"uuid": client_uuid, "name": client.get("name") or "",
"email": client.get("email") or "", "expires_at": client.get("expires_at") or "",
"max_connections": client.get("max_conns") or 0,
"data_quota_bytes": client.get("data_quota_bytes") or 0,
"quota_action": client.get("quota_action") or "block",
"quota_throttle_mbps": client.get("quota_throttle_mbps") or 1}
print("1 Expiry 2 Connection limit 3 Quota 4 Name")
choice = ask("Option")
if choice == "1":
p["expires_at"] = expiry(str(p["expires_at"])[:10])
elif choice == "2":
p["max_connections"] = number("Max connections (0 = unlimited)", p["max_connections"], 0, 10000)
elif choice == "3":
p["data_quota_bytes"] = number("Quota GiB (0 = unlimited)", round(p["data_quota_bytes"] / 1024**3)) * 1024**3
p["quota_action"] = ask("On quota: block/throttle", p["quota_action"])
p["quota_throttle_mbps"] = number("Throttle Mbps", p["quota_throttle_mbps"])
elif choice == "4":
p["name"] = ask("Name", p["name"])
else:
return
request("POST", "/api/xray/clients/update", p)
print("Saved.")
def xray_reset_traffic():
client_uuid = ask("Client UUID")
if confirm(f"Reset traffic for {client_uuid}?"):
request("POST", "/api/xray/clients/reset-traffic", {"uuid": client_uuid})
print("Traffic reset.")
def edit_json(path):
data = request("GET", path)
fd, name = tempfile.mkstemp(prefix="dragoncore-", suffix=".json")
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as out:
json.dump(data, out, indent=2, ensure_ascii=False)
out.write("\n")
before = Path(name).read_bytes()
editor = shlex.split(os.environ.get("EDITOR") or (shutil.which("nano") or shutil.which("vi") or ""))
if not editor or subprocess.run([*editor, name]).returncode:
raise CLIError("No working editor (install nano or set EDITOR); changes discarded")
after = Path(name).read_bytes()
if after == before:
print("No changes.")
return
updated = json.loads(after)
if not confirm("Apply these configuration changes through the API?"):
return
request("POST", path, updated)
print("Configuration saved.")
finally:
os.unlink(name)
def set_banner():
cfg = request("GET", "/api/server/config")
print("Enter banner text, finish with a line containing only a dot:")
lines = []
while True:
line = input()
if line == ".":
break
lines.append(line)
cfg["banner"] = "\n".join(lines)
request("POST", "/api/server/config", cfg)
print("Banner applied.")
def set_ssh_ports():
cfg = request("GET", "/api/server/config")
cfg["listen"] = ask("Primary SSH address (IP:port)", cfg.get("listen") or "0.0.0.0:80")
current = ", ".join(cfg.get("extra_listen") or [])
extras = input(f"Extra addresses, comma separated [{current}] (enter - to clear): ").strip()
extras = "" if extras == "-" else (extras or current)
cfg["extra_listen"] = [part.strip() for part in extras.split(",") if part.strip()]
result = request("POST", "/api/server/config", cfg)
print("SSH listener settings applied.")
if result:
print(json.dumps(result, indent=2)[:2000])
def set_ssh_limits():
cfg = request("GET", "/api/server/config")
cfg["default_limit_mbps_up"] = number("Default upload Mbps (0 = unlimited)", cfg.get("default_limit_mbps_up", 0))
cfg["default_limit_mbps_down"] = number("Default download Mbps (0 = unlimited)", cfg.get("default_limit_mbps_down", 0))
cfg["max_total_connections"] = number("Global SSH connection cap (0 = default)", cfg.get("max_total_connections", 0), 0, 1000000)
request("POST", "/api/server/config", cfg)
print("Default limits applied.")
def status():
print(render_vps_status(collect_vps_status()))
try:
stats = request("GET", "/api/stats")
print("\nNetwork interfaces:")
for iface in stats.get("interfaces") or []:
if terminal_columns() < 72:
print_wrapped(f"{iface['name']} ↓ {iface.get('rx_mbps', 0):.2f} Mbps "
f"↑ {iface.get('tx_mbps', 0):.2f} Mbps", " ")
print_wrapped(f"RX {size(iface.get('rx_bytes', 0))} "
f"TX {size(iface.get('tx_bytes', 0))}", " ")
else:
print(f" {iface['name']:<18} ↓ {iface.get('rx_mbps', 0):>8.2f} Mbps "
f"↑ {iface.get('tx_mbps', 0):>8.2f} Mbps "
f"RX {size(iface.get('rx_bytes', 0))} TX {size(iface.get('tx_bytes', 0))}")
except CLIError as exc:
print(exc)
def connection_status():
cfg = request("GET", "/api/server/config")
print_wrapped("Public SSH: " + ", ".join([cfg.get("listen", "--"), *(cfg.get("extra_listen") or [])]))
print_wrapped("Local SSH: " + cfg.get("local_ssh_listen", "127.0.0.1:2222"))
for listener in cfg.get("tls_forwarders") or []:
print_wrapped("TLS SSH: " + listener.get("listen", "--"))
for name, label, fields in (
("bhttp", "BHTTP", ("listen", "shared_ports")),
("hcr", "HCR", ("listen", "shared_ports")),
("btun", "BTUN", ("tcp_listen", "udp_listen", "shared_ports")),
("dnstt", "DNSTT", ("domain", "udp_listen")),
("udpgw", "UDPGW", ("listen",)),
("xray", "Xray", ("mode", "enabled")),
):
block = cfg.get(name)
if block is None:
print(f"{label}: disabled")
else:
details = " ".join(f"{f}={block[f]}" for f in fields if f in block)
print_wrapped(f"{label}: configured {details}")
def protocol_stats():
for label, path in (("DNSTT", "/api/dnstt"), ("BHTTP", "/api/bhttp"),
("HCR", "/api/hcr"), ("BTUN", "/api/btun")):
try:
print(f"\n{label}: {json.dumps(request('GET', path), indent=2)[:1200]}")
except CLIError as exc:
print(f"{label}: {exc}")
def protocol_logs():
print("1 DNSTT 2 BHTTP 3 HCR 4 BTUN")
selected = ask("Protocol")
endpoint = {"1": "dnstt", "2": "bhttp", "3": "hcr", "4": "btun"}.get(selected)
if not endpoint:
raise CLIError("Invalid protocol")
result = request("GET", f"/api/{endpoint}/logs")
if isinstance(result, list):
print("\n".join(str(line) for line in result[-60:]))
else:
print(json.dumps(result, indent=2)[-8000:])
def generate_tls_certificate(lets_encrypt=False):
domain = ask("Certificate domain")
if not domain:
raise CLIError("Domain required")
payload = {"domain": domain}
path = "/api/tls/generate-selfsigned"
if lets_encrypt:
payload["email"] = ask("Contact email")
path = "/api/tls/letsencrypt"
result = request("POST", path, payload)
print(json.dumps(result, indent=2))
def regenerate_dnstt_key():
if confirm("Replace the DNSTT private key? Existing client keys will stop working."):
print(json.dumps(request("POST", "/api/dnstt/genkey", {}), indent=2))
def connection_menu():
menu("CONNECTION MODES", {
"1": ("Ports and transports", connection_status),
"2": ("DNSTT / BHTTP / HCR / BTUN statistics", protocol_stats),
"3": ("Edit listeners and protocol settings", lambda: edit_json("/api/server/config")),
"4": ("TLS certificates", lambda: print(json.dumps(request("GET", "/api/tls/certs"), indent=2))),
"5": ("DNSTT public key", lambda: print(json.dumps(request("GET", "/api/dnstt/pubkey"), indent=2))),
"6": ("Protocol logs", protocol_logs),
"7": ("Generate self-signed TLS certificate", generate_tls_certificate),
"8": ("Request Let's Encrypt certificate", lambda: generate_tls_certificate(True)),
"9": ("Regenerate DNSTT key", regenerate_dnstt_key),
})
def traffic_history():
data = request("GET", "/api/vnstat")
print(f"Today: {size(data.get('today_total_bytes', 0))} "
f"This month: {size(data.get('month_total_bytes', 0))}")
for label in ("daily", "monthly"):
print(f"\n{label.title()} by interface:")
for row in data.get(label) or []:
print_wrapped(f"{row.get('period', '--')} {row.get('iface', '--')} "
f"↓ {size(row.get('rx_bytes', 0))} "
f"↑ {size(row.get('tx_bytes', 0))}", " ")
def system_log_view():
source = ask("Log source: panel/dnstt/xray", "panel").lower()
if source not in ("panel", "dnstt", "xray"):
raise CLIError("Choose panel, dnstt or xray")
data = request("GET", f"/api/system/logs?source={source}&lines=100")
print("\n".join(data.get("lines") or []))
def observability_menu():
menu("VPS AND TRAFFIC", {
"1": ("VPS and live network rates", status),
"2": ("SSH online / traffic report", user_report),
"3": ("Xray online / clients", xray_inbounds),
"4": ("Daily and monthly traffic", traffic_history),
"5": ("System logs", system_log_view),
"6": ("Build and update status", lambda: print(json.dumps(request("GET", "/api/system/update-status"), indent=2))),
})
def logs():
subprocess.run(["journalctl", "-u", SERVICE, "-n", "80", "--no-pager"])
def render_menu(title, options, vps_status=None, columns=None):
cols = columns or terminal_columns()
width = min(48, max(20, cols - 2))
lines = []
if vps_status is not None:
lines.extend((render_vps_status(vps_status, cols), ""))
heading = " DRAGONCORESSH │ " + title
lines.extend(("═" * width, *textwrap.wrap(heading, width=width), "═" * width))
for key, (label, _) in options.items():
prefix = f" {key:>2} "
parts = textwrap.wrap(label, width=width - len(prefix), break_long_words=True) or [""]
lines.append(prefix + parts[0])
lines.extend(" " * len(prefix) + part for part in parts[1:])
lines.append(" 0 Back / exit")
return "\n".join(lines)
def menu(title, options):
while True:
vps = collect_vps_status() if title == "MAIN MENU" else None
print("\n" + render_menu(title, options, vps))
choice = input("Choose: ").strip().lstrip("0") or "0"
if choice == "0":
return
entry = options.get(choice)
if not entry:
print("Invalid option.")
continue
try:
entry[1]()
except (CLIError, ValueError, json.JSONDecodeError, OSError) as exc:
print("Error:", exc)
except KeyboardInterrupt:
print("\nCancelled.")
def ssh_menu():
menu("SSH ACCOUNTS", {"1": ("List / online / usage", list_users),
"2": ("Create (generated password)", create_user),
"3": ("Create test (24 hours)", lambda: create_user(test_hours=24)),
"4": ("Edit / renew / reset password", edit_user),
"5": ("Detailed account report", user_report),
"6": ("Reset traffic", reset_traffic),
"7": ("Delete expired users", delete_expired_users),
"8": ("Delete one user", delete_user)})
def xray_action(action):
request("POST", f"/api/xray/{action}", {})
print(f"Xray {action} completed.")
def xray_menu():
menu("XRAY", {"1": ("Inbounds and clients", xray_inbounds),
"2": ("Create client (generated UUID)", xray_create),
"3": ("Edit client", xray_edit),
"4": ("Reset client traffic", xray_reset_traffic),
"5": ("Delete client", xray_delete),
"6": ("Status", lambda: print(json.dumps(request("GET", "/api/xray/status"), indent=2))),
"7": ("Edit Xray JSON", lambda: edit_json("/api/xray/config")),
"8": ("Start Xray", lambda: xray_action("start")),
"9": ("Stop Xray", lambda: xray_action("stop") if confirm("Stop Xray connections?") else None),
"10": ("Restart Xray", lambda: xray_action("restart")),
"11": ("Xray logs", lambda: print(json.dumps(request("GET", "/api/xray/logs"), indent=2)[-8000:])),
"12": ("Repair Xray stats", lambda: request("POST", "/api/xray/stats/repair", {}) if confirm("Repair Xray statistics?") else None),
"13": ("Share SSH/TLS ports (WS/XHTTP)", xray_shared_port)})
def config_menu():
menu("CONFIGURATION", {"1": ("Set SSH banner", set_banner),
"2": ("Change SSH listener ports", set_ssh_ports),
"3": ("Default bandwidth / connection limits", set_ssh_limits),
"4": ("All SSH / DNSTT / BHTTP / BTUN / HCR settings", lambda: edit_json("/api/server/config")),
"5": ("Xray JSON", lambda: edit_json("/api/xray/config")),
"6": ("Telegram bot configuration", lambda: print(json.dumps(request("GET", "/api/bot/config"), indent=2))),
"7": ("Managed servers", lambda: print(json.dumps(request("GET", "/api/servers"), indent=2)))})
def api_menu():
menu("API PASSWORD", {"1": ("View current password", lambda: print("API password:", api_password())),
"2": ("Generate new password and restart service", rotate_api_password)})
def main_menu_options():
return {
"1": ("SSH accounts", ssh_menu),
"2": ("Xray accounts and service", xray_menu),
"3": ("Connection modes and ports", connection_menu),
"4": ("VPS status, users and traffic", observability_menu),
"5": ("Configuration", config_menu),
"6": ("API password (view / rotate)", api_menu),
"7": ("Recent logs", logs),
"8": ("Restart service", lambda: service_action("restart")),
}
def main():
parser = argparse.ArgumentParser(description="DragonCoreSSH CLI administration")
parser.add_argument("--mobile", action="store_true", help="force a 40-column phone layout")
parser.add_argument("command", nargs="?", choices=("menu", "status", "users", "api-password", "logs"), default="menu")
parser.add_argument("action", nargs="?", choices=("show", "change"))
args = parser.parse_args()
require_root()
if args.mobile:
os.environ["DRAGONCORE_COLUMNS"] = "40"
if args.command == "api-password":
if args.action == "show":
print(api_password())
elif args.action == "change":
rotate_api_password()
else:
api_menu()
elif args.action:
parser.error("action is only valid with api-password")
elif args.command == "users":
list_users()
elif args.command == "status":
status()
elif args.command == "logs":
logs()
else:
menu("MAIN MENU", main_menu_options())
if __name__ == "__main__":
try:
main()
except (CLIError, KeyboardInterrupt) as error:
print(f"Error: {error}", file=sys.stderr)
sys.exit(1)
+25
View File
@@ -0,0 +1,25 @@
module shell2
go 1.25.4
require (
github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5
github.com/lib/pq v1.10.9
github.com/openwall/yescrypt-go v1.0.0
github.com/xtaci/kcp-go/v5 v5.6.61
github.com/xtaci/smux v1.5.50
golang.org/x/crypto v0.45.0
golang.org/x/net v0.47.0
golang.org/x/time v0.14.0
www.bamsoftware.com/git/dnstt.git v1.20241021.0
)
require (
github.com/flynn/noise v1.0.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
github.com/klauspost/reedsolomon v1.12.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/tjfoc/gmsm v1.4.1 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
)
+125
View File
@@ -0,0 +1,125 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5 h1:IEjq88XO4PuBDcvmjQJcQGg+w+UaafSy8G5Kcb5tBhI=
github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5/go.mod h1:exZ0C/1emQJAw5tHOaUDyY1ycttqBAPcxuzf7QbY6ec=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/flynn/noise v1.0.0 h1:DlTHqmzmvcEiKj+4RYo/imoswx/4r6iBlCMfVtrMXpQ=
github.com/flynn/noise v1.0.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc=
github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/klauspost/reedsolomon v1.12.0 h1:I5FEp3xSwVCcEh3F5A7dofEfhXdF/bWhQWPH+XwBFno=
github.com/klauspost/reedsolomon v1.12.0/go.mod h1:EPLZJeh4l27pUGC3aXOjheaoh1I9yut7xTURiW3LQ9Y=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/openwall/yescrypt-go v1.0.0 h1:jsGk48zkFvtUjGVOhYPGh+CS595JmTRcKnpggK2AON4=
github.com/openwall/yescrypt-go v1.0.0/go.mod h1:e6CWtFizUEOUttaOjeVMiv1lJaJie3mfOtLJ9CCD6sA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
github.com/xtaci/kcp-go/v5 v5.6.61 h1:ajm12pGuWO+GWQNusPyPESC7Rq0yTC2rEXVYkM8ExOg=
github.com/xtaci/kcp-go/v5 v5.6.61/go.mod h1:9O3D8WR+cyyUjGiTILYfg17vn72otWuXK2AFfqIe6CM=
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE=
github.com/xtaci/smux v1.5.50 h1:y/1DlWQC9bnMeZzsyk4oL2hbLK6uVk4BKTz5BeQqUEA=
github.com/xtaci/smux v1.5.50/go.mod h1:IGQ9QYrBphmb/4aTnLEcJby0TNr3NV+OslIOMrX825Q=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
www.bamsoftware.com/git/dnstt.git v1.20241021.0 h1:Xi0lmT+5kcgzY7P+r726eBXKMZKgGoD8GTNKrlh8TuE=
www.bamsoftware.com/git/dnstt.git v1.20241021.0/go.mod h1:J4kVFxhn2bZqSqfE9l7keNTtsc+dRR6+uNH4kPu5VIs=
+437
View File
@@ -0,0 +1,437 @@
package main
// This file embeds the HCR (HTTP/Custom Relay) transport into the panel. HCR is
// a request/response tunnel: the client sends 62-byte-header frames (connect,
// data, poll, ack, close, ping) and the server relays the stream to a target.
//
// Exactly like BHTTP, every HCR session is handed to this process's own SSH
// server through dialInternalSSH, so panel accounts, expiry, TOTP, per-user
// bandwidth limits, data quotas and connection counters all apply. There is no
// dependency on the system sshd, PAM or /etc/shadow.
//
// HCR is built to coexist with BHTTP on the same ports: see tunnel_share.go for
// how a shared listener tells an HCR frame (62-byte header, version byte 0x01)
// apart from a BHTTP frame (29-byte header) and from SSH/HTTP.
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net"
"os"
"strings"
"sync"
"time"
"shell2/internal/hcr"
)
// HCRConfig defines the settings for the integrated HCR transport. A nil
// *HCRConfig in the main config disables it entirely.
type HCRConfig struct {
// Listen lists the TCP addresses to bind. IPv6 addresses must use bracket
// form, e.g. "[::]:8181". Empty with SharedPorts off uses the default.
Listen []string `json:"listen"`
// SharedPorts also accepts HCR on the ports the panel already owns (the
// HTTP+SSH proxy listeners and every TLS forwarder), alongside BHTTP, SSH
// and HTTP-injection clients. See tunnel_share.go.
SharedPorts bool `json:"shared_ports,omitempty"`
// MaxConnections caps concurrently accepted client sockets. Zero uses a
// safe default; negative disables the cap.
MaxConnections int `json:"max_connections,omitempty"`
// MaxSessions caps concurrently tracked HCR sessions. Zero uses a safe
// default; negative disables the cap.
MaxSessions int `json:"max_sessions,omitempty"`
// MaxSourceSessions caps sessions per client IP. Zero disables the per-IP
// cap.
MaxSourceSessions int `json:"max_source_sessions,omitempty"`
// DownloadPollTimeout bounds a long-poll with no data. Empty defaults to
// "10s".
DownloadPollTimeout string `json:"download_poll_timeout,omitempty"`
// MaxDownloadFrame is the largest record read from the target per frame, in
// bytes. Zero or out-of-range uses 16384.
MaxDownloadFrame int `json:"max_download_frame,omitempty"`
// IdleSessionTimeout drops a session that sees no traffic for this long.
// Empty defaults to "5m".
IdleSessionTimeout string `json:"idle_session_timeout,omitempty"`
// DisableConsoleLog keeps HCR log lines out of stderr. They are still
// captured in memory and served by /api/hcr/logs for the panel.
DisableConsoleLog bool `json:"disable_console_log,omitempty"`
// LogConnections raises the engine to debug logging (per-frame events).
// Leave off on busy servers.
LogConnections bool `json:"log_connections,omitempty"`
// AutoRestartInterval controls a watchdog that periodically hard-restarts
// only the HCR listeners and drops their sessions. Empty, "0s", "off" or
// "disabled" turns it off. Minimum accepted value is 1m.
AutoRestartInterval string `json:"auto_restart_interval,omitempty"`
// AutoRestartGrace is the delay between closing the old listeners and
// binding them again during an auto restart. Empty defaults to "2s".
AutoRestartGrace string `json:"auto_restart_grace,omitempty"`
}
const (
defaultHCRListen = "0.0.0.0:8181"
defaultHCRMaxConnections = 10000
defaultHCRMaxSessions = 10000
// hcrTargetLabel is only what shows up in logs; HCR never dials a real TCP
// target, it hands each session to the built-in SSH server.
hcrTargetLabel = "hcr"
)
var (
hcrMu sync.Mutex
hcrServer *hcr.Server
hcrListeners []net.Listener
hcrAddrs []string
hcrSharedPorts bool
hcrCtx context.Context
hcrCancel context.CancelFunc
hcrAutoMu sync.Mutex
hcrAutoCancel context.CancelFunc
hcrLogBuf *ringLogBuffer
)
func getHCRLogLines() []string { return hcrLogBuf.GetLines() }
// hcrLogger builds an slog logger that writes into the in-memory ring buffer
// (always) and to stderr (unless the console log is disabled), at debug level
// when connection logging is on.
func hcrLogger(cfg *HCRConfig) *slog.Logger {
level := slog.LevelInfo
if cfg.LogConnections {
level = slog.LevelDebug
}
var writer io.Writer = hcrLogBuf
if !cfg.DisableConsoleLog {
writer = io.MultiWriter(hcrLogBuf, os.Stderr)
}
return slog.New(slog.NewTextHandler(writer, &slog.HandlerOptions{Level: level}))
}
// ---------- Lifecycle ----------
func stopHCR() {
stopHCRAutoRestart()
stopHCRInstance()
}
func stopHCRInstance() {
hcrMu.Lock()
listeners := hcrListeners
server := hcrServer
cancel := hcrCancel
hcrListeners = nil
hcrAddrs = nil
hcrServer = nil
hcrSharedPorts = false
hcrCtx = nil
hcrCancel = nil
hcrMu.Unlock()
if cancel != nil {
cancel()
}
for _, listener := range listeners {
if listener != nil {
_ = listener.Close()
}
}
if server != nil {
server.Close()
server.Wait()
}
}
func stopHCRAutoRestart() {
hcrAutoMu.Lock()
defer hcrAutoMu.Unlock()
if hcrAutoCancel != nil {
hcrAutoCancel()
hcrAutoCancel = nil
}
}
func hcrRunning() bool {
hcrMu.Lock()
defer hcrMu.Unlock()
return hcrServer != nil
}
// hcrShareEnabled reports whether a running HCR server wants the shared proxy
// and TLS ports.
func hcrShareEnabled() bool {
hcrMu.Lock()
defer hcrMu.Unlock()
return hcrServer != nil && hcrSharedPorts
}
func hcrListenList() string {
hcrMu.Lock()
addrs := append([]string(nil), hcrAddrs...)
shared := hcrSharedPorts
hcrMu.Unlock()
if shared {
addrs = append(addrs, "shared proxy/TLS ports")
}
return strings.Join(addrs, ", ")
}
func hcrEnabledInCurrentConfig() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.HCR != nil
}
// startHCR starts the integrated HCR transport if cfg is non-nil.
func startHCR(cfg *HCRConfig) error {
if cfg == nil {
return nil
}
stopHCRAutoRestart()
if err := startHCRInstance(cfg); err != nil {
return err
}
startHCRAutoRestart(cfg)
return nil
}
func startHCRInstance(cfg *HCRConfig) error {
if cfg == nil {
return nil
}
if hcrLogBuf == nil {
hcrLogBuf = newRingLogBuffer(200)
}
logger := hcrLogger(cfg)
addrs := normalizeHCRListenList(cfg.Listen)
if len(addrs) == 0 && !cfg.SharedPorts {
msg := errors.New("hcr: needs either a listen address or shared_ports")
logger.Error(msg.Error())
return msg
}
cfg.Listen = addrs
maxConnections := cfg.MaxConnections
if maxConnections == 0 {
maxConnections = defaultHCRMaxConnections
} else if maxConnections < 0 {
maxConnections = 0
}
maxSessions := cfg.MaxSessions
if maxSessions == 0 {
maxSessions = defaultHCRMaxSessions
} else if maxSessions < 0 {
maxSessions = 0
}
server := hcr.NewServer(&hcr.Config{
TargetAddr: hcrTargetLabel,
DialTarget: func() (net.Conn, error) { return dialInternalSSH(hcrTargetLabel) },
Logger: logger,
MaxConnections: maxConnections,
MaxSessions: maxSessions,
MaxSourceSessions: cfg.MaxSourceSessions,
DownloadPollTimeout: hcrDurationOrDefault(cfg.DownloadPollTimeout, 10*time.Second, "download_poll_timeout", logger),
MaxDownloadFrame: cfg.MaxDownloadFrame,
IdleSessionTimeout: hcrDurationOrDefault(cfg.IdleSessionTimeout, 5*time.Minute, "idle_session_timeout", logger),
})
// Release the previous instance before rebinding the same addresses.
stopHCRInstance()
listeners := make([]net.Listener, 0, len(addrs))
bound := make([]string, 0, len(addrs))
for _, addr := range addrs {
listener, err := net.Listen("tcp", addr)
if err != nil {
for _, opened := range listeners {
_ = opened.Close()
}
server.Close()
msg := fmt.Errorf("hcr: listen failed on %s: %w", addr, err)
logger.Error(msg.Error())
return msg
}
listeners = append(listeners, listener)
bound = append(bound, addr)
}
ctx, cancel := context.WithCancel(context.Background())
hcrMu.Lock()
hcrServer = server
hcrListeners = listeners
hcrAddrs = bound
hcrSharedPorts = cfg.SharedPorts
hcrCtx = ctx
hcrCancel = cancel
hcrMu.Unlock()
logger.Info("starting",
"listen", bound, "shared_ports", cfg.SharedPorts,
"max_connections", maxConnections, "max_sessions", maxSessions,
"log_connections", cfg.LogConnections)
for _, listener := range listeners {
go func(current net.Listener) {
defer func() {
if r := recover(); r != nil {
logger.Error("recovered panic in accept loop", "err", r)
}
}()
if err := server.Serve(ctx, current); err != nil && !isListenerClosed(err) {
logger.Warn("listener stopped", "addr", current.Addr().String(), "err", err)
}
}(listener)
}
return nil
}
func startHCRAutoRestart(cfg *HCRConfig) {
interval := hcrAutoRestartInterval(cfg)
if interval <= 0 {
return
}
grace := hcrAutoRestartGrace(cfg)
cfgCopy := *cfg
cfgCopy.Listen = append([]string(nil), cfg.Listen...)
ctx, cancel := context.WithCancel(context.Background())
hcrAutoMu.Lock()
if hcrAutoCancel != nil {
hcrAutoCancel()
}
hcrAutoCancel = cancel
hcrAutoMu.Unlock()
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
stopHCRInstance()
if !sleepOrContextDone(ctx, grace) {
return
}
for attempt := 1; ; attempt++ {
if err := startHCRInstance(&cfgCopy); err != nil {
if !sleepOrContextDone(ctx, 10*time.Second) {
return
}
continue
}
break
}
}
}
}()
}
func hcrAutoRestartInterval(cfg *HCRConfig) time.Duration {
if cfg == nil {
return 0
}
raw := strings.TrimSpace(cfg.AutoRestartInterval)
if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") {
return 0
}
d, err := time.ParseDuration(raw)
if err != nil || d < time.Minute {
return 0
}
return d
}
func hcrAutoRestartGrace(cfg *HCRConfig) time.Duration {
if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" {
return 2 * time.Second
}
d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace))
if err != nil || d < 0 {
return 2 * time.Second
}
if d > time.Minute {
return time.Minute
}
return d
}
func hcrDurationOrDefault(raw string, fallback time.Duration, field string, logger *slog.Logger) time.Duration {
raw = strings.TrimSpace(raw)
if raw == "" {
return fallback
}
d, err := time.ParseDuration(raw)
if err != nil || d <= 0 {
logger.Warn("invalid duration; using default", "field", field, "value", raw, "default", fallback)
return fallback
}
return d
}
func normalizeHCRListenList(addrs []string) []string {
seen := make(map[string]bool, len(addrs))
out := make([]string, 0, len(addrs))
for _, addr := range addrs {
addr = strings.TrimSpace(addr)
if addr == "" || seen[addr] {
continue
}
seen[addr] = true
out = append(out, addr)
}
return out
}
// hcrConfiguredListen describes the addresses a config asks for, for status
// reports when the server failed to bind them.
func hcrConfiguredListen(cfg *HCRConfig) string {
if cfg == nil {
return ""
}
return strings.Join(normalizeHCRListenList(cfg.Listen), ", ")
}
// ---------- Stats ----------
// HCRStatsSnapshot is what /api/hcr returns.
type HCRStatsSnapshot struct {
Enabled bool `json:"enabled"`
Running bool `json:"running"`
Listen string `json:"listen,omitempty"`
hcr.StatsSnapshot
}
// GetHCRStatsSnapshot returns the current HCR counters. Safe for concurrent use.
func GetHCRStatsSnapshot() HCRStatsSnapshot {
snapshot := HCRStatsSnapshot{
Enabled: hcrEnabledInCurrentConfig(),
Running: hcrRunning(),
Listen: hcrListenList(),
}
hcrMu.Lock()
server := hcrServer
hcrMu.Unlock()
if server != nil {
snapshot.StatsSnapshot = server.Stats()
}
return snapshot
}
+514
View File
@@ -0,0 +1,514 @@
package main
import (
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
)
// ---------- Global SSH config ----------
var (
sshCfgMu sync.RWMutex
currentSSHCfg *ssh.ServerConfig
)
func setSSHConfig(c *ssh.ServerConfig) {
sshCfgMu.Lock()
currentSSHCfg = c
sshCfgMu.Unlock()
}
func getSSHConfig() *ssh.ServerConfig {
sshCfgMu.RLock()
defer sshCfgMu.RUnlock()
return currentSSHCfg
}
// ---------- Dynamic TCP listener pool ----------
// listenerPool manages a set of net.Listener instances by address.
// Calling Sync() opens new addresses and closes removed ones; unchanged
// addresses are left untouched so existing connections are not disrupted.
type listenerPool struct {
mu sync.Mutex
entries map[string]net.Listener
serve func(net.Listener) // goroutine launched for each new listener
}
func newListenerPool(serve func(net.Listener)) *listenerPool {
return &listenerPool{entries: make(map[string]net.Listener), serve: serve}
}
// Sync ensures exactly addrs are listening. Returns errors for addresses
// that could not be opened.
func (p *listenerPool) Sync(addrs []string) []error {
p.mu.Lock()
defer p.mu.Unlock()
want := make(map[string]bool, len(addrs))
for _, a := range addrs {
if a != "" {
want[a] = true
}
}
for addr, ln := range p.entries {
if !want[addr] {
_ = ln.Close() // causes the serve goroutine to exit
delete(p.entries, addr)
log.Printf("hotreload: stopped %s", addr)
}
}
var errs []error
for addr := range want {
if _, ok := p.entries[addr]; ok {
continue
}
ln, err := net.Listen("tcp", addr)
if err != nil {
errs = append(errs, fmt.Errorf("listen %s: %w", addr, err))
continue
}
p.entries[addr] = ln
log.Printf("hotreload: listening on %s", addr)
go p.serve(ln)
}
return errs
}
func (p *listenerPool) Has(addr string) bool {
if p == nil || addr == "" {
return false
}
p.mu.Lock()
defer p.mu.Unlock()
_, ok := p.entries[addr]
return ok
}
// StopAll closes every listener in the pool. Active SSH sessions are not owned
// by this pool; callers that want a hard restart should also close tracked SSH
// server connections through userMgr.DisconnectAll().
func (p *listenerPool) StopAll(reason string) {
if p == nil {
return
}
p.mu.Lock()
defer p.mu.Unlock()
for addr, ln := range p.entries {
_ = ln.Close()
delete(p.entries, addr)
if reason != "" {
log.Printf("hotreload: stopped %s (%s)", addr, reason)
} else {
log.Printf("hotreload: stopped %s", addr)
}
}
}
func (p *listenerPool) HasAll(addrs []string) bool {
if p == nil {
return false
}
for _, addr := range addrs {
if addr == "" {
continue
}
if !p.Has(addr) {
return false
}
}
return true
}
// ---------- Dynamic TLS listener pool ----------
type tlsListenerPool struct {
mu sync.Mutex
entries map[string]net.Listener
}
func newTLSListenerPool() *tlsListenerPool {
return &tlsListenerPool{entries: make(map[string]net.Listener)}
}
// Sync ensures exactly forwarders are listening (matched by listen address).
func (p *tlsListenerPool) Sync(forwarders []TLSForwarderConfig) []error {
p.mu.Lock()
defer p.mu.Unlock()
want := make(map[string]TLSForwarderConfig, len(forwarders))
for _, f := range forwarders {
if f.Listen != "" {
want[f.Listen] = f
}
}
for addr, ln := range p.entries {
if _, ok := want[addr]; !ok {
_ = ln.Close()
delete(p.entries, addr)
log.Printf("hotreload: stopped TLS %s", addr)
}
}
var errs []error
for addr, fwd := range want {
if _, ok := p.entries[addr]; ok {
continue
}
cert, err := tls.LoadX509KeyPair(fwd.CertFile, fwd.KeyFile)
if err != nil {
errs = append(errs, fmt.Errorf("TLS cert/key %s: %w", addr, err))
continue
}
ln, err := tls.Listen("tcp", addr, &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
NextProtos: []string{"h2", "http/1.1"},
})
if err != nil {
errs = append(errs, fmt.Errorf("TLS listen %s: %w", addr, err))
continue
}
p.entries[addr] = ln
log.Printf("hotreload: TLS+SSH listening on %s", addr)
go serveTLSSSH(ln)
}
return errs
}
func (p *tlsListenerPool) Has(addr string) bool {
if p == nil || addr == "" {
return false
}
p.mu.Lock()
defer p.mu.Unlock()
_, ok := p.entries[addr]
return ok
}
// Drop closes the listeners for the given addresses so a following Sync rebinds
// them. Used after a certificate is replaced on disk: tls.Listen captures the
// certificate when the listener is created, so the socket has to be recreated
// for new material to be served. Accepted connections are not owned by the pool
// and keep running.
func (p *tlsListenerPool) Drop(addrs []string, reason string) {
if p == nil {
return
}
p.mu.Lock()
defer p.mu.Unlock()
for _, addr := range addrs {
entry, ok := p.entries[addr]
if !ok {
continue
}
_ = entry.Close()
delete(p.entries, addr)
if reason != "" {
log.Printf("hotreload: dropped TLS %s (%s)", addr, reason)
} else {
log.Printf("hotreload: dropped TLS %s", addr)
}
}
}
func (p *tlsListenerPool) StopAll(reason string) {
if p == nil {
return
}
p.mu.Lock()
defer p.mu.Unlock()
for addr, ln := range p.entries {
_ = ln.Close()
delete(p.entries, addr)
if reason != "" {
log.Printf("hotreload: stopped TLS %s (%s)", addr, reason)
} else {
log.Printf("hotreload: stopped TLS %s", addr)
}
}
}
func (p *tlsListenerPool) HasAll(forwarders []TLSForwarderConfig) bool {
if p == nil {
return false
}
for _, f := range forwarders {
if f.Listen == "" {
continue
}
if !p.Has(f.Listen) {
return false
}
}
return true
}
// ---------- Global pool instances (initialised in main) ----------
var (
publicPool *listenerPool // HTTP+SSH: listen + extra_listen
localPool *listenerPool // raw SSH: loopback-only local_ssh_listen
tlsPool *tlsListenerPool // TLS forwarders
)
// isListenerClosed reports whether err came from using a closed listener.
func isListenerClosed(err error) bool {
return errors.Is(err, net.ErrClosed)
}
// ---------- Runtime settings ----------
var (
defaultLimitsMu sync.RWMutex
runtimeLimitMbpsUp int
runtimeLimitMbpsDown int
)
func setDefaultLimits(up, down int) {
defaultLimitsMu.Lock()
runtimeLimitMbpsUp = up
runtimeLimitMbpsDown = down
defaultLimitsMu.Unlock()
}
func getDefaultLimits() (up, down int) {
defaultLimitsMu.RLock()
defer defaultLimitsMu.RUnlock()
return runtimeLimitMbpsUp, runtimeLimitMbpsDown
}
// ---------- Full live reload ----------
// applyFullConfigReload applies every field in newCfg to the running server
// without a process restart. Port changes, DNSTT/UDPGW changes, Xray changes,
// and bandwidth defaults all take effect immediately.
// It returns a status report for the API and CLI.
type ServiceReloadStatus struct {
Enabled bool `json:"enabled"`
Running bool `json:"running"`
Listen string `json:"listen,omitempty"`
Error string `json:"error,omitempty"`
}
type ConfigReloadReport struct {
Applied bool `json:"applied"`
Warnings []string `json:"warnings,omitempty"`
Services map[string]ServiceReloadStatus `json:"services"`
}
func newReloadReport() ConfigReloadReport {
return ConfigReloadReport{Applied: true, Services: map[string]ServiceReloadStatus{}}
}
func (r *ConfigReloadReport) warnf(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
r.Warnings = append(r.Warnings, msg)
log.Printf("config reload: %s", msg)
}
func joinAddrs(addrs []string) string {
clean := make([]string, 0, len(addrs))
for _, a := range addrs {
if a = strings.TrimSpace(a); a != "" {
clean = append(clean, a)
}
}
return strings.Join(clean, ", ")
}
func applyFullConfigReload(newCfg *Config) ConfigReloadReport {
report := newReloadReport()
stopProxyAutoRestart()
// Banner
bt := newCfg.Banner
if bt == "" && newCfg.BannerFile != "" {
if data, err := os.ReadFile(newCfg.BannerFile); err == nil {
bt = string(data)
}
}
setBannerText(bt)
// Default per-connection bandwidth limits and SSH inactivity cleanup
// (picked up by new connections).
setDefaultLimits(newCfg.DefaultLimitMbpsUp, newCfg.DefaultLimitMbpsDown)
setSSHIdleTimeoutFromConfig(newCfg.SSHIdleTimeout)
setMaxTotalConnsFromConfig(newCfg.MaxTotalConnections)
setPAMAuthEnabled(newCfg.PAMAuthEnabled)
// Quiet logging / user count display
if newCfg.Quiet {
log.SetOutput(io.Discard)
} else if !newCfg.UserCount {
log.SetOutput(os.Stderr)
}
userCountEnabled = newCfg.UserCount
// Internal raw SSH listener. Keep it separate from the public listener
// pool so proxy auto-restarts never take the local integration endpoint
// offline. normalizeRuntimePorts guarantees one loopback address here.
localAddrs := []string{newCfg.LocalSSHListen}
for _, e := range localPool.Sync(localAddrs) {
report.warnf("internal SSH listener error: %v", e)
}
report.Services["local_ssh"] = ServiceReloadStatus{
Enabled: true,
Running: localPool.HasAll(localAddrs),
Listen: newCfg.LocalSSHListen,
}
if !report.Services["local_ssh"].Running {
report.Services["local_ssh"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: newCfg.LocalSSHListen, Error: "internal SSH listener could not be opened"}
}
// Public SSH listeners (main listen + extra_listen)
publicAddrs := append([]string{newCfg.Listen}, newCfg.ExtraListen...)
for _, e := range publicPool.Sync(publicAddrs) {
report.warnf("SSH listener error: %v", e)
}
report.Services["ssh"] = ServiceReloadStatus{
Enabled: true,
Running: publicPool.HasAll(publicAddrs),
Listen: joinAddrs(publicAddrs),
}
if !report.Services["ssh"].Running {
report.Services["ssh"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: joinAddrs(publicAddrs), Error: "one or more SSH listeners could not be opened"}
}
// TLS forwarders
for _, e := range tlsPool.Sync(newCfg.TLSForwarders) {
report.warnf("TLS listener error: %v", e)
}
if len(newCfg.TLSForwarders) > 0 {
report.Services["tls"] = ServiceReloadStatus{
Enabled: true,
Running: tlsPool.HasAll(newCfg.TLSForwarders),
Listen: tlsForwarderList(newCfg.TLSForwarders),
}
if !report.Services["tls"].Running {
report.Services["tls"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: tlsForwarderList(newCfg.TLSForwarders), Error: "one or more TLS forwarders could not be opened"}
}
} else {
report.Services["tls"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// DNSTT — stop current instance (no-op if not running) then start new one.
stopDNSTT()
if newCfg.DNSTT != nil {
if err := startDNSTT(newCfg.DNSTT, getSSHConfig()); err != nil {
report.warnf("DNSTT failed to start: %v", err)
report.Services["dnstt"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: newCfg.DNSTT.UDPListen, Error: err.Error()}
} else {
report.Services["dnstt"] = ServiceReloadStatus{Enabled: true, Running: true, Listen: newCfg.DNSTT.UDPListen}
}
} else {
report.Services["dnstt"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// UDPGW — same pattern.
stopUDPGW()
if newCfg.UDPGW != nil {
if err := startUDPGW(newCfg.UDPGW); err != nil {
report.warnf("UDPGW failed to start: %v", err)
report.Services["udpgw"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: newCfg.UDPGW.Listen, Error: err.Error()}
} else {
report.Services["udpgw"] = ServiceReloadStatus{Enabled: true, Running: udpgwRunning(), Listen: newCfg.UDPGW.Listen}
}
} else {
report.Services["udpgw"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// BHTTP — stop current instance (no-op if not running) then start new one.
stopBHTTP()
if newCfg.BHTTP != nil {
if err := startBHTTP(newCfg.BHTTP); err != nil {
report.warnf("BHTTP failed to start: %v", err)
report.Services["bhttp"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: joinAddrs(newCfg.BHTTP.Listen), Error: err.Error()}
} else {
report.Services["bhttp"] = ServiceReloadStatus{Enabled: true, Running: bhttpRunning(), Listen: bhttpListenList()}
}
} else {
report.Services["bhttp"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// BTUN — same pattern. A failure here is usually a missing /dev/net/tun or
// an interface name already taken, both of which the panel surfaces.
stopBTUN()
if newCfg.BTUN != nil {
if err := startBTUN(newCfg.BTUN); err != nil {
report.warnf("BTUN failed to start: %v", err)
report.Services["btun"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: btunConfiguredListen(newCfg.BTUN), Error: err.Error()}
} else {
report.Services["btun"] = ServiceReloadStatus{Enabled: true, Running: btunRunning(), Listen: btunListenList()}
}
} else {
report.Services["btun"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// HCR — stop current instance (no-op if not running) then start new one.
stopHCR()
if newCfg.HCR != nil {
if err := startHCR(newCfg.HCR); err != nil {
report.warnf("HCR failed to start: %v", err)
report.Services["hcr"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: hcrConfiguredListen(newCfg.HCR), Error: err.Error()}
} else {
report.Services["hcr"] = ServiceReloadStatus{Enabled: true, Running: hcrRunning(), Listen: hcrListenList()}
}
} else {
report.Services["hcr"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// Xray — update stored config then restart/stop as needed.
if newCfg.Xray != nil {
newCfg.Xray.NormalizeDefaults()
xrayMgr.mu.Lock()
xrayMgr.cfg = newCfg.Xray
xrayMgr.mu.Unlock()
if !newCfg.Xray.UseNative() {
xrayMgr.startStatsPoller()
}
if newCfg.Xray.Enabled {
if err := xrayMgr.Restart(); err != nil {
report.warnf("Xray failed to restart: %v", err)
}
time.Sleep(500 * time.Millisecond)
st := xrayMgr.Status()
report.Services["xray"] = ServiceReloadStatus{Enabled: true, Running: st.Running, Error: st.Error}
if !st.Running && st.Error == "" {
report.Services["xray"] = ServiceReloadStatus{Enabled: true, Running: false, Error: "xray exited immediately; check logs"}
}
} else {
_ = xrayMgr.Stop()
report.Services["xray"] = ServiceReloadStatus{Enabled: false, Running: false}
}
} else {
_ = xrayMgr.Stop()
report.Services["xray"] = ServiceReloadStatus{Enabled: false, Running: false}
}
setGlobalCfg(newCfg)
startProxyAutoRestart(newCfg)
return report
}
func tlsForwarderList(forwarders []TLSForwarderConfig) string {
addrs := make([]string, 0, len(forwarders))
for _, f := range forwarders {
if strings.TrimSpace(f.Listen) != "" {
addrs = append(addrs, strings.TrimSpace(f.Listen))
}
}
return strings.Join(addrs, ", ")
}
+716
View File
@@ -0,0 +1,716 @@
#!/bin/bash
# DragonCoreSSH CLI + SSH/Xray service (multi-distro Linux/systemd)
# Usage: sudo bash install.sh
set -euo pipefail
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info() { echo -e "${GREEN}[+]${NC} $*"; }
warn() { echo -e "${YELLOW}[!]${NC} $*"; }
error() { echo -e "${RED}[x]${NC} $*"; exit 1; }
# ── config ──────────────────────────────────────────────────────────────────
INSTALL_DIR="/opt/sshpanel"
SERVICE_NAME="sshpanel"
LOG_TMPFS_SIZE="${LOG_TMPFS_SIZE:-15m}"
PANEL_LOG_MAX_BYTES="${PANEL_LOG_MAX_BYTES:-1048576}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GO_VERSION="${GO_VERSION:-$(awk '$1 == "go" {print $2; exit}' "$SCRIPT_DIR/go.mod" 2>/dev/null || echo "1.22.5")}"
REPO_URL="DragonCoreSSH-CLI local release"
MKDIR_BIN="$(command -v mkdir 2>/dev/null || true)"
[[ -n "$MKDIR_BIN" ]] || MKDIR_BIN="/bin/mkdir"
# ────────────────────────────────────────────────────────────────────────────
[[ $EUID -ne 0 ]] && error "Run as root: sudo bash $0"
# Cross-distro helpers -------------------------------------------------------
PKG_MANAGER=""
PKG_DEPS=()
PKG_OPTIONAL_DEPS=()
SYSTEMCTL_BIN=""
SH_BIN="$(command -v sh 2>/dev/null || echo /bin/sh)"
MOUNT_BIN="$(command -v mount 2>/dev/null || echo /bin/mount)"
MOUNTPOINT_BIN="$(command -v mountpoint 2>/dev/null || echo /usr/bin/mountpoint)"
TOUCH_BIN="$(command -v touch 2>/dev/null || echo /usr/bin/touch)"
CHMOD_BIN="$(command -v chmod 2>/dev/null || echo /usr/bin/chmod)"
require_systemd() {
SYSTEMCTL_BIN="$(command -v systemctl 2>/dev/null || true)"
if [[ -z "$SYSTEMCTL_BIN" ]]; then
error "systemd was not found. This installer supports Linux distributions that use systemd for services."
fi
}
detect_pkg_manager() {
if command -v apt-get >/dev/null 2>&1; then
PKG_MANAGER="apt"
elif command -v dnf >/dev/null 2>&1; then
PKG_MANAGER="dnf"
elif command -v yum >/dev/null 2>&1; then
PKG_MANAGER="yum"
elif command -v zypper >/dev/null 2>&1; then
PKG_MANAGER="zypper"
elif command -v pacman >/dev/null 2>&1; then
PKG_MANAGER="pacman"
elif command -v apk >/dev/null 2>&1; then
PKG_MANAGER="apk"
else
error "No supported package manager found. Supported: apt, dnf, yum, zypper, pacman, apk."
fi
}
set_package_deps() {
case "$PKG_MANAGER" in
apt)
PKG_DEPS=(curl wget git rsync build-essential postgresql ca-certificates unzip openssh-client openssl python3 tar gzip)
PKG_OPTIONAL_DEPS=(postgresql-contrib iptables nftables)
;;
dnf|yum)
PKG_DEPS=(curl wget git rsync gcc make postgresql-server ca-certificates unzip openssh-clients openssl python3 tar gzip)
PKG_OPTIONAL_DEPS=(postgresql-contrib iptables nftables)
;;
zypper)
PKG_DEPS=(curl wget git rsync gcc make postgresql-server ca-certificates unzip openssh openssl python3 tar gzip)
PKG_OPTIONAL_DEPS=(postgresql-contrib iptables nftables)
;;
pacman)
PKG_DEPS=(curl wget git rsync base-devel postgresql ca-certificates unzip openssh openssl python tar gzip)
PKG_OPTIONAL_DEPS=(iptables-nft nftables)
;;
apk)
PKG_DEPS=(curl wget git rsync build-base postgresql ca-certificates unzip openssh-client openssl python3 tar gzip)
PKG_OPTIONAL_DEPS=(postgresql-contrib iptables nftables)
;;
esac
}
pkg_update() {
case "$PKG_MANAGER" in
apt) apt-get update -qq ;;
dnf) dnf makecache -q ;;
yum) yum makecache -q ;;
zypper) zypper --non-interactive refresh ;;
pacman) pacman -Sy --noconfirm ;;
apk) apk update ;;
esac
}
pkg_install() {
case "$PKG_MANAGER" in
apt) DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@" ;;
dnf) dnf install -y "$@" ;;
yum) yum install -y "$@" ;;
zypper) zypper --non-interactive install -y "$@" ;;
pacman) pacman -S --noconfirm --needed "$@" ;;
apk) apk add --no-cache "$@" ;;
esac
}
pkg_install_optional() {
local pkg
for pkg in "$@"; do
pkg_install "$pkg" >/dev/null 2>&1 || warn " Optional package '$pkg' could not be installed; continuing."
done
}
postgres_data_dir() {
for dir in /var/lib/postgresql/data /var/lib/pgsql/data /var/lib/postgres/data; do
[[ -d "$dir" || -d "$(dirname "$dir")" ]] && { printf '%s\n' "$dir"; return 0; }
done
printf '%s\n' /var/lib/postgresql/data
}
init_postgresql_if_needed() {
case "$PKG_MANAGER" in
dnf|yum|zypper)
postgresql-setup --initdb >/dev/null 2>&1 || true
;;
pacman)
local data_dir
data_dir="$(postgres_data_dir)"
if [[ ! -s "$data_dir/PG_VERSION" ]]; then
mkdir -p "$data_dir"
chown -R postgres:postgres "$(dirname "$data_dir")"
if command -v runuser >/dev/null 2>&1; then
runuser -u postgres -- initdb -D "$data_dir" >/dev/null 2>&1 || true
else
su - postgres -c "initdb -D '$data_dir'" >/dev/null 2>&1 || true
fi
fi
;;
apk)
if command -v rc-service >/dev/null 2>&1; then
rc-service postgresql setup >/dev/null 2>&1 || true
fi
;;
esac
}
start_enable_postgresql() {
local started=false svc
for svc in postgresql postgresql.service; do
if "$SYSTEMCTL_BIN" start "$svc" >/dev/null 2>&1; then
"$SYSTEMCTL_BIN" enable "$svc" >/dev/null 2>&1 || true
started=true
break
fi
done
if ! $started && command -v service >/dev/null 2>&1; then
service postgresql start >/dev/null 2>&1 && started=true || true
fi
$started || warn " Could not start PostgreSQL automatically; continuing in case it is already running."
}
ensure_log_tmpfs_mount() {
local log_dir="${INSTALL_DIR}/logs"
local opts="rw,nosuid,nodev,noexec,noatime,nofail,size=${LOG_TMPFS_SIZE},mode=0755"
local tmp_fstab
mkdir -p "$log_dir"
if [[ -f /etc/fstab ]]; then
cp /etc/fstab "/etc/fstab.sshpanel.bak.$(date +%s)" 2>/dev/null || true
tmp_fstab="$(mktemp)"
awk -v mp="$log_dir" '!(($1 == "tmpfs") && ($2 == mp) && ($3 == "tmpfs")) {print}' /etc/fstab > "$tmp_fstab"
printf 'tmpfs %s tmpfs %s 0 0\n' "$log_dir" "$opts" >> "$tmp_fstab"
cat "$tmp_fstab" > /etc/fstab
rm -f "$tmp_fstab"
info " Log RAM disk automount saved in /etc/fstab: $log_dir (${LOG_TMPFS_SIZE})"
else
warn " /etc/fstab not found; service startup fallback will mount $log_dir as tmpfs"
fi
"${SYSTEMCTL_BIN:-systemctl}" daemon-reload >/dev/null 2>&1 || true
if command -v mountpoint >/dev/null 2>&1 && mountpoint -q "$log_dir"; then
mount -o "remount,size=${LOG_TMPFS_SIZE},mode=0755" "$log_dir" >/dev/null 2>&1 || true
else
mount "$log_dir" >/dev/null 2>&1 || mount -t tmpfs -o "size=${LOG_TMPFS_SIZE},mode=0755" tmpfs "$log_dir" >/dev/null 2>&1 || \
warn " Could not mount $log_dir as tmpfs now; service startup fallback will try again"
fi
touch "$log_dir/panel.log" >/dev/null 2>&1 || true
chmod 0644 "$log_dir/panel.log" >/dev/null 2>&1 || true
}
echo -e "\n${GREEN}══════════════════════════════════════════${NC}"
echo -e "${GREEN} SSH Panel + Xray-core · Installer ${NC}"
echo -e "${GREEN}══════════════════════════════════════════${NC}\n"
# ── 1. OS / package-manager detection ────────────────────────────────────────
info "[1/10] Detecting Linux distribution and package manager…"
if [[ -f /etc/os-release ]]; then
# shellcheck disable=SC1091
. /etc/os-release
OS_ID="${ID:-unknown}"
OS_LIKE="${ID_LIKE:-}"
OS_PRETTY="${PRETTY_NAME:-$OS_ID}"
else
OS_ID="unknown"
OS_LIKE=""
OS_PRETTY="unknown Linux"
fi
require_systemd
detect_pkg_manager
set_package_deps
info " OS : $OS_PRETTY"
info " ID / ID_LIKE : $OS_ID / ${OS_LIKE:-none}"
info " Package manager: $PKG_MANAGER"
info " Service manager: systemd"
# ── 2. System dependencies ───────────────────────────────────────────────────
info "[2/10] Installing system packages…"
pkg_update
pkg_install "${PKG_DEPS[@]}"
pkg_install_optional "${PKG_OPTIONAL_DEPS[@]}"
# ── 3. Go ────────────────────────────────────────────────────────────────────
info "[3/10] Installing Go ${GO_VERSION}…"
NEED_GO=true
if command -v go &>/dev/null; then
CURRENT_GO=$(go version 2>/dev/null | awk '{print $3}' | sed 's/go//')
if [[ "$(printf '%s\n' "$GO_VERSION" "$CURRENT_GO" | sort -V | head -1)" == "$GO_VERSION" ]]; then
info " Go $CURRENT_GO already installed — skipping"
NEED_GO=false
fi
fi
if $NEED_GO; then
MACHINE=$(uname -m)
case "$MACHINE" in
x86_64) GOARCH="amd64" ;;
aarch64) GOARCH="arm64" ;;
armv7l) GOARCH="armv6l" ;;
*) GOARCH="amd64" ;;
esac
GO_URL="https://go.dev/dl/go${GO_VERSION}.linux-${GOARCH}.tar.gz"
info " Downloading $GO_URL"
wget -q --show-progress -O /tmp/go.tar.gz "$GO_URL"
rm -rf /usr/local/go
tar -C /usr/local -xzf /tmp/go.tar.gz
rm -f /tmp/go.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' > /etc/profile.d/go.sh
chmod +x /etc/profile.d/go.sh
fi
export PATH=$PATH:/usr/local/go/bin
go version
# ── 4. Directory layout ──────────────────────────────────────────────────────
info "[4/10] Setting up ${INSTALL_DIR}…"
mkdir -p "$INSTALL_DIR/keys" "$INSTALL_DIR/logs"
ensure_log_tmpfs_mount
# ── 5. Build SSH panel binary ────────────────────────────────────────────────
info "[5/10] Building SSH Panel binary…"
cd "$SCRIPT_DIR"
export GOPATH=/tmp/gopath_sshpanel
export GOCACHE=/tmp/gocache_sshpanel
BUILD_COMMIT="$(git -C "$SCRIPT_DIR" rev-parse HEAD 2>/dev/null || true)"
BUILD_BRANCH="$(git -C "$SCRIPT_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
BUILD_TIME="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
BUILD_REPO_URL="$(git -C "$SCRIPT_DIR" config --get remote.origin.url 2>/dev/null || true)"
[[ -n "$BUILD_COMMIT" ]] || BUILD_COMMIT="unknown"
[[ -n "$BUILD_BRANCH" && "$BUILD_BRANCH" != "HEAD" ]] || BUILD_BRANCH="main"
[[ -n "$BUILD_REPO_URL" ]] || BUILD_REPO_URL="$REPO_URL"
go mod download
go mod tidy
go build -ldflags="-s -w -X main.buildCommit=$BUILD_COMMIT -X main.buildBranch=$BUILD_BRANCH -X main.buildTime=$BUILD_TIME" -o "$INSTALL_DIR/sshpanel" .
printf '%s\n' "$BUILD_COMMIT" > "$INSTALL_DIR/.installed_commit"
printf '%s\n' "$BUILD_BRANCH" > "$INSTALL_DIR/.installed_branch"
printf '%s\n' "$BUILD_TIME" > "$INSTALL_DIR/.installed_build_time"
printf '%s\n' "$BUILD_REPO_URL" > "$INSTALL_DIR/.installed_repo_url"
chmod 0644 "$INSTALL_DIR/.installed_commit" "$INSTALL_DIR/.installed_branch" "$INSTALL_DIR/.installed_build_time"
chmod 0600 "$INSTALL_DIR/.installed_repo_url"
info " Binary: $INSTALL_DIR/sshpanel"
info " Build commit: $BUILD_COMMIT ($BUILD_BRANCH)"
install -m 700 "$SCRIPT_DIR/dragoncore_cli.py" "$INSTALL_DIR/dragoncore_cli.py"
ln -sfn "$INSTALL_DIR/dragoncore_cli.py" /usr/local/bin/dragoncore
if [[ ( -e /usr/local/bin/menu || -L /usr/local/bin/menu ) && "$(readlink -f /usr/local/bin/menu 2>/dev/null || true)" != "$INSTALL_DIR/dragoncore_cli.py" ]]; then
MENU_BACKUP="/usr/local/bin/menu.backup.$(date +%s%N)"
mv /usr/local/bin/menu "$MENU_BACKUP"
warn " Previous menu command saved to $MENU_BACKUP"
fi
ln -sfn "$INSTALL_DIR/dragoncore_cli.py" /usr/local/bin/menu
info " DragonCoreSSH CLI installed: menu (also dragoncore)"
mkdir -p "$INSTALL_DIR/source"
rsync -a --delete --exclude '.git' --exclude 'source/' --exclude '__pycache__/' "$SCRIPT_DIR/" "$INSTALL_DIR/source/"
if [[ -f "$SCRIPT_DIR/update.sh" ]]; then
cp "$SCRIPT_DIR/update.sh" "$INSTALL_DIR/update.sh"
chmod 700 "$INSTALL_DIR/update.sh"
info " Local CLI updater copied"
fi
# ── 6. Xray binary ──────────────────────────────────────────────────────────
info "[6/10] Downloading Xray-core…"
XRAY_VER=$(curl -sf "https://api.github.com/repos/XTLS/Xray-core/releases/latest" \
| grep '"tag_name"' | head -1 | cut -d'"' -f4 || echo "v24.11.30")
MACHINE=$(uname -m)
case "$MACHINE" in
x86_64) XRAY_ARCH="64" ;;
aarch64) XRAY_ARCH="arm64-v8a" ;;
armv7l) XRAY_ARCH="arm32-v7a" ;;
*) XRAY_ARCH="64" ;;
esac
XRAY_URL="https://github.com/XTLS/Xray-core/releases/download/${XRAY_VER}/Xray-linux-${XRAY_ARCH}.zip"
info " Xray ${XRAY_VER} (${XRAY_ARCH})"
wget -q --show-progress -O /tmp/xray.zip "$XRAY_URL"
unzip -o /tmp/xray.zip xray -d "$INSTALL_DIR" > /dev/null 2>&1 || {
mkdir -p /tmp/xray_extract
unzip -o /tmp/xray.zip -d /tmp/xray_extract > /dev/null 2>&1
mv /tmp/xray_extract/xray "$INSTALL_DIR/xray"
}
chmod +x "$INSTALL_DIR/xray"
rm -f /tmp/xray.zip
"$INSTALL_DIR/xray" version
# ── 7. PostgreSQL ────────────────────────────────────────────────────────────
info "[7/10] Configuring PostgreSQL…"
init_postgresql_if_needed
start_enable_postgresql
DB_NAME="sshpanel"
DB_USER="sshpanel"
DB_PASS=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32 || true)
if [[ ${#DB_PASS} -lt 32 ]]; then
DB_PASS=$(openssl rand -hex 16 2>/dev/null || date +%s%N)
fi
su -c "psql -tc \"SELECT 1 FROM pg_roles WHERE rolname='${DB_USER}'\" | grep -q 1 || \
psql -c \"CREATE USER ${DB_USER} WITH PASSWORD '${DB_PASS}';\"" postgres
# Reinstall-safe: if the role already existed, make the new .env password valid.
su -c "psql -c \"ALTER USER ${DB_USER} WITH PASSWORD '${DB_PASS}';\"" postgres
su -c "psql -tc \"SELECT 1 FROM pg_database WHERE datname='${DB_NAME}'\" | grep -q 1 || \
psql -c \"CREATE DATABASE ${DB_NAME} OWNER ${DB_USER};\"" postgres
# Reinstall-safe: if the database already existed, make sshpanel its owner.
su -c "psql -c \"ALTER DATABASE ${DB_NAME} OWNER TO ${DB_USER};\"" postgres
su -c "psql -d ${DB_NAME} -c \"
CREATE TABLE IF NOT EXISTS ssh_users (
username TEXT PRIMARY KEY,
password TEXT NOT NULL DEFAULT '',
max_connections INT NOT NULL DEFAULT 0,
expires_at TEXT,
limit_mbps_up INT NOT NULL DEFAULT 0,
limit_mbps_down INT NOT NULL DEFAULT 0,
totp_secret TEXT NOT NULL DEFAULT '',
totp_period INT NOT NULL DEFAULT 60,
totp_window INT NOT NULL DEFAULT 1,
totp_digits INT NOT NULL DEFAULT 6,
allow_static_password BOOLEAN NOT NULL DEFAULT FALSE,
owner_username TEXT NOT NULL DEFAULT ''
);
ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_period INT NOT NULL DEFAULT 60;
ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_window INT NOT NULL DEFAULT 1;
ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS totp_digits INT NOT NULL DEFAULT 6;
ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS allow_static_password BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE ssh_users ADD COLUMN IF NOT EXISTS owner_username TEXT NOT NULL DEFAULT '';
ALTER TABLE ssh_users ALTER COLUMN password SET DEFAULT '';
CREATE TABLE IF NOT EXISTS ssh_iface_totals (
iface TEXT PRIMARY KEY,
total_rx_bytes BIGINT NOT NULL DEFAULT 0,
total_tx_bytes BIGINT NOT NULL DEFAULT 0,
last_kernel_rx_bytes BIGINT NOT NULL DEFAULT 0,
last_kernel_tx_bytes BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS total_rx_bytes BIGINT NOT NULL DEFAULT 0;
ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS total_tx_bytes BIGINT NOT NULL DEFAULT 0;
ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS last_kernel_rx_bytes BIGINT NOT NULL DEFAULT 0;
ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS last_kernel_tx_bytes BIGINT NOT NULL DEFAULT 0;
ALTER TABLE ssh_iface_totals ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
CREATE TABLE IF NOT EXISTS admin_users (
id SERIAL PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'reseller',
max_users INT NOT NULL DEFAULT 30,
expires_at TIMESTAMPTZ,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS xray_clients (
uuid TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
inbound_tag TEXT NOT NULL DEFAULT '',
expires_at TIMESTAMPTZ,
max_conns INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Telegram sales bot (created idempotently by the app too; mirrored here for a clean install)
CREATE TABLE IF NOT EXISTS bot_users (
telegram_id BIGINT PRIMARY KEY,
username TEXT NOT NULL DEFAULT '',
first_name TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT 'customer',
linked_admin_username TEXT NOT NULL DEFAULT '',
credit_balance INT NOT NULL DEFAULT 0,
trial_used BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS bot_plans (
id SERIAL PRIMARY KEY, name TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT 'ssh',
days INT NOT NULL DEFAULT 30, max_connections INT NOT NULL DEFAULT 1,
limit_mbps_up INT NOT NULL DEFAULT 0, limit_mbps_down INT NOT NULL DEFAULT 0,
xray_inbound_tag TEXT NOT NULL DEFAULT '', xray_protocol TEXT NOT NULL DEFAULT '',
price_cents INT NOT NULL DEFAULT 0, credit_cost INT NOT NULL DEFAULT 1,
server_id TEXT NOT NULL DEFAULT '', is_active BOOLEAN NOT NULL DEFAULT true, sort_order INT NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS bot_credit_packages (
id SERIAL PRIMARY KEY, name TEXT NOT NULL DEFAULT '', credits INT NOT NULL DEFAULT 0,
price_cents INT NOT NULL DEFAULT 0, is_active BOOLEAN NOT NULL DEFAULT true, sort_order INT NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS bot_transactions (
id SERIAL PRIMARY KEY, telegram_id BIGINT NOT NULL, type TEXT NOT NULL,
plan_id INT, package_id INT, credits INT NOT NULL DEFAULT 0, amount_cents INT NOT NULL DEFAULT 0,
mp_payment_id TEXT NOT NULL DEFAULT '', mp_qr_code TEXT NOT NULL DEFAULT '', mp_qr_base64 TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending', target_username TEXT NOT NULL DEFAULT '', renew_target TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), paid_at TIMESTAMPTZ, expires_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX IF NOT EXISTS bot_transactions_mp_payment_id_uidx ON bot_transactions (mp_payment_id) WHERE mp_payment_id <> '';
CREATE TABLE IF NOT EXISTS bot_credits_ledger (
id SERIAL PRIMARY KEY, telegram_id BIGINT NOT NULL, delta INT NOT NULL, reason TEXT NOT NULL DEFAULT '',
ref_transaction_id INT, balance_after INT NOT NULL DEFAULT 0, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS bot_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL DEFAULT '');
CREATE TABLE IF NOT EXISTS bot_config (
id INT PRIMARY KEY DEFAULT 1 CHECK (id = 1), enabled BOOLEAN NOT NULL DEFAULT false,
telegram_mode TEXT NOT NULL DEFAULT 'polling', telegram_webhook_url TEXT NOT NULL DEFAULT '',
mp_confirm_mode TEXT NOT NULL DEFAULT 'polling', mp_poll_interval TEXT NOT NULL DEFAULT '20s',
pix_expiration_minutes INT NOT NULL DEFAULT 30, trial_enabled BOOLEAN NOT NULL DEFAULT true,
trial_hours INT NOT NULL DEFAULT 1, trial_max_connections INT NOT NULL DEFAULT 1,
trial_kind TEXT NOT NULL DEFAULT 'ssh', trial_inbound_tag TEXT NOT NULL DEFAULT '',
admin_telegram_ids BIGINT[] NOT NULL DEFAULT '{}', currency TEXT NOT NULL DEFAULT 'BRL',
public_host TEXT NOT NULL DEFAULT '', xray_public_host TEXT NOT NULL DEFAULT '',
telegram_token_enc BYTEA, telegram_webhook_secret_enc BYTEA, mp_access_token_enc BYTEA, mp_webhook_secret_enc BYTEA,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
INSERT INTO bot_config (id) VALUES (1) ON CONFLICT (id) DO NOTHING;
ALTER SCHEMA public OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS ssh_users OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS ssh_iface_totals OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS admin_users OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS xray_clients OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS bot_users OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS bot_plans OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS bot_credit_packages OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS bot_transactions OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS bot_credits_ledger OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS bot_settings OWNER TO ${DB_USER};
ALTER TABLE IF EXISTS bot_config OWNER TO ${DB_USER};
ALTER SEQUENCE IF EXISTS admin_users_id_seq OWNER TO ${DB_USER};
GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};
GRANT ALL PRIVILEGES ON SCHEMA public TO ${DB_USER};
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO ${DB_USER};
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO ${DB_USER};
\"" postgres
info " PostgreSQL database '${DB_NAME}' ready"
# ── 8. Config files ──────────────────────────────────────────────────────────
info "[8/10] Generating config files…"
# Admin token
ADMIN_TOKEN=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 48 || true)
if [[ ${#ADMIN_TOKEN} -lt 48 ]]; then
ADMIN_TOKEN=$(openssl rand -hex 24 2>/dev/null || date +%s%N)
fi
# Preserve an admin account for API clients using session authentication.
ADMIN_PASSWORD=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 20 || true)
if [[ ${#ADMIN_PASSWORD} -lt 20 ]]; then
ADMIN_PASSWORD=$(openssl rand -hex 10 2>/dev/null || date +%s%N)
fi
ADMIN_PASSWORD_HASH=$(printf '%s' "${ADMIN_PASSWORD}" | "$INSTALL_DIR/sshpanel" -hash-admin-password-stdin 2>/dev/null)
[[ "$ADMIN_PASSWORD_HASH" == \$2* ]] || error "Failed to generate admin bcrypt password hash"
su -c "psql -d ${DB_NAME}" postgres <<SQL
INSERT INTO admin_users (username, password_hash, role, max_users, expires_at, is_active)
VALUES ('admin', '${ADMIN_PASSWORD_HASH}', 'superadmin', 0, NULL, TRUE)
ON CONFLICT (username) DO UPDATE SET
password_hash = EXCLUDED.password_hash,
role = 'superadmin',
max_users = 0,
expires_at = NULL,
is_active = TRUE;
SQL
# .env
cat > "$INSTALL_DIR/.env" <<EOF
PG_DSN=postgres://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}?sslmode=disable
ADMIN_TOKEN=${ADMIN_TOKEN}
ADMIN_HTTP_ADDR=127.0.0.1:9090
EOF
chmod 600 "$INSTALL_DIR/.env"
# SSH host key (RSA, required by current build)
if [[ ! -f "$INSTALL_DIR/ssh_host_rsa_key" ]]; then
ssh-keygen -t rsa -b 2048 -f "$INSTALL_DIR/ssh_host_rsa_key" -N "" -C "sshpanel-hostkey" -q
info " Generated RSA host key"
fi
# Server public IP (best-effort)
SERVER_IP=$(curl -sf --max-time 5 https://checkip.amazonaws.com 2>/dev/null \
|| curl -sf --max-time 5 https://api.ipify.org 2>/dev/null \
|| hostname -I | awk '{print $1}')
# config.json
cat > "$INSTALL_DIR/config.json" <<EOF
{
"listen": "0.0.0.0:80",
"extra_listen": ["0.0.0.0:8080"],
"local_ssh_listen": "127.0.0.1:2222",
"host_key_file": "${INSTALL_DIR}/ssh_host_rsa_key",
"quiet": false,
"banner_file": "${INSTALL_DIR}/banner.txt",
"xray": {
"enabled": true,
"mode": "native",
"native": true,
"bin_path": "${INSTALL_DIR}/xray",
"config_file": "${INSTALL_DIR}/xray_config.json",
"native_config_file": "${INSTALL_DIR}/xray_native_config.json"
}
}
EOF
touch "$INSTALL_DIR/banner.txt"
# UUID for default VLESS client
UUID=$(cat /proc/sys/kernel/random/uuid 2>/dev/null \
|| python3 -c "import uuid; print(uuid.uuid4())" 2>/dev/null \
|| echo "11111111-2222-3333-4444-555555555555")
# xray_native_config.json is used by the internal emulator. xray_config.json is
# kept only for optional external-xray mode. Both start with the same default.
cat > "$INSTALL_DIR/xray_native_config.json" <<EOF
{
"log": { "loglevel": "warning" },
"inbounds": [
{
"tag": "vless-in",
"port": 10086,
"listen": "0.0.0.0",
"protocol": "vless",
"settings": {
"clients": [{ "id": "${UUID}", "level": 0 }],
"decryption": "none"
},
"streamSettings": { "network": "tcp" }
},
{
"tag": "socks-local",
"port": 10088,
"listen": "127.0.0.1",
"protocol": "socks",
"settings": { "auth": "noauth", "udp": true }
}
],
"outbounds": [
{ "tag": "direct", "protocol": "freedom", "settings": {} },
{ "tag": "blocked", "protocol": "blackhole", "settings": {} }
]
}
EOF
cp -f "$INSTALL_DIR/xray_native_config.json" "$INSTALL_DIR/xray_config.json"
chmod 600 "$INSTALL_DIR/xray_native_config.json" "$INSTALL_DIR/xray_config.json"
info " VLESS UUID: ${UUID}"
# ── 9. DNSTT DNS/53 redirect ─────────────────────────────────────────────────
info "[9/10] Configuring DNSTT DNS redirect (UDP 53 -> 5300)…"
cat > /usr/local/sbin/sshpanel-dnstt-redirect.sh <<'EOS'
#!/bin/bash
set -euo pipefail
DNS_UPSTREAM="${DNS_UPSTREAM:-1.1.1.1}"
DNSTT_PORT="${DNSTT_PORT:-5300}"
# Free port 53 on systemd-resolved based systems and keep outbound DNS working.
if command -v systemctl >/dev/null 2>&1; then
systemctl disable --now systemd-resolved.service >/dev/null 2>&1 || true
fi
rm -f /etc/resolv.conf
printf 'nameserver %s\n' "$DNS_UPSTREAM" > /etc/resolv.conf
# Open DNS/UDP in common Linux firewalls when they are active.
if command -v ufw >/dev/null 2>&1; then
ufw allow 53/udp >/dev/null 2>&1 || true
fi
if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
firewall-cmd --permanent --add-port=53/udp >/dev/null 2>&1 || true
firewall-cmd --reload >/dev/null 2>&1 || true
fi
add_iptables_rule() {
local bin="$1" chain="$2"
"$bin" -t nat -C "$chain" -p udp --dport 53 -j REDIRECT --to-ports "$DNSTT_PORT" 2>/dev/null \
|| "$bin" -t nat -A "$chain" -p udp --dport 53 -j REDIRECT --to-ports "$DNSTT_PORT"
}
if command -v iptables >/dev/null 2>&1; then
add_iptables_rule iptables PREROUTING
fi
if command -v ip6tables >/dev/null 2>&1; then
add_iptables_rule ip6tables PREROUTING || true
fi
# Fallback for minimal systems where only nft is present.
if ! command -v iptables >/dev/null 2>&1 && command -v nft >/dev/null 2>&1; then
nft add table inet sshpanel_nat 2>/dev/null || true
nft 'add chain inet sshpanel_nat prerouting { type nat hook prerouting priority dstnat; policy accept; }' 2>/dev/null || true
nft list chain inet sshpanel_nat prerouting 2>/dev/null | grep -q "udp dport 53 redirect to :$DNSTT_PORT" \
|| nft add rule inet sshpanel_nat prerouting udp dport 53 redirect to :"$DNSTT_PORT"
fi
EOS
chmod +x /usr/local/sbin/sshpanel-dnstt-redirect.sh
cat > /etc/systemd/system/sshpanel-dnstt-redirect.service <<'EOF'
[Unit]
Description=SSH Panel DNSTT DNS redirect (UDP 53 to 5300)
After=network.target
Before=sshpanel.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/sshpanel-dnstt-redirect.sh
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
EOF
"$SYSTEMCTL_BIN" daemon-reload
"$SYSTEMCTL_BIN" enable --now sshpanel-dnstt-redirect.service || warn "DNSTT DNS redirect service failed; check: journalctl -u sshpanel-dnstt-redirect -e"
info " DNSTT DNS redirect installed: UDP 53 -> 5300"
# ── 10. Systemd service ──────────────────────────────────────────────────────
info "[10/10] Creating systemd service '${SERVICE_NAME}'…"
cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=SSH Panel + Xray-core Server
After=local-fs.target network.target postgresql.service sshpanel-dnstt-redirect.service
Wants=postgresql.service sshpanel-dnstt-redirect.service
[Service]
Type=simple
WorkingDirectory=${INSTALL_DIR}
EnvironmentFile=${INSTALL_DIR}/.env
Environment=PANEL_LOG_FILE=${INSTALL_DIR}/logs/panel.log
Environment=PANEL_LOG_MAX_BYTES=${PANEL_LOG_MAX_BYTES}
ExecStartPre=${MKDIR_BIN} -p ${INSTALL_DIR}/logs
ExecStartPre=${SH_BIN} -c '${MOUNTPOINT_BIN} -q ${INSTALL_DIR}/logs || ${MOUNT_BIN} -t tmpfs -o size=${LOG_TMPFS_SIZE},mode=0755 tmpfs ${INSTALL_DIR}/logs || true'
ExecStartPre=${SH_BIN} -c '${TOUCH_BIN} ${INSTALL_DIR}/logs/panel.log && ${CHMOD_BIN} 0644 ${INSTALL_DIR}/logs/panel.log || true'
ExecStart=${INSTALL_DIR}/sshpanel -config ${INSTALL_DIR}/config.json
Restart=always
RestartSec=5
User=root
LimitNOFILE=1048576
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
EOF
"$SYSTEMCTL_BIN" daemon-reload
"$SYSTEMCTL_BIN" enable "$SERVICE_NAME"
"$SYSTEMCTL_BIN" restart "$SERVICE_NAME"
sleep 2
echo ""
echo -e "${GREEN}══════════════════════════════════════════${NC}"
echo -e "${GREEN} Installation complete! ${NC}"
echo -e "${GREEN}══════════════════════════════════════════${NC}"
echo ""
echo -e " Server IP : ${YELLOW}${SERVER_IP}${NC}"
echo -e " SSH ports : 80, 8080 (HTTP-injected SSH)"
echo -e " Internal SSH : 127.0.0.1:2222 (raw SSH for local proxies)"
echo -e " VLESS port : 10086"
echo -e " VLESS UUID : ${YELLOW}${UUID}${NC}"
echo -e " DNSTT DNS : UDP 53 redirects to local UDP 5300"
echo ""
echo -e " CLI menu : ${YELLOW}menu${NC} (or sudo menu outside a root shell)"
echo -e " API endpoint : ${YELLOW}http://127.0.0.1:9090${NC}"
echo -e " API password : ${YELLOW}${ADMIN_TOKEN}${NC}"
echo -e " API session login (integrations): admin / ${ADMIN_PASSWORD}"
echo ""
echo -e " API token + DB credentials stored in: ${INSTALL_DIR}/.env"
echo -e " Logs: journalctl -u ${SERVICE_NAME} -f"
echo -e " tail -f ${INSTALL_DIR}/logs/panel.log"
echo ""
echo -e "${YELLOW}View/rotate the API password later with: sudo dragoncore api-password show|change${NC}"
echo ""
"$SYSTEMCTL_BIN" status "$SERVICE_NAME" --no-pager -l || true
+124
View File
@@ -0,0 +1,124 @@
package bhttp
import (
"crypto/sha256"
"encoding/binary"
"errors"
"io"
)
const (
ModeProbe byte = 0
ModeUpload byte = 1
ModeDownload byte = 2
ModeBatch byte = 3
ModeACK byte = 4
ModeLane byte = 5
StatusOK byte = 0
StatusError byte = 1
StatusData byte = 2
HeaderSize = 29
MaxPayload = 524288
MaxDownloadSize = 524284
)
type SessionID [16]byte
type Request struct {
Mode byte
SID SessionID
Seq uint64
Value uint32
Payload []byte
}
func Crypt(data []byte, sid SessionID, mode byte, seq uint64, response bool) []byte {
if len(data) == 0 {
return nil
}
seed := make([]byte, 26)
copy(seed[:16], sid[:])
seed[16] = mode
binary.BigEndian.PutUint64(seed[17:25], seq)
if response {
seed[25] = 1
}
out := make([]byte, len(data))
blockInput := make([]byte, 30)
copy(blockInput, seed)
for offset, counter := 0, uint32(0); offset < len(data); offset, counter = offset+32, counter+1 {
binary.BigEndian.PutUint32(blockInput[26:30], counter)
key := sha256.Sum256(blockInput)
end := offset + len(key)
if end > len(data) {
end = len(data)
}
for index := offset; index < end; index++ {
out[index] = data[index] ^ key[index-offset]
}
}
return out
}
func ReadRequest(reader io.Reader) (Request, error) {
var request Request
var header [HeaderSize]byte
if _, err := io.ReadFull(reader, header[:]); err != nil {
return request, err
}
request.Mode = header[0]
if request.Mode > ModeLane {
return request, errors.New("unknown BHTTP mode")
}
copy(request.SID[:], header[1:17])
request.Seq = binary.BigEndian.Uint64(header[17:25])
request.Value = binary.BigEndian.Uint32(header[25:29])
// Mode 2 overloads Value as a size hint. Mode 4 is an empty cumulative ACK.
if request.Mode == ModeDownload || request.Mode == ModeACK {
return request, nil
}
if request.Value > MaxPayload {
return request, errors.New("BHTTP request is too large")
}
if request.Value > 0 {
request.Payload = make([]byte, int(request.Value))
if _, err := io.ReadFull(reader, request.Payload); err != nil {
return request, err
}
}
return request, nil
}
func WriteStatus(writer io.Writer, status byte, data []byte) error {
packet := make([]byte, 5+len(data))
packet[0] = status
binary.BigEndian.PutUint32(packet[1:5], uint32(len(data)))
copy(packet[5:], data)
return writeAll(writer, packet)
}
func WriteDownload(writer io.Writer, sid SessionID, mode byte, seq uint64, data []byte) error {
encrypted := Crypt(data, sid, mode, seq, true)
packet := make([]byte, 9+len(encrypted))
packet[0] = StatusData
binary.BigEndian.PutUint32(packet[1:5], uint32(4+len(encrypted)))
binary.BigEndian.PutUint32(packet[5:9], uint32(len(data)))
copy(packet[9:], encrypted)
return writeAll(writer, packet)
}
func writeAll(writer io.Writer, data []byte) error {
for len(data) > 0 {
count, err := writer.Write(data)
if err != nil {
return err
}
if count <= 0 {
return io.ErrShortWrite
}
data = data[count:]
}
return nil
}
+256
View File
@@ -0,0 +1,256 @@
package bhttp
import (
"bytes"
"encoding/binary"
"encoding/hex"
"io"
"net"
"testing"
"time"
)
func TestCryptMatchesRestoredPythonServer(t *testing.T) {
var sid SessionID
for index := range sid {
sid[index] = byte(index)
}
tests := []struct {
clearHex string
mode byte
seq uint64
response bool
wantHex string
}{
{"42696c6f6c612d4248545450", 1, 0, false, "7ca4d6c962b839cf1fb68990"},
{"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", 3, 123456789, true, "ccd73e4b14777caaa138d17c7016770da44fe50c4d7322a759298098a47230347567293f767bb2f8069a2ede76ac97ec5e031832b023b44f69918e02c6f313ea"},
{"42485031010300000008", 0, 0, false, "1185931614521a40b889"},
}
for _, test := range tests {
clear, _ := hex.DecodeString(test.clearHex)
want, _ := hex.DecodeString(test.wantHex)
got := Crypt(clear, sid, test.mode, test.seq, test.response)
if !bytes.Equal(got, want) {
t.Fatalf("mode=%d seq=%d got=%x want=%x", test.mode, test.seq, got, want)
}
if decoded := Crypt(got, sid, test.mode, test.seq, test.response); !bytes.Equal(decoded, clear) {
t.Fatalf("cipher did not round-trip mode=%d seq=%d", test.mode, test.seq)
}
}
}
func writeTestRequest(writer io.Writer, mode byte, sid SessionID, sequence uint64, payload []byte, value uint32) error {
if mode != ModeDownload && mode != ModeACK {
value = uint32(len(payload))
}
packet := make([]byte, HeaderSize+len(payload))
packet[0] = mode
copy(packet[1:17], sid[:])
binary.BigEndian.PutUint64(packet[17:25], sequence)
binary.BigEndian.PutUint32(packet[25:29], value)
copy(packet[29:], payload)
return writeAll(writer, packet)
}
func readTestResponse(reader io.Reader) (byte, []byte, []byte, error) {
var header [5]byte
if _, err := io.ReadFull(reader, header[:]); err != nil {
return 0, nil, nil, err
}
size := binary.BigEndian.Uint32(header[1:5])
body := make([]byte, int(size))
if _, err := io.ReadFull(reader, body); err != nil {
return 0, nil, nil, err
}
raw := append(append([]byte(nil), header[:]...), body...)
return header[0], body, raw, nil
}
func waitBuffered(t *testing.T, session *Session, minimum int) {
t.Helper()
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
session.readyMu.Lock()
available := session.downloadBuffer.available()
session.readyMu.Unlock()
if available >= minimum {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("target bytes were not buffered")
}
func TestServerSSHRelayBatchRetryAndACK(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
dialed := false
server := NewServer(Config{
TargetAddress: "test:22",
DialTarget: func(address string) (net.Conn, error) {
if address != "test:22" || dialed {
t.Fatalf("unexpected target dial %q repeated=%v", address, dialed)
}
dialed = true
return targetServer, nil
},
})
defer server.Close()
accepted, client := net.Pipe()
done := make(chan error, 1)
go func() {
done <- server.handleConnection(accepted)
accepted.Close()
}()
defer func() {
client.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("connection handler did not stop")
}
}()
_ = client.SetDeadline(time.Now().Add(3 * time.Second))
var sid SessionID
copy(sid[:], []byte("bilola-test-sid!"))
if err := writeTestRequest(client, ModeUpload, sid, 0, nil, 0); err != nil {
t.Fatal(err)
}
status, _, _, err := readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("registration status=%d err=%v", status, err)
}
session := server.sessions.GetOrCreate(sid)
banner := []byte("SSH-2.0-BilolaGo\r\n")
go targetPeer.Write(banner)
waitBuffered(t, session, len(banner))
if err := writeTestRequest(client, ModeDownload, sid, 0, nil, 65536); err != nil {
t.Fatal(err)
}
status, body, _, err := readTestResponse(client)
if err != nil || status != StatusData || len(body) < 4 {
t.Fatalf("banner response status=%d len=%d err=%v", status, len(body), err)
}
plainSize := int(binary.BigEndian.Uint32(body[:4]))
decoded := Crypt(body[4:], sid, ModeDownload, 0, true)
if plainSize != len(banner) || !bytes.Equal(decoded, banner) {
t.Fatalf("banner got=%q size=%d", decoded, plainSize)
}
upload := []byte("SSH upload sequence zero")
encryptedUpload := Crypt(upload, sid, ModeUpload, 0, false)
targetUpload := make(chan []byte, 1)
go func() {
read := make([]byte, len(upload))
if _, readErr := io.ReadFull(targetPeer, read); readErr != nil {
targetUpload <- nil
return
}
targetUpload <- read
}()
if err := writeTestRequest(client, ModeUpload, sid, 0, encryptedUpload, 0); err != nil {
t.Fatal(err)
}
status, _, _, err = readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("upload status=%d err=%v", status, err)
}
targetRead := <-targetUpload
if !bytes.Equal(targetRead, upload) {
t.Fatalf("target upload=%q", targetRead)
}
downstream := make([]byte, 3000)
for index := range downstream {
downstream[index] = byte(index * 17)
}
go targetPeer.Write(downstream)
waitBuffered(t, session, len(downstream))
batchClear := make([]byte, 6)
binary.BigEndian.PutUint32(batchClear[:4], 1399)
binary.BigEndian.PutUint16(batchClear[4:6], 3)
batchRequest := Crypt(batchClear, sid, ModeBatch, 1, false)
if err := writeTestRequest(client, ModeBatch, sid, 1, batchRequest, 0); err != nil {
t.Fatal(err)
}
var firstRaw [][]byte
var downloaded []byte
var raw []byte
for offset := 0; offset < 3; offset++ {
status, body, raw, err = readTestResponse(client)
if err != nil || status != StatusData || len(body) < 4 {
t.Fatalf("batch %d status=%d len=%d err=%v", offset, status, len(body), err)
}
plainSize = int(binary.BigEndian.Uint32(body[:4]))
decoded = Crypt(body[4:], sid, ModeBatch, 1+uint64(offset), true)
if len(decoded) != plainSize {
t.Fatalf("batch %d declared=%d decoded=%d", offset, plainSize, len(decoded))
}
downloaded = append(downloaded, decoded...)
firstRaw = append(firstRaw, raw)
}
if !bytes.Equal(downloaded, downstream) {
t.Fatalf("batch data mismatch got=%d want=%d", len(downloaded), len(downstream))
}
if err := writeTestRequest(client, ModeBatch, sid, 1, batchRequest, 0); err != nil {
t.Fatal(err)
}
for offset := 0; offset < 3; offset++ {
_, _, raw, err := readTestResponse(client)
if err != nil || !bytes.Equal(raw, firstRaw[offset]) {
t.Fatalf("retry frame %d changed err=%v", offset, err)
}
}
if err := writeTestRequest(client, ModeACK, sid, 3, nil, 0); err != nil {
t.Fatal(err)
}
status, _, _, err = readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("ACK status=%d err=%v", status, err)
}
session.downloadMu.Lock()
remaining := len(session.downloadFrames)
session.downloadMu.Unlock()
if remaining != 0 {
t.Fatalf("ACK retained %d replay frames", remaining)
}
}
func TestProbeEchoMatchesBHP1(t *testing.T) {
server, client := net.Pipe()
done := make(chan error, 1)
go func() {
request, err := ReadRequest(server)
if err == nil {
err = handleProbe(server, request)
}
done <- err
server.Close()
}()
defer client.Close()
var sid SessionID
for index := range sid {
sid[index] = byte(index)
}
clear := []byte{'B', 'H', 'P', '1', 1, ModeDownload, 0, 0, 2, 0}
encrypted := Crypt(clear, sid, ModeProbe, 7, false)
if err := writeTestRequest(client, ModeProbe, sid, 7, encrypted, 0); err != nil {
t.Fatal(err)
}
status, body, _, err := readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("probe status=%d err=%v", status, err)
}
decoded := Crypt(body, sid, ModeProbe, 7, true)
if len(decoded) != 512 || !bytes.Equal(decoded[:10], clear) {
t.Fatalf("probe response len=%d prefix=%x", len(decoded), decoded[:10])
}
if err := <-done; err != nil {
t.Fatal(err)
}
}
+589
View File
@@ -0,0 +1,589 @@
package bhttp
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
"strings"
"sync"
"sync/atomic"
"time"
)
type Config struct {
TargetAddress string
SessionTimeout time.Duration
DialTimeout time.Duration
MaxV2Lanes int
Logger *log.Logger
DialTarget func(string) (net.Conn, error)
// MaxConnections caps concurrently accepted client sockets across every
// listener served by this server. Zero or negative disables the cap.
MaxConnections int
// MaxSessions caps concurrently tracked BHTTP sessions. Zero or negative
// disables the cap. A session is one logical tunnel; BHTTP v2 attaches
// several sockets ("lanes") to the same session.
MaxSessions int
// LogConnections enables one log line per accepted socket. Leave it off on
// busy servers.
LogConnections bool
}
// StatsSnapshot is the counter set the admin panel reads.
type StatsSnapshot struct {
StartedAt time.Time `json:"startedAt"`
ActiveConnections int64 `json:"activeConnections"`
ActiveSessions int64 `json:"activeSessions"`
Accepted uint64 `json:"accepted"`
ConnectionsRejected uint64 `json:"connectionsRejected"`
SessionsRejected uint64 `json:"sessionsRejected"`
SessionsExpired uint64 `json:"sessionsExpired"`
Probes uint64 `json:"probes"`
ProbesV2 uint64 `json:"probesV2"`
HTTPUpgrades uint64 `json:"httpUpgrades"`
LanesAttached uint64 `json:"lanesAttached"`
LanesRejected uint64 `json:"lanesRejected"`
UploadBytes uint64 `json:"uploadBytes"`
DownloadBytes uint64 `json:"downloadBytes"`
TargetFailures uint64 `json:"targetFailures"`
ProtocolErrors uint64 `json:"protocolErrors"`
}
type counters struct {
accepted atomic.Uint64
connectionsRejected atomic.Uint64
sessionsRejected atomic.Uint64
sessionsExpired atomic.Uint64
probes atomic.Uint64
probesV2 atomic.Uint64
httpUpgrades atomic.Uint64
lanesAttached atomic.Uint64
lanesRejected atomic.Uint64
uploadBytes atomic.Uint64
downloadBytes atomic.Uint64
targetFailures atomic.Uint64
protocolErrors atomic.Uint64
activeConnections atomic.Int64
}
type Server struct {
config Config
sessions *SessionManager
closed chan struct{}
once sync.Once
wait sync.WaitGroup
connMu sync.Mutex
active map[net.Conn]struct{}
started time.Time
stats counters
}
const (
bhttpV2Version = 2
bhttpV2FeatureLanes = 1 << 0
bhttpV2FeatureResume = 1 << 1
bhttpV2FeatureAck = 1 << 2
bhttpV2MaxLanes = 128
laneUpload = 1
laneDownload = 2
laneDuplex = 3
)
func NewServer(config Config) *Server {
if config.TargetAddress == "" {
config.TargetAddress = "127.0.0.1:22"
}
if config.SessionTimeout <= 0 {
config.SessionTimeout = 2 * time.Minute
}
if config.DialTimeout <= 0 {
config.DialTimeout = 10 * time.Second
}
if config.MaxV2Lanes <= 0 {
config.MaxV2Lanes = bhttpV2MaxLanes
}
if config.Logger == nil {
config.Logger = log.Default()
}
if config.DialTarget == nil {
dialer := net.Dialer{Timeout: config.DialTimeout, KeepAlive: 30 * time.Second}
config.DialTarget = func(address string) (net.Conn, error) {
connection, err := dialer.Dial("tcp", address)
if err == nil {
if tcp, ok := connection.(*net.TCPConn); ok {
_ = tcp.SetNoDelay(true)
}
}
return connection, err
}
}
server := &Server{
config: config,
sessions: NewSessionManager(config.SessionTimeout),
closed: make(chan struct{}),
active: make(map[net.Conn]struct{}),
started: time.Now(),
}
server.sessions.limit = config.MaxSessions
server.sessions.rejected = &server.stats.sessionsRejected
server.wait.Add(1)
go server.cleanupLoop()
return server
}
func (server *Server) cleanupLoop() {
defer server.wait.Done()
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case now := <-ticker.C:
removed := server.sessions.Cleanup(now)
if removed > 0 {
server.stats.sessionsExpired.Add(uint64(removed))
server.config.Logger.Printf("cleaned %d stale BHTTP sessions", removed)
}
case <-server.closed:
return
}
}
}
func (server *Server) Serve(listener net.Listener) error {
for {
connection, err := listener.Accept()
if err != nil {
select {
case <-server.closed:
return nil
default:
return err
}
}
if tcp, ok := connection.(*net.TCPConn); ok {
_ = tcp.SetNoDelay(true)
}
server.stats.accepted.Add(1)
if !server.track(connection) {
continue
}
server.wait.Add(1)
go func() {
defer server.wait.Done()
server.run(connection)
}()
}
}
// ServeConn serves one already-accepted connection, for listeners this server
// does not own. A port shared with SSH or HTTP routes a client here once the
// first bytes have been identified as BHTTP; the connection is then counted,
// capped and closed exactly like one from Serve's own accept loop.
//
// It blocks until the connection ends. It reports whether the connection was
// admitted: a refused connection has already been closed, and the caller must
// not keep using it either way.
func (server *Server) ServeConn(connection net.Conn) bool {
select {
case <-server.closed:
_ = connection.Close()
return false
default:
}
server.stats.accepted.Add(1)
if !server.track(connection) {
return false
}
server.wait.Add(1)
defer server.wait.Done()
server.run(connection)
return true
}
// track registers a connection against the socket cap. It reports whether the
// connection was admitted; a rejected connection is closed here.
func (server *Server) track(connection net.Conn) bool {
server.connMu.Lock()
// Reject past the socket cap before any protocol work, so a surge cannot
// exhaust memory the way an unbounded accept loop would.
if limit := server.config.MaxConnections; limit > 0 && len(server.active) >= limit {
server.connMu.Unlock()
rejected := server.stats.connectionsRejected.Add(1)
if rejected == 1 || rejected%1000 == 0 {
server.config.Logger.Printf("connection cap reached (%d); rejected %d client(s) so far",
limit, rejected)
}
_ = connection.Close()
return false
}
server.active[connection] = struct{}{}
server.connMu.Unlock()
server.stats.activeConnections.Add(1)
if server.config.LogConnections {
server.config.Logger.Printf("client %s connected", connection.RemoteAddr())
}
return true
}
// run drives one tracked connection to completion and releases it.
func (server *Server) run(connection net.Conn) {
defer func() {
server.connMu.Lock()
delete(server.active, connection)
server.connMu.Unlock()
server.stats.activeConnections.Add(-1)
_ = connection.Close()
if server.config.LogConnections {
server.config.Logger.Printf("client %s disconnected", connection.RemoteAddr())
}
}()
if err := server.handleConnection(connection); err != nil && !isNormalClose(err) {
server.stats.protocolErrors.Add(1)
server.config.Logger.Printf("client %s: %v", connection.RemoteAddr(), err)
}
}
func isNormalClose(err error) bool {
return errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) || strings.Contains(err.Error(), "connection reset")
}
func (server *Server) handleConnection(connection net.Conn) error {
reader := bufio.NewReader(connection)
first, err := reader.Peek(1)
if err != nil {
return err
}
if first[0] == ModeProbe {
request, err := ReadRequest(reader)
if err != nil {
return err
}
server.stats.probes.Add(1)
if isV2Probe(request) {
server.stats.probesV2.Add(1)
}
return handleProbeLimit(connection, request, server.config.MaxV2Lanes)
}
if first[0] > ModeLane {
if err := handleHTTPUpgrade(reader, connection); err != nil {
return err
}
server.stats.httpUpgrades.Add(1)
}
var laneRole byte
var laneLease *LaneLease
defer func() {
if laneLease != nil {
laneLease.ReleaseLane()
}
}()
for {
request, err := ReadRequest(reader)
if err != nil {
return err
}
if request.Mode == ModeLane {
if laneLease != nil {
return errors.New("BHTTP v2 lane already attached")
}
role, attached, attachErr := server.attachLane(connection, request)
if attachErr != nil {
return attachErr
}
laneRole = role
laneLease = attached
continue
}
if laneRole == laneUpload && request.Mode != ModeUpload {
return errors.New("BHTTP v2 upload lane received non-upload request")
}
if laneRole == laneDownload && request.Mode != ModeDownload &&
request.Mode != ModeBatch && request.Mode != ModeACK {
return errors.New("BHTTP v2 download lane received invalid request")
}
session := server.sessions.GetOrCreate(request.SID)
if session == nil {
_ = WriteStatus(connection, StatusError, []byte("BHTTP session limit reached"))
return errors.New("BHTTP session limit reached")
}
session.touch()
if err := server.handleRequest(connection, session, request, laneRole != 0); err != nil {
return err
}
}
}
func handleHTTPUpgrade(reader *bufio.Reader, writer io.Writer) error {
var request bytes.Buffer
for request.Len() < 64*1024 {
value, err := reader.ReadByte()
if err != nil {
return err
}
request.WriteByte(value)
if bytes.HasSuffix(request.Bytes(), []byte("\r\n\r\n")) {
return writeAll(writer, []byte("HTTP/1.1 101 DTunnel\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\nHTTP/1.1 200 DTunnel\r\n\r\n"))
}
}
return errors.New("HTTP upgrade header is too large")
}
// isV2Probe reports whether a probe payload announces the BHP2 capability
// handshake rather than the original BHP1 profile.
func isV2Probe(request Request) bool {
clear := Crypt(request.Payload, request.SID, ModeProbe, request.Seq, false)
return len(clear) == 10 && bytes.Equal(clear[:4], []byte("BHP2")) && clear[4] == bhttpV2Version
}
// Stats returns a snapshot of the server counters for the admin panel.
func (server *Server) Stats() StatsSnapshot {
return StatsSnapshot{
StartedAt: server.started,
ActiveConnections: server.stats.activeConnections.Load(),
ActiveSessions: int64(server.sessions.Len()),
Accepted: server.stats.accepted.Load(),
ConnectionsRejected: server.stats.connectionsRejected.Load(),
SessionsRejected: server.stats.sessionsRejected.Load(),
SessionsExpired: server.stats.sessionsExpired.Load(),
Probes: server.stats.probes.Load(),
ProbesV2: server.stats.probesV2.Load(),
HTTPUpgrades: server.stats.httpUpgrades.Load(),
LanesAttached: server.stats.lanesAttached.Load(),
LanesRejected: server.stats.lanesRejected.Load(),
UploadBytes: server.stats.uploadBytes.Load(),
DownloadBytes: server.stats.downloadBytes.Load(),
TargetFailures: server.stats.targetFailures.Load(),
ProtocolErrors: server.stats.protocolErrors.Load(),
}
}
func handleProbe(writer io.Writer, request Request) error {
return handleProbeLimit(writer, request, bhttpV2MaxLanes)
}
func handleProbeLimit(writer io.Writer, request Request, maxLanes int) error {
clear := Crypt(request.Payload, request.SID, ModeProbe, request.Seq, false)
if len(clear) == 10 && bytes.Equal(clear[:4], []byte("BHP2")) && clear[4] == bhttpV2Version {
response := make([]byte, 14)
copy(response[:4], []byte("BHP2"))
response[4] = bhttpV2Version
binary.BigEndian.PutUint32(response[6:10], bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck)
binary.BigEndian.PutUint32(response[10:14], uint32(maxLanes))
return WriteStatus(writer, StatusOK, Crypt(response, request.SID, ModeProbe, request.Seq, true))
}
if len(clear) < 10 || !bytes.Equal(clear[:4], []byte("BHP1")) || clear[4] != 1 {
return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe"))
}
submode := clear[5]
parameter := int(binary.BigEndian.Uint32(clear[6:10]))
if submode > ModeACK {
return WriteStatus(writer, StatusError, []byte("unsupported BHTTP probe mode"))
}
expected := 10
if submode == ModeUpload && parameter >= 10 {
expected = parameter
}
if len(clear) != expected {
return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe length"))
}
for index := 10; index < len(clear); index++ {
if clear[index] != byte(index*31) {
return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe pattern"))
}
}
responseSize := 10
if submode == ModeDownload && parameter > responseSize {
responseSize = parameter
}
if responseSize > MaxPayload {
return WriteStatus(writer, StatusError, []byte("BHTTP v1 probe too large"))
}
response := make([]byte, responseSize)
copy(response[:4], []byte("BHP1"))
response[4] = 1
response[5] = submode
binary.BigEndian.PutUint32(response[6:10], uint32(parameter))
for index := 10; index < len(response); index++ {
response[index] = byte(index * 31)
}
encrypted := Crypt(response, request.SID, ModeProbe, request.Seq, true)
count := 1
if submode == ModeACK {
count = parameter
if count < 1 {
count = 1
}
if count > 256 {
count = 256
}
}
for index := 0; index < count; index++ {
if err := WriteStatus(writer, StatusOK, encrypted); err != nil {
return err
}
}
return nil
}
func (server *Server) handleRequest(writer io.Writer, session *Session, request Request, version2 bool) error {
switch request.Mode {
case ModeUpload:
payload := request.Payload
if len(payload) > 0 {
payload = Crypt(payload, request.SID, request.Mode, request.Seq, false)
}
if request.Seq == 0 && len(payload) == 0 {
if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil {
server.stats.targetFailures.Add(1)
return WriteStatus(writer, StatusError, []byte("SSH target unavailable"))
}
return WriteStatus(writer, StatusOK, nil)
}
if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil {
server.stats.targetFailures.Add(1)
return WriteStatus(writer, StatusError, []byte("SSH target unavailable"))
}
if err := session.WriteUpload(request.Seq, payload); err != nil {
return WriteStatus(writer, StatusError, []byte("SSH upload failed"))
}
server.stats.uploadBytes.Add(uint64(len(payload)))
if !version2 {
return WriteStatus(writer, StatusOK, nil)
}
ack := make([]byte, 9)
if sequence, ok := session.UploadCommitted(); ok {
ack[0] = 1
binary.BigEndian.PutUint64(ack[1:], sequence)
}
return WriteStatus(writer, StatusOK, ack)
case ModeDownload:
chunks := session.AssignDownload(request.Seq, 1, 65536)
server.stats.downloadBytes.Add(uint64(len(chunks[0])))
return WriteDownload(writer, request.SID, request.Mode, request.Seq, chunks[0])
case ModeBatch:
clear := Crypt(request.Payload, request.SID, request.Mode, request.Seq, false)
if len(clear) != 6 {
return WriteStatus(writer, StatusError, []byte("invalid BHTTP batch request"))
}
limit := int(binary.BigEndian.Uint32(clear[:4]))
count := int(binary.BigEndian.Uint16(clear[4:6]))
if limit < 1 {
limit = 1
}
if limit > MaxDownloadSize {
limit = MaxDownloadSize
}
if count < 1 {
count = 1
}
if count > 256 {
count = 256
}
chunks := session.AssignDownload(request.Seq, count, limit)
for offset, chunk := range chunks {
server.stats.downloadBytes.Add(uint64(len(chunk)))
if err := WriteDownload(writer, request.SID, request.Mode, request.Seq+uint64(offset), chunk); err != nil {
return err
}
}
return nil
case ModeACK:
session.Acknowledge(request.Seq)
return WriteStatus(writer, StatusOK, nil)
}
return fmt.Errorf("unsupported BHTTP mode %d", request.Mode)
}
func (server *Server) attachLane(writer io.Writer, request Request) (byte, *LaneLease, error) {
clear := Crypt(request.Payload, request.SID, ModeLane, request.Seq, false)
if len(clear) != 12 || !bytes.Equal(clear[:4], []byte("BLN2")) || clear[4] != bhttpV2Version {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("invalid BHTTP v2 lane hello"))
return 0, nil, errors.New("invalid BHTTP v2 lane hello")
}
role := clear[5]
if role != laneUpload && role != laneDownload && role != laneDuplex {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("invalid BHTTP v2 lane role"))
return 0, nil, errors.New("invalid BHTTP v2 lane role")
}
requireResume := binary.BigEndian.Uint16(clear[6:8])&1 != 0
laneID := binary.BigEndian.Uint32(clear[8:12])
session, resumed := server.sessions.Get(request.SID)
if requireResume && !resumed {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("BHTTP v2 session expired"))
return 0, nil, errors.New("BHTTP v2 resume rejected: session expired")
}
if !resumed {
session, _ = server.sessions.GetOrCreateState(request.SID)
if session == nil {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("BHTTP session limit reached"))
return 0, nil, errors.New("BHTTP session limit reached")
}
}
lease, acquired := session.AcquireLane(laneID, server.config.MaxV2Lanes)
if !acquired {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("BHTTP v2 lane limit exceeded"))
return 0, nil, errors.New("BHTTP v2 lane limit exceeded")
}
attached := true
defer func() {
if attached {
lease.ReleaseLane()
}
}()
if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil {
server.stats.targetFailures.Add(1)
_ = WriteStatus(writer, StatusError, []byte("SSH target unavailable"))
return 0, nil, err
}
response := make([]byte, 18)
copy(response[:4], []byte("BOK2"))
response[4] = bhttpV2Version
if resumed {
response[5] = 1
}
binary.BigEndian.PutUint32(response[6:10], bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck)
if sequence, ok := session.UploadCommitted(); ok {
binary.BigEndian.PutUint64(response[10:18], sequence+1)
}
encoded := Crypt(response, request.SID, ModeLane, request.Seq, true)
if err := WriteStatus(writer, StatusOK, encoded); err != nil {
return 0, nil, err
}
session.touch()
attached = false
server.stats.lanesAttached.Add(1)
return role, lease, nil
}
func (server *Server) Close() {
server.once.Do(func() {
close(server.closed)
server.connMu.Lock()
connections := make([]net.Conn, 0, len(server.active))
for connection := range server.active {
connections = append(connections, connection)
}
server.connMu.Unlock()
for _, connection := range connections {
_ = connection.Close()
}
server.sessions.Close()
})
}
func (server *Server) Wait() {
server.wait.Wait()
}
+415
View File
@@ -0,0 +1,415 @@
package bhttp
import (
"errors"
"io"
"net"
"sync"
"sync/atomic"
"time"
)
type byteQueue struct {
data []byte
offset int
}
func (queue *byteQueue) append(data []byte) {
queue.data = append(queue.data, data...)
}
func (queue *byteQueue) available() int {
return len(queue.data) - queue.offset
}
func (queue *byteQueue) take(limit int) []byte {
if queue.available() == 0 {
return nil
}
end := queue.offset + limit
if end > len(queue.data) {
end = len(queue.data)
}
out := append([]byte(nil), queue.data[queue.offset:end]...)
queue.offset = end
if queue.offset == len(queue.data) {
queue.data = queue.data[:0]
queue.offset = 0
} else if queue.offset >= 1<<20 && queue.offset*2 >= len(queue.data) {
copy(queue.data, queue.data[queue.offset:])
queue.data = queue.data[:len(queue.data)-queue.offset]
queue.offset = 0
}
return out
}
type Session struct {
sid SessionID
openOnce sync.Once
openErr error
target net.Conn
uploadMu sync.Mutex
uploadPending map[uint64][]byte
uploadNext uint64
laneMu sync.Mutex
activeLanes map[uint32]uint64
nextLaneLease uint64
readyMu sync.Mutex
readySignal chan struct{}
downloadBuffer byteQueue
bannerDelivered bool
targetEOF bool
targetError error
downloadMu sync.Mutex
downloadSignal chan struct{}
downloadNext uint64
downloadAcked uint64
hasACK bool
downloadClosed bool
downloadFrames map[uint64][]byte
lastSeen atomic.Int64
closeOnce sync.Once
}
type LaneLease struct {
session *Session
laneID uint32
generation uint64
once sync.Once
}
// AcquireLane gives a stable lane ID a new generation. Reconnecting the same
// logical lane replaces its previous socket immediately instead of consuming
// another slot until the old handler notices the close.
func (session *Session) AcquireLane(laneID uint32, maximum int) (*LaneLease, bool) {
session.laneMu.Lock()
defer session.laneMu.Unlock()
if _, replacing := session.activeLanes[laneID]; !replacing &&
maximum > 0 && len(session.activeLanes) >= maximum {
return nil, false
}
session.nextLaneLease++
generation := session.nextLaneLease
session.activeLanes[laneID] = generation
return &LaneLease{session: session, laneID: laneID, generation: generation}, true
}
func (lease *LaneLease) ReleaseLane() {
if lease == nil || lease.session == nil {
return
}
lease.once.Do(func() {
lease.session.laneMu.Lock()
if lease.session.activeLanes[lease.laneID] == lease.generation {
delete(lease.session.activeLanes, lease.laneID)
}
lease.session.laneMu.Unlock()
})
}
func NewSession(sid SessionID) *Session {
session := &Session{
sid: sid,
uploadPending: make(map[uint64][]byte),
activeLanes: make(map[uint32]uint64),
readySignal: make(chan struct{}),
downloadSignal: make(chan struct{}),
downloadFrames: make(map[uint64][]byte),
}
session.touch()
return session
}
func (session *Session) touch() {
session.lastSeen.Store(time.Now().UnixNano())
}
func (session *Session) LastSeen() time.Time {
return time.Unix(0, session.lastSeen.Load())
}
func (session *Session) signalReadyLocked() {
close(session.readySignal)
session.readySignal = make(chan struct{})
}
func (session *Session) signalDownloadLocked() {
close(session.downloadSignal)
session.downloadSignal = make(chan struct{})
}
func (session *Session) OpenTarget(address string, dialer func(string) (net.Conn, error)) error {
session.openOnce.Do(func() {
target, err := dialer(address)
if err != nil {
session.openErr = err
session.readyMu.Lock()
session.targetError = err
session.targetEOF = true
session.signalReadyLocked()
session.readyMu.Unlock()
return
}
session.target = target
go session.readTarget()
})
return session.openErr
}
func (session *Session) readTarget() {
buffer := make([]byte, 65536)
for {
count, err := session.target.Read(buffer)
if count > 0 {
session.readyMu.Lock()
session.downloadBuffer.append(buffer[:count])
session.touch()
session.signalReadyLocked()
session.readyMu.Unlock()
}
if err != nil {
session.readyMu.Lock()
if !errors.Is(err, io.EOF) {
session.targetError = err
}
session.targetEOF = true
session.signalReadyLocked()
session.readyMu.Unlock()
session.downloadMu.Lock()
session.downloadClosed = true
session.signalDownloadLocked()
session.downloadMu.Unlock()
return
}
}
}
func (session *Session) WriteUpload(sequence uint64, payload []byte) error {
session.uploadMu.Lock()
defer session.uploadMu.Unlock()
if sequence < session.uploadNext {
return nil
}
if _, exists := session.uploadPending[sequence]; !exists {
session.uploadPending[sequence] = append([]byte(nil), payload...)
}
for {
chunk, exists := session.uploadPending[session.uploadNext]
if !exists {
return nil
}
delete(session.uploadPending, session.uploadNext)
if len(chunk) > 0 && session.target != nil {
if err := writeAll(session.target, chunk); err != nil {
return err
}
}
session.uploadNext++
session.touch()
}
}
// UploadCommitted reports the highest contiguous upload sequence written to
// the target. Receipt alone is not a commit when lanes arrive out of order.
func (session *Session) UploadCommitted() (uint64, bool) {
session.uploadMu.Lock()
defer session.uploadMu.Unlock()
if session.uploadNext == 0 {
return 0, false
}
return session.uploadNext - 1, true
}
func (session *Session) TakeDownload(sequence uint64, limit int, bannerTimeout time.Duration) []byte {
if limit < 1 {
limit = 1
}
if limit > MaxDownloadSize {
limit = MaxDownloadSize
}
deadline := time.NewTimer(bannerTimeout)
defer deadline.Stop()
session.readyMu.Lock()
defer session.readyMu.Unlock()
if !session.bannerDelivered && sequence != 0 {
return nil
}
for session.downloadBuffer.available() == 0 && !session.targetEOF {
if session.bannerDelivered {
return nil
}
signal := session.readySignal
session.readyMu.Unlock()
select {
case <-signal:
case <-deadline.C:
session.readyMu.Lock()
return nil
}
session.readyMu.Lock()
}
chunk := session.downloadBuffer.take(limit)
if len(chunk) == 0 {
return nil
}
session.bannerDelivered = true
session.touch()
return chunk
}
func (session *Session) AssignDownload(sequence uint64, count int, limit int) [][]byte {
session.downloadMu.Lock()
for sequence > session.downloadNext && !session.downloadClosed {
signal := session.downloadSignal
session.downloadMu.Unlock()
<-signal
session.downloadMu.Lock()
}
isNew := sequence == session.downloadNext
chunks := make([][]byte, count)
for offset := 0; offset < count; offset++ {
current := sequence + uint64(offset)
if isNew {
chunk := session.TakeDownload(current, limit, 5*time.Second)
if len(chunk) > 0 {
session.downloadFrames[current] = chunk
}
chunks[offset] = chunk
} else {
chunks[offset] = append([]byte(nil), session.downloadFrames[current]...)
}
}
if isNew {
session.downloadNext += uint64(count)
session.signalDownloadLocked()
}
session.downloadMu.Unlock()
return chunks
}
func (session *Session) Acknowledge(sequence uint64) {
session.downloadMu.Lock()
defer session.downloadMu.Unlock()
if session.hasACK && sequence <= session.downloadAcked {
return
}
session.hasACK = true
session.downloadAcked = sequence
for number := range session.downloadFrames {
if number <= sequence {
delete(session.downloadFrames, number)
}
}
}
func (session *Session) Close() {
session.closeOnce.Do(func() {
if session.target != nil {
_ = session.target.Close()
}
session.readyMu.Lock()
session.targetEOF = true
session.signalReadyLocked()
session.readyMu.Unlock()
session.downloadMu.Lock()
session.downloadClosed = true
session.signalDownloadLocked()
session.downloadMu.Unlock()
})
}
type SessionManager struct {
mu sync.RWMutex
sessions map[SessionID]*Session
timeout time.Duration
// limit caps concurrently tracked sessions. Zero or negative disables it.
limit int
// rejected, when set, counts sessions turned away at the limit.
rejected *atomic.Uint64
}
func NewSessionManager(timeout time.Duration) *SessionManager {
return &SessionManager{sessions: make(map[SessionID]*Session), timeout: timeout}
}
// GetOrCreate returns the session for sid, creating it if needed. It returns
// nil when the session limit is already reached and sid is not known yet.
func (manager *SessionManager) GetOrCreate(sid SessionID) *Session {
session, _ := manager.GetOrCreateState(sid)
return session
}
// GetOrCreateState reports whether the returned session already existed. A nil
// session means the manager is at its configured limit.
func (manager *SessionManager) GetOrCreateState(sid SessionID) (*Session, bool) {
manager.mu.RLock()
session := manager.sessions[sid]
manager.mu.RUnlock()
if session != nil {
return session, true
}
manager.mu.Lock()
defer manager.mu.Unlock()
if session = manager.sessions[sid]; session != nil {
return session, true
}
if manager.limit > 0 && len(manager.sessions) >= manager.limit {
if manager.rejected != nil {
manager.rejected.Add(1)
}
return nil, false
}
session = NewSession(sid)
manager.sessions[sid] = session
return session, false
}
// Len reports how many sessions are currently tracked.
func (manager *SessionManager) Len() int {
manager.mu.RLock()
defer manager.mu.RUnlock()
return len(manager.sessions)
}
func (manager *SessionManager) Get(sid SessionID) (*Session, bool) {
manager.mu.RLock()
session := manager.sessions[sid]
manager.mu.RUnlock()
return session, session != nil
}
func (manager *SessionManager) Cleanup(now time.Time) int {
manager.mu.Lock()
var stale []*Session
for sid, session := range manager.sessions {
if now.Sub(session.LastSeen()) > manager.timeout {
delete(manager.sessions, sid)
stale = append(stale, session)
}
}
manager.mu.Unlock()
for _, session := range stale {
session.Close()
}
return len(stale)
}
func (manager *SessionManager) Close() {
manager.mu.Lock()
sessions := make([]*Session, 0, len(manager.sessions))
for sid, session := range manager.sessions {
delete(manager.sessions, sid)
sessions = append(sessions, session)
}
manager.mu.Unlock()
for _, session := range sessions {
session.Close()
}
}
+99
View File
@@ -0,0 +1,99 @@
package bhttp
import (
"bytes"
"encoding/binary"
)
// Verdict is the result of inspecting the first bytes of a connection.
type Verdict int
const (
// VerdictNo means the bytes cannot begin a BHTTP frame.
VerdictNo Verdict = iota
// VerdictMore means the bytes so far are consistent with BHTTP but more
// are needed to decide. The caller should peek further and ask again.
VerdictMore
// VerdictYes means the bytes begin a BHTTP frame.
VerdictYes
)
// SniffLimit is the largest number of bytes SniffFrame will ever ask for. It
// covers a full frame header plus a probe/lane payload, which is where the
// magic strings that make the decision conclusive live.
const SniffLimit = HeaderSize + 4096
// SniffFrame reports whether data begins a BHTTP frame, so a listener shared
// with other protocols can route the connection without consuming anything.
//
// The first byte alone already separates BHTTP from the protocols it shares a
// port with: a BHTTP frame opens with a mode number (0..5), while SSH opens
// with 'S' (0x53) and an HTTP request or status line opens with a method or
// version letter. Every one of those is far above ModeLane, so a single byte
// rejects them outright and costs nothing.
//
// A low first byte is not proof on its own, because HTTP-injection clients may
// prepend arbitrary junk. So the frame header is range-checked, and for the two
// modes that carry a magic string — the probe that opens every client session
// and the v2 lane hello — the magic is decrypted and verified. That check is
// keyed by the session ID in the same header, so junk cannot pass it by chance.
func SniffFrame(data []byte) Verdict {
if len(data) == 0 {
return VerdictMore
}
mode := data[0]
if mode > ModeLane {
return VerdictNo
}
if len(data) < HeaderSize {
return VerdictMore
}
request := Request{Mode: mode}
copy(request.SID[:], data[1:17])
request.Seq = binary.BigEndian.Uint64(data[17:25])
request.Value = binary.BigEndian.Uint32(data[25:29])
// Modes 2 and 4 overload Value as a size hint and an empty cumulative ACK,
// so they carry no payload to verify.
if mode == ModeDownload || mode == ModeACK {
return VerdictYes
}
if request.Value > MaxPayload {
return VerdictNo
}
magic, ok := frameMagic(mode)
if !ok {
// Modes 1 and 3 have no magic string. A sane header is all there is.
return VerdictYes
}
// An oversized payload cannot be a probe or lane hello, both of which are
// short, so the magic would not be where it belongs.
if int(request.Value) > SniffLimit-HeaderSize {
return VerdictNo
}
end := HeaderSize + int(request.Value)
if len(data) < end {
return VerdictMore
}
clear := Crypt(data[HeaderSize:end], request.SID, mode, request.Seq, false)
if len(clear) < len(magic) || !bytes.Equal(clear[:len(magic)], magic) {
return VerdictNo
}
return VerdictYes
}
// frameMagic returns the plaintext prefix a mode's payload must start with,
// and whether that mode has one at all.
func frameMagic(mode byte) ([]byte, bool) {
switch mode {
case ModeProbe:
// A probe is either the BHP1 profile or the BHP2 capability handshake;
// both share the first three bytes, which is what is checked here.
return []byte("BHP"), true
case ModeLane:
return []byte("BLN2"), true
}
return nil, false
}
+164
View File
@@ -0,0 +1,164 @@
package bhttp
import (
"encoding/binary"
"testing"
)
// frame builds a wire frame for the sniffer to inspect.
func frame(mode byte, sid SessionID, sequence uint64, clear []byte) []byte {
payload := Crypt(clear, sid, mode, sequence, false)
out := make([]byte, HeaderSize+len(payload))
out[0] = mode
copy(out[1:17], sid[:])
binary.BigEndian.PutUint64(out[17:25], sequence)
binary.BigEndian.PutUint32(out[25:29], uint32(len(payload)))
copy(out[HeaderSize:], payload)
return out
}
func probeClear(magic string, submode byte, parameter uint32) []byte {
clear := make([]byte, 10)
copy(clear[:4], magic)
clear[4] = 1
clear[5] = submode
binary.BigEndian.PutUint32(clear[6:10], parameter)
return clear
}
// Everything BHTTP shares a port with has to be rejected on the first byte,
// otherwise sharing the port would break SSH and HTTP-injection clients.
func TestSniffRejectsTheProtocolsItSharesPortsWith(t *testing.T) {
tests := map[string]string{
"SSH identification": "SSH-2.0-OpenSSH_9.6\r\n",
"HTTP GET": "GET / HTTP/1.1\r\nHost: x\r\n\r\n",
"HTTP POST": "POST /path HTTP/1.1\r\n\r\n",
"HTTP HEAD": "HEAD / HTTP/1.0\r\n\r\n",
"HTTP CONNECT": "CONNECT host:443 HTTP/1.1\r\n\r\n",
"HTTP OPTIONS": "OPTIONS / HTTP/1.1\r\n\r\n",
"HTTP PATCH": "PATCH / HTTP/1.1\r\n\r\n",
"HTTP status line": "HTTP/1.1 200 OK\r\n\r\n",
"TLS client hello": "\x16\x03\x01\x02\x00\x01\x00\x01\xfc\x03\x03",
"bare CRLF": "\r\n\r\n",
}
for name, input := range tests {
t.Run(name, func(t *testing.T) {
if got := SniffFrame([]byte(input)); got != VerdictNo {
t.Fatalf("SniffFrame(%q) = %v, want VerdictNo", input, got)
}
})
}
}
func TestSniffAcceptsProbeFrames(t *testing.T) {
var sid SessionID
copy(sid[:], "sniff-probe-sid1")
bhp1 := frame(ModeProbe, sid, 0, probeClear("BHP1", ModeUpload, 0))
if got := SniffFrame(bhp1); got != VerdictYes {
t.Fatalf("BHP1 probe = %v, want VerdictYes", got)
}
capability := make([]byte, 10)
copy(capability[:4], "BHP2")
capability[4] = 2
bhp2 := frame(ModeProbe, sid, 3, capability)
if got := SniffFrame(bhp2); got != VerdictYes {
t.Fatalf("BHP2 probe = %v, want VerdictYes", got)
}
}
func TestSniffAcceptsLaneAndDataFrames(t *testing.T) {
var sid SessionID
copy(sid[:], "sniff-lane-sid01")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
binary.BigEndian.PutUint32(hello[8:], 4)
if got := SniffFrame(frame(ModeLane, sid, 9, hello)); got != VerdictYes {
t.Fatalf("v2 lane hello = %v, want VerdictYes", got)
}
// Modes 2 and 4 carry no payload; a sane header is the whole signal.
if got := SniffFrame(frame(ModeDownload, sid, 1, nil)); got != VerdictYes {
t.Fatalf("download frame = %v, want VerdictYes", got)
}
if got := SniffFrame(frame(ModeACK, sid, 2, nil)); got != VerdictYes {
t.Fatalf("ACK frame = %v, want VerdictYes", got)
}
if got := SniffFrame(frame(ModeUpload, sid, 0, nil)); got != VerdictYes {
t.Fatalf("session-open upload frame = %v, want VerdictYes", got)
}
}
// An injection client may prepend arbitrary junk, and some of that junk starts
// with a low byte. The magic check on the frame types that carry one is what
// keeps such a connection out of BHTTP.
func TestSniffRejectsLowByteJunk(t *testing.T) {
var sid SessionID
copy(sid[:], "sniff-junk-sid01")
// A probe-shaped frame whose payload is not a BHP probe at all.
bogus := frame(ModeProbe, sid, 0, []byte("not-a-probe-payload"))
if got := SniffFrame(bogus); got != VerdictNo {
t.Fatalf("probe with wrong magic = %v, want VerdictNo", got)
}
// A lane-shaped frame whose payload is not a BLN2 hello.
bogusLane := frame(ModeLane, sid, 0, make([]byte, 12))
if got := SniffFrame(bogusLane); got != VerdictNo {
t.Fatalf("lane with wrong magic = %v, want VerdictNo", got)
}
// Unencrypted plaintext magic must also fail: the sniff decrypts with the
// session ID from the same header, so a copied magic string does not pass.
plaintext := make([]byte, HeaderSize+10)
plaintext[0] = ModeProbe
copy(plaintext[1:17], sid[:])
binary.BigEndian.PutUint32(plaintext[25:29], 10)
copy(plaintext[HeaderSize:], "BHP1")
if got := SniffFrame(plaintext); got != VerdictNo {
t.Fatalf("plaintext magic = %v, want VerdictNo", got)
}
// A declared payload larger than the protocol allows is not a frame.
oversized := make([]byte, HeaderSize)
oversized[0] = ModeUpload
binary.BigEndian.PutUint32(oversized[25:29], MaxPayload+1)
if got := SniffFrame(oversized); got != VerdictNo {
t.Fatalf("oversized payload = %v, want VerdictNo", got)
}
// A probe claiming more payload than a probe can hold is not a probe.
longProbe := make([]byte, HeaderSize)
longProbe[0] = ModeProbe
binary.BigEndian.PutUint32(longProbe[25:29], SniffLimit)
if got := SniffFrame(longProbe); got != VerdictNo {
t.Fatalf("over-long probe = %v, want VerdictNo", got)
}
}
func TestSniffAsksForMoreBytesWhenUndecided(t *testing.T) {
var sid SessionID
copy(sid[:], "sniff-partial-s1")
full := frame(ModeProbe, sid, 0, probeClear("BHP1", ModeUpload, 0))
if got := SniffFrame(nil); got != VerdictMore {
t.Fatalf("empty input = %v, want VerdictMore", got)
}
if got := SniffFrame(full[:1]); got != VerdictMore {
t.Fatalf("mode byte only = %v, want VerdictMore", got)
}
if got := SniffFrame(full[:HeaderSize-1]); got != VerdictMore {
t.Fatalf("partial header = %v, want VerdictMore", got)
}
// Header complete but the probe payload still missing.
if got := SniffFrame(full[:HeaderSize]); got != VerdictMore {
t.Fatalf("header without payload = %v, want VerdictMore", got)
}
if got := SniffFrame(full); got != VerdictYes {
t.Fatalf("complete probe = %v, want VerdictYes", got)
}
}
+369
View File
@@ -0,0 +1,369 @@
package bhttp
import (
"bytes"
"encoding/binary"
"io"
"net"
"testing"
"time"
)
func v2Request(mode byte, sid SessionID, sequence uint64, clear []byte) Request {
return Request{
Mode: mode, SID: sid, Seq: sequence,
Payload: Crypt(clear, sid, mode, sequence, false),
}
}
func TestBHTTPV2CapabilityIsExplicitAndVersioned(t *testing.T) {
var sid SessionID
copy(sid[:], "capability-v2")
clear := make([]byte, 10)
copy(clear[:4], "BHP2")
clear[4] = bhttpV2Version
request := v2Request(ModeProbe, sid, 0, clear)
var response bytes.Buffer
if err := handleProbe(&response, request); err != nil {
t.Fatal(err)
}
status, body, _, err := readTestResponse(&response)
if err != nil || status != StatusOK {
t.Fatalf("status=%d err=%v", status, err)
}
decoded := Crypt(body, sid, ModeProbe, 0, true)
if len(decoded) != 14 || string(decoded[:4]) != "BHP2" || decoded[4] != 2 {
t.Fatalf("invalid capability response %x", decoded)
}
features := binary.BigEndian.Uint32(decoded[6:10])
if features != bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck {
t.Fatalf("features=%x", features)
}
if maximum := binary.BigEndian.Uint32(decoded[10:14]); maximum != bhttpV2MaxLanes {
t.Fatalf("max lanes=%d", maximum)
}
}
func TestBHTTPV2LaneResumeAndCommittedUploadACK(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
server := NewServer(Config{DialTarget: func(string) (net.Conn, error) {
return targetServer, nil
}})
defer server.Close()
var sid SessionID
copy(sid[:], "lane-resume-v2!!")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
binary.BigEndian.PutUint32(hello[8:], 7)
request := v2Request(ModeLane, sid, 7, hello)
var first bytes.Buffer
role, firstSession, err := server.attachLane(&first, request)
if err != nil || role != laneUpload {
t.Fatalf("first attach role=%d err=%v", role, err)
}
defer firstSession.ReleaseLane()
_, firstBody, _, err := readTestResponse(&first)
if err != nil {
t.Fatal(err)
}
firstDecoded := Crypt(firstBody, sid, ModeLane, 7, true)
if firstDecoded[5] != 0 {
t.Fatal("first lane unexpectedly resumed")
}
hello[7] = 1
request = v2Request(ModeLane, sid, 8, hello)
var resumed bytes.Buffer
_, resumedSession, err := server.attachLane(&resumed, request)
if err != nil {
t.Fatal(err)
}
defer resumedSession.ReleaseLane()
_, resumedBody, _, _ := readTestResponse(&resumed)
resumedDecoded := Crypt(resumedBody, sid, ModeLane, 8, true)
if resumedDecoded[5] != 1 {
t.Fatal("replacement lane did not resume existing SID")
}
session := server.sessions.GetOrCreate(sid)
var outOfOrder bytes.Buffer
request = v2Request(ModeUpload, sid, 1, []byte("one"))
if err := server.handleRequest(&outOfOrder, session, request, true); err != nil {
t.Fatal(err)
}
_, ackBody, _, _ := readTestResponse(&outOfOrder)
if len(ackBody) != 9 || ackBody[0] != 0 {
t.Fatalf("out-of-order frame was incorrectly committed: %x", ackBody)
}
targetRead := make(chan []byte, 1)
go func() {
value := make([]byte, len("zeroone"))
_, _ = io.ReadFull(targetPeer, value)
targetRead <- value
}()
var ordered bytes.Buffer
request = v2Request(ModeUpload, sid, 0, []byte("zero"))
if err := server.handleRequest(&ordered, session, request, true); err != nil {
t.Fatal(err)
}
_, ackBody, _, _ = readTestResponse(&ordered)
if len(ackBody) != 9 || ackBody[0] != 1 || binary.BigEndian.Uint64(ackBody[1:]) != 1 {
t.Fatalf("cumulative committed ACK invalid: %x", ackBody)
}
select {
case value := <-targetRead:
if string(value) != "zeroone" {
t.Fatalf("target received %q", value)
}
case <-time.After(time.Second):
t.Fatal("ordered upload did not reach target")
}
}
func TestBHTTPV2ResumeNeverCreatesExpiredSession(t *testing.T) {
server := NewServer(Config{})
defer server.Close()
var sid SessionID
copy(sid[:], "expired-resume")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneDownload
hello[7] = 1
var response bytes.Buffer
if _, _, err := server.attachLane(&response, v2Request(ModeLane, sid, 1, hello)); err == nil {
t.Fatal("expired resume was accepted")
}
if _, exists := server.sessions.Get(sid); exists {
t.Fatal("resume rejection silently created a new session")
}
}
func TestBHTTPV2PersistentLaneCarriesMultipleRequests(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
server := NewServer(Config{DialTarget: func(string) (net.Conn, error) {
return targetServer, nil
}})
defer server.Close()
accepted, client := net.Pipe()
done := make(chan error, 1)
go func() { done <- server.handleConnection(accepted) }()
defer func() {
_ = client.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("persistent handler did not stop")
}
}()
_ = client.SetDeadline(time.Now().Add(2 * time.Second))
var sid SessionID
copy(sid[:], "persistent-v2")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
binary.BigEndian.PutUint32(hello[8:], 11)
request := v2Request(ModeLane, sid, 11, hello)
if err := writeTestRequest(client, request.Mode, request.SID, request.Seq, request.Payload, 0); err != nil {
t.Fatal(err)
}
status, _, _, err := readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("lane attach status=%d err=%v", status, err)
}
want := []byte("firstsecond")
received := make(chan []byte, 1)
go func() {
value := make([]byte, len(want))
_, _ = io.ReadFull(targetPeer, value)
received <- value
}()
for sequence, clear := range [][]byte{[]byte("first"), []byte("second")} {
request = v2Request(ModeUpload, sid, uint64(sequence), clear)
if err := writeTestRequest(client, request.Mode, request.SID, request.Seq, request.Payload, 0); err != nil {
t.Fatal(err)
}
status, body, _, readErr := readTestResponse(client)
if readErr != nil || status != StatusOK || len(body) != 9 || body[0] != 1 {
t.Fatalf("upload %d status=%d body=%x err=%v", sequence, status, body, readErr)
}
if committed := binary.BigEndian.Uint64(body[1:]); committed != uint64(sequence) {
t.Fatalf("upload %d committed=%d", sequence, committed)
}
}
select {
case got := <-received:
if !bytes.Equal(got, want) {
t.Fatalf("persistent lane target=%q", got)
}
case <-time.After(time.Second):
t.Fatal("persistent lane did not forward both requests")
}
}
func TestBHTTPV2ReplayAfterLaneReplacementDoesNotDuplicateBytes(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
server := NewServer(Config{DialTarget: func(string) (net.Conn, error) {
return targetServer, nil
}})
defer server.Close()
var sid SessionID
copy(sid[:], "replay-lane-v2")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
firstRequest := v2Request(ModeLane, sid, 1, hello)
var first bytes.Buffer
_, firstSession, err := server.attachLane(&first, firstRequest)
if err != nil {
t.Fatal(err)
}
firstSession.ReleaseLane()
want := []byte("firstsecond")
received := make(chan []byte, 1)
go func() {
value := make([]byte, len(want))
_, _ = io.ReadFull(targetPeer, value)
received <- value
}()
session := server.sessions.GetOrCreate(sid)
var response bytes.Buffer
if err := server.handleRequest(&response, session,
v2Request(ModeUpload, sid, 0, []byte("first")), true); err != nil {
t.Fatal(err)
}
hello[7] = 1
var replacement bytes.Buffer
_, replacementSession, err := server.attachLane(&replacement,
v2Request(ModeLane, sid, 2, hello))
if err != nil {
t.Fatal(err)
}
defer replacementSession.ReleaseLane()
response.Reset()
if err := server.handleRequest(&response, session,
v2Request(ModeUpload, sid, 0, []byte("first")), true); err != nil {
t.Fatal(err)
}
response.Reset()
if err := server.handleRequest(&response, session,
v2Request(ModeUpload, sid, 1, []byte("second")), true); err != nil {
t.Fatal(err)
}
select {
case got := <-received:
if !bytes.Equal(got, want) {
t.Fatalf("replayed target bytes=%q", got)
}
case <-time.After(time.Second):
t.Fatal("replacement lane did not finish upload")
}
}
func TestBHTTPV2LaneLimitIsEnforced(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
server := NewServer(Config{MaxV2Lanes: 1, DialTarget: func(string) (net.Conn, error) {
return targetServer, nil
}})
defer server.Close()
var sid SessionID
copy(sid[:], "lane-limit-v2")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
var first bytes.Buffer
_, session, err := server.attachLane(&first, v2Request(ModeLane, sid, 1, hello))
if err != nil {
t.Fatal(err)
}
defer session.ReleaseLane()
hello[5] = laneDownload
hello[7] = 1
binary.BigEndian.PutUint32(hello[8:], 2)
var rejected bytes.Buffer
if _, _, err := server.attachLane(&rejected,
v2Request(ModeLane, sid, 2, hello)); err == nil {
t.Fatal("second lane exceeded configured limit")
}
}
func TestBHTTPV2LaneReplacementKeepsSingleLogicalSlot(t *testing.T) {
session := NewSession(SessionID{})
first, ok := session.AcquireLane(7, 1)
if !ok {
t.Fatal("first logical lane was rejected")
}
replacement, ok := session.AcquireLane(7, 1)
if !ok {
t.Fatal("replacement of the same lane ID consumed another slot")
}
first.ReleaseLane()
if _, ok := session.AcquireLane(8, 1); ok {
t.Fatal("stale release removed the replacement generation")
}
replacement.ReleaseLane()
if final, ok := session.AcquireLane(8, 1); !ok {
t.Fatal("released replacement did not free its logical slot")
} else {
final.ReleaseLane()
}
}
func TestServerCloseAbortsIdlePersistentConnections(t *testing.T) {
server := NewServer(Config{})
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
serveDone := make(chan error, 1)
go func() { serveDone <- server.Serve(listener) }()
connection, err := net.Dial("tcp", listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer connection.Close()
deadline := time.Now().Add(time.Second)
for {
server.connMu.Lock()
active := len(server.active)
server.connMu.Unlock()
if active == 1 {
break
}
if time.Now().After(deadline) {
t.Fatal("server did not track idle connection")
}
time.Sleep(time.Millisecond)
}
_ = listener.Close()
server.Close()
waitDone := make(chan struct{})
go func() {
server.Wait()
close(waitDone)
}()
select {
case <-waitDone:
case <-time.After(time.Second):
t.Fatal("server shutdown waited on idle persistent connection")
}
select {
case <-serveDone:
case <-time.After(time.Second):
t.Fatal("Serve did not return after listener close")
}
}
+62
View File
@@ -0,0 +1,62 @@
package btun
import (
"context"
"io"
)
// Authenticator verifies a BTUN credential. The panel supplies its own
// implementation backed by the same account database the built-in SSH server
// uses, so a BTUN login is exactly as strong as an SSH login on this server.
//
// This package deliberately ships no PAM, /etc/shadow or password-file
// backend: BTUN accounts are panel accounts and nothing else.
type Authenticator interface {
Authenticate(username, password string) error
Name() string
}
// AllowAuthenticator accepts every credential. It exists only for the package
// tests, which exercise the wire protocol rather than the account database. It
// is never selectable from the panel configuration.
type AllowAuthenticator struct{}
func (AllowAuthenticator) Authenticate(_, _ string) error { return nil }
func (AllowAuthenticator) Name() string { return "allow-insecure" }
// Accountant lets the embedding application admit a freshly authenticated
// session and then meter its traffic. It is optional: when Config.Accountant
// is nil, sessions are admitted unconditionally and no metering happens.
type Accountant interface {
// Admit is called once per session, immediately after the credential was
// accepted. Returning an error refuses the session, which is how
// per-account connection limits are enforced. The returned Ledger is
// closed exactly once when the session ends.
//
// closer ends this session on demand, so the application can force a
// disconnect (an account being deleted, edited, or hit by a panel-wide
// restart) without waiting for the next packet to be metered.
Admit(username, remote string, closer io.Closer) (Ledger, error)
}
// Ledger meters one BTUN session. Uplink and Downlink are called before the
// corresponding packet is forwarded, so returning an error drops the session
// instead of letting it exceed its allowance. Implementations must be safe for
// concurrent use: Uplink runs on the session's reader goroutine while Downlink
// runs on the shared TUN reader goroutine.
type Ledger interface {
// Uplink accounts for n bytes travelling client -> internet. It may block
// while rate limiting and returns an error when the session must end.
Uplink(ctx context.Context, n int) error
// Downlink accounts for n bytes travelling internet -> client.
Downlink(ctx context.Context, n int) error
// Close releases whatever the ledger reserved for this session.
Close()
}
// nopLedger is used when no Accountant is configured.
type nopLedger struct{}
func (nopLedger) Uplink(context.Context, int) error { return nil }
func (nopLedger) Downlink(context.Context, int) error { return nil }
func (nopLedger) Close() {}
+73
View File
@@ -0,0 +1,73 @@
package btun
import (
"encoding/binary"
"errors"
"fmt"
"net"
"sync"
)
type AddressPool struct {
mu sync.Mutex
network uint32
first uint32
last uint32
next uint32
used map[uint32]struct{}
}
func NewAddressPool(cidr string) (*AddressPool, error) {
ip, network, err := net.ParseCIDR(cidr)
if err != nil {
return nil, fmt.Errorf("parse subnet: %w", err)
}
v4 := ip.To4()
if v4 == nil {
return nil, errors.New("BTUN subnet must be IPv4")
}
ones, bits := network.Mask.Size()
if bits != 32 || ones > 30 {
return nil, errors.New("BTUN subnet must contain at least four IPv4 addresses")
}
base := binary.BigEndian.Uint32(v4) & binary.BigEndian.Uint32(network.Mask)
size := uint64(1) << uint(32-ones)
last := uint32(uint64(base) + size - 2)
first := base + 2
if first > last {
return nil, errors.New("BTUN subnet has no client addresses")
}
return &AddressPool{network: base, first: first, last: last, next: first, used: make(map[uint32]struct{})}, nil
}
func (pool *AddressPool) Acquire() (net.IP, error) {
pool.mu.Lock()
defer pool.mu.Unlock()
capacity := uint64(pool.last) - uint64(pool.first) + 1
for checked := uint64(0); checked < capacity; checked++ {
candidate := pool.next
pool.next++
if pool.next > pool.last {
pool.next = pool.first
}
if _, exists := pool.used[candidate]; exists {
continue
}
pool.used[candidate] = struct{}{}
var raw [4]byte
binary.BigEndian.PutUint32(raw[:], candidate)
return net.IPv4(raw[0], raw[1], raw[2], raw[3]), nil
}
return nil, errors.New("BTUN address pool exhausted")
}
func (pool *AddressPool) Release(ip net.IP) {
v4 := ip.To4()
if v4 == nil {
return
}
value := binary.BigEndian.Uint32(v4)
pool.mu.Lock()
delete(pool.used, value)
pool.mu.Unlock()
}
+161
View File
@@ -0,0 +1,161 @@
package btun
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
)
const (
PacketAuth byte = 1
PacketAuthResponse byte = 2
PacketIP byte = 3
PacketData byte = 4
PacketKeepAlive byte = 5
HeaderSize = 6
DefaultMaxPacket = 64 * 1024
)
var (
ClientHello = []byte("DTUNNEL/1.1 CLIENT_HELLO\r\n")
ServerHello = []byte("DTUNNEL/1.1 SERVER_HELLO\r\n")
)
type Packet struct {
Type byte
Flags byte
Payload []byte
}
func MarshalPacket(packet Packet, maxPayload int) ([]byte, error) {
if maxPayload <= 0 {
maxPayload = DefaultMaxPacket
}
if len(packet.Payload) > maxPayload {
return nil, fmt.Errorf("packet payload too large: %d", len(packet.Payload))
}
encoded := make([]byte, HeaderSize+len(packet.Payload))
encoded[0] = packet.Type
encoded[1] = packet.Flags
binary.BigEndian.PutUint32(encoded[2:6], uint32(len(packet.Payload)))
copy(encoded[HeaderSize:], packet.Payload)
return encoded, nil
}
func ReadPacket(reader io.Reader, maxPayload int) (Packet, error) {
if maxPayload <= 0 {
maxPayload = DefaultMaxPacket
}
var header [HeaderSize]byte
if _, err := io.ReadFull(reader, header[:]); err != nil {
return Packet{}, err
}
length := int(binary.BigEndian.Uint32(header[2:6]))
if length > maxPayload {
return Packet{}, fmt.Errorf("packet payload too large: %d", length)
}
payload := make([]byte, length)
if _, err := io.ReadFull(reader, payload); err != nil {
return Packet{}, err
}
return Packet{Type: header[0], Flags: header[1], Payload: payload}, nil
}
func ParseDatagram(datagram []byte, maxPayload int) (Packet, error) {
if len(datagram) < HeaderSize {
return Packet{}, errors.New("datagram is shorter than the packet header")
}
if maxPayload <= 0 {
maxPayload = DefaultMaxPacket
}
length := int(binary.BigEndian.Uint32(datagram[2:6]))
if length > maxPayload {
return Packet{}, fmt.Errorf("packet payload too large: %d", length)
}
if len(datagram) != HeaderSize+length {
return Packet{}, fmt.Errorf("invalid datagram length: got %d, want %d", len(datagram), HeaderSize+length)
}
payload := append([]byte(nil), datagram[HeaderSize:]...)
return Packet{Type: datagram[0], Flags: datagram[1], Payload: payload}, nil
}
func ReadClientHello(reader io.Reader, maxCoverBytes int) (int, error) {
if maxCoverBytes < 0 {
maxCoverBytes = 0
}
readLimit := maxCoverBytes + len(ClientHello)
window := make([]byte, 0, len(ClientHello))
var one [1]byte
for consumed := 0; consumed < readLimit; consumed++ {
if _, err := io.ReadFull(reader, one[:]); err != nil {
return consumed, err
}
if len(window) == cap(window) {
copy(window, window[1:])
window = window[:len(window)-1]
}
window = append(window, one[0])
if bytes.Equal(window, ClientHello) {
return consumed + 1 - len(ClientHello), nil
}
}
return maxCoverBytes, errors.New("client hello not found")
}
func ParseCredential(payload []byte) (string, string, error) {
separator := bytes.IndexByte(payload, ':')
if separator <= 0 {
return "", "", errors.New("invalid credential")
}
username := string(payload[:separator])
password := string(payload[separator+1:])
if len(username) > 256 || len(password) > 4096 || bytes.IndexByte(payload, 0) >= 0 {
return "", "", errors.New("invalid credential")
}
return username, password, nil
}
func AuthResponse(accepted bool, message string) Packet {
payload := make([]byte, 1, 1+len(message))
if accepted {
payload[0] = 1
}
payload = append(payload, message...)
return Packet{Type: PacketAuthResponse, Payload: payload}
}
func ParseIPv4Packet(packet []byte) (source [4]byte, destination [4]byte, ok bool) {
source, destination, _, ok = parseIPv4Packet(packet)
return source, destination, ok
}
func parseIPv4Packet(packet []byte) (source [4]byte, destination [4]byte, totalLength int, ok bool) {
if len(packet) < 20 || packet[0]>>4 != 4 {
return source, destination, 0, false
}
headerLength := int(packet[0]&0x0f) * 4
if headerLength < 20 || headerLength > len(packet) {
return source, destination, 0, false
}
totalLength = int(binary.BigEndian.Uint16(packet[2:4]))
if totalLength < headerLength || totalLength > len(packet) {
return source, destination, 0, false
}
copy(source[:], packet[12:16])
copy(destination[:], packet[16:20])
return source, destination, totalLength, true
}
func ipKey(ip net.IP) ([4]byte, bool) {
var key [4]byte
v4 := ip.To4()
if v4 == nil {
return key, false
}
copy(key[:], v4)
return key, true
}
+68
View File
@@ -0,0 +1,68 @@
package btun
import (
"bytes"
"encoding/binary"
"net"
"testing"
)
func TestPacketRoundTrip(t *testing.T) {
want := Packet{Type: PacketData, Payload: []byte{1, 2, 3, 4}}
encoded, err := MarshalPacket(want, 1024)
if err != nil {
t.Fatal(err)
}
got, err := ReadPacket(bytes.NewReader(encoded), 1024)
if err != nil {
t.Fatal(err)
}
if got.Type != want.Type || got.Flags != want.Flags || !bytes.Equal(got.Payload, want.Payload) {
t.Fatalf("packet mismatch: %#v != %#v", got, want)
}
}
func TestReadClientHelloAfterCoverBytes(t *testing.T) {
cover := []byte("GET / HTTP/1.1\r\nHost: example.test\r\n\r\n")
stream := append(append([]byte(nil), cover...), ClientHello...)
consumed, err := ReadClientHello(bytes.NewReader(stream), len(cover))
if err != nil {
t.Fatal(err)
}
if consumed != len(cover) {
t.Fatalf("cover bytes = %d, want %d", consumed, len(cover))
}
}
func TestAddressPool(t *testing.T) {
pool, err := NewAddressPool("10.77.0.0/29")
if err != nil {
t.Fatal(err)
}
first, err := pool.Acquire()
if err != nil {
t.Fatal(err)
}
if !first.Equal(net.IPv4(10, 77, 0, 2)) {
t.Fatalf("first address = %s", first)
}
pool.Release(first)
}
func TestIPv4ParserAcceptsTransportPadding(t *testing.T) {
packet := make([]byte, 28)
packet[0] = 0x45
binary.BigEndian.PutUint16(packet[2:4], 20)
copy(packet[12:16], []byte{10, 77, 0, 2})
copy(packet[16:20], []byte{1, 1, 1, 1})
source, destination, totalLength, ok := parseIPv4Packet(packet)
if !ok {
t.Fatal("padded IPv4 packet was rejected")
}
if source != [4]byte{10, 77, 0, 2} || destination != [4]byte{1, 1, 1, 1} {
t.Fatalf("unexpected addresses: %v -> %v", source, destination)
}
if totalLength != 20 {
t.Fatalf("IPv4 length = %d, want 20", totalLength)
}
}
+798
View File
@@ -0,0 +1,798 @@
package btun
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"time"
)
type PacketDevice interface {
io.ReadWriteCloser
Name() string
}
type Config struct {
Subnet string
Authenticator Authenticator
// Accountant is an optional hook the embedding application uses to admit
// authenticated sessions and meter their traffic. Nil admits every session
// and meters nothing.
Accountant Accountant
Logger *log.Logger
HandshakeTimeout time.Duration
IdleTimeout time.Duration
MaxPacketSize int
MaxCoverBytes int
// MaxSessions caps concurrently tracked sessions across both transports.
// Zero or negative disables the cap.
MaxSessions int
// LogConnections enables one log line per session start/stop. Leave it off
// on busy servers.
LogConnections bool
}
type StatsSnapshot struct {
StartedAt time.Time `json:"startedAt"`
ActiveSessions uint64 `json:"activeSessions"`
Accepted uint64 `json:"accepted"`
AuthSucceeded uint64 `json:"authSucceeded"`
AuthRejected uint64 `json:"authRejected"`
ClientPackets uint64 `json:"clientPackets"`
InternetPackets uint64 `json:"internetPackets"`
ClientBytes uint64 `json:"clientBytes"`
InternetBytes uint64 `json:"internetBytes"`
DroppedPackets uint64 `json:"droppedPackets"`
SessionsRejected uint64 `json:"sessionsRejected"`
}
type counters struct {
activeSessions atomic.Uint64
accepted atomic.Uint64
authSucceeded atomic.Uint64
authRejected atomic.Uint64
clientPackets atomic.Uint64
internetPackets atomic.Uint64
clientBytes atomic.Uint64
internetBytes atomic.Uint64
droppedPackets atomic.Uint64
sessionsRejected atomic.Uint64
}
type Server struct {
config Config
tun PacketDevice
pool *AddressPool
started time.Time
stats counters
mu sync.RWMutex
sessions map[*session]struct{}
byIP map[[4]byte]*session
udpByAddr map[string]*session
closers []io.Closer
tunWriteMu sync.Mutex
closed chan struct{}
closeOnce sync.Once
wait sync.WaitGroup
}
type session struct {
server *Server
transport sessionTransport
udpKey string
user string
ledger Ledger
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
authenticated bool
assignedIP net.IP
lastActive time.Time
handleMu sync.Mutex
closeOnce sync.Once
invalidFrames uint64
}
type sessionTransport interface {
Send(Packet, int) (int, error)
Close() error
Remote() string
}
type tcpTransport struct {
connection net.Conn
writeMu sync.Mutex
}
func (transport *tcpTransport) Send(packet Packet, maxPayload int) (int, error) {
encoded, err := MarshalPacket(packet, maxPayload)
if err != nil {
return 0, err
}
transport.writeMu.Lock()
defer transport.writeMu.Unlock()
return len(encoded), writeFull(transport.connection, encoded)
}
func (transport *tcpTransport) Close() error { return transport.connection.Close() }
func (transport *tcpTransport) Remote() string { return transport.connection.RemoteAddr().String() }
type udpTransport struct {
connection net.PacketConn
address net.Addr
writeMu sync.Mutex
}
func (transport *udpTransport) Send(packet Packet, maxPayload int) (int, error) {
encoded, err := MarshalPacket(packet, maxPayload)
if err != nil {
return 0, err
}
transport.writeMu.Lock()
defer transport.writeMu.Unlock()
written, err := transport.connection.WriteTo(encoded, transport.address)
if err == nil && written != len(encoded) {
err = io.ErrShortWrite
}
return written, err
}
func (transport *udpTransport) Close() error { return nil }
func (transport *udpTransport) Remote() string { return transport.address.String() }
func NewServer(config Config, tun PacketDevice) (*Server, error) {
if tun == nil {
return nil, errors.New("TUN device is required")
}
if config.Authenticator == nil {
return nil, errors.New("authenticator is required")
}
if config.Subnet == "" {
config.Subnet = "10.77.0.0/16"
}
if config.Logger == nil {
config.Logger = log.Default()
}
if config.HandshakeTimeout <= 0 {
config.HandshakeTimeout = 15 * time.Second
}
if config.IdleTimeout <= 0 {
config.IdleTimeout = 2 * time.Minute
}
if config.MaxPacketSize <= 0 {
config.MaxPacketSize = DefaultMaxPacket
}
if config.MaxPacketSize > 4*1024*1024 {
return nil, errors.New("maximum packet size cannot exceed 4 MiB")
}
if config.MaxCoverBytes <= 0 {
config.MaxCoverBytes = 64 * 1024
}
pool, err := NewAddressPool(config.Subnet)
if err != nil {
return nil, err
}
server := &Server{
config: config, tun: tun, pool: pool, started: time.Now(),
sessions: make(map[*session]struct{}), byIP: make(map[[4]byte]*session),
udpByAddr: make(map[string]*session), closed: make(chan struct{}),
}
server.wait.Add(2)
go server.tunLoop()
go server.cleanupLoop()
return server, nil
}
func (server *Server) ServeTCP(listener net.Listener) error {
server.addCloser(listener)
server.config.Logger.Printf("BTUN TCP listening on %s", listener.Addr())
for {
connection, err := listener.Accept()
if err != nil {
if server.isClosed() || errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
server.stats.accepted.Add(1)
if tcp, ok := connection.(*net.TCPConn); ok {
_ = tcp.SetNoDelay(true)
_ = tcp.SetKeepAlive(true)
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
}
server.wait.Add(1)
go func() {
defer server.wait.Done()
server.runTCP(connection)
}()
}
}
// ServeConn serves one already-accepted TCP connection, for listeners this
// server does not own. A port shared with SSH or HTTP routes a client here once
// its hello has been identified; the session is then authenticated, counted and
// closed exactly like one from ServeTCP's own accept loop.
//
// It blocks until the session ends, and reports whether the server was still
// running when the connection arrived. A refused connection is closed here, and
// the caller must not keep using the connection either way.
func (server *Server) ServeConn(connection net.Conn) bool {
if server.isClosed() {
_ = connection.Close()
return false
}
server.stats.accepted.Add(1)
server.wait.Add(1)
defer server.wait.Done()
server.runTCP(connection)
return true
}
// runTCP drives one TCP connection to completion.
func (server *Server) runTCP(connection net.Conn) {
if err := server.handleTCP(connection); err != nil && !normalClose(err) {
server.config.Logger.Printf("BTUN TCP %s: %v", connection.RemoteAddr(), err)
}
}
func (server *Server) handleTCP(connection net.Conn) error {
transport := &tcpTransport{connection: connection}
current := server.newSession(transport, "")
if current == nil {
return errors.New("BTUN session limit reached")
}
defer current.close()
_ = connection.SetDeadline(time.Now().Add(server.config.HandshakeTimeout))
coverBytes, err := ReadClientHello(connection, server.config.MaxCoverBytes)
if err != nil {
return fmt.Errorf("handshake: %w", err)
}
if coverBytes > 0 {
server.config.Logger.Printf("BTUN TCP %s accepted %d cover bytes", transport.Remote(), coverBytes)
}
if err := writeFull(connection, ServerHello); err != nil {
return fmt.Errorf("write server hello: %w", err)
}
authPacket, err := ReadPacket(connection, server.config.MaxPacketSize)
if err != nil {
return fmt.Errorf("read authentication: %w", err)
}
if err := server.authenticate(current, authPacket); err != nil {
return err
}
_ = connection.SetDeadline(time.Time{})
for {
if server.config.IdleTimeout > 0 {
_ = connection.SetReadDeadline(time.Now().Add(server.config.IdleTimeout))
}
packet, err := ReadPacket(connection, server.config.MaxPacketSize)
if err != nil {
return err
}
if err := server.handleClientPacket(current, packet); err != nil {
return err
}
}
}
func (server *Server) ServeUDP(connection net.PacketConn) error {
server.addCloser(connection)
server.config.Logger.Printf("BTUN UDP listening on %s", connection.LocalAddr())
buffer := make([]byte, server.config.MaxPacketSize+HeaderSize)
for {
length, address, err := connection.ReadFrom(buffer)
if err != nil {
if server.isClosed() || errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
datagram := append([]byte(nil), buffer[:length]...)
if bytes.Equal(datagram, ClientHello) {
server.startUDPSession(connection, address)
continue
}
server.mu.RLock()
current := server.udpByAddr[address.String()]
server.mu.RUnlock()
if current == nil {
server.stats.droppedPackets.Add(1)
continue
}
packet, err := ParseDatagram(datagram, server.config.MaxPacketSize)
if err != nil {
server.stats.droppedPackets.Add(1)
continue
}
current.handleMu.Lock()
if !current.isAuthenticated() {
err = server.authenticate(current, packet)
} else {
err = server.handleClientPacket(current, packet)
}
current.handleMu.Unlock()
if err != nil {
server.config.Logger.Printf("BTUN UDP %s: %v", address, err)
current.close()
}
}
}
func (server *Server) startUDPSession(connection net.PacketConn, address net.Addr) {
server.stats.accepted.Add(1)
key := address.String()
transport := &udpTransport{connection: connection, address: address}
current := server.newSession(transport, key)
if current == nil {
return
}
server.mu.Lock()
previous := server.udpByAddr[key]
server.udpByAddr[key] = current
server.mu.Unlock()
if previous != nil && previous != current {
previous.close()
}
if _, err := connection.WriteTo(ServerHello, address); err != nil {
current.close()
return
}
server.config.Logger.Printf("BTUN UDP handshake from %s", address)
}
func (server *Server) authenticate(current *session, packet Packet) error {
if packet.Type != PacketAuth || packet.Flags != 0 {
server.stats.authRejected.Add(1)
_ = current.send(AuthResponse(false, "authentication required"))
return errors.New("authentication packet required")
}
username, password, err := ParseCredential(packet.Payload)
if err != nil {
server.stats.authRejected.Add(1)
_ = current.send(AuthResponse(false, "invalid credential"))
return err
}
if err := server.config.Authenticator.Authenticate(username, password); err != nil {
server.stats.authRejected.Add(1)
_ = current.send(AuthResponse(false, "invalid username or password"))
return errors.New("authentication rejected")
}
// Admission comes after the credential check so per-account connection
// limits and data quotas are enforced by the same code path the built-in
// SSH server uses. A refusal here is a policy decision, not a bad password,
// and is reported to the client as such.
if server.config.Accountant != nil {
ledger, err := server.config.Accountant.Admit(username, current.transport.Remote(), sessionCloser{session: current})
if err != nil {
server.stats.authRejected.Add(1)
_ = current.send(AuthResponse(false, err.Error()))
return fmt.Errorf("session refused for %s: %w", username, err)
}
if ledger == nil {
ledger = nopLedger{}
}
current.mu.Lock()
current.ledger = ledger
current.mu.Unlock()
}
current.mu.Lock()
current.authenticated = true
current.user = username
current.lastActive = time.Now()
current.mu.Unlock()
server.stats.authSucceeded.Add(1)
if err := current.send(AuthResponse(true, "authenticated")); err != nil {
return fmt.Errorf("write authentication response: %w", err)
}
if server.config.LogConnections {
server.config.Logger.Printf("BTUN %s authenticated user=%s via %s", current.transport.Remote(), username, server.config.Authenticator.Name())
}
return nil
}
func (server *Server) handleClientPacket(current *session, packet Packet) error {
current.touch()
if packet.Flags != 0 {
return errors.New("unsupported packet flags")
}
switch packet.Type {
case PacketIP:
if len(packet.Payload) != 0 {
return errors.New("invalid IP request")
}
ip, err := server.assignIP(current)
if err != nil {
return err
}
return current.send(Packet{Type: PacketIP, Payload: append([]byte(nil), ip.To4()...)})
case PacketData:
source, _, totalLength, ok := parseIPv4Packet(packet.Payload)
assigned, assignedOK := current.ipKey()
if !ok {
server.stats.droppedPackets.Add(1)
server.logDroppedFrame(current, "invalid IPv4", packet.Payload, assigned, assignedOK)
return nil
}
if !assignedOK || source != assigned {
server.stats.droppedPackets.Add(1)
server.logDroppedFrame(current, "source mismatch", packet.Payload, assigned, assignedOK)
return nil
}
payload := packet.Payload[:totalLength]
if err := current.meter(true, len(payload)); err != nil {
return err
}
server.tunWriteMu.Lock()
written, err := server.tun.Write(payload)
server.tunWriteMu.Unlock()
if err != nil {
return fmt.Errorf("write TUN: %w", err)
}
if written != len(payload) {
return io.ErrShortWrite
}
server.stats.clientPackets.Add(1)
server.stats.clientBytes.Add(uint64(written))
return nil
case PacketKeepAlive:
if len(packet.Payload) != 0 {
return errors.New("invalid keep-alive packet")
}
return nil
default:
return fmt.Errorf("unknown packet type %d", packet.Type)
}
}
func (server *Server) logDroppedFrame(current *session, reason string, payload []byte,
assigned [4]byte, assignedOK bool) {
current.mu.Lock()
current.invalidFrames++
count := current.invalidFrames
current.mu.Unlock()
if count > 3 {
return
}
version := byte(0)
declared := 0
if len(payload) > 0 {
version = payload[0] >> 4
}
if len(payload) >= 4 {
declared = int(binary.BigEndian.Uint16(payload[2:4]))
}
source := "n/a"
if len(payload) >= 16 {
source = net.IP(payload[12:16]).String()
}
assignedText := "none"
if assignedOK {
assignedText = net.IP(assigned[:]).String()
}
server.config.Logger.Printf(
"BTUN %s dropped data frame (%s): frameLen=%d ipVersion=%d ipLen=%d source=%s assigned=%s",
current.transport.Remote(), reason, len(payload), version, declared, source, assignedText)
}
func (server *Server) assignIP(current *session) (net.IP, error) {
current.mu.Lock()
if current.assignedIP != nil {
ip := append(net.IP(nil), current.assignedIP...)
current.mu.Unlock()
return ip, nil
}
current.mu.Unlock()
ip, err := server.pool.Acquire()
if err != nil {
return nil, err
}
key, _ := ipKey(ip)
server.mu.Lock()
if existing := server.byIP[key]; existing != nil && existing != current {
server.mu.Unlock()
server.pool.Release(ip)
return nil, errors.New("address collision")
}
current.mu.Lock()
if current.assignedIP == nil {
current.assignedIP = append(net.IP(nil), ip.To4()...)
server.byIP[key] = current
} else {
server.pool.Release(ip)
ip = append(net.IP(nil), current.assignedIP...)
}
current.mu.Unlock()
server.mu.Unlock()
server.config.Logger.Printf("BTUN %s assigned %s", current.transport.Remote(), ip)
return ip, nil
}
func (server *Server) tunLoop() {
defer server.wait.Done()
buffer := make([]byte, server.config.MaxPacketSize)
for {
length, err := server.tun.Read(buffer)
if err != nil {
if !server.isClosed() && !errors.Is(err, net.ErrClosed) && !errors.Is(err, io.EOF) {
server.config.Logger.Printf("BTUN TUN read stopped: %v", err)
}
return
}
packet := append([]byte(nil), buffer[:length]...)
_, destination, ok := ParseIPv4Packet(packet)
if !ok {
server.stats.droppedPackets.Add(1)
continue
}
server.mu.RLock()
current := server.byIP[destination]
server.mu.RUnlock()
if current == nil {
server.stats.droppedPackets.Add(1)
continue
}
if err := current.meter(false, length); err != nil {
current.close()
continue
}
if err := current.send(Packet{Type: PacketData, Payload: packet}); err != nil {
current.close()
continue
}
server.stats.internetPackets.Add(1)
server.stats.internetBytes.Add(uint64(length))
}
}
func (server *Server) cleanupLoop() {
defer server.wait.Done()
interval := server.config.IdleTimeout / 2
if interval < time.Second {
interval = time.Second
}
if interval > 30*time.Second {
interval = 30 * time.Second
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case now := <-ticker.C:
server.mu.RLock()
candidates := make([]*session, 0, len(server.sessions))
for current := range server.sessions {
candidates = append(candidates, current)
}
server.mu.RUnlock()
for _, current := range candidates {
if now.Sub(current.lastSeen()) > server.config.IdleTimeout {
current.close()
}
}
case <-server.closed:
return
}
}
}
func (server *Server) newSession(transport sessionTransport, udpKey string) *session {
ctx, cancel := context.WithCancel(context.Background())
current := &session{
server: server, transport: transport, udpKey: udpKey,
lastActive: time.Now(), ledger: nopLedger{}, ctx: ctx, cancel: cancel,
}
server.mu.Lock()
if maximum := server.config.MaxSessions; maximum > 0 && len(server.sessions) >= maximum {
server.mu.Unlock()
cancel()
server.stats.sessionsRejected.Add(1)
rejected := server.stats.sessionsRejected.Load()
if rejected == 1 || rejected%1000 == 0 {
server.config.Logger.Printf("BTUN session cap reached (%d); rejected %d session(s) so far",
maximum, rejected)
}
_ = transport.Close()
return nil
}
server.sessions[current] = struct{}{}
server.mu.Unlock()
server.stats.activeSessions.Add(1)
return current
}
func (current *session) send(packet Packet) error {
written, err := current.transport.Send(packet, current.server.config.MaxPacketSize)
if err == nil {
current.touch()
_ = written
}
return err
}
func (current *session) touch() {
current.mu.Lock()
current.lastActive = time.Now()
current.mu.Unlock()
}
func (current *session) lastSeen() time.Time {
current.mu.Lock()
defer current.mu.Unlock()
return current.lastActive
}
func (current *session) isAuthenticated() bool {
current.mu.Lock()
defer current.mu.Unlock()
return current.authenticated
}
func (current *session) ipKey() ([4]byte, bool) {
current.mu.Lock()
defer current.mu.Unlock()
return ipKey(current.assignedIP)
}
func (current *session) close() {
current.closeOnce.Do(func() {
if current.cancel != nil {
current.cancel()
}
// The ledger is installed by authenticate under this lock, so it has to
// be read under it too.
current.mu.Lock()
ledger := current.ledger
current.ledger = nil
current.mu.Unlock()
if ledger != nil {
ledger.Close()
}
_ = current.transport.Close()
server := current.server
server.mu.Lock()
delete(server.sessions, current)
if current.udpKey != "" && server.udpByAddr[current.udpKey] == current {
delete(server.udpByAddr, current.udpKey)
}
current.mu.Lock()
assigned := append(net.IP(nil), current.assignedIP...)
current.assignedIP = nil
current.mu.Unlock()
if key, ok := ipKey(assigned); ok && server.byIP[key] == current {
delete(server.byIP, key)
}
server.mu.Unlock()
if assigned != nil {
server.pool.Release(assigned)
}
server.stats.activeSessions.Add(^uint64(0))
if server.config.LogConnections {
server.config.Logger.Printf("BTUN session end: remote=%s user=%s", current.transport.Remote(), current.username())
}
})
}
// sessionCloser lets an Accountant end a session it previously admitted.
type sessionCloser struct{ session *session }
func (c sessionCloser) Close() error {
c.session.close()
return nil
}
// meter runs the session's ledger for n forwarded bytes. Uplink is
// client -> internet; downlink is internet -> client. An error means the
// account ran out of allowance (or was closed) and the session must end.
func (current *session) meter(uplink bool, n int) error {
if n <= 0 {
return nil
}
current.mu.Lock()
ledger := current.ledger
current.mu.Unlock()
if ledger == nil {
return nil
}
if uplink {
return ledger.Uplink(current.ctx, n)
}
return ledger.Downlink(current.ctx, n)
}
func (current *session) username() string {
current.mu.Lock()
defer current.mu.Unlock()
return current.user
}
func (server *Server) addCloser(closer io.Closer) {
server.mu.Lock()
server.closers = append(server.closers, closer)
server.mu.Unlock()
}
func (server *Server) isClosed() bool {
select {
case <-server.closed:
return true
default:
return false
}
}
func (server *Server) Close() error {
var closeError error
server.closeOnce.Do(func() {
close(server.closed)
server.mu.RLock()
closers := append([]io.Closer(nil), server.closers...)
sessions := make([]*session, 0, len(server.sessions))
for current := range server.sessions {
sessions = append(sessions, current)
}
server.mu.RUnlock()
for _, closer := range closers {
if err := closer.Close(); err != nil && closeError == nil && !errors.Is(err, net.ErrClosed) {
closeError = err
}
}
for _, current := range sessions {
current.close()
}
if err := server.tun.Close(); err != nil && closeError == nil && !errors.Is(err, os.ErrClosed) {
closeError = err
}
})
return closeError
}
func (server *Server) Wait() { server.wait.Wait() }
func (server *Server) Stats() StatsSnapshot {
return StatsSnapshot{
StartedAt: server.started, ActiveSessions: server.stats.activeSessions.Load(),
Accepted: server.stats.accepted.Load(), AuthSucceeded: server.stats.authSucceeded.Load(),
AuthRejected: server.stats.authRejected.Load(), ClientPackets: server.stats.clientPackets.Load(),
InternetPackets: server.stats.internetPackets.Load(), ClientBytes: server.stats.clientBytes.Load(),
InternetBytes: server.stats.internetBytes.Load(), DroppedPackets: server.stats.droppedPackets.Load(),
SessionsRejected: server.stats.sessionsRejected.Load(),
}
}
func writeFull(writer io.Writer, data []byte) error {
for len(data) > 0 {
written, err := writer.Write(data)
if err != nil {
return err
}
if written == 0 {
return io.ErrShortWrite
}
data = data[written:]
}
return nil
}
func normalClose(err error) bool {
if err == nil || errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) {
return true
}
var networkError net.Error
if errors.As(err, &networkError) && networkError.Timeout() {
return true
}
message := strings.ToLower(err.Error())
return strings.Contains(message, "connection reset") || strings.Contains(message, "broken pipe")
}
+253
View File
@@ -0,0 +1,253 @@
package btun
import (
"bytes"
"encoding/binary"
"io"
"log"
"net"
"sync"
"testing"
"time"
)
type fakeTUN struct {
reads chan []byte
writes chan []byte
closed chan struct{}
once sync.Once
}
func newFakeTUN() *fakeTUN {
return &fakeTUN{reads: make(chan []byte, 4), writes: make(chan []byte, 4), closed: make(chan struct{})}
}
func (tun *fakeTUN) Name() string { return "test0" }
func (tun *fakeTUN) Read(buffer []byte) (int, error) {
select {
case packet := <-tun.reads:
return copy(buffer, packet), nil
case <-tun.closed:
return 0, io.EOF
}
}
func (tun *fakeTUN) Write(packet []byte) (int, error) {
copyOfPacket := append([]byte(nil), packet...)
select {
case tun.writes <- copyOfPacket:
return len(packet), nil
case <-tun.closed:
return 0, io.ErrClosedPipe
}
}
func (tun *fakeTUN) Close() error {
tun.once.Do(func() { close(tun.closed) })
return nil
}
func TestTCPAuthenticationAndPacketRouting(t *testing.T) {
tun := newFakeTUN()
server, err := NewServer(Config{
Subnet: "10.77.0.0/29", Authenticator: AllowAuthenticator{},
Logger: log.New(io.Discard, "", 0), HandshakeTimeout: time.Second,
IdleTimeout: time.Minute,
}, tun)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = server.Close()
server.Wait()
})
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
serveDone := make(chan error, 1)
go func() { serveDone <- server.ServeTCP(listener) }()
connection, err := net.DialTimeout("tcp", listener.Addr().String(), time.Second)
if err != nil {
t.Fatal(err)
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(2 * time.Second))
if _, err := connection.Write(append([]byte("cover request\r\n"), ClientHello...)); err != nil {
t.Fatal(err)
}
hello := make([]byte, len(ServerHello))
if _, err := io.ReadFull(connection, hello); err != nil {
t.Fatal(err)
}
if !bytes.Equal(hello, ServerHello) {
t.Fatalf("server hello = %q", hello)
}
writeTestPacket(t, connection, Packet{Type: PacketAuth, Payload: []byte("user:password")})
auth := readTestPacket(t, connection)
if auth.Type != PacketAuthResponse || len(auth.Payload) == 0 || auth.Payload[0] != 1 {
t.Fatalf("unexpected auth response: %#v", auth)
}
writeTestPacket(t, connection, Packet{Type: PacketIP})
ipResponse := readTestPacket(t, connection)
if ipResponse.Type != PacketIP || len(ipResponse.Payload) != 4 {
t.Fatalf("unexpected IP response: %#v", ipResponse)
}
assigned := net.IP(ipResponse.Payload)
// DT5 may emit a non-IPv4 frame while its TUN is coming up. The server
// must drop it without destroying the authenticated stream.
writeTestPacket(t, connection, Packet{Type: PacketData, Payload: []byte{0x60, 0, 0, 0}})
outbound := ipv4Packet(assigned, net.IPv4(1, 1, 1, 1), []byte("out"))
writeTestPacket(t, connection, Packet{Type: PacketData, Payload: outbound})
select {
case got := <-tun.writes:
if !bytes.Equal(got, outbound) {
t.Fatal("outbound TUN packet mismatch")
}
case <-time.After(time.Second):
t.Fatal("outbound packet did not reach TUN")
}
inbound := ipv4Packet(net.IPv4(1, 1, 1, 1), assigned, []byte("in"))
tun.reads <- inbound
data := readTestPacket(t, connection)
if data.Type != PacketData || !bytes.Equal(data.Payload, inbound) {
t.Fatalf("unexpected inbound packet: %#v", data)
}
_ = server.Close()
server.Wait()
if err := <-serveDone; err != nil {
t.Fatal(err)
}
}
func TestUDPAuthenticationAndPacketRouting(t *testing.T) {
tun := newFakeTUN()
server, err := NewServer(Config{
Subnet: "10.77.1.0/29", Authenticator: AllowAuthenticator{},
Logger: log.New(io.Discard, "", 0), IdleTimeout: time.Minute,
}, tun)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = server.Close()
server.Wait()
})
packetConnection, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
serveDone := make(chan error, 1)
go func() { serveDone <- server.ServeUDP(packetConnection) }()
connection, err := net.Dial("udp", packetConnection.LocalAddr().String())
if err != nil {
t.Fatal(err)
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(2 * time.Second))
if _, err := connection.Write(ClientHello); err != nil {
t.Fatal(err)
}
hello := make([]byte, len(ServerHello))
if _, err := io.ReadFull(connection, hello); err != nil {
t.Fatal(err)
}
if !bytes.Equal(hello, ServerHello) {
t.Fatalf("server hello = %q", hello)
}
writeUDPTestPacket(t, connection, Packet{Type: PacketAuth, Payload: []byte("user:password")})
auth := readUDPTestPacket(t, connection)
if auth.Type != PacketAuthResponse || len(auth.Payload) == 0 || auth.Payload[0] != 1 {
t.Fatalf("unexpected auth response: %#v", auth)
}
writeUDPTestPacket(t, connection, Packet{Type: PacketIP})
ipResponse := readUDPTestPacket(t, connection)
if ipResponse.Type != PacketIP || len(ipResponse.Payload) != 4 {
t.Fatalf("unexpected IP response: %#v", ipResponse)
}
assigned := net.IP(ipResponse.Payload)
outbound := ipv4Packet(assigned, net.IPv4(8, 8, 8, 8), []byte("udp-out"))
writeUDPTestPacket(t, connection, Packet{Type: PacketData, Payload: outbound})
select {
case got := <-tun.writes:
if !bytes.Equal(got, outbound) {
t.Fatal("outbound UDP TUN packet mismatch")
}
case <-time.After(time.Second):
t.Fatal("outbound UDP packet did not reach TUN")
}
inbound := ipv4Packet(net.IPv4(8, 8, 8, 8), assigned, []byte("udp-in"))
tun.reads <- inbound
data := readUDPTestPacket(t, connection)
if data.Type != PacketData || !bytes.Equal(data.Payload, inbound) {
t.Fatalf("unexpected inbound UDP packet: %#v", data)
}
_ = server.Close()
server.Wait()
if err := <-serveDone; err != nil {
t.Fatal(err)
}
}
func writeTestPacket(t *testing.T, writer io.Writer, packet Packet) {
t.Helper()
encoded, err := MarshalPacket(packet, DefaultMaxPacket)
if err != nil {
t.Fatal(err)
}
if err := writeFull(writer, encoded); err != nil {
t.Fatal(err)
}
}
func readTestPacket(t *testing.T, reader io.Reader) Packet {
t.Helper()
packet, err := ReadPacket(reader, DefaultMaxPacket)
if err != nil {
t.Fatal(err)
}
return packet
}
func writeUDPTestPacket(t *testing.T, writer io.Writer, packet Packet) {
t.Helper()
encoded, err := MarshalPacket(packet, DefaultMaxPacket)
if err != nil {
t.Fatal(err)
}
written, err := writer.Write(encoded)
if err != nil {
t.Fatal(err)
}
if written != len(encoded) {
t.Fatal(io.ErrShortWrite)
}
}
func readUDPTestPacket(t *testing.T, reader io.Reader) Packet {
t.Helper()
buffer := make([]byte, DefaultMaxPacket+HeaderSize)
length, err := reader.Read(buffer)
if err != nil {
t.Fatal(err)
}
packet, err := ParseDatagram(buffer[:length], DefaultMaxPacket)
if err != nil {
t.Fatal(err)
}
return packet
}
func ipv4Packet(source, destination net.IP, payload []byte) []byte {
packet := make([]byte, 20+len(payload))
packet[0] = 0x45
binary.BigEndian.PutUint16(packet[2:4], uint16(len(packet)))
packet[8] = 64
packet[9] = 17
copy(packet[12:16], source.To4())
copy(packet[16:20], destination.To4())
copy(packet[20:], payload)
return packet
}
+47
View File
@@ -0,0 +1,47 @@
package btun
import "bytes"
// Verdict is the result of inspecting the first bytes of a connection.
type Verdict int
const (
// VerdictNo means the bytes cannot begin a BTUN handshake.
VerdictNo Verdict = iota
// VerdictMore means the bytes so far are consistent with one but more are
// needed to decide. The caller should peek further and ask again.
VerdictMore
// VerdictYes means the bytes begin a BTUN handshake.
VerdictYes
)
// SniffLimit is the largest number of bytes SniffClientHello ever needs.
var SniffLimit = len(ClientHello)
// SniffClientHello reports whether data begins with the BTUN client hello, so
// a listener shared with other protocols can route the connection without
// consuming anything.
//
// The hello is a fixed 25-byte ASCII marker, which makes this decisive in a
// way a length or range check never is: no SSH identification and no HTTP
// request line can match it, and the very first byte already rejects both in
// the overwhelming majority of cases.
//
// The match is anchored at offset zero. A TCP client may legitimately prepend
// cover bytes before its hello, and ServeTCP still tolerates that on a
// dedicated BTUN port, but a shared port cannot buffer an unbounded prefix
// while some other protocol waits to be recognised. Cover that is itself an
// HTTP request is still handled: the panel's HTTP cleanup consumes it, which
// leaves the hello at offset zero for a second look.
func SniffClientHello(data []byte) Verdict {
if len(data) >= len(ClientHello) {
if bytes.Equal(data[:len(ClientHello)], ClientHello) {
return VerdictYes
}
return VerdictNo
}
if bytes.Equal(data, ClientHello[:len(data)]) {
return VerdictMore
}
return VerdictNo
}
+46
View File
@@ -0,0 +1,46 @@
package btun
import "testing"
// Everything BTUN shares a port with has to be rejected, and the marker itself
// has to be accepted, or sharing the port would break SSH and HTTP clients.
func TestSniffClientHello(t *testing.T) {
tests := []struct {
name string
input string
want Verdict
}{
{name: "exact marker", input: string(ClientHello), want: VerdictYes},
{name: "marker then payload", input: string(ClientHello) + "\x01\x02", want: VerdictYes},
{name: "partial marker", input: "DTUNNEL/1.1 CLI", want: VerdictMore},
{name: "first byte only", input: "D", want: VerdictMore},
{name: "empty", input: "", want: VerdictMore},
{name: "SSH identification", input: "SSH-2.0-OpenSSH_9.6\r\n", want: VerdictNo},
{name: "HTTP GET", input: "GET / HTTP/1.1\r\n\r\n", want: VerdictNo},
{name: "HTTP DELETE shares a first byte", input: "DELETE / HTTP/1.1\r\n\r\n", want: VerdictNo},
{name: "TLS client hello", input: "\x16\x03\x01\x02\x00", want: VerdictNo},
{name: "BHTTP frame", input: "\x00\x01\x02\x03", want: VerdictNo},
{name: "wrong version", input: "DTUNNEL/2.0 CLIENT_HELLO\r\n", want: VerdictNo},
{name: "marker not at offset zero", input: "xxDTUNNEL/1.1 CLIENT_HELLO\r\n", want: VerdictNo},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SniffClientHello([]byte(tt.input)); got != tt.want {
t.Fatalf("SniffClientHello(%q) = %v, want %v", tt.input, got, tt.want)
}
})
}
}
// A partial marker must never be mistaken for a complete one, however it is
// split across reads.
func TestSniffClientHelloIsProgressive(t *testing.T) {
for cut := 0; cut < len(ClientHello); cut++ {
if got := SniffClientHello(ClientHello[:cut]); got != VerdictMore {
t.Fatalf("SniffClientHello(first %d bytes) = %v, want VerdictMore", cut, got)
}
}
if got := SniffClientHello(ClientHello); got != VerdictYes {
t.Fatalf("SniffClientHello(full marker) = %v, want VerdictYes", got)
}
}
+164
View File
@@ -0,0 +1,164 @@
//go:build linux
package btun
import (
"bytes"
"fmt"
"io"
"os"
"sync"
"syscall"
"time"
"unsafe"
)
const (
tunSetIFF = 0x400454ca
iffTUN = 0x0001
iffNoPI = 0x1000
)
type linuxTUN struct {
file *os.File
fd int
name string
closed chan struct{}
readerDone chan struct{}
packets chan []byte
readErrors chan error
fdMu sync.RWMutex
closeOnce sync.Once
closeErr error
}
func OpenTUN(requestedName string) (PacketDevice, error) {
if len(requestedName) == 0 || len(requestedName) >= 16 {
return nil, fmt.Errorf("invalid TUN interface name %q", requestedName)
}
file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
if err != nil {
return nil, fmt.Errorf("open /dev/net/tun: %w", err)
}
var request [40]byte
copy(request[:16], requestedName)
*(*uint16)(unsafe.Pointer(&request[16])) = iffTUN | iffNoPI
fd := int(file.Fd())
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), tunSetIFF, uintptr(unsafe.Pointer(&request[0])))
if errno != 0 {
file.Close()
return nil, fmt.Errorf("TUNSETIFF %s: %w", requestedName, errno)
}
if err := syscall.SetNonblock(fd, true); err != nil {
file.Close()
return nil, fmt.Errorf("set TUN nonblocking: %w", err)
}
nameLength := bytes.IndexByte(request[:16], 0)
if nameLength < 0 {
nameLength = 16
}
actual := string(request[:nameLength])
tun := &linuxTUN{
file: file, fd: fd, name: actual, closed: make(chan struct{}),
readerDone: make(chan struct{}), packets: make(chan []byte, 64),
readErrors: make(chan error, 1),
}
go tun.readLoop()
return tun, nil
}
func (tun *linuxTUN) Read(buffer []byte) (int, error) {
select {
case packet := <-tun.packets:
if len(packet) > len(buffer) {
return 0, io.ErrShortBuffer
}
return copy(buffer, packet), nil
case err := <-tun.readErrors:
return 0, err
case <-tun.closed:
return 0, os.ErrClosed
}
}
func (tun *linuxTUN) readLoop() {
defer close(tun.readerDone)
buffer := make([]byte, DefaultMaxPacket)
for {
select {
case <-tun.closed:
return
default:
}
tun.fdMu.RLock()
length, err := syscall.Read(tun.fd, buffer)
tun.fdMu.RUnlock()
if err == nil && length > 0 {
packet := append([]byte(nil), buffer[:length]...)
select {
case tun.packets <- packet:
case <-tun.closed:
return
}
continue
}
if err == nil {
continue
}
if err == syscall.EINTR {
continue
}
if err != syscall.EAGAIN && err != syscall.EWOULDBLOCK {
select {
case tun.readErrors <- err:
case <-tun.closed:
}
return
}
select {
case <-tun.closed:
return
case <-time.After(25 * time.Millisecond):
}
}
}
func (tun *linuxTUN) Write(buffer []byte) (int, error) {
for {
select {
case <-tun.closed:
return 0, os.ErrClosed
default:
}
tun.fdMu.RLock()
length, err := syscall.Write(tun.fd, buffer)
tun.fdMu.RUnlock()
if err == nil {
return length, nil
}
if err == syscall.EINTR {
continue
}
if err != syscall.EAGAIN && err != syscall.EWOULDBLOCK {
return 0, err
}
select {
case <-tun.closed:
return 0, os.ErrClosed
case <-time.After(25 * time.Millisecond):
}
}
}
func (tun *linuxTUN) Close() error {
tun.closeOnce.Do(func() {
close(tun.closed)
<-tun.readerDone
tun.fdMu.Lock()
tun.closeErr = tun.file.Close()
tun.fdMu.Unlock()
})
return tun.closeErr
}
func (tun *linuxTUN) Name() string { return tun.name }
+9
View File
@@ -0,0 +1,9 @@
//go:build !linux
package btun
import "errors"
func OpenTUN(_ string) (PacketDevice, error) {
return nil, errors.New("BTUN TUN is only supported on Linux")
}
File diff suppressed because it is too large Load Diff
+84
View File
@@ -0,0 +1,84 @@
package hcr
import "encoding/binary"
// Verdict is the result of inspecting the first bytes of a connection.
type Verdict int
const (
// VerdictNo means the bytes cannot begin an HCR request.
VerdictNo Verdict = iota
// VerdictMore means the bytes so far are consistent with HCR but more are
// needed to decide. The caller should peek further and ask again.
VerdictMore
// VerdictYes means the bytes begin a valid HCR request header.
VerdictYes
)
// SniffLimit is the largest number of bytes SniffFrame ever needs: the full
// fixed request header.
const SniffLimit = RequestHeaderSize
// IsHeader reports whether buf is a complete, valid 62-byte HCR request header.
// This is the strict check the coexistence design relies on: only a full header
// with the fixed protocol version and an in-range payload length counts.
func IsHeader(buf []byte) bool {
if len(buf) < RequestHeaderSize {
return false
}
code := buf[0]
if code < 1 || code > 6 {
return false
}
if buf[1] != ProtoVersion {
return false
}
if binary.BigEndian.Uint32(buf[58:62]) > MaxPayloadLimit {
return false
}
return true
}
// SniffFrame reports whether data begins an HCR request, so a port shared with
// BHTTP (and SSH, HTTP injection) can route the connection without consuming
// anything.
//
// HCR and BHTTP deliberately overlap on the first byte (opcodes 1..4 mean
// upload/download/… in both). The discriminator is HCR's fixed protocol version
// at byte [1] (always 0x01) and its 62-byte header layout, checked in full:
//
// - byte 0 must be an HCR opcode (1..6); anything else (including BHTTP's
// probe 0x00) is not HCR.
// - byte 1 must be 0x01. A BHTTP frame's byte [1] is the first byte of its
// random session UUID, so it is 0x01 only by chance — and that is the only
// case where HCR waits for the full 62 bytes. A "clean" BHTTP frame is
// rejected here at two bytes, with no stall, and falls through to BHTTP.
// - the full 62-byte header must pass IsHeader. A BHTTP frame whose UUID
// happens to start 0x01 almost never has a valid HCR payload length at
// [58:62], so it is rejected and BHTTP still handles it.
//
// The caller must try HCR before BHTTP, exactly because a real HCR Connect
// (opcode 1) also looks like a BHTTP upload on the first byte.
func SniffFrame(data []byte) Verdict {
if len(data) == 0 {
return VerdictMore
}
if data[0] < 1 || data[0] > 6 {
return VerdictNo
}
if len(data) < 2 {
return VerdictMore
}
if data[1] != ProtoVersion {
// Not HCR: a BHTTP frame or junk. Reject now so BHTTP gets its fast
// 29-byte path with no wait for 62 bytes.
return VerdictNo
}
if len(data) < RequestHeaderSize {
return VerdictMore
}
if IsHeader(data[:RequestHeaderSize]) {
return VerdictYes
}
return VerdictNo
}
+83
View File
@@ -0,0 +1,83 @@
package hcr
import (
"encoding/binary"
"testing"
)
// hcrHeader builds a valid 62-byte request header.
func hcrHeader(code, version byte, payloadLen uint32) []byte {
b := make([]byte, RequestHeaderSize)
b[0] = code
b[1] = version
b[2] = 0xAB // session id byte
binary.BigEndian.PutUint32(b[58:62], payloadLen)
return b
}
func TestSniffRejectsOtherProtocols(t *testing.T) {
cases := map[string]string{
"SSH": "SSH-2.0-x\r\n",
"HTTP GET": "GET / HTTP/1.1\r\n",
"BTUN": "DTUNNEL/1.1 CLIENT_HELLO\r\n",
"BHTTP probe": "\x00\x11\x22\x33",
"TLS hello": "\x16\x03\x01\x00",
}
for name, in := range cases {
if got := SniffFrame([]byte(in)); got != VerdictNo {
t.Fatalf("%s: SniffFrame = %v, want VerdictNo", name, got)
}
}
}
func TestSniffAcceptsValidHeaders(t *testing.T) {
for code := byte(1); code <= 6; code++ {
if got := SniffFrame(hcrHeader(code, ProtoVersion, 100)); got != VerdictYes {
t.Fatalf("code %d: SniffFrame = %v, want VerdictYes", code, got)
}
}
}
// A BHTTP frame whose session UUID happens to start 0x01 must NOT be stolen:
// its bytes at [58:62] are not a valid HCR payload length.
func TestSniffRejectsBhttpLookalike(t *testing.T) {
b := make([]byte, RequestHeaderSize)
b[0] = 0x01 // BHTTP upload / HCR connect
b[1] = 0x01 // UUID happens to start 0x01
binary.BigEndian.PutUint32(b[58:62], MaxPayloadLimit+1) // invalid HCR len
if got := SniffFrame(b); got != VerdictNo {
t.Fatalf("lookalike: SniffFrame = %v, want VerdictNo", got)
}
}
// A clean BHTTP frame (byte1 != 0x01) is rejected at two bytes — no 62-byte wait.
func TestSniffFastRejectsCleanBhttp(t *testing.T) {
if got := SniffFrame([]byte{0x01, 0x7A}); got != VerdictNo {
t.Fatalf("clean BHTTP: SniffFrame(2B) = %v, want VerdictNo", got)
}
}
func TestSniffProgressive(t *testing.T) {
full := hcrHeader(1, ProtoVersion, 10)
if got := SniffFrame(nil); got != VerdictMore {
t.Fatalf("empty = %v, want More", got)
}
if got := SniffFrame(full[:1]); got != VerdictMore {
t.Fatalf("1 byte = %v, want More", got)
}
if got := SniffFrame(full[:2]); got != VerdictMore {
t.Fatalf("2 bytes (ver=1) = %v, want More", got)
}
if got := SniffFrame(full[:RequestHeaderSize-1]); got != VerdictMore {
t.Fatalf("61 bytes = %v, want More", got)
}
if got := SniffFrame(full); got != VerdictYes {
t.Fatalf("full = %v, want Yes", got)
}
}
func TestSniffRejectsWrongVersion(t *testing.T) {
if got := SniffFrame(hcrHeader(1, 0x02, 10)); got != VerdictNo {
t.Fatalf("version 2 = %v, want No", got)
}
}
+37
View File
@@ -0,0 +1,37 @@
// This package is a local fork of www.bamsoftware.com/git/dnstt.git/turbotunnel
// (upstream v1.20241021.0). The only behavioural change from upstream is that
// RemoteMap's background expiry goroutine is now stoppable via Close(), wired
// through QueuePacketConn.Close(); see remotemap.go and queuepacketconn.go.
// Upstream leaks that goroutine for the process lifetime, which is harmless for
// the upstream one-shot server but leaks one goroutine per DNSTT restart in this
// integration (hot-reload / auto-restart). clientid.go and consts.go are copied
// verbatim.
package turbotunnel
import (
"crypto/rand"
"encoding/hex"
)
// ClientID is an abstract identifier that binds together all the communications
// belonging to a single client session, even though those communications may
// arrive from multiple IP addresses or over multiple lower-level connections.
// It plays the same role that an (IP address, port number) tuple plays in a
// net.UDPConn: it's the return address pertaining to a long-lived abstract
// client session. The client attaches its ClientID to each of its
// communications, enabling the server to disambiguate requests among its many
// clients. ClientID implements the net.Addr interface.
type ClientID [8]byte
func NewClientID() ClientID {
var id ClientID
_, err := rand.Read(id[:])
if err != nil {
panic(err)
}
return id
}
func (id ClientID) Network() string { return "clientid" }
func (id ClientID) String() string { return hex.EncodeToString(id[:]) }
+22
View File
@@ -0,0 +1,22 @@
// Package turbotunnel is facilities for embedding packet-based reliability
// protocols inside other protocols.
//
// https://github.com/net4people/bbs/issues/9
package turbotunnel
import "errors"
// QueueSize is the size of send and receive queues in QueuePacketConn and
// RemoteMap.
const QueueSize = 128
var errClosedPacketConn = errors.New("operation on closed connection")
var errNotImplemented = errors.New("not implemented")
// DummyAddr is a placeholder net.Addr, for when a programming interface
// requires a net.Addr but there is none relevant. All DummyAddrs compare equal
// to each other.
type DummyAddr struct{}
func (addr DummyAddr) Network() string { return "dummy" }
func (addr DummyAddr) String() string { return "dummy" }
+165
View File
@@ -0,0 +1,165 @@
package turbotunnel
import (
"net"
"sync"
"sync/atomic"
"time"
)
// taggedPacket is a combination of a []byte and a net.Addr, encapsulating the
// return type of PacketConn.ReadFrom.
type taggedPacket struct {
P []byte
Addr net.Addr
}
// QueuePacketConn implements net.PacketConn by storing queues of packets. There
// is one incoming queue (where packets are additionally tagged by the source
// address of the peer that sent them). There are many outgoing queues, one for
// each remote peer address that has been recently seen. The QueueIncoming
// method inserts a packet into the incoming queue, to eventually be returned by
// ReadFrom. WriteTo inserts a packet into an address-specific outgoing queue,
// which can later by accessed through the OutgoingQueue method.
//
// Besides the outgoing queues, there is also a one-element "stash" for each
// remote peer address. You can stash a packet using the Stash method, and get
// it back later by receiving from the channel returned by Unstash. The stash is
// meant as a convenient place to temporarily store a single packet, such as
// when you've read one too many packets from the send queue and need to store
// the extra packet to be processed first in the next pass. It's the caller's
// responsibility to Unstash what they have Stashed. Calling Stash does not put
// the packet at the head of the send queue; if there is the possibility that a
// packet has been stashed, it must be checked for by calling Unstash in
// addition to OutgoingQueue.
type QueuePacketConn struct {
remotes *RemoteMap
localAddr net.Addr
recvQueue chan taggedPacket
closeOnce sync.Once
closed chan struct{}
// What error to return when the QueuePacketConn is closed.
err atomic.Value
}
// NewQueuePacketConn makes a new QueuePacketConn, set to track recent peers
// for at least a duration of timeout.
func NewQueuePacketConn(localAddr net.Addr, timeout time.Duration) *QueuePacketConn {
return &QueuePacketConn{
remotes: NewRemoteMap(timeout),
localAddr: localAddr,
recvQueue: make(chan taggedPacket, QueueSize),
closed: make(chan struct{}),
}
}
// QueueIncoming queues and incoming packet and its source address, to be
// returned in a future call to ReadFrom.
func (c *QueuePacketConn) QueueIncoming(p []byte, addr net.Addr) {
select {
case <-c.closed:
// If we're closed, silently drop it.
return
default:
}
// Copy the slice so that the caller may reuse it.
buf := make([]byte, len(p))
copy(buf, p)
select {
case c.recvQueue <- taggedPacket{buf, addr}:
default:
// Drop the incoming packet if the receive queue is full.
}
}
// OutgoingQueue returns the queue of outgoing packets corresponding to addr,
// creating it if necessary. The contents of the queue will be packets that are
// written to the address in question using WriteTo.
func (c *QueuePacketConn) OutgoingQueue(addr net.Addr) <-chan []byte {
return c.remotes.SendQueue(addr)
}
// Stash places p in the stash for addr, if the stash is not already occupied.
// Returns true if the packet was placed in the stash, or false if the stash was
// already occupied. This method is similar to WriteTo, except that it puts the
// packet in the stash queue (accessible via Unstash), rather than the outgoing
// queue (accessible via OutgoingQueue).
func (c *QueuePacketConn) Stash(p []byte, addr net.Addr) bool {
return c.remotes.Stash(addr, p)
}
// Unstash returns the channel that represents the stash for addr.
func (c *QueuePacketConn) Unstash(addr net.Addr) <-chan []byte {
return c.remotes.Unstash(addr)
}
// ReadFrom returns a packet and address previously stored by QueueIncoming.
func (c *QueuePacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
select {
case <-c.closed:
return 0, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Addr: c.LocalAddr(), Err: c.err.Load().(error)}
default:
}
select {
case <-c.closed:
return 0, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Addr: c.LocalAddr(), Err: c.err.Load().(error)}
case packet := <-c.recvQueue:
return copy(p, packet.P), packet.Addr, nil
}
}
// WriteTo queues an outgoing packet for the given address. The queue can later
// be retrieved using the OutgoingQueue method.
func (c *QueuePacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
select {
case <-c.closed:
return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Addr: c.LocalAddr(), Err: c.err.Load().(error)}
default:
}
// Copy the slice so that the caller may reuse it.
buf := make([]byte, len(p))
copy(buf, p)
select {
case c.remotes.SendQueue(addr) <- buf:
return len(buf), nil
default:
// Drop the outgoing packet if the send queue is full.
return len(buf), nil
}
}
// closeWithError unblocks pending operations and makes future operations fail
// with the given error. If err is nil, it becomes errClosedPacketConn.
func (c *QueuePacketConn) closeWithError(err error) error {
var newlyClosed bool
c.closeOnce.Do(func() {
newlyClosed = true
// Store the error to be returned by future PacketConn
// operations.
if err == nil {
err = errClosedPacketConn
}
c.err.Store(err)
close(c.closed)
// LOCAL FORK ADDITION: stop the RemoteMap expiry goroutine so it is not
// leaked for the process lifetime. Upstream never does this.
c.remotes.Close()
})
if !newlyClosed {
return &net.OpError{Op: "close", Net: c.LocalAddr().Network(), Addr: c.LocalAddr(), Err: c.err.Load().(error)}
}
return nil
}
// Close unblocks pending operations and makes future operations fail with a
// "closed connection" error.
func (c *QueuePacketConn) Close() error {
return c.closeWithError(nil)
}
// LocalAddr returns the localAddr value that was passed to NewQueuePacketConn.
func (c *QueuePacketConn) LocalAddr() net.Addr { return c.localAddr }
func (c *QueuePacketConn) SetDeadline(t time.Time) error { return errNotImplemented }
func (c *QueuePacketConn) SetReadDeadline(t time.Time) error { return errNotImplemented }
func (c *QueuePacketConn) SetWriteDeadline(t time.Time) error { return errNotImplemented }
+198
View File
@@ -0,0 +1,198 @@
package turbotunnel
import (
"container/heap"
"net"
"sync"
"time"
)
// remoteRecord is a record of a recently seen remote peer, with the time it was
// last seen and queues of outgoing packets.
type remoteRecord struct {
Addr net.Addr
LastSeen time.Time
SendQueue chan []byte
Stash chan []byte
}
// RemoteMap manages a mapping of live remote peers, keyed by address, to their
// respective send queues. Each peer has two queues: a primary send queue, and a
// "stash". The primary send queue is returned by the SendQueue method. The
// stash is an auxiliary one-element queue accessed using the Stash and Unstash
// methods. The stash is meant for use by callers that need to "unread" a packet
// that's already been removed from the primary send queue.
//
// RemoteMap's functions are safe to call from multiple goroutines.
type RemoteMap struct {
// We use an inner structure to avoid exposing public heap.Interface
// functions to users of remoteMap.
inner remoteMapInner
// Synchronizes access to inner.
lock sync.Mutex
// closed stops the background expiry goroutine. LOCAL FORK ADDITION:
// upstream has no way to stop that goroutine, which leaks it for the
// process lifetime on every RemoteMap created.
closed chan struct{}
closeOnce sync.Once
}
// NewRemoteMap creates a RemoteMap that expires peers after a timeout.
//
// If the timeout is 0, peers never expire.
//
// The timeout does not have to be kept in sync with smux's idle timeout. If a
// peer is removed from the map while the smux session is still live, the worst
// that can happen is a loss of whatever packets were in the send queue at the
// time. If smux later decides to send more packets to the same peer, we'll
// instantiate a new send queue, and if the peer is ever seen again with a
// matching address, we'll deliver them.
func NewRemoteMap(timeout time.Duration) *RemoteMap {
m := &RemoteMap{
inner: remoteMapInner{
byAge: make([]*remoteRecord, 0),
byAddr: make(map[net.Addr]int),
},
closed: make(chan struct{}),
}
if timeout > 0 {
// LOCAL FORK CHANGE: upstream is `for { time.Sleep(timeout/2); ... }`
// with no exit. Use a ticker and select on m.closed so Close() can stop
// this goroutine.
go func() {
ticker := time.NewTicker(timeout / 2)
defer ticker.Stop()
for {
select {
case <-m.closed:
return
case now := <-ticker.C:
m.lock.Lock()
m.inner.removeExpired(now, timeout)
m.lock.Unlock()
}
}
}()
}
return m
}
// Close stops the background expiry goroutine started by NewRemoteMap. It is
// safe to call more than once. LOCAL FORK ADDITION.
func (m *RemoteMap) Close() error {
m.closeOnce.Do(func() { close(m.closed) })
return nil
}
// SendQueue returns the send queue corresponding to addr, creating it if
// necessary.
func (m *RemoteMap) SendQueue(addr net.Addr) chan []byte {
m.lock.Lock()
defer m.lock.Unlock()
return m.inner.Lookup(addr, time.Now()).SendQueue
}
// Stash places p in the stash corresponding to addr, if the stash is not
// already occupied. Returns true if the p was placed in the stash, false
// otherwise.
func (m *RemoteMap) Stash(addr net.Addr, p []byte) bool {
m.lock.Lock()
defer m.lock.Unlock()
select {
case m.inner.Lookup(addr, time.Now()).Stash <- p:
return true
default:
return false
}
}
// Unstash returns the channel that reads from the stash for addr.
func (m *RemoteMap) Unstash(addr net.Addr) <-chan []byte {
m.lock.Lock()
defer m.lock.Unlock()
return m.inner.Lookup(addr, time.Now()).Stash
}
// remoteMapInner is the inner type of RemoteMap, implementing heap.Interface.
// byAge is the backing store, a heap ordered by LastSeen time, to facilitate
// expiring old records. byAddr is a map from addresses to heap indices, to
// allow looking up by address. Unlike RemoteMap, remoteMapInner requires
// external synchonization.
type remoteMapInner struct {
byAge []*remoteRecord
byAddr map[net.Addr]int
}
// removeExpired removes all records whose LastSeen timestamp is more than
// timeout in the past.
func (inner *remoteMapInner) removeExpired(now time.Time, timeout time.Duration) {
for len(inner.byAge) > 0 && now.Sub(inner.byAge[0].LastSeen) >= timeout {
record := heap.Pop(inner).(*remoteRecord)
close(record.SendQueue)
}
}
// Lookup finds the existing record corresponding to addr, or creates a new
// one if none exists yet. It updates the record's LastSeen time and returns the
// record.
func (inner *remoteMapInner) Lookup(addr net.Addr, now time.Time) *remoteRecord {
var record *remoteRecord
i, ok := inner.byAddr[addr]
if ok {
// Found one, update its LastSeen.
record = inner.byAge[i]
record.LastSeen = now
heap.Fix(inner, i)
} else {
// Not found, create a new one.
record = &remoteRecord{
Addr: addr,
LastSeen: now,
SendQueue: make(chan []byte, QueueSize),
Stash: make(chan []byte, 1),
}
heap.Push(inner, record)
}
return record
}
// heap.Interface for remoteMapInner.
func (inner *remoteMapInner) Len() int {
if len(inner.byAge) != len(inner.byAddr) {
panic("inconsistent remoteMap")
}
return len(inner.byAge)
}
func (inner *remoteMapInner) Less(i, j int) bool {
return inner.byAge[i].LastSeen.Before(inner.byAge[j].LastSeen)
}
func (inner *remoteMapInner) Swap(i, j int) {
inner.byAge[i], inner.byAge[j] = inner.byAge[j], inner.byAge[i]
inner.byAddr[inner.byAge[i].Addr] = i
inner.byAddr[inner.byAge[j].Addr] = j
}
func (inner *remoteMapInner) Push(x interface{}) {
record := x.(*remoteRecord)
if _, ok := inner.byAddr[record.Addr]; ok {
panic("duplicate address in remoteMap")
}
// Insert into byAddr map.
inner.byAddr[record.Addr] = len(inner.byAge)
// Insert into byAge slice.
inner.byAge = append(inner.byAge, record)
}
func (inner *remoteMapInner) Pop() interface{} {
n := len(inner.byAddr)
// Remove from byAge slice.
record := inner.byAge[n-1]
inner.byAge[n-1] = nil
inner.byAge = inner.byAge[:n-1]
// Remove from byAddr map.
delete(inner.byAddr, record.Addr)
return record
}
@@ -0,0 +1,51 @@
package turbotunnel
import (
"runtime"
"testing"
"time"
)
// TestQueuePacketConnCloseStopsGoroutine is the regression test for the local
// fork's reason to exist: upstream's RemoteMap expiry goroutine runs forever,
// so creating and discarding many QueuePacketConns (as DNSTT restart does)
// leaks one goroutine each. After Close(), the count must return to baseline.
func TestQueuePacketConnCloseStopsGoroutine(t *testing.T) {
// Let any goroutines from earlier settle.
settle := func() {
for i := 0; i < 50; i++ {
runtime.GC()
time.Sleep(2 * time.Millisecond)
}
}
settle()
base := runtime.NumGoroutine()
const n = 200
for i := 0; i < n; i++ {
// Short timeout so the goroutine is definitely started (timeout > 0).
c := NewQueuePacketConn(DummyAddr{}, 50*time.Millisecond)
if err := c.Close(); err != nil {
t.Fatalf("Close returned error: %v", err)
}
}
settle()
got := runtime.NumGoroutine()
// Allow a small slack for scheduler/runtime goroutines; the key point is we
// are nowhere near base+n (which is what the upstream leak would produce).
if got > base+20 {
t.Fatalf("goroutine leak: baseline=%d after %d create/close cycles=%d (want <= baseline+20)", base, n, got)
}
}
// TestRemoteMapCloseIdempotent verifies Close can be called repeatedly.
func TestRemoteMapCloseIdempotent(t *testing.T) {
m := NewRemoteMap(10 * time.Millisecond)
if err := m.Close(); err != nil {
t.Fatalf("first Close: %v", err)
}
if err := m.Close(); err != nil {
t.Fatalf("second Close: %v", err)
}
}
+3686
View File
File diff suppressed because it is too large Load Diff
+779
View File
@@ -0,0 +1,779 @@
package main
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const managedCredentialPrefix = "enc:v1:"
func sealManagedCredential(plain string) (string, error) {
return sealCredential(managedCredentialPrefix, plain)
}
func openManagedCredential(stored string) (string, error) {
return openCredential(managedCredentialPrefix, stored)
}
func managedServerHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{
Timeout: timeout,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
type ManagedServer struct {
ID int
Name string
BaseURL string
AdminUsername string
AdminKey string
EnableSSH bool
EnableXray bool
IsActive bool
CreatedAt time.Time
UpdatedAt time.Time
}
type ManagedServerDTO struct {
ID string `json:"id"`
Name string `json:"name"`
BaseURL string `json:"base_url"`
AdminUsername string `json:"admin_username,omitempty"`
EnableSSH bool `json:"enable_ssh"`
EnableXray bool `json:"enable_xray"`
IsActive bool `json:"is_active"`
IsLocal bool `json:"is_local"`
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
type ManagedServerPayload struct {
ID string `json:"id"`
Name string `json:"name"`
BaseURL string `json:"base_url"`
AdminUsername string `json:"admin_username"`
AdminKey string `json:"admin_key"`
EnableSSH bool `json:"enable_ssh"`
EnableXray bool `json:"enable_xray"`
IsActive bool `json:"is_active"`
}
func (s *Store) EnsureManagedServersSchema(ctx context.Context) error {
_, err := s.db.ExecContext(ctx, `
CREATE TABLE IF NOT EXISTS managed_servers (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
base_url TEXT NOT NULL UNIQUE,
admin_username TEXT NOT NULL DEFAULT 'admin',
admin_key TEXT NOT NULL DEFAULT '',
enable_ssh BOOLEAN NOT NULL DEFAULT TRUE,
enable_xray BOOLEAN NOT NULL DEFAULT TRUE,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`)
if err != nil {
return err
}
return s.migrateManagedServerCredentials(ctx)
}
func (s *Store) migrateManagedServerCredentials(ctx context.Context) error {
rows, err := s.db.QueryContext(ctx, `SELECT id, admin_key FROM managed_servers WHERE admin_key <> '' AND admin_key NOT LIKE 'enc:v1:%'`)
if err != nil {
return err
}
type legacyCredential struct {
id int
key string
}
var legacy []legacyCredential
for rows.Next() {
var item legacyCredential
if err := rows.Scan(&item.id, &item.key); err != nil {
rows.Close()
return err
}
legacy = append(legacy, item)
}
if err := rows.Close(); err != nil {
return err
}
for _, item := range legacy {
sealed, err := sealManagedCredential(item.key)
if err != nil {
return fmt.Errorf("encrypt managed server credential %d: %w", item.id, err)
}
if _, err := s.db.ExecContext(ctx, `UPDATE managed_servers SET admin_key=$2 WHERE id=$1`, item.id, sealed); err != nil {
return err
}
}
return nil
}
func (s *Store) ListManagedServers(ctx context.Context) ([]*ManagedServer, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, name, base_url, admin_username, admin_key, enable_ssh, enable_xray, is_active, created_at, updated_at
FROM managed_servers ORDER BY id ASC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*ManagedServer
for rows.Next() {
ms := &ManagedServer{}
if err := rows.Scan(&ms.ID, &ms.Name, &ms.BaseURL, &ms.AdminUsername, &ms.AdminKey, &ms.EnableSSH, &ms.EnableXray, &ms.IsActive, &ms.CreatedAt, &ms.UpdatedAt); err != nil {
return nil, err
}
plainKey, err := openManagedCredential(ms.AdminKey)
if err != nil {
return nil, err
}
ms.AdminKey = plainKey
out = append(out, ms)
}
return out, rows.Err()
}
func (s *Store) GetManagedServer(ctx context.Context, id int) (*ManagedServer, error) {
ms := &ManagedServer{}
err := s.db.QueryRowContext(ctx, `
SELECT id, name, base_url, admin_username, admin_key, enable_ssh, enable_xray, is_active, created_at, updated_at
FROM managed_servers WHERE id=$1`, id).
Scan(&ms.ID, &ms.Name, &ms.BaseURL, &ms.AdminUsername, &ms.AdminKey, &ms.EnableSSH, &ms.EnableXray, &ms.IsActive, &ms.CreatedAt, &ms.UpdatedAt)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
plainKey, err := openManagedCredential(ms.AdminKey)
if err != nil {
return nil, err
}
ms.AdminKey = plainKey
return ms, nil
}
func (s *Store) UpsertManagedServer(ctx context.Context, p ManagedServerPayload) (*ManagedServer, error) {
name := strings.TrimSpace(p.Name)
baseURL, baseURLErr := validateManagedServerBaseURL(p.BaseURL)
adminUsername := strings.TrimSpace(p.AdminUsername)
if adminUsername == "" {
adminUsername = "admin"
}
if name == "" {
return nil, fmt.Errorf("server name required")
}
if len(name) > 120 || strings.IndexFunc(name, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {
return nil, fmt.Errorf("invalid server name")
}
if len(adminUsername) > 128 || strings.IndexFunc(adminUsername, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {
return nil, fmt.Errorf("invalid admin username")
}
if len(p.AdminKey) > 4096 || strings.IndexFunc(p.AdminKey, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {
return nil, fmt.Errorf("invalid admin credential")
}
if baseURLErr != nil {
return nil, baseURLErr
}
if p.ID != "" && p.ID != "local" {
id, err := strconv.Atoi(p.ID)
if err != nil || id <= 0 {
return nil, fmt.Errorf("invalid server id")
}
if strings.TrimSpace(p.AdminKey) == "" {
_, err = s.db.ExecContext(ctx, `
UPDATE managed_servers
SET name=$2, base_url=$3, admin_username=$4, enable_ssh=$5, enable_xray=$6, is_active=$7, updated_at=NOW()
WHERE id=$1`, id, name, baseURL, adminUsername, p.EnableSSH, p.EnableXray, p.IsActive)
} else {
sealedKey, sealErr := sealManagedCredential(p.AdminKey)
if sealErr != nil {
return nil, fmt.Errorf("encrypt admin credential: %w", sealErr)
}
_, err = s.db.ExecContext(ctx, `
UPDATE managed_servers
SET name=$2, base_url=$3, admin_username=$4, admin_key=$5, enable_ssh=$6, enable_xray=$7, is_active=$8, updated_at=NOW()
WHERE id=$1`, id, name, baseURL, adminUsername, sealedKey, p.EnableSSH, p.EnableXray, p.IsActive)
}
if err != nil {
return nil, err
}
return s.GetManagedServer(ctx, id)
}
if strings.TrimSpace(p.AdminKey) == "" {
return nil, fmt.Errorf("admin key/password required")
}
sealedKey, err := sealManagedCredential(p.AdminKey)
if err != nil {
return nil, fmt.Errorf("encrypt admin credential: %w", err)
}
var id int
err = s.db.QueryRowContext(ctx, `
INSERT INTO managed_servers (name, base_url, admin_username, admin_key, enable_ssh, enable_xray, is_active)
VALUES ($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT (base_url) DO UPDATE SET
name=EXCLUDED.name,
admin_username=EXCLUDED.admin_username,
admin_key=EXCLUDED.admin_key,
enable_ssh=EXCLUDED.enable_ssh,
enable_xray=EXCLUDED.enable_xray,
is_active=EXCLUDED.is_active,
updated_at=NOW()
RETURNING id`, name, baseURL, adminUsername, sealedKey, p.EnableSSH, p.EnableXray, p.IsActive).Scan(&id)
if err != nil {
return nil, err
}
return s.GetManagedServer(ctx, id)
}
func (s *Store) DeleteManagedServer(ctx context.Context, id int) error {
_, err := s.db.ExecContext(ctx, `DELETE FROM managed_servers WHERE id=$1`, id)
return err
}
func managedServerToDTO(ms *ManagedServer) ManagedServerDTO {
return ManagedServerDTO{
ID: strconv.Itoa(ms.ID),
Name: ms.Name,
BaseURL: ms.BaseURL,
AdminUsername: ms.AdminUsername,
EnableSSH: ms.EnableSSH,
EnableXray: ms.EnableXray,
IsActive: ms.IsActive,
CreatedAt: ms.CreatedAt,
UpdatedAt: ms.UpdatedAt,
}
}
func localManagedServerDTO() ManagedServerDTO {
cfg := getGlobalCfg()
xrayEnabled := cfg != nil && cfg.Xray != nil && cfg.Xray.Enabled
return ManagedServerDTO{
ID: "local",
Name: "Master node",
BaseURL: "local",
EnableSSH: true,
EnableXray: xrayEnabled,
IsActive: true,
IsLocal: true,
}
}
func normalizeManagedServerBaseURL(raw string) string {
normalized, _ := validateManagedServerBaseURL(raw)
return normalized
}
func validateManagedServerBaseURL(raw string) (string, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", fmt.Errorf("base url required")
}
lowerRaw := strings.ToLower(raw)
if !strings.HasPrefix(lowerRaw, "http://") && !strings.HasPrefix(lowerRaw, "https://") {
raw = "http://" + raw
}
u, err := url.Parse(raw)
if err != nil || u.Scheme == "" || u.Host == "" {
return "", fmt.Errorf("invalid base url")
}
if u.Scheme != "http" && u.Scheme != "https" {
return "", fmt.Errorf("base url must use http or https")
}
if u.User != nil {
return "", fmt.Errorf("base url must not contain credentials")
}
if u.Path != "" && u.Path != "/" {
return "", fmt.Errorf("base url must not contain a path")
}
if ip := net.ParseIP(u.Hostname()); ip != nil && (ip.IsUnspecified() || ip.IsMulticast() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()) {
return "", fmt.Errorf("base url uses a forbidden address")
}
u.Path = ""
u.RawQuery = ""
u.Fragment = ""
return strings.TrimRight(u.String(), "/"), nil
}
func requestedServerID(r *http.Request) string {
id := strings.TrimSpace(r.URL.Query().Get("server_id"))
if id == "" {
id = strings.TrimSpace(r.URL.Query().Get("server"))
}
return id
}
func managedServerFromID(ctx context.Context, store *Store, id string) (*ManagedServer, bool, error) {
id = strings.TrimSpace(id)
if id == "" || id == "local" || id == "0" {
return nil, false, nil
}
if store == nil {
return nil, false, fmt.Errorf("database not configured")
}
n, err := strconv.Atoi(id)
if err != nil || n <= 0 {
return nil, false, fmt.Errorf("invalid server id")
}
ms, err := store.GetManagedServer(ctx, n)
if err != nil {
return nil, false, err
}
if ms == nil {
return nil, false, fmt.Errorf("server not found")
}
if !ms.IsActive {
return nil, false, fmt.Errorf("server is disabled")
}
return ms, true, nil
}
func remoteLoginToken(ctx context.Context, ms *ManagedServer) (string, error) {
body, _ := json.Marshal(map[string]string{"username": ms.AdminUsername, "password": ms.AdminKey})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, ms.BaseURL+"/api/auth/login", bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
client := managedServerHTTPClient(15 * time.Second)
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, _ := io.ReadAll(io.LimitReader(resp.Body, 128*1024))
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", fmt.Errorf("remote login failed: %s", strings.TrimSpace(string(data)))
}
var out struct {
Token string `json:"token"`
}
if err := json.Unmarshal(data, &out); err != nil || out.Token == "" {
return "", fmt.Errorf("remote login returned no token")
}
return out.Token, nil
}
func proxyManagedServer(ctx context.Context, ms *ManagedServer, method, path string, body []byte, contentType string) (int, []byte, string, error) {
token, err := remoteLoginToken(ctx, ms)
if err != nil {
return 0, nil, "", err
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
req, err := http.NewRequestWithContext(ctx, method, ms.BaseURL+path, bytes.NewReader(body))
if err != nil {
return 0, nil, "", err
}
if contentType == "" {
contentType = "application/json"
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("X-Session-Token", token)
client := managedServerHTTPClient(30 * time.Second)
resp, err := client.Do(req)
if err != nil {
return 0, nil, "", err
}
defer resp.Body.Close()
data, _ := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024))
return resp.StatusCode, data, resp.Header.Get("Content-Type"), nil
}
func handleManagedProxyOrLocal(store *Store, local http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if proxyManagedServerFromRequest(w, r, store, "", nil, "") {
return
}
local(w, r)
}
}
func writeProxyResponse(w http.ResponseWriter, status int, body []byte, contentType string) {
if contentType != "" {
w.Header().Set("Content-Type", contentType)
}
if status == 0 {
status = http.StatusBadGateway
}
w.WriteHeader(status)
if len(body) > 0 {
_, _ = w.Write(body)
}
}
func proxyManagedServerFromRequest(w http.ResponseWriter, r *http.Request, store *Store, remotePath string, body []byte, filterOwner string) bool {
ms, remote, err := managedServerFromID(r.Context(), store, requestedServerID(r))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return true
}
if !remote {
return false
}
if remotePath == "" {
remotePath = r.URL.Path
if r.URL.RawQuery != "" {
q := r.URL.Query()
q.Del("server_id")
q.Del("server")
if enc := q.Encode(); enc != "" {
remotePath += "?" + enc
}
}
}
if body == nil && r.Body != nil && r.Method != http.MethodGet {
body, _ = io.ReadAll(io.LimitReader(r.Body, 2*1024*1024))
}
status, data, ct, err := proxyManagedServer(r.Context(), ms, r.Method, remotePath, body, r.Header.Get("Content-Type"))
if err != nil {
http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway)
return true
}
if status >= 200 && status < 300 && filterOwner != "" && strings.Contains(ct, "json") {
if filtered, ok := filterRemoteOwnerJSON(remotePath, data, filterOwner); ok {
data = filtered
}
}
writeProxyResponse(w, status, data, ct)
return true
}
func filterRemoteOwnerJSON(path string, data []byte, owner string) ([]byte, bool) {
if owner == "" || len(data) == 0 {
return data, false
}
if strings.HasPrefix(path, "/api/users") {
var rows []map[string]interface{}
if err := json.Unmarshal(data, &rows); err != nil {
return data, false
}
out := rows[:0]
for _, row := range rows {
if strings.TrimSpace(fmt.Sprint(row["owner_username"])) == owner {
out = append(out, row)
}
}
filtered, _ := json.Marshal(out)
return filtered, true
}
if strings.HasPrefix(path, "/api/xray/inbounds") {
var inbounds []map[string]interface{}
if err := json.Unmarshal(data, &inbounds); err != nil {
return data, false
}
for _, ib := range inbounds {
clients, _ := ib["clients"].([]interface{})
filtered := make([]interface{}, 0, len(clients))
for _, c := range clients {
m, _ := c.(map[string]interface{})
if strings.TrimSpace(fmt.Sprint(m["owner_username"])) == owner {
filtered = append(filtered, c)
}
}
ib["clients"] = filtered
}
filtered, _ := json.Marshal(inbounds)
return filtered, true
}
return data, false
}
func handleServers(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if store == nil {
http.Error(w, "database not configured", http.StatusServiceUnavailable)
return
}
sess := sessionFromCtx(r.Context())
switch r.Method {
case http.MethodGet:
rows, err := store.ListManagedServers(r.Context())
if err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
out := []ManagedServerDTO{localManagedServerDTO()}
for _, ms := range rows {
if sess != nil && sess.Role == RoleReseller && !ms.IsActive {
continue
}
dto := managedServerToDTO(ms)
if sess != nil && sess.Role == RoleReseller {
dto.AdminUsername = ""
}
out = append(out, dto)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(out)
case http.MethodPost:
if sess == nil || sess.Role != RoleSuperAdmin {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
var p ManagedServerPayload
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
ms, err := store.UpsertManagedServer(r.Context(), p)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(managedServerToDTO(ms))
case http.MethodDelete:
if sess == nil || sess.Role != RoleSuperAdmin {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
idStr := strings.TrimSpace(r.URL.Query().Get("id"))
id, err := strconv.Atoi(idStr)
if err != nil || id <= 0 {
http.Error(w, "invalid server id", http.StatusBadRequest)
return
}
if err := store.DeleteManagedServer(r.Context(), id); err != nil {
http.Error(w, "db error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
func handleServerTest(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if store == nil {
http.Error(w, "database not configured", http.StatusServiceUnavailable)
return
}
var p ManagedServerPayload
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
ms := &ManagedServer{Name: p.Name, BaseURL: normalizeManagedServerBaseURL(p.BaseURL), AdminUsername: strings.TrimSpace(p.AdminUsername), AdminKey: p.AdminKey, EnableSSH: p.EnableSSH, EnableXray: p.EnableXray, IsActive: true}
if p.ID != "" && p.ID != "local" && (ms.BaseURL == "" || ms.AdminKey == "") {
id, _ := strconv.Atoi(p.ID)
if id > 0 {
stored, err := store.GetManagedServer(r.Context(), id)
if err == nil && stored != nil {
if ms.BaseURL == "" {
ms.BaseURL = stored.BaseURL
}
if ms.AdminUsername == "" {
ms.AdminUsername = stored.AdminUsername
}
if ms.AdminKey == "" {
ms.AdminKey = stored.AdminKey
}
}
}
}
if ms.AdminUsername == "" {
ms.AdminUsername = "admin"
}
if ms.BaseURL == "" || ms.AdminKey == "" {
http.Error(w, "base url and admin key/password required", http.StatusBadRequest)
return
}
token, err := remoteLoginToken(r.Context(), ms)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
_ = token
status, data, _, err := proxyManagedServer(r.Context(), ms, http.MethodGet, "/api/auth/me", nil, "application/json")
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
if status < 200 || status >= 300 {
http.Error(w, strings.TrimSpace(string(data)), http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "message": "remote login ok"})
}
}
func handleManagedServerConfig(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := requestedServerID(r)
if id == "" || id == "local" || id == "0" {
handleServerConfig(w, r)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
body := []byte(nil)
if r.Method == http.MethodPost {
var err error
body, err = io.ReadAll(io.LimitReader(r.Body, 512*1024))
if err != nil {
http.Error(w, "failed to read body", http.StatusBadRequest)
return
}
}
ms, remote, err := managedServerFromID(r.Context(), store, id)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !remote {
handleServerConfig(w, r)
return
}
status, data, ct, err := proxyManagedServer(r.Context(), ms, r.Method, "/api/server/config", body, "application/json")
if err != nil {
log.Printf("managed server config proxy %s: %v", ms.BaseURL, err)
http.Error(w, "remote server error: "+err.Error(), http.StatusBadGateway)
return
}
writeProxyResponse(w, status, data, ct)
}
}
func remoteSSHUserOwner(ctx context.Context, ms *ManagedServer, username string) (owner string, exists bool, err error) {
if username == "" {
return "", false, nil
}
status, data, _, err := proxyManagedServer(ctx, ms, http.MethodGet, "/api/users", nil, "application/json")
if err != nil || status < 200 || status >= 300 {
if err == nil {
err = fmt.Errorf("remote users returned HTTP %d", status)
}
return "", false, err
}
var rows []map[string]interface{}
if err := json.Unmarshal(data, &rows); err != nil {
return "", false, err
}
for _, row := range rows {
if fmt.Sprint(row["username"]) == username {
return strings.TrimSpace(fmt.Sprint(row["owner_username"])), true, nil
}
}
return "", false, nil
}
func remoteSSHUserOwned(ctx context.Context, ms *ManagedServer, username, owner string) bool {
actualOwner, exists, err := remoteSSHUserOwner(ctx, ms, username)
return err == nil && exists && actualOwner == owner
}
func remoteXrayClientOwner(ctx context.Context, ms *ManagedServer, uuid string) (owner string, exists bool, err error) {
if uuid == "" {
return "", false, nil
}
status, data, _, err := proxyManagedServer(ctx, ms, http.MethodGet, "/api/xray/inbounds", nil, "application/json")
if err != nil || status < 200 || status >= 300 {
if err == nil {
err = fmt.Errorf("remote Xray inbounds returned HTTP %d", status)
}
return "", false, err
}
var inbounds []map[string]interface{}
if err := json.Unmarshal(data, &inbounds); err != nil {
return "", false, err
}
for _, ib := range inbounds {
clients, _ := ib["clients"].([]interface{})
for _, c := range clients {
m, _ := c.(map[string]interface{})
if fmt.Sprint(m["id"]) == uuid {
return strings.TrimSpace(fmt.Sprint(m["owner_username"])), true, nil
}
}
}
return "", false, nil
}
func remoteXrayClientOwned(ctx context.Context, ms *ManagedServer, uuid, owner string) bool {
actualOwner, exists, err := remoteXrayClientOwner(ctx, ms, uuid)
return err == nil && exists && actualOwner == owner
}
func countOwnedQuotaAcrossManagedServers(ctx context.Context, store *Store, owner string) (int, error) {
if store == nil || owner == "" {
return 0, nil
}
total := countOwnedQuota(ctx, store, owner)
servers, err := store.ListManagedServers(ctx)
if err != nil {
return 0, err
}
for _, ms := range servers {
if !ms.IsActive {
continue
}
if ms.EnableSSH {
status, data, _, err := proxyManagedServer(ctx, ms, http.MethodGet, "/api/users", nil, "application/json")
if err != nil || status < 200 || status >= 300 {
if err == nil {
err = fmt.Errorf("remote users returned HTTP %d", status)
}
return 0, err
}
var users []map[string]interface{}
if err := json.Unmarshal(data, &users); err != nil {
return 0, err
}
for _, user := range users {
if strings.TrimSpace(fmt.Sprint(user["owner_username"])) == owner {
total++
}
}
}
if ms.EnableXray {
status, data, _, err := proxyManagedServer(ctx, ms, http.MethodGet, "/api/xray/inbounds", nil, "application/json")
if err != nil || status < 200 || status >= 300 {
if err == nil {
err = fmt.Errorf("remote Xray inbounds returned HTTP %d", status)
}
return 0, err
}
var inbounds []map[string]interface{}
if err := json.Unmarshal(data, &inbounds); err != nil {
return 0, err
}
for _, inbound := range inbounds {
clients, _ := inbound["clients"].([]interface{})
for _, client := range clients {
item, _ := client.(map[string]interface{})
if strings.TrimSpace(fmt.Sprint(item["owner_username"])) == owner {
total++
}
}
}
}
}
return total, nil
}
+227
View File
@@ -0,0 +1,227 @@
package main
import (
"context"
"crypto/subtle"
"errors"
"fmt"
"log"
"os"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/GehirnInc/crypt"
_ "github.com/GehirnInc/crypt/apr1_crypt"
_ "github.com/GehirnInc/crypt/md5_crypt"
_ "github.com/GehirnInc/crypt/sha256_crypt"
_ "github.com/GehirnInc/crypt/sha512_crypt"
"github.com/openwall/yescrypt-go"
"golang.org/x/crypto/bcrypt"
)
const (
shadowFile = "/etc/shadow"
passwdFile = "/etc/passwd"
// minLoginUID / nobodyUID bound the accounts eligible for auto-import.
// Regular human login accounts start at UID 1000 on Debian/Ubuntu; system
// and service accounts (and "nobody") are excluded.
minLoginUID = 1000
nobodyUID = 65534
)
var errNoSystemPassword = errors.New("account has no usable password")
// pamLogger writes PAM auth diagnostics straight to stderr (captured by
// journald) so they remain visible even when "Quiet Logs" redirects the default
// logger to io.Discard. Use pamLogf for anything an operator needs to see when
// debugging why a system login was accepted or refused.
var pamLogger = log.New(os.Stderr, "", log.LstdFlags)
func pamLogf(format string, args ...interface{}) { pamLogger.Printf(format, args...) }
// pamAuthEnabled mirrors Config.PAMAuthEnabled and is toggled live on config
// reload. Guarded atomically so passwordCallback can read it lock-free.
var pamAuthEnabled atomic.Bool
func setPAMAuthEnabled(v bool) {
pamAuthEnabled.Store(v)
state := "disabled"
if v {
state = "ENABLED"
}
pamLogf("PAM: system (Linux /etc/shadow) login is now %s", state)
}
func isPAMAuthEnabled() bool { return pamAuthEnabled.Load() }
// importPAMUser registers a freshly PAM-authenticated account in the running
// user manager and persists it (marked use_pam) so it shows up in the panel and
// later logins are re-verified against the system password. Idempotent: a
// second concurrent/subsequent login for the same user is a no-op.
func importPAMUser(username string) {
cfg := UserConfig{Username: username, UsePAM: true}
// Carry over the Linux account expiry (/etc/shadow field 8) so the panel's
// "Vence em" shows the real expiration instead of "—".
var expPtr *time.Time
if exp := shadowAccountExpiry(username); exp != nil {
cfg.ExpiresAt = exp.Format(time.RFC3339)
expPtr = exp
}
st := &UserState{Cfg: cfg, ExpiresAt: expPtr}
if !userMgr.AddIfAbsent(st) {
return // already present in memory
}
pamLogf("PAM: auto-imported system user %s into the panel", username)
if statsStore != nil {
if err := statsStore.UpsertUser(context.Background(), cfg); err != nil {
pamLogf("PAM: failed to persist auto-imported user %s: %v", username, err)
}
}
}
// isRegularLoginUser reports whether username is a regular human login account
// (UID >= 1000 and not "nobody"), by parsing /etc/passwd. System/service
// accounts and root are excluded from auto-import.
func isRegularLoginUser(username string) bool {
data, err := os.ReadFile(passwdFile)
if err != nil {
pamLogf("PAM: cannot read %s: %v", passwdFile, err)
return false
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimRight(line, "\r")
fields := strings.Split(line, ":")
if len(fields) < 3 || fields[0] != username {
continue
}
uid, err := strconv.Atoi(fields[2])
if err != nil {
return false
}
return uid >= minLoginUID && uid != nobodyUID
}
return false
}
// shadowAccountExpiry returns the account expiration date from /etc/shadow
// field 8 (days since 1970-01-01), or nil if the account never expires (empty
// field) or the value is unusable. This is the `chage -E` / `useradd -e` date,
// which maps to the panel's per-user expiry.
func shadowAccountExpiry(username string) *time.Time {
data, err := os.ReadFile(shadowFile)
if err != nil {
return nil
}
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Split(strings.TrimRight(line, "\r"), ":")
if len(fields) < 8 || fields[0] != username {
continue
}
expStr := strings.TrimSpace(fields[7])
if expStr == "" {
return nil // no account expiry set
}
days, err := strconv.Atoi(expStr)
if err != nil || days <= 0 {
return nil
}
t := time.Unix(int64(days)*86400, 0).UTC()
return &t
}
return nil
}
// authenticatePAM verifies password against the Linux system account matching
// username. It reads the account's hash from /etc/shadow (the panel runs as
// root) and recomputes it with the same algorithm — this is the "just the auth"
// behaviour: the supplied password is checked exactly as the system would,
// with no account/session management and nothing to do with the SSH daemon.
//
// It is called "PAM" for continuity with the user-facing flag, but it does not
// link libpam; it verifies the crypt(3) hash directly. Supported hash formats:
// yescrypt ($y$), sha512-crypt ($6$), sha256-crypt ($5$), md5-crypt ($1$),
// apr1 ($apr1$) and bcrypt ($2a$/$2b$/$2y$). Returns nil on success.
func authenticatePAM(username, password string) error {
if username == "" {
return errors.New("shadow: empty username")
}
hash, err := lookupShadowHash(username)
if err != nil {
return err
}
return verifyCryptHash(hash, password)
}
// lookupShadowHash returns the password hash field for username from /etc/shadow.
func lookupShadowHash(username string) (string, error) {
data, err := os.ReadFile(shadowFile)
if err != nil {
return "", fmt.Errorf("read %s: %w", shadowFile, err)
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimRight(line, "\r")
if line == "" {
continue
}
fields := strings.Split(line, ":")
if len(fields) < 2 || fields[0] != username {
continue
}
hash := fields[1]
// Empty, or locked/disabled accounts (! or * in the hash field) have no
// password that any input can match — reject rather than risk a match.
if hash == "" || strings.HasPrefix(hash, "!") || strings.HasPrefix(hash, "*") {
return "", errNoSystemPassword
}
return hash, nil
}
return "", fmt.Errorf("shadow: user %q not found", username)
}
// verifyCryptHash checks password against a crypt(3)-style hash string,
// dispatching on the hash prefix. Returns nil only on an exact match.
func verifyCryptHash(hash, password string) error {
switch {
case strings.HasPrefix(hash, "$y$"):
computed, err := yescrypt.Hash([]byte(password), []byte(hash))
if err != nil {
return fmt.Errorf("yescrypt: %w", err)
}
if subtle.ConstantTimeCompare(computed, []byte(hash)) == 1 {
return nil
}
return errors.New("password mismatch")
case strings.HasPrefix(hash, "$2a$"), strings.HasPrefix(hash, "$2b$"), strings.HasPrefix(hash, "$2y$"):
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
case crypt.IsHashSupported(hash):
return crypt.NewFromHash(hash).Verify(hash, []byte(password))
case isTraditionalDES(hash):
computed, err := desCrypt(password, hash)
if err != nil {
return fmt.Errorf("descrypt: %w", err)
}
if subtle.ConstantTimeCompare([]byte(computed), []byte(hash)) == 1 {
return nil
}
return errors.New("password mismatch")
default:
return fmt.Errorf("shadow: unsupported hash format")
}
}
// isTraditionalDES reports whether hash looks like a classic 13-character
// DES crypt(3) hash (2 salt chars + 11 hash chars, all from the crypt alphabet,
// no "$" scheme prefix). Used by old Linux/UNIX accounts.
func isTraditionalDES(hash string) bool {
if len(hash) != 13 {
return false
}
for i := 0; i < len(hash); i++ {
if crypt64Decode(hash[i]) < 0 {
return false
}
}
return true
}
+51
View File
@@ -0,0 +1,51 @@
package main
import "testing"
// Known crypt(3) test vectors covering the formats found in /etc/shadow across
// old and new Linux. verifyCryptHash must accept the right password and reject
// the wrong one for each.
func TestVerifyCryptHashVectors(t *testing.T) {
cases := []struct {
name string
hash string
pw string
}{
{
name: "sha512crypt $6$ (glibc, older Linux)",
// openssl passwd -6 -salt saltstring "Hello world!"
hash: "$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1",
pw: "Hello world!",
},
{
name: "yescrypt $y$ (Debian 11+/Ubuntu 22.04+)",
hash: "$y$j9T$e8R9q85ZuzUkArEUurdtS.$esON.7y6H.u3UCPVCpbRFueRpAut2n2cMf1EhpjbuiC",
pw: "pleaseletmein",
},
{
// Real DES-crypt account from the production server's /etc/shadow.
name: "traditional DES (old Linux) — testedragon",
hash: "pae9A3UKpfaU6",
pw: "testedragon",
},
{
name: "traditional DES (old Linux) — ipv6dragon",
hash: "pa9eao3LI6u.6",
pw: "0tMGUL9chq8D",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if err := verifyCryptHash(c.hash, c.pw); err != nil {
t.Errorf("correct password REJECTED: %v", err)
}
// Build a wrong password that differs in the FIRST character, so the
// check is meaningful even for traditional DES (which only considers
// the first 8 bytes of the password).
wrong := "Z" + c.pw
if err := verifyCryptHash(c.hash, wrong); err == nil {
t.Errorf("wrong password ACCEPTED")
}
})
}
}
+105
View File
@@ -0,0 +1,105 @@
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const (
defaultPanelLogMaxBytes int64 = 1 * 1024 * 1024
defaultPanelLogCheckEvery = 10 * time.Second
)
type panelLogResetResponse struct {
OK bool `json:"ok"`
Path string `json:"path"`
MaxBytes int64 `json:"max_bytes"`
}
func panelLogFilePath() string {
path := strings.TrimSpace(os.Getenv("PANEL_LOG_FILE"))
if path == "" {
path = defaultPanelLogFile
}
return path
}
func panelLogMaxBytes() int64 {
raw := strings.TrimSpace(os.Getenv("PANEL_LOG_MAX_BYTES"))
if raw == "" {
return defaultPanelLogMaxBytes
}
n, err := strconv.ParseInt(raw, 10, 64)
if err != nil || n <= 0 {
return defaultPanelLogMaxBytes
}
// Do not allow a tiny limit that would cause continuous truncation.
if n < 64*1024 {
return 64 * 1024
}
return n
}
func startPanelLogLimiter() {
path := panelLogFilePath()
maxBytes := panelLogMaxBytes()
if path == "" || maxBytes <= 0 {
return
}
go func() {
_ = enforcePanelLogLimit(path, maxBytes)
ticker := time.NewTicker(defaultPanelLogCheckEvery)
defer ticker.Stop()
for range ticker.C {
_ = enforcePanelLogLimit(path, maxBytes)
}
}()
}
func enforcePanelLogLimit(path string, maxBytes int64) error {
st, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
if st.Size() <= maxBytes {
return nil
}
return truncatePanelLog(path, maxBytes, "automatic 1 MiB log limit")
}
func truncatePanelLog(path string, maxBytes int64, reason string) error {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = fmt.Fprintf(f, "%s sshpanel: panel log cleaned (%s, max=%d bytes)\n", time.Now().Format(time.RFC3339), reason, maxBytes)
return err
}
func handleSystemLogsReset(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
path := panelLogFilePath()
maxBytes := panelLogMaxBytes()
if err := truncatePanelLog(path, maxBytes, "manual clean from admin panel"); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(panelLogResetResponse{OK: true, Path: path, MaxBytes: maxBytes})
}
+176
View File
@@ -0,0 +1,176 @@
package main
import (
"context"
"log"
"strings"
"sync"
"time"
)
var (
proxyAutoMu sync.Mutex
proxyAutoCancel context.CancelFunc
)
// startProxyAutoRestart starts a watchdog that periodically hard-restarts the
// public SSH/HTTP proxy layer. Unlike a normal hot reload, this intentionally
// closes active SSH sessions so the behavior is close to a service reboot.
func startProxyAutoRestart(cfg *Config) {
interval := proxyAutoRestartInterval(cfg)
if interval <= 0 {
return
}
grace := proxyAutoRestartGrace(cfg)
cfgCopy := cloneProxyRestartConfig(cfg)
ctx, cancel := context.WithCancel(context.Background())
proxyAutoMu.Lock()
if proxyAutoCancel != nil {
proxyAutoCancel()
}
proxyAutoCancel = cancel
proxyAutoMu.Unlock()
go func() {
t := time.NewTicker(interval)
defer t.Stop()
log.Printf("proxy auto restart enabled: interval=%s grace=%s mode=hard", interval, grace)
for {
select {
case <-ctx.Done():
return
case <-t.C:
restartProxyHard(ctx, cfgCopy, grace)
}
}
}()
}
func stopProxyAutoRestart() {
proxyAutoMu.Lock()
defer proxyAutoMu.Unlock()
if proxyAutoCancel != nil {
proxyAutoCancel()
proxyAutoCancel = nil
}
}
func cloneProxyRestartConfig(cfg *Config) *Config {
if cfg == nil {
return nil
}
out := &Config{
Listen: cfg.Listen,
ProxyAutoRestartInterval: cfg.ProxyAutoRestartInterval,
ProxyAutoRestartGrace: cfg.ProxyAutoRestartGrace,
}
out.ExtraListen = append([]string(nil), cfg.ExtraListen...)
out.TLSForwarders = append([]TLSForwarderConfig(nil), cfg.TLSForwarders...)
return out
}
func restartProxyHard(ctx context.Context, cfg *Config, grace time.Duration) {
if cfg == nil {
return
}
log.Printf("proxy auto restart: stopping public proxy listeners and active SSH sessions")
if publicPool != nil {
publicPool.StopAll("proxy auto restart")
}
if tlsPool != nil {
tlsPool.StopAll("proxy auto restart")
}
closed := userMgr.DisconnectAll()
if closed > 0 {
log.Printf("proxy auto restart: closed %d active SSH session(s)", closed)
}
if !sleepOrContextDone(ctx, grace) {
return
}
publicAddrs := append([]string{cfg.Listen}, cfg.ExtraListen...)
for attempt := 1; ; attempt++ {
errs := []error{}
if publicPool != nil {
errs = append(errs, publicPool.Sync(publicAddrs)...)
}
if tlsPool != nil {
errs = append(errs, tlsPool.Sync(cfg.TLSForwarders)...)
}
ok := len(errs) == 0
if publicPool != nil && !publicPool.HasAll(publicAddrs) {
ok = false
}
if tlsPool != nil && !tlsPool.HasAll(cfg.TLSForwarders) {
ok = false
}
if ok {
log.Printf("proxy auto restart: public proxy restarted")
return
}
for _, err := range errs {
log.Printf("proxy auto restart: start attempt %d failed: %v", attempt, err)
}
if len(errs) == 0 {
log.Printf("proxy auto restart: start attempt %d incomplete; one or more listeners are still down", attempt)
}
if !sleepOrContextDone(ctx, 10*time.Second) {
return
}
}
}
func proxyAutoRestartInterval(cfg *Config) time.Duration {
if cfg == nil {
return 0
}
raw := strings.TrimSpace(cfg.ProxyAutoRestartInterval)
if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") {
return 0
}
d, err := time.ParseDuration(raw)
if err != nil {
log.Printf("proxy auto restart disabled: invalid interval %q: %v", raw, err)
return 0
}
if d < time.Minute {
log.Printf("proxy auto restart disabled: interval %q is below minimum 1m", raw)
return 0
}
return d
}
func proxyAutoRestartGrace(cfg *Config) time.Duration {
if cfg == nil || strings.TrimSpace(cfg.ProxyAutoRestartGrace) == "" {
return 2 * time.Second
}
d, err := time.ParseDuration(strings.TrimSpace(cfg.ProxyAutoRestartGrace))
if err != nil || d < 0 {
log.Printf("proxy auto restart: invalid grace %q, using 2s", cfg.ProxyAutoRestartGrace)
return 2 * time.Second
}
if d > time.Minute {
return time.Minute
}
return d
}
func sleepOrContextDone(ctx context.Context, d time.Duration) bool {
if d <= 0 {
select {
case <-ctx.Done():
return false
default:
return true
}
}
select {
case <-ctx.Done():
return false
case <-time.After(d):
return true
}
}
+367
View File
@@ -0,0 +1,367 @@
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/time/rate"
)
const (
quotaActionBlock = "block"
quotaActionThrottle = "throttle"
)
var errDataQuotaExceeded = errors.New("data quota exceeded")
func normalizeQuotaAction(v string) string {
if strings.EqualFold(strings.TrimSpace(v), quotaActionThrottle) {
return quotaActionThrottle
}
return quotaActionBlock
}
func quotaThrottleMbpsOrDefault(v int) int {
if v <= 0 {
return 1
}
return v
}
type sshTrafficDelta struct {
Uplink int64
Downlink int64
}
var (
sshTrafficPersistenceMu sync.Mutex
sshTrafficDirtyMu sync.Mutex
sshTrafficDirty = make(map[string]*UserState)
)
func markSSHUserTrafficDirty(u *UserState) {
if u == nil || strings.TrimSpace(u.Cfg.Username) == "" {
return
}
sshTrafficDirtyMu.Lock()
sshTrafficDirty[u.Cfg.Username] = u
sshTrafficDirtyMu.Unlock()
}
func takeSSHUserTrafficDirty() map[string]*UserState {
sshTrafficDirtyMu.Lock()
dirty := sshTrafficDirty
sshTrafficDirty = make(map[string]*UserState)
sshTrafficDirtyMu.Unlock()
return dirty
}
func clearSSHUserTrafficDirty(username string, u *UserState) {
sshTrafficDirtyMu.Lock()
if current := sshTrafficDirty[username]; u == nil || current == u {
delete(sshTrafficDirty, username)
}
sshTrafficDirtyMu.Unlock()
}
func (s *Store) AddSSHUserTrafficBatch(ctx context.Context, deltas map[string]sshTrafficDelta) error {
if s == nil || len(deltas) == 0 {
return nil
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
stmt, err := tx.PrepareContext(ctx, `
UPDATE ssh_users SET
total_uplink_bytes = GREATEST(total_uplink_bytes + GREATEST($2::BIGINT, 0), 0),
total_downlink_bytes = GREATEST(total_downlink_bytes + GREATEST($3::BIGINT, 0), 0)
WHERE username = $1`)
if err != nil {
_ = tx.Rollback()
return err
}
defer stmt.Close()
for username, d := range deltas {
if strings.TrimSpace(username) == "" || (d.Uplink == 0 && d.Downlink == 0) {
continue
}
if _, err := stmt.ExecContext(ctx, username, d.Uplink, d.Downlink); err != nil {
_ = tx.Rollback()
return err
}
}
return tx.Commit()
}
func (s *Store) ResetSSHUserTraffic(ctx context.Context, username string) error {
if s == nil || strings.TrimSpace(username) == "" {
return nil
}
_, err := s.db.ExecContext(ctx, `
UPDATE ssh_users
SET total_uplink_bytes = 0, total_downlink_bytes = 0
WHERE username = $1`, username)
return err
}
func initSSHRuntimeUsage(u *UserState, uplink, downlink int64) {
if u == nil {
return
}
if uplink < 0 {
uplink = 0
}
if downlink < 0 {
downlink = 0
}
atomic.StoreInt64(&u.TotalUplinkBytes, uplink)
atomic.StoreInt64(&u.TotalDownlinkBytes, downlink)
atomic.StoreInt64(&u.totalBytes, uplink+downlink)
atomic.StoreInt64(&u.pendingUplinkBytes, 0)
atomic.StoreInt64(&u.pendingDownlinkBytes, 0)
}
func resetSSHRuntimeUsageLocked(u *UserState) {
if u == nil {
return
}
initSSHRuntimeUsage(u, 0, 0)
u.mu.Lock()
u.quotaLimiter = nil
u.quotaLimiterMbps = 0
u.mu.Unlock()
}
func resetSSHRuntimeUsage(username string) {
u, ok := userMgr.Get(username)
if !ok || u == nil {
return
}
u.trafficMu.Lock()
resetSSHRuntimeUsageLocked(u)
clearSSHUserTrafficDirty(username, u)
u.trafficMu.Unlock()
}
func resetSSHUserTrafficAccounting(ctx context.Context, store *Store, username string) error {
u, _ := userMgr.Get(username)
if u != nil {
u.trafficMu.Lock()
defer u.trafficMu.Unlock()
}
sshTrafficPersistenceMu.Lock()
defer sshTrafficPersistenceMu.Unlock()
if err := store.ResetSSHUserTraffic(ctx, username); err != nil {
return err
}
if u != nil {
resetSSHRuntimeUsageLocked(u)
clearSSHUserTrafficDirty(username, u)
}
return nil
}
func sshUserQuotaBlocked(u *UserState) bool {
if u == nil {
return false
}
u.mu.Lock()
quota := u.Cfg.DataQuotaBytes
action := normalizeQuotaAction(u.Cfg.QuotaAction)
u.mu.Unlock()
return quota > 0 && action == quotaActionBlock && atomic.LoadInt64(&u.totalBytes) >= quota
}
func sshQuotaLimiter(u *UserState, mbps int) *rate.Limiter {
mbps = quotaThrottleMbpsOrDefault(mbps)
u.mu.Lock()
defer u.mu.Unlock()
if u.quotaLimiter == nil || u.quotaLimiterMbps != mbps {
bps := mbpsToBytesPerSec(mbps)
burst := int(bps)
if burst < copyBufSize {
burst = copyBufSize
}
u.quotaLimiter = rate.NewLimiter(rate.Limit(bps), burst)
u.quotaLimiterMbps = mbps
}
return u.quotaLimiter
}
func reserveSSHUserBytes(u *UserState, requested int) (allowed int, throttle *rate.Limiter, stopAfter bool) {
if u == nil || requested <= 0 {
return 0, nil, false
}
u.mu.Lock()
quota := u.Cfg.DataQuotaBytes
action := normalizeQuotaAction(u.Cfg.QuotaAction)
throttleMbps := u.Cfg.QuotaThrottleMbps
u.mu.Unlock()
n := int64(requested)
if quota <= 0 {
atomic.AddInt64(&u.totalBytes, n)
return requested, nil, false
}
if action == quotaActionThrottle {
previous := atomic.AddInt64(&u.totalBytes, n) - n
if previous+n > quota {
return requested, sshQuotaLimiter(u, throttleMbps), false
}
return requested, nil, false
}
for {
used := atomic.LoadInt64(&u.totalBytes)
remaining := quota - used
if remaining <= 0 {
return 0, nil, true
}
take := n
if take > remaining {
take = remaining
}
if atomic.CompareAndSwapInt64(&u.totalBytes, used, used+take) {
return int(take), nil, take < n || used+take >= quota
}
}
}
func finishSSHUserReservation(u *UserState, uplink bool, reserved, written int) {
if u == nil || reserved <= 0 {
return
}
if written < 0 {
written = 0
}
if written > reserved {
written = reserved
}
if written < reserved {
atomic.AddInt64(&u.totalBytes, -int64(reserved-written))
}
if written == 0 {
return
}
if uplink {
atomic.AddInt64(&u.TotalUplinkBytes, int64(written))
atomic.AddInt64(&u.pendingUplinkBytes, int64(written))
} else {
atomic.AddInt64(&u.TotalDownlinkBytes, int64(written))
atomic.AddInt64(&u.pendingDownlinkBytes, int64(written))
}
markSSHUserTrafficDirty(u)
}
type sshQuotaWriter struct {
w io.Writer
user *UserState
uplink bool
ctx context.Context
}
func (qw sshQuotaWriter) Write(p []byte) (int, error) {
if qw.user != nil {
qw.user.trafficMu.RLock()
defer qw.user.trafficMu.RUnlock()
}
allowed, quotaLimiter, stopAfter := reserveSSHUserBytes(qw.user, len(p))
if allowed <= 0 {
return 0, errDataQuotaExceeded
}
if quotaLimiter != nil {
ctx := qw.ctx
if ctx == nil {
ctx = context.Background()
}
if err := quotaLimiter.WaitN(ctx, allowed); err != nil {
finishSSHUserReservation(qw.user, qw.uplink, allowed, 0)
return 0, err
}
}
n, err := qw.w.Write(p[:allowed])
finishSSHUserReservation(qw.user, qw.uplink, allowed, n)
if err != nil {
return n, err
}
if stopAfter || allowed < len(p) {
return n, errDataQuotaExceeded
}
return n, nil
}
func startSSHUserTrafficFlusher(store *Store) {
if store == nil {
return
}
go func() {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for range ticker.C {
flushSSHUserTraffic(store)
}
}()
}
func flushSSHUserTraffic(store *Store) {
if store == nil {
return
}
sshTrafficPersistenceMu.Lock()
defer sshTrafficPersistenceMu.Unlock()
deltas := make(map[string]sshTrafficDelta)
states := make(map[string]*UserState)
for username, u := range takeSSHUserTrafficDirty() {
if u == nil || strings.TrimSpace(username) == "" {
continue
}
up := atomic.SwapInt64(&u.pendingUplinkBytes, 0)
down := atomic.SwapInt64(&u.pendingDownlinkBytes, 0)
if up == 0 && down == 0 {
continue
}
deltas[username] = sshTrafficDelta{Uplink: up, Downlink: down}
states[username] = u
}
if len(deltas) == 0 {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := store.AddSSHUserTrafficBatch(ctx, deltas); err != nil {
log.Printf("ssh traffic flush failed: %v", err)
for username, d := range deltas {
if u := states[username]; u != nil {
atomic.AddInt64(&u.pendingUplinkBytes, d.Uplink)
atomic.AddInt64(&u.pendingDownlinkBytes, d.Downlink)
markSSHUserTrafficDirty(u)
}
}
}
}
func validateQuotaConfig(quotaBytes int64, action string, throttleMbps int) error {
if quotaBytes < 0 {
return fmt.Errorf("data_quota_bytes must be non-negative")
}
rawAction := strings.ToLower(strings.TrimSpace(action))
if rawAction != "" && rawAction != quotaActionBlock && rawAction != quotaActionThrottle {
return fmt.Errorf("quota_action must be block or throttle")
}
if throttleMbps < 0 {
return fmt.Errorf("quota_throttle_mbps must be non-negative")
}
if throttleMbps > 1000000 {
return fmt.Errorf("quota_throttle_mbps must not exceed 1000000")
}
return nil
}
+870
View File
@@ -0,0 +1,870 @@
package main
import (
"context"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/time/rate"
)
func TestNativeClientMaxConnectionsAndBatchedActiveDelta(t *testing.T) {
oldStore := statsStore
statsStore = &Store{}
defer func() { statsStore = oldStore }()
const uuid = "11111111-1111-1111-1111-111111111111"
m := &XrayManager{
nativeQuotaByUUID: map[string]*xrayNativeQuotaState{
uuid: {maxConns: 1, generation: 1},
},
}
state := m.nativeQuotaState(uuid)
release, acquiredState, ok := m.acquireNativeClientConnection(uuid, "user@example")
if !ok || release == nil {
t.Fatal("first native connection was rejected")
}
if acquiredState != state {
t.Fatal("connection lease did not retain the authenticated policy state")
}
if _, _, ok := m.acquireNativeClientConnection(uuid, "user@example"); ok {
t.Fatal("connection above max_conns was accepted")
}
m.nativeDBMu.Lock()
pending := m.nativeActivePending[uuid]
m.nativeDBMu.Unlock()
if pending.Delta != 1 || !pending.Connected || pending.State != state {
t.Fatalf("connect was not queued for batch persistence: %+v", pending)
}
release()
release() // idempotent release must not underflow counters.
m.nativeDBMu.Lock()
pending = m.nativeActivePending[uuid]
m.nativeDBMu.Unlock()
if pending.Delta != 0 || !pending.Connected {
t.Fatalf("connect/disconnect batch should net to zero and retain last-active: %+v", pending)
}
state.mu.Lock()
active := state.activeConns
state.mu.Unlock()
if active != 0 {
t.Fatalf("active connection count = %d, want 0", active)
}
release2, _, ok := m.acquireNativeClientConnection(uuid, "user@example")
if !ok {
t.Fatal("slot was not reusable after release")
}
release2()
}
func TestNativeOnlineUsersAreKeyedByUUID(t *testing.T) {
oldStore := statsStore
statsStore = nil
defer func() { statsStore = oldStore }()
m := &XrayManager{}
m.recordNativeConnect("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "shared@example", nil)
m.recordNativeConnect("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "shared@example", nil)
if got := m.CountOnlineUsers(); got != 2 {
t.Fatalf("online UUID count = %d, want 2 for two UUIDs sharing one email", got)
}
m.statsMu.RLock()
_, first := m.statsByEmail["aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"]
_, second := m.statsByEmail["bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"]
m.statsMu.RUnlock()
if !first || !second {
t.Fatal("native runtime stats were not stored under canonical UUID keys")
}
}
func TestNativeExpiryRejectsAndDisconnectsClient(t *testing.T) {
const uuid = "cccccccc-cccc-cccc-cccc-cccccccccccc"
state := &xrayNativeQuotaState{hasExpiry: true, expiresAt: time.Now().Add(time.Hour), generation: 1}
m := &XrayManager{nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: state}}
closer := &closeTrackingReader{}
release, _, ok := m.acquireNativeClientConnection(uuid, "expiry@example", closer)
if !ok {
t.Fatal("unexpired client was rejected")
}
m.disconnectNativeClient(uuid)
if !closer.closed.Load() {
t.Fatal("active native client was not closed during revocation")
}
release()
state.mu.Lock()
state.expiresAt = time.Now().Add(-time.Second)
state.mu.Unlock()
if reason := m.nativeClientAccessDenied(uuid); reason != "expired" {
t.Fatalf("expired client denial = %q, want expired", reason)
}
if _, _, ok := m.acquireNativeClientConnection(uuid, "expiry@example"); ok {
t.Fatal("expired client acquired a new connection")
}
}
func TestQuotaAndExpiryValidationRejectsUnsafeInput(t *testing.T) {
if err := validateQuotaConfig(1, "typo", 1); err == nil {
t.Fatal("unknown quota action was accepted")
}
if err := validateQuotaConfig(1, quotaActionBlock, -1); err == nil {
t.Fatal("negative throttle setting was accepted")
}
if _, err := parseOptionalXrayExpiry("not-a-date"); err == nil {
t.Fatal("invalid Xray expiry was accepted")
}
if exp, err := parseOptionalXrayExpiry(""); err != nil || exp != nil {
t.Fatalf("empty Xray expiry = (%v, %v), want nil, nil", exp, err)
}
}
func TestRemoveNativeQuotaPolicyPrunesPendingMaps(t *testing.T) {
m := &XrayManager{
nativeQuotaByUUID: map[string]*xrayNativeQuotaState{
"gone": {generation: 1},
},
nativeTrafficPending: map[string]xrayPendingTraffic{
"gone": {Uplink: 10},
},
nativeActivePending: map[string]xrayPendingActive{
"gone": {Delta: 1},
},
}
m.removeNativeQuotaPolicy("gone")
if m.nativeQuotaState("gone") != nil {
t.Fatal("quota policy was not removed")
}
m.nativeDBMu.Lock()
_, trafficExists := m.nativeTrafficPending["gone"]
_, activeExists := m.nativeActivePending["gone"]
m.nativeDBMu.Unlock()
if trafficExists || activeExists {
t.Fatal("deleted UUID remained in a pending persistence map")
}
}
func TestNativeCounterIsBoundedAndReleaseIsIdempotent(t *testing.T) {
var active atomicInt64ForTest
release1, ok := acquireNativeCounter(&active.Int64, 2)
if !ok {
t.Fatal("first slot rejected")
}
release2, ok := acquireNativeCounter(&active.Int64, 2)
if !ok {
t.Fatal("second slot rejected")
}
if _, ok := acquireNativeCounter(&active.Int64, 2); ok {
t.Fatal("slot above limit accepted")
}
release1()
release1()
if got := active.Load(); got != 1 {
t.Fatalf("active after double release = %d, want 1", got)
}
release2()
if got := active.Load(); got != 0 {
t.Fatalf("active after releases = %d, want 0", got)
}
}
// Embedding keeps the test declaration readable while still passing the exact
// atomic.Int64 type required by acquireNativeCounter.
type atomicInt64ForTest struct{ Int64 atomic.Int64 }
func (a *atomicInt64ForTest) Load() int64 { return a.Int64.Load() }
func TestTrackedNativeConnectionsAreClosedOnShutdown(t *testing.T) {
oldAccepting := nativeTransportAccepting.Load()
defer nativeTransportAccepting.Store(oldAccepting)
beginNativeTransportAccepting()
before := nativeTransportConnections.Load()
serverSide, clientSide := net.Pipe()
defer clientSide.Close()
wrapped, ok := wrapTrackedNativeTransportConn(serverSide)
if !ok {
t.Fatal("tracked connection was rejected")
}
if got := nativeTransportConnections.Load(); got != before+1 {
t.Fatalf("transport count = %d, want %d", got, before+1)
}
stopNativeTransportAccepting()
closeAllNativeTransportConnections()
_ = clientSide.SetReadDeadline(time.Now().Add(time.Second))
if _, err := clientSide.Read(make([]byte, 1)); err == nil {
t.Fatal("peer remained open after native shutdown")
}
if err := wrapped.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
t.Fatalf("second close returned unexpected error: %v", err)
}
if got := nativeTransportConnections.Load(); got != before {
t.Fatalf("transport count after shutdown = %d, want %d", got, before)
}
}
func TestXHTTPSessionsIgnoreLegacyGlobalCapAndReleaseCounters(t *testing.T) {
before := nativeXHTTPSessions.Load()
ib := &nativeInbound{xhttpMaxBufferedPosts: 2}
for _, id := range []string{"one", "two"} {
if sess := ib.upsertXHTTPSession(httptest.NewRecorder(), id); sess == nil {
t.Fatalf("session %q was rejected", id)
}
}
if got := nativeXHTTPSessions.Load(); got != before+2 {
t.Fatalf("global XHTTP sessions = %d, want %d", got, before+2)
}
ib.closeAllXHTTPSessions()
if got := nativeXHTTPSessions.Load(); got != before {
t.Fatalf("global XHTTP sessions after close = %d, want %d", got, before)
}
ib.xhttpMu.Lock()
remaining := len(ib.xhttpSessions)
ib.xhttpMu.Unlock()
if remaining != 0 {
t.Fatalf("inbound retained %d XHTTP sessions", remaining)
}
}
func TestXHTTPSessionSafetyWindowIsAboveProductionScale(t *testing.T) {
if got := (&nativeInbound{}).xhttpMaxActiveSessions(); got != fixedNativeMaxXHTTPSessions {
t.Fatalf("XHTTP session safety window = %d, want %d", got, fixedNativeMaxXHTTPSessions)
}
if got := nativeXHTTPSessionLimit(); got < 8_000 {
t.Fatalf("XHTTP session safety window = %d, want room for at least 8K users", got)
}
}
func TestNativeHTTP2StreamsUseFiniteTransportBackpressure(t *testing.T) {
if got := nativeHTTP2MaxConcurrentStreams(); got != fixedNativeHTTP2ConcurrentStreams {
t.Fatalf("HTTP/2 stream setting = %d, want %d", got, fixedNativeHTTP2ConcurrentStreams)
}
if got := nativeHTTP2MaxConcurrentStreams(); got < 1024 {
t.Fatalf("HTTP/2 stream setting = %d, too small for XHTTP packet bursts", got)
}
if got := nativeMuxMaxSessionLimit(); got != 64 {
t.Fatalf("per-transport Mux session guard = %d, want 64", got)
}
}
func TestXHTTPHandlerDoesNotApplyWebRequestCeiling(t *testing.T) {
ib := &nativeInbound{transport: "xhttp", path: "/"}
req := httptest.NewRequest(http.MethodOptions, "/", nil)
rec := httptest.NewRecorder()
ib.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("XHTTP OPTIONS at legacy request ceiling = %d, want 200", rec.Code)
}
}
func TestXHTTPHandlerSafetySlotIsReleased(t *testing.T) {
before := nativeXHTTPRequests.Load()
ib := &nativeInbound{transport: "xhttp", path: "/"}
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
ib.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("empty XHTTP request status = %d, want 400", rec.Code)
}
if got := nativeXHTTPRequests.Load(); got != before {
t.Fatalf("XHTTP handler counter after return = %d, want %d", got, before)
}
}
func TestPersistedXHTTPAdmissionTuningIsAlwaysUnlimited(t *testing.T) {
got := normalizeNativeXrayTuning(&XrayNativeTuning{
MuxGlobalSessions: 8192,
MaxConcurrentConnections: 4096,
MaxConcurrentXHTTPRequests: 8192,
XHTTPMaxSessions: 4096,
})
if got.MuxGlobalSessions != 8192 ||
got.MaxConcurrentConnections != -1 ||
got.MaxConcurrentXHTTPRequests != defaultNativeMaxXHTTPRequests ||
got.XHTTPMaxSessions != -1 {
t.Fatalf("persisted admission limits were not removed: %+v", got)
}
}
func TestXHTTPMetadataLengthIsBoundedBeforeSessionAllocation(t *testing.T) {
ib := &nativeInbound{transport: "xhttp", path: "/"}
req := httptest.NewRequest("GET", "/"+strings.Repeat("a", nativeXHTTPMaxSessionIDBytes+1), nil)
rec := httptest.NewRecorder()
ib.ServeHTTP(rec, req)
if rec.Code != 400 {
t.Fatalf("oversized XHTTP session id status = %d, want 400", rec.Code)
}
ib.xhttpMu.Lock()
sessions := len(ib.xhttpSessions)
ib.xhttpMu.Unlock()
if sessions != 0 {
t.Fatalf("oversized metadata allocated %d sessions", sessions)
}
}
func TestXHTTPUploadMemoryIsReleasedOnReadAndClose(t *testing.T) {
before := nativeXHTTPBufferedBytes.Load()
q := newNativeXHTTPUploadQueue(4, 512)
accounted := nativeXHTTPAccountedPacketBytes(4)
lease, ok := acquireNativeXHTTPMemory(accounted)
if !ok {
t.Fatal("failed to reserve XHTTP test memory")
}
if err := q.push(context.Background(), nativeXHTTPPacket{Payload: []byte("test"), Seq: 0}, lease); err != nil {
lease.release()
t.Fatalf("queue push failed: %v", err)
}
lease.release() // transferred leases are a no-op for the producer.
if got := nativeXHTTPBufferedBytes.Load(); got != before+accounted {
t.Fatalf("buffered bytes after push = %d, want %d", got, before+accounted)
}
buf := make([]byte, 4)
if n, err := q.Read(buf); err != nil || n != 4 || string(buf) != "test" {
t.Fatalf("queue read = (%d, %v, %q), want (4, nil, test)", n, err, string(buf))
}
if got := nativeXHTTPBufferedBytes.Load(); got != before {
t.Fatalf("buffered bytes after read = %d, want %d", got, before)
}
lease, ok = acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(3))
if !ok {
t.Fatal("failed to reserve second XHTTP test memory")
}
if err := q.push(context.Background(), nativeXHTTPPacket{Payload: []byte("xyz"), Seq: 2}, lease); err != nil {
lease.release()
t.Fatalf("second queue push failed: %v", err)
}
lease.release()
q.close()
if got := nativeXHTTPBufferedBytes.Load(); got != before {
t.Fatalf("buffered bytes after close = %d, want %d", got, before)
}
}
func TestXHTTPUploadQueueEnforcesPerSessionByteBudget(t *testing.T) {
before := nativeXHTTPBufferedBytes.Load()
q := newNativeXHTTPUploadQueue(4, nativeXHTTPMinPacketAccountingBytes-1)
defer q.close()
lease, ok := acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(5))
if !ok {
t.Fatal("failed to reserve XHTTP test memory")
}
defer lease.release()
err := q.push(context.Background(), nativeXHTTPPacket{Payload: make([]byte, 5)}, lease)
if !errors.Is(err, errNativeXHTTPUploadBufferFull) {
t.Fatalf("oversized queue push error = %v, want buffer limit", err)
}
lease.release()
if got := nativeXHTTPBufferedBytes.Load(); got != before {
t.Fatalf("rejected payload retained %d bytes, baseline %d", got, before)
}
}
func TestXHTTPUploadQueueBackpressuresInsteadOfRejectingBurst(t *testing.T) {
before := nativeXHTTPBufferedBytes.Load()
q := newNativeXHTTPUploadQueue(2, nativeXHTTPMinPacketAccountingBytes)
defer q.close()
first, ok := acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(4))
if !ok {
t.Fatal("failed to reserve first XHTTP payload")
}
if err := q.push(context.Background(), nativeXHTTPPacket{Payload: []byte("one!"), Seq: 0}, first); err != nil {
first.release()
t.Fatalf("first queue push failed: %v", err)
}
first.release()
second, ok := acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(4))
if !ok {
t.Fatal("failed to reserve second XHTTP payload")
}
done := make(chan error, 1)
go func() {
done <- q.push(context.Background(), nativeXHTTPPacket{Payload: []byte("two!"), Seq: 1}, second)
}()
select {
case err := <-done:
second.release()
t.Fatalf("second burst packet did not backpressure: %v", err)
case <-time.After(25 * time.Millisecond):
}
buf := make([]byte, 4)
if n, err := q.Read(buf); err != nil || n != 4 || string(buf) != "one!" {
second.release()
t.Fatalf("first queue read = (%d, %v, %q)", n, err, string(buf))
}
select {
case err := <-done:
if err != nil {
second.release()
t.Fatalf("backpressured packet failed after space released: %v", err)
}
second.release()
case <-time.After(time.Second):
second.release()
t.Fatal("backpressured packet did not resume")
}
q.close()
if got := nativeXHTTPBufferedBytes.Load(); got != before {
t.Fatalf("backpressure test leaked %d buffered bytes (baseline %d)", got, before)
}
}
func TestXHTTPGlobalMemoryBackpressureWakesWaitersFIFO(t *testing.T) {
before := nativeXHTTPBufferedBytes.Load()
fillBytes := nativeXHTTPMaxBufferedGlobalBytes - before
filler, ok := acquireNativeXHTTPMemory(fillBytes)
if !ok {
t.Fatal("failed to fill XHTTP memory budget for waiter test")
}
defer filler.release()
type result struct {
lease *nativeXHTTPMemoryLease
err error
}
startWaiter := func() <-chan result {
done := make(chan result, 1)
go func() {
lease, err := acquireNativeXHTTPMemoryContext(context.Background(), nativeXHTTPMinPacketAccountingBytes)
done <- result{lease: lease, err: err}
}()
return done
}
waitForWaiters := func(want int) {
t.Helper()
deadline := time.Now().Add(time.Second)
for {
nativeXHTTPMemoryWait.Lock()
got := nativeXHTTPMemoryWait.queued
nativeXHTTPMemoryWait.Unlock()
if got == want {
return
}
if time.Now().After(deadline) {
t.Fatalf("memory waiters = %d, want %d", got, want)
}
time.Sleep(time.Millisecond)
}
}
firstDone := startWaiter()
waitForWaiters(1)
secondDone := startWaiter()
waitForWaiters(2)
filler.shrink(fillBytes - nativeXHTTPMinPacketAccountingBytes)
first := <-firstDone
if first.err != nil || first.lease == nil {
t.Fatalf("first memory waiter = (%v, %v)", first.lease, first.err)
}
select {
case second := <-secondDone:
if second.lease != nil {
second.lease.release()
}
t.Fatalf("second waiter woke before FIFO capacity was released: %v", second.err)
case <-time.After(25 * time.Millisecond):
}
first.lease.release()
select {
case second := <-secondDone:
if second.err != nil || second.lease == nil {
t.Fatalf("second memory waiter = (%v, %v)", second.lease, second.err)
}
second.lease.release()
case <-time.After(time.Second):
t.Fatal("second memory waiter did not wake after first released")
}
filler.release()
if got := nativeXHTTPBufferedBytes.Load(); got != before {
t.Fatalf("FIFO waiter test leaked %d buffered bytes (baseline %d)", got, before)
}
}
func TestXHTTPReassemblyHasNoPacketRequestCountCeiling(t *testing.T) {
before := nativeXHTTPBufferedBytes.Load()
q := newNativeXHTTPUploadQueue(1, 4*nativeXHTTPMinPacketAccountingBytes)
defer q.close()
done := make(chan error, 1)
go func() {
for _, seq := range []uint64{3, 2, 1, 0} {
lease, ok := acquireNativeXHTTPMemory(nativeXHTTPAccountedPacketBytes(1))
if !ok {
done <- errors.New("could not reserve packet memory")
return
}
err := q.push(context.Background(), nativeXHTTPPacket{Payload: []byte{byte('a' + seq)}, Seq: seq}, lease)
lease.release()
if err != nil {
done <- err
return
}
}
done <- nil
}()
buf := make([]byte, 1)
for want := byte('a'); want <= byte('d'); want++ {
n, err := q.Read(buf)
if err != nil || n != 1 || buf[0] != want {
t.Fatalf("reassembled packet = (%d, %v, %q), want %q", n, err, buf[:n], []byte{want})
}
}
if err := <-done; err != nil {
t.Fatalf("out-of-order burst was rejected: %v", err)
}
q.close()
if got := nativeXHTTPBufferedBytes.Load(); got != before {
t.Fatalf("reassembly test leaked %d buffered bytes (baseline %d)", got, before)
}
}
func TestXHTTPBodyReservationUsesActualContentLength(t *testing.T) {
ib := &nativeInbound{xhttpMaxEachPostBytes: 1_000_000}
req := httptest.NewRequest(http.MethodPost, "/session/0", strings.NewReader("small"))
if got := ib.xhttpUploadReservationBytes(req); got != nativeXHTTPMinPacketAccountingBytes {
t.Fatalf("body reservation = %d, want minimum accounted packet size", got)
}
req.ContentLength = -1
if got := ib.xhttpUploadReservationBytes(req); got != 1_000_000 {
t.Fatalf("chunked body reservation = %d, want configured maximum", got)
}
}
func TestNativeQuotaResetWaitsForInFlightTraffic(t *testing.T) {
const uuid = "22222222-2222-2222-2222-222222222222"
state := &xrayNativeQuotaState{usedBytes: 123, generation: 1}
m := &XrayManager{nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: state}}
state.trafficMu.RLock()
done := make(chan struct{})
go func() {
m.resetNativeQuotaUsage(uuid)
close(done)
}()
select {
case <-done:
state.trafficMu.RUnlock()
t.Fatal("traffic reset crossed an in-flight writer boundary")
case <-time.After(25 * time.Millisecond):
}
state.trafficMu.RUnlock()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("traffic reset did not complete after writer released")
}
state.mu.Lock()
used, generation := state.usedBytes, state.generation
state.mu.Unlock()
if used != 0 || generation != 2 {
t.Fatalf("reset state = used %d generation %d, want 0/2", used, generation)
}
}
func TestNativeRateWaitCanBeCanceled(t *testing.T) {
lim := rate.NewLimiter(1, 1)
if !lim.AllowN(time.Now(), 1) {
t.Fatal("failed to consume initial limiter token")
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := waitNativeRate(ctx, lim, 1); !errors.Is(err, context.Canceled) {
t.Fatalf("waitNativeRate error = %v, want context.Canceled", err)
}
}
func TestSSHDirtyQueueDoesNotScanInactiveUsers(t *testing.T) {
sshTrafficDirtyMu.Lock()
old := sshTrafficDirty
sshTrafficDirty = make(map[string]*UserState)
sshTrafficDirtyMu.Unlock()
defer func() {
sshTrafficDirtyMu.Lock()
sshTrafficDirty = old
sshTrafficDirtyMu.Unlock()
}()
active := &UserState{Cfg: UserConfig{Username: "active"}}
inactive := &UserState{Cfg: UserConfig{Username: "inactive"}}
markSSHUserTrafficDirty(active)
dirty := takeSSHUserTrafficDirty()
if len(dirty) != 1 || dirty["active"] != active {
t.Fatalf("dirty queue = %#v", dirty)
}
if _, found := dirty[inactive.Cfg.Username]; found {
t.Fatal("inactive user appeared in dirty queue")
}
if next := takeSSHUserTrafficDirty(); len(next) != 0 {
t.Fatalf("dirty queue was not drained: %#v", next)
}
}
func TestOldNativeConnectionCannotDecrementReplacementAccount(t *testing.T) {
oldStore := statsStore
statsStore = &Store{}
defer func() { statsStore = oldStore }()
const uuid = "replacement-active-user"
oldState := &xrayNativeQuotaState{maxConns: 1, generation: 1}
m := &XrayManager{nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: oldState}}
release, acquiredState, ok := m.acquireNativeClientConnection(uuid, "old@example")
if !ok || acquiredState != oldState {
t.Fatal("failed to acquire old account connection")
}
// Discard the old account's successful connect delta so this assertion only
// measures what happens when that old connection later disconnects.
m.nativeDBMu.Lock()
m.nativeActivePending = nil
m.nativeDBMu.Unlock()
newState := &xrayNativeQuotaState{maxConns: 1, generation: 1}
m.nativeQuotaMu.Lock()
m.nativeQuotaByUUID[uuid] = newState
m.nativeQuotaMu.Unlock()
release()
m.nativeDBMu.Lock()
pending := m.nativeActivePending[uuid]
m.nativeDBMu.Unlock()
if pending.Delta != 0 || pending.State != nil {
t.Fatalf("old disconnect was queued against replacement account: %+v", pending)
}
newState.mu.Lock()
active := newState.activeConns
newState.mu.Unlock()
if active != 0 {
t.Fatalf("replacement account active count changed to %d", active)
}
}
func TestOldNativeTrafficCannotAttachToReplacementAccount(t *testing.T) {
oldStore := statsStore
statsStore = &Store{}
defer func() { statsStore = oldStore }()
const uuid = "replacement-traffic-user"
oldState := &xrayNativeQuotaState{generation: 1}
newState := &xrayNativeQuotaState{generation: 1}
m := &XrayManager{nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: oldState}}
meter := newTrafficMeter(uuid, "old@example", true, oldState)
meter.n = 1234
m.nativeQuotaMu.Lock()
m.nativeQuotaByUUID[uuid] = newState
m.nativeQuotaMu.Unlock()
oldMgr := xrayMgr
xrayMgr = m
defer func() { xrayMgr = oldMgr }()
meter.flush()
m.nativeDBMu.Lock()
pending := m.nativeTrafficPending[uuid]
m.nativeDBMu.Unlock()
if pending.Uplink != 0 || pending.Downlink != 0 || pending.State != nil {
t.Fatalf("old traffic was queued against replacement account: %+v", pending)
}
m.statsMu.RLock()
stat := m.statsByEmail["old@example"]
m.statsMu.RUnlock()
if stat.Uplink != 0 || stat.Downlink != 0 {
t.Fatalf("old traffic resurfaced in runtime stats: %+v", stat)
}
}
func TestNativeFlusherDropsMismatchedPolicyIdentity(t *testing.T) {
oldStore := statsStore
statsStore = &Store{}
defer func() { statsStore = oldStore }()
const uuid = "identity-prune-user"
oldState := &xrayNativeQuotaState{generation: 1}
newState := &xrayNativeQuotaState{generation: 1}
m := &XrayManager{
nativeQuotaByUUID: map[string]*xrayNativeQuotaState{uuid: newState},
nativeTrafficPending: map[string]xrayPendingTraffic{
uuid: {Email: "old@example", Uplink: 99, State: oldState},
},
nativeActivePending: map[string]xrayPendingActive{
uuid: {Email: "old@example", Delta: -1, State: oldState},
},
}
m.flushNativeStatsToDB()
m.nativeDBMu.Lock()
defer m.nativeDBMu.Unlock()
if len(m.nativeTrafficPending) != 0 || len(m.nativeActivePending) != 0 {
t.Fatalf("mismatched pending deltas survived prune: traffic=%v active=%v", m.nativeTrafficPending, m.nativeActivePending)
}
}
func TestNativeMuxFinishRunsOnce(t *testing.T) {
var calls atomic.Int32
s := &nativeMuxSession{
closed: make(chan struct{}),
uplink: make(chan nativeMuxUplinkItem),
onClose: func(*nativeMuxSession) {
calls.Add(1)
},
}
var wg sync.WaitGroup
for i := 0; i < 32; i++ {
wg.Add(1)
go func() {
defer wg.Done()
s.finish()
}()
}
wg.Wait()
if got := calls.Load(); got != 1 {
t.Fatalf("mux onClose called %d times, want 1", got)
}
}
type closeTrackingReader struct {
closed atomic.Bool
}
func (r *closeTrackingReader) Read([]byte) (int, error) { return 0, io.EOF }
func (r *closeTrackingReader) Close() error {
r.closed.Store(true)
return nil
}
func TestNativeXHTTPQueueCloseClosesQueuedStreamReader(t *testing.T) {
q := newNativeXHTTPUploadQueue(1, 1024)
r := &closeTrackingReader{}
if err := q.push(context.Background(), nativeXHTTPPacket{Reader: r}, nil); err != nil {
t.Fatalf("queue stream reader: %v", err)
}
q.close()
if !r.closed.Load() {
t.Fatal("queued stream reader was not closed during queue shutdown")
}
}
func TestNativeXHTTPQueueSkipsEmptyPacketsWithoutZeroProgressRead(t *testing.T) {
before := nativeXHTTPBufferedBytes.Load()
q := newNativeXHTTPUploadQueue(2, 2*nativeXHTTPMinPacketAccountingBytes)
defer q.close()
for seq, payload := range [][]byte{nil, []byte("x")} {
accounted := nativeXHTTPAccountedPacketBytes(int64(len(payload)))
lease, ok := acquireNativeXHTTPMemory(accounted)
if !ok {
t.Fatal("failed to reserve packet memory")
}
if err := q.push(context.Background(), nativeXHTTPPacket{Payload: payload, Seq: uint64(seq)}, lease); err != nil {
lease.release()
t.Fatalf("queue packet %d: %v", seq, err)
}
lease.release()
}
buf := make([]byte, 1)
n, err := q.Read(buf)
if err != nil || n != 1 || string(buf[:n]) != "x" {
t.Fatalf("queue read after empty packet = (%d, %v, %q), want (1, nil, x)", n, err, buf[:n])
}
q.close()
if got := nativeXHTTPBufferedBytes.Load(); got != before {
t.Fatalf("empty-packet test leaked %d buffered bytes (baseline %d)", got, before)
}
}
type deadlineUnblockingResponseWriter struct {
header http.Header
writeStart chan struct{}
unblock chan struct{}
startOnce sync.Once
unblockOnce sync.Once
}
func newDeadlineUnblockingResponseWriter() *deadlineUnblockingResponseWriter {
return &deadlineUnblockingResponseWriter{
header: make(http.Header),
writeStart: make(chan struct{}),
unblock: make(chan struct{}),
}
}
func (w *deadlineUnblockingResponseWriter) Header() http.Header { return w.header }
func (w *deadlineUnblockingResponseWriter) WriteHeader(int) {}
func (w *deadlineUnblockingResponseWriter) Flush() {}
func (w *deadlineUnblockingResponseWriter) Write([]byte) (int, error) {
w.startOnce.Do(func() { close(w.writeStart) })
<-w.unblock
return 0, os.ErrDeadlineExceeded
}
func (w *deadlineUnblockingResponseWriter) SetWriteDeadline(deadline time.Time) error {
if !deadline.IsZero() && !deadline.After(time.Now().Add(10*time.Millisecond)) {
w.unblockOnce.Do(func() { close(w.unblock) })
}
return nil
}
func TestNativeXHTTPResponseCloseInterruptsStalledWrite(t *testing.T) {
underlying := newDeadlineUnblockingResponseWriter()
writer := newNativeXHTTPResponseWriter(underlying)
writeDone := make(chan error, 1)
go func() {
_, err := writer.Write([]byte("blocked"))
writeDone <- err
}()
select {
case <-underlying.writeStart:
case <-time.After(time.Second):
t.Fatal("response write did not start")
}
closeDone := make(chan struct{})
go func() {
writer.close()
close(closeDone)
}()
select {
case <-closeDone:
case <-time.After(time.Second):
t.Fatal("response close blocked behind stalled write")
}
select {
case err := <-writeDone:
if !errors.Is(err, os.ErrDeadlineExceeded) {
t.Fatalf("stalled write error = %v, want deadline exceeded", err)
}
case <-time.After(time.Second):
t.Fatal("stalled response write was not interrupted")
}
}
+73
View File
@@ -0,0 +1,73 @@
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"testing"
"time"
)
func TestAdminPasswordHashAndLegacyUpgrade(t *testing.T) {
password := "correct-horse-battery-staple"
hash, err := hashAdminPassword(password)
if err != nil {
t.Fatal(err)
}
if valid, upgrade := verifyAdminPassword(hash, password); !valid || upgrade {
t.Fatalf("bcrypt verification = valid %v, upgrade %v", valid, upgrade)
}
if valid, _ := verifyAdminPassword(hash, "wrong-password"); valid {
t.Fatal("wrong bcrypt password was accepted")
}
legacy := legacyAdminPasswordHash(password)
if valid, upgrade := verifyAdminPassword(legacy, password); !valid || !upgrade {
t.Fatalf("legacy verification = valid %v, upgrade %v", valid, upgrade)
}
}
func TestTLSDomainRejectsTraversal(t *testing.T) {
for _, value := range []string{"../root", `..\\root`, "/absolute", "host\nname"} {
if _, _, err := normalizeTLSDomain(value, true); err == nil {
t.Fatalf("normalizeTLSDomain(%q) accepted unsafe value", value)
}
}
if domain, _, err := normalizeTLSDomain("vpn.example.com", false); err != nil || domain != "vpn.example.com" {
t.Fatalf("valid domain rejected: %q, %v", domain, err)
}
}
func TestManagedServerURLValidation(t *testing.T) {
for _, value := range []string{
"ftp://example.com", "https://user:pass@example.com", "https://example.com/admin", "http://169.254.10.20",
} {
if _, err := validateManagedServerBaseURL(value); err == nil {
t.Fatalf("validateManagedServerBaseURL(%q) accepted unsafe value", value)
}
}
if got, err := validateManagedServerBaseURL("https://node.example.com/"); err != nil || got != "https://node.example.com" {
t.Fatalf("valid managed server URL = %q, %v", got, err)
}
}
func TestMPSignatureRequiresSecretAndValidHMAC(t *testing.T) {
const (
secret = "test-secret-with-enough-entropy"
dataID = "123456789"
requestID = "request-123"
)
ts := time.Now().Format("150405")
manifest := "id:" + dataID + ";request-id:" + requestID + ";ts:" + ts + ";"
mac := hmac.New(sha256.New, []byte(secret))
_, _ = mac.Write([]byte(manifest))
signature := "ts=" + ts + ",v1=" + hex.EncodeToString(mac.Sum(nil))
if !verifyMPSignature(signature, requestID, dataID, secret) {
t.Fatal("valid Mercado Pago signature was rejected")
}
if verifyMPSignature(signature, requestID, dataID, "") {
t.Fatal("unsigned webhook mode was accepted")
}
if verifyMPSignature(signature, requestID, dataID, "wrong-secret") {
t.Fatal("signature with wrong secret was accepted")
}
}
+59
View File
@@ -0,0 +1,59 @@
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
)
const maxAPIRequestBody = 8 << 20
// secureAPIHandler applies baseline HTTP protections and a global request
// body ceiling. Endpoint-specific handlers may impose a smaller limit.
func secureAPIHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()")
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'; form-action 'self'; img-src 'self' data:; connect-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'")
w.Header().Set("Cache-Control", "no-store")
if r.Body != nil && r.Method != http.MethodGet && r.Method != http.MethodHead {
r.Body = http.MaxBytesReader(w, r.Body, maxAPIRequestBody)
}
next.ServeHTTP(w, r)
})
}
// writeFileAtomic replaces a sensitive configuration file without leaving a
// partially written file behind after a crash or interrupted request.
func writeFileAtomic(path string, data []byte, mode os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".dragoncore-*.tmp")
if err != nil {
return err
}
tmpName := tmp.Name()
defer os.Remove(tmpName)
if err := tmp.Chmod(mode); err != nil {
tmp.Close()
return err
}
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("replace %s: %w", path, err)
}
return nil
}
+159
View File
@@ -0,0 +1,159 @@
package main
import (
"encoding/json"
"io"
"net/http"
"os"
"sync"
)
// Note: applyFullConfigReload is defined in hotreload.go
// ---------- Global config holder ----------
var (
globalCfgMu sync.RWMutex
globalCfg *Config
globalCfgPath string // set in main() from the -config flag
bannerMu sync.RWMutex
currentBannerText string
)
func setGlobalCfg(c *Config) {
globalCfgMu.Lock()
globalCfg = c
globalCfgMu.Unlock()
}
func getGlobalCfg() *Config {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg
}
func setBannerText(s string) {
bannerMu.Lock()
currentBannerText = s
bannerMu.Unlock()
}
func getBannerText() string {
bannerMu.RLock()
defer bannerMu.RUnlock()
return currentBannerText
}
// ---------- HTTP handler ----------
// handleServerConfig dispatches GET (read) and POST (write) for /api/server/config.
func handleServerConfig(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
serverConfigGet(w, r)
case http.MethodPost:
serverConfigPost(w, r)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func serverConfigGet(w http.ResponseWriter, _ *http.Request) {
if globalCfgPath == "" {
http.Error(w, "config path not set", http.StatusInternalServerError)
return
}
data, err := os.ReadFile(globalCfgPath)
if err != nil {
http.Error(w, "failed to read config: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(data)
}
func serverConfigPost(w http.ResponseWriter, r *http.Request) {
if globalCfgPath == "" {
http.Error(w, "config path not set", http.StatusInternalServerError)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 512*1024+1))
if err != nil {
http.Error(w, "failed to read body", http.StatusBadRequest)
return
}
if len(body) > 512*1024 {
http.Error(w, "config exceeds 512 KiB", http.StatusRequestEntityTooLarge)
return
}
// Keep track of optional field presence separately from its value. This
// protects a newly-added setting from being reset by a stale cached panel
// bundle that does not know how to send the field yet. For the service
// blocks the distinction matters twice over: a missing key must keep the
// running service, while an explicit null is the panel disabling it.
var fieldPresence struct {
PAMAuthEnabled *bool `json:"pam_auth_enabled"`
BHTTP *json.RawMessage `json:"bhttp"`
BTUN *json.RawMessage `json:"btun"`
HCR *json.RawMessage `json:"hcr"`
}
if err := json.Unmarshal(body, &fieldPresence); err != nil {
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
return
}
var newCfg Config
if err := json.Unmarshal(body, &newCfg); err != nil {
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
return
}
if newCfg.Listen == "" {
http.Error(w, "listen address required", http.StatusBadRequest)
return
}
if newCfg.Xray != nil {
newCfg.Xray.NormalizeDefaults()
}
// Preserve file-based users array (not editable through the UI).
globalCfgMu.RLock()
if globalCfg != nil {
newCfg.Users = globalCfg.Users
if fieldPresence.PAMAuthEnabled == nil {
newCfg.PAMAuthEnabled = globalCfg.PAMAuthEnabled
}
if fieldPresence.BHTTP == nil {
newCfg.BHTTP = globalCfg.BHTTP
}
if fieldPresence.BTUN == nil {
newCfg.BTUN = globalCfg.BTUN
}
if fieldPresence.HCR == nil {
newCfg.HCR = globalCfg.HCR
}
}
globalCfgMu.RUnlock()
portWarnings := normalizeRuntimePorts(&newCfg)
out, err := json.MarshalIndent(newCfg, "", " ")
if err != nil {
http.Error(w, "marshal error", http.StatusInternalServerError)
return
}
if err := writeFileAtomic(globalCfgPath, out, 0o600); err != nil {
http.Error(w, "failed to write config: "+err.Error(), http.StatusInternalServerError)
return
}
// Apply all changes live and return health checks to the panel.
report := applyFullConfigReload(&newCfg)
if len(portWarnings) > 0 {
report.Warnings = append(portWarnings, report.Warnings...)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(report)
}
+113
View File
@@ -0,0 +1,113 @@
package main
import (
"bufio"
"encoding/json"
"net/http"
"os"
"strconv"
"strings"
)
const defaultPanelLogFile = "/opt/sshpanel/logs/panel.log"
type systemLogsResponse struct {
Source string `json:"source"`
Path string `json:"path,omitempty"`
Lines []string `json:"lines"`
}
func handleSystemLogs(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
limit := 300
if raw := strings.TrimSpace(r.URL.Query().Get("lines")); raw != "" {
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
limit = n
}
}
if limit > 2000 {
limit = 2000
}
source := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("source")))
if source == "" {
source = "panel"
}
resp := systemLogsResponse{Source: source, Lines: []string{}}
switch source {
case "dnstt":
resp.Lines = limitLines(getDNSTTLogLines(), limit)
case "xray":
resp.Lines = limitLines(xrayLogBuf.snapshot(), limit)
default:
resp.Source = "panel"
path := panelLogFilePath()
resp.Path = path
lines, err := tailTextFile(path, limit)
if err != nil {
lines = []string{"unable to read " + path + ": " + err.Error()}
}
resp.Lines = lines
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
func tailTextFile(path string, limit int) ([]string, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
if limit <= 0 {
limit = 300
}
ring := make([]string, limit)
count := 0
scanner := bufio.NewScanner(f)
buf := make([]byte, 0, 64*1024)
scanner.Buffer(buf, 1024*1024)
for scanner.Scan() {
ring[count%limit] = scanner.Text()
count++
}
if err := scanner.Err(); err != nil {
return nil, err
}
if count == 0 {
return []string{}, nil
}
outLen := count
if outLen > limit {
outLen = limit
}
out := make([]string, 0, outLen)
start := 0
if count > limit {
start = count % limit
}
for i := 0; i < outLen; i++ {
out = append(out, ring[(start+i)%limit])
}
return out, nil
}
func limitLines(lines []string, limit int) []string {
if len(lines) == 0 {
return []string{}
}
if limit <= 0 || len(lines) <= limit {
out := make([]string, len(lines))
copy(out, lines)
return out
}
out := make([]string, limit)
copy(out, lines[len(lines)-limit:])
return out
}
+121
View File
@@ -0,0 +1,121 @@
import importlib.util
import io
from pathlib import Path
import tempfile
import unittest
from contextlib import redirect_stdout
from types import SimpleNamespace
from unittest.mock import patch
MODULE = Path(__file__).with_name("dragoncore_cli.py")
spec = importlib.util.spec_from_file_location("dragoncore_cli", MODULE)
cli = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cli)
class TokenManagementTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
env = Path(self.temp.name) / ".env"
env.write_text("PG_DSN=test\nADMIN_TOKEN=" + "a" * 48 + "\nADMIN_HTTP_ADDR=127.0.0.1:9090\n")
env.chmod(0o600)
self.path = env
patcher = patch.object(cli, "ENV_FILE", env)
patcher.start()
self.addCleanup(patcher.stop)
def test_rotation_preserves_other_env_and_never_prompts(self):
with patch.object(cli, "service_action") as service, patch.object(cli, "request", return_value=[]):
with patch("builtins.input", side_effect=AssertionError("prompted")):
with redirect_stdout(io.StringIO()):
cli.rotate_api_password()
self.assertNotEqual(cli.api_password(), "a" * 48)
self.assertIn("PG_DSN=test\n", self.path.read_text())
self.assertEqual(self.path.stat().st_mode & 0o777, 0o600)
service.assert_called_once_with("restart")
def test_failed_rotation_restores_previous_token(self):
with patch.object(cli, "service_action", side_effect=[None, None]), \
patch.object(cli, "request", side_effect=cli.CLIError("bad API")), \
patch.object(cli.time, "sleep"):
with self.assertRaises(cli.CLIError):
cli.rotate_api_password()
self.assertEqual(cli.api_password(), "a" * 48)
def test_live_vps_header_counts_users_and_rates(self):
responses = [
{"cpu_percent": 12.5, "mem_total_bytes": 8 * 1024**3,
"mem_used_bytes": 2 * 1024**3,
"interfaces": [{"rx_mbps": 18.5, "tx_mbps": 4.2}]},
[{"username": "alice", "active_conns": 2, "expires_at": "2099-01-01T00:00:00Z"},
{"username": "bob", "active_conns": 0, "expires_at": "2020-01-01T00:00:00Z"}],
{"online_users": 3},
]
with patch.object(cli, "request", side_effect=responses), \
patch.object(cli.shutil, "disk_usage", return_value=SimpleNamespace(used=50, total=100)), \
patch.object(cli.subprocess, "run", return_value=SimpleNamespace(stdout="active\n")):
status = cli.collect_vps_status()
header = cli.render_vps_status(status)
self.assertIn("12.5%", header)
self.assertIn("1 online | 1 expired | 2 total", header)
self.assertIn("Xray: 3 online", header)
self.assertIn("18.50 Mbps", header)
self.assertEqual(len({len(row) for row in header.splitlines()}), 1)
menu_text = cli.render_menu("MAIN MENU", cli.main_menu_options(), status)
self.assertIn("CONNECTION", menu_text.upper())
self.assertNotIn("Resellers", menu_text)
mobile = cli.render_menu("MAIN MENU", cli.main_menu_options(), status, columns=40)
self.assertLessEqual(max(map(len, mobile.splitlines())), 40)
self.assertIn("CPU: 12.5%", mobile)
self.assertIn("SSH: 1 on / 2 total", mobile)
def test_user_list_fits_phone_terminal(self):
users = [{"username": "account-with-a-long-name", "active_conns": 2,
"max_connections": 5, "total_bytes": 1234567,
"expires_at": "2099-05-01T12:00:00Z"}]
with patch.object(cli, "request", return_value=users), \
patch.object(cli, "terminal_columns", return_value=40), \
redirect_stdout(io.StringIO()) as output:
cli.list_users()
self.assertLessEqual(max(map(len, output.getvalue().splitlines())), 40)
def test_shared_xray_generates_path_without_password_prompt(self):
server = {"listen": "0.0.0.0:80", "tls_forwarders": [{"listen": "0.0.0.0:443"}],
"xray": {"mode": "native"}}
config = {"inbounds": [{"tag": "first", "protocol": "vless", "dragoncoreSharedPort": True,
"streamSettings": {"network": "ws", "wsSettings": {"path": "/c1"}}}]}
calls = []
def fake_request(method, path, data=None):
calls.append((method, path, data))
if path == "/api/server/config":
return server
if path == "/api/xray/config" and method == "GET":
return config
if path == "/api/xray/status":
return {"running": False}
return None
# The flow asks only for the tag, transport, path, protocol, and consent.
with patch.object(cli, "request", side_effect=fake_request), \
patch("builtins.input", side_effect=["second", "", "", "", "YES"]), \
redirect_stdout(io.StringIO()):
cli.xray_shared_port()
new = config["inbounds"][1]
self.assertEqual(new["streamSettings"]["wsSettings"]["path"], "/c2")
self.assertEqual(new["streamSettings"]["security"], "none")
self.assertTrue(new["dragoncoreSharedPort"])
self.assertEqual([item[1] for item in calls[-3:]],
["/api/xray/config", "/api/xray/status", "/api/xray/start"])
def test_shared_xray_rejects_external_mode(self):
with patch.object(cli, "request", return_value={"xray": {"mode": "external"}}), \
patch("builtins.input", side_effect=AssertionError("prompted")):
with self.assertRaisesRegex(cli.CLIError, "native"):
cli.xray_shared_port()
if __name__ == "__main__":
unittest.main()
+243
View File
@@ -0,0 +1,243 @@
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"fmt"
"math/big"
"net"
"net/http"
"net/mail"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
)
// tlsCertsDir holds panel-managed certificates. It is a var so tests can point
// it at a temporary directory.
var tlsCertsDir = "/opt/sshpanel/certs"
var (
tlsDNSNamePattern = regexp.MustCompile(`^(?:\*\.)?(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$`)
tlsStoreNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
)
func normalizeTLSDomain(raw string, allowWildcard bool) (domain string, dirName string, err error) {
domain = strings.TrimSuffix(strings.TrimSpace(raw), ".")
if domain == "" || len(domain) > 253 || strings.ContainsAny(domain, "/\\\x00\r\n") {
return "", "", fmt.Errorf("invalid domain")
}
if ip := net.ParseIP(domain); ip != nil {
return domain, strings.ReplaceAll(domain, ":", "_"), nil
}
if strings.HasPrefix(domain, "*.") && !allowWildcard {
return "", "", fmt.Errorf("wildcard domains are not supported by this operation")
}
if !tlsDNSNamePattern.MatchString(domain) {
return "", "", fmt.Errorf("invalid domain")
}
dirName = strings.ReplaceAll(domain, "*", "_wildcard_")
return domain, dirName, nil
}
func normalizeTLSStoreName(raw string) (string, error) {
name := strings.TrimSpace(raw)
if !tlsStoreNamePattern.MatchString(name) {
return "", fmt.Errorf("name must use only letters, numbers, dot, underscore, or hyphen")
}
return name, nil
}
// handleTLSGenerateSelfSigned generates a self-signed TLS certificate for the
// given domain, writes it to /opt/sshpanel/certs/<domain>/, and returns the paths.
func handleTLSGenerateSelfSigned(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req struct {
Domain string `json:"domain"`
}
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Domain == "" {
http.Error(w, "domain required", http.StatusBadRequest)
return
}
domain, dirName, err := normalizeTLSDomain(req.Domain, true)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
certDir := filepath.Join(tlsCertsDir, dirName)
if err := os.MkdirAll(certDir, 0o700); err != nil {
http.Error(w, "mkdir: "+err.Error(), http.StatusInternalServerError)
return
}
certFile := filepath.Join(certDir, "cert.pem")
keyFile := filepath.Join(certDir, "key.pem")
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
http.Error(w, "keygen: "+err.Error(), http.StatusInternalServerError)
return
}
serialLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialLimit)
if err != nil {
http.Error(w, "serial generation failed", http.StatusInternalServerError)
return
}
tmpl := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{CommonName: domain},
NotBefore: time.Now().Add(-time.Minute),
NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{domain},
}
if net.ParseIP(domain) != nil {
tmpl.DNSNames = nil
tmpl.IPAddresses = []net.IP{net.ParseIP(domain)}
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
if err != nil {
http.Error(w, "certgen: "+err.Error(), http.StatusInternalServerError)
return
}
privDER, err := x509.MarshalECPrivateKey(priv)
if err != nil {
http.Error(w, "marshal key: "+err.Error(), http.StatusInternalServerError)
return
}
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privDER})
if err := writeFileAtomic(certFile, certPEM, 0o600); err != nil {
http.Error(w, "write cert: "+err.Error(), http.StatusInternalServerError)
return
}
if err := writeFileAtomic(keyFile, keyPEM, 0o600); err != nil {
http.Error(w, "write key: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"cert_file": certFile,
"key_file": keyFile,
})
}
// handleTLSLetsEncrypt runs certbot to obtain a certificate via Let's Encrypt.
// Requires certbot installed on the server and port 80 available.
func handleTLSLetsEncrypt(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req struct {
Domain string `json:"domain"`
Email string `json:"email"`
}
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Domain == "" || req.Email == "" {
http.Error(w, "domain and email required", http.StatusBadRequest)
return
}
domain, _, err := normalizeTLSDomain(req.Domain, false)
if err != nil || net.ParseIP(domain) != nil {
http.Error(w, "a valid DNS domain is required", http.StatusBadRequest)
return
}
email := strings.TrimSpace(req.Email)
parsedEmail, err := mail.ParseAddress(email)
if err != nil || parsedEmail.Address != email || len(email) > 254 {
http.Error(w, "valid email required", http.StatusBadRequest)
return
}
cmd := exec.Command("certbot", "certonly", "--standalone", "--non-interactive",
"--agree-tos", "-m", email, "-d", domain)
out, err := cmd.CombinedOutput()
if err != nil {
http.Error(w, fmt.Sprintf("certbot failed: %v\n%s", err, string(out)), http.StatusInternalServerError)
return
}
certFile := "/etc/letsencrypt/live/" + domain + "/fullchain.pem"
keyFile := "/etc/letsencrypt/live/" + domain + "/privkey.pem"
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"cert_file": certFile,
"key_file": keyFile,
"output": string(out),
})
}
// handleTLSUploadPEM accepts PEM text for cert and key, saves them to disk under
// /opt/sshpanel/certs/<name>/, and returns the file paths.
func handleTLSUploadPEM(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req struct {
Name string `json:"name"`
Cert string `json:"cert"`
Key string `json:"key"`
}
r.Body = http.MaxBytesReader(w, r.Body, 2<<20)
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Name == "" || req.Cert == "" || req.Key == "" {
http.Error(w, "name, cert, and key required", http.StatusBadRequest)
return
}
name, err := normalizeTLSStoreName(req.Name)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(req.Cert) > 1024*1024 || len(req.Key) > 1024*1024 {
http.Error(w, "certificate or key is too large", http.StatusRequestEntityTooLarge)
return
}
pair, err := tls.X509KeyPair([]byte(req.Cert), []byte(req.Key))
if err != nil || len(pair.Certificate) == 0 {
http.Error(w, "certificate and private key are invalid or do not match", http.StatusBadRequest)
return
}
if _, err := x509.ParseCertificate(pair.Certificate[0]); err != nil {
http.Error(w, "invalid leaf certificate", http.StatusBadRequest)
return
}
certDir := filepath.Join(tlsCertsDir, name)
if err := os.MkdirAll(certDir, 0o700); err != nil {
http.Error(w, "mkdir: "+err.Error(), http.StatusInternalServerError)
return
}
certFile := filepath.Join(certDir, "cert.pem")
keyFile := filepath.Join(certDir, "key.pem")
if err := writeFileAtomic(certFile, []byte(req.Cert), 0o600); err != nil {
http.Error(w, "write cert: "+err.Error(), http.StatusInternalServerError)
return
}
if err := writeFileAtomic(keyFile, []byte(req.Key), 0o600); err != nil {
http.Error(w, "write key: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"cert_file": certFile,
"key_file": keyFile,
})
}
+715
View File
@@ -0,0 +1,715 @@
package main
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
// Certificate management for the panel: list the TLS material this node already
// uses and replace it in place (fullchain + privkey) when an operator renews a
// certificate. Replacing in place is what makes renewal painless — every place
// that references the old paths (TLS forwarders, Xray inbounds) keeps working,
// and only the listeners that actually serve the certificate are rebound.
const (
tlsCertFileName = "cert.pem"
tlsKeyFileName = "key.pem"
// Two PEM blobs plus JSON overhead. Certificates are a few KB; RSA chains
// with several intermediates still stay far below this.
maxTLSCertRequestBody = 4 << 20
maxTLSPEMBytes = 1 << 20
// Certificates expiring inside this window are flagged in the panel.
tlsCertExpiryWarnDays = 21
)
// tlsCertUsage records one consumer of a certificate so the panel can show what
// a replacement is going to affect.
type tlsCertUsage struct {
Kind string `json:"kind"` // tls_forwarder | xray_inbound
Ref string `json:"ref"` // listen address or inbound tag
}
type tlsCertInfo struct {
Name string `json:"name"`
CertFile string `json:"cert_file"`
KeyFile string `json:"key_file"`
Managed bool `json:"managed"` // stored under /opt/sshpanel/certs
Exists bool `json:"exists"`
Subject string `json:"subject,omitempty"`
Issuer string `json:"issuer,omitempty"`
Domains []string `json:"domains"`
NotBefore string `json:"not_before,omitempty"`
NotAfter string `json:"not_after,omitempty"`
DaysLeft int `json:"days_left"`
Expired bool `json:"expired"`
Expiring bool `json:"expiring"`
SelfSigned bool `json:"self_signed"`
ChainLen int `json:"chain_length"`
KeyType string `json:"key_type,omitempty"`
KeyOK bool `json:"key_ok"`
Modified string `json:"modified,omitempty"`
Error string `json:"error,omitempty"`
UsedBy []tlsCertUsage `json:"used_by"`
}
type tlsCertRef struct {
certFile string
keyFile string
managed bool
usage []tlsCertUsage
}
type tlsCertRefSet struct {
byCert map[string]*tlsCertRef
order []string
}
func newTLSCertRefSet() *tlsCertRefSet {
return &tlsCertRefSet{byCert: map[string]*tlsCertRef{}}
}
func (s *tlsCertRefSet) add(certFile, keyFile string, usage ...tlsCertUsage) *tlsCertRef {
certFile = strings.TrimSpace(certFile)
if certFile == "" {
return nil
}
certFile = filepath.Clean(certFile)
ref, ok := s.byCert[certFile]
if !ok {
ref = &tlsCertRef{certFile: certFile, managed: isUnderTLSCertsDir(certFile)}
s.byCert[certFile] = ref
s.order = append(s.order, certFile)
}
if ref.keyFile == "" && strings.TrimSpace(keyFile) != "" {
ref.keyFile = filepath.Clean(strings.TrimSpace(keyFile))
}
for _, u := range usage {
if u.Kind == "" {
continue
}
dup := false
for _, have := range ref.usage {
if have == u {
dup = true
break
}
}
if !dup {
ref.usage = append(ref.usage, u)
}
}
return ref
}
func (s *tlsCertRefSet) list() []*tlsCertRef {
out := make([]*tlsCertRef, 0, len(s.order))
for _, key := range s.order {
out = append(out, s.byCert[key])
}
return out
}
func isUnderTLSCertsDir(path string) bool {
rel, err := filepath.Rel(filepath.Clean(tlsCertsDir), filepath.Clean(path))
if err != nil {
return false
}
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
// samePathRef compares two file paths, following symlinks when both sides can be
// resolved. /etc/letsencrypt/live/<domain>/fullchain.pem is a symlink, so a
// plain string compare is not enough to match a config reference to a real file.
func samePathRef(a, b string) bool {
a, b = strings.TrimSpace(a), strings.TrimSpace(b)
if a == "" || b == "" {
return false
}
if filepath.Clean(a) == filepath.Clean(b) {
return true
}
ra, errA := filepath.EvalSymlinks(a)
rb, errB := filepath.EvalSymlinks(b)
return errA == nil && errB == nil && ra == rb
}
// collectTLSCertRefs gathers every certificate this node knows about: the ones
// stored in the panel's cert directory plus the ones referenced by the running
// config (TLS forwarders) and the Xray config (inbound tlsSettings).
func collectTLSCertRefs() *tlsCertRefSet {
set := newTLSCertRefSet()
gc := getGlobalCfg()
var fallbackCert, fallbackKey string
if gc != nil {
for _, fwd := range gc.TLSForwarders {
if strings.TrimSpace(fwd.CertFile) == "" {
continue
}
if fallbackCert == "" {
fallbackCert, fallbackKey = fwd.CertFile, fwd.KeyFile
}
listen := strings.TrimSpace(fwd.Listen)
if listen == "" {
listen = "(unbound)"
}
set.add(fwd.CertFile, fwd.KeyFile, tlsCertUsage{Kind: "tls_forwarder", Ref: listen})
}
}
for _, u := range xrayInboundCertUsage(fallbackCert, fallbackKey) {
set.add(u.certFile, u.keyFile, tlsCertUsage{Kind: "xray_inbound", Ref: u.tag})
}
// Panel-managed certificates (self-signed, pasted, or previously updated).
entries, err := os.ReadDir(tlsCertsDir)
if err == nil {
names := make([]string, 0, len(entries))
for _, e := range entries {
if e.IsDir() {
names = append(names, e.Name())
}
}
sort.Strings(names)
for _, name := range names {
certFile := filepath.Join(tlsCertsDir, name, tlsCertFileName)
if _, err := os.Stat(certFile); err != nil {
continue
}
set.add(certFile, filepath.Join(tlsCertsDir, name, tlsKeyFileName))
}
}
return set
}
type xrayCertRef struct {
tag string
certFile string
keyFile string
}
// xrayInboundCertUsage returns the certificate each TLS-enabled Xray inbound
// serves. Inbounds that enable TLS without naming a certificate inherit the
// first TLS forwarder's material (see buildInboundTLS), so they are reported
// against that path — replacing it does affect them.
func xrayInboundCertUsage(fallbackCert, fallbackKey string) []xrayCertRef {
if xrayMgr == nil {
return nil
}
data, err := xrayMgr.GetConfig()
if err != nil || len(data) == 0 {
return nil
}
var cf struct {
Inbounds []struct {
Tag string `json:"tag"`
StreamSettings struct {
Security string `json:"security"`
TLSSettings struct {
Certificates []struct {
CertificateFile string `json:"certificateFile"`
KeyFile string `json:"keyFile"`
} `json:"certificates"`
} `json:"tlsSettings"`
} `json:"streamSettings"`
} `json:"inbounds"`
}
if err := json.Unmarshal(data, &cf); err != nil {
return nil
}
var out []xrayCertRef
for i, in := range cf.Inbounds {
security := strings.ToLower(strings.TrimSpace(in.StreamSettings.Security))
certs := in.StreamSettings.TLSSettings.Certificates
if security != "tls" && len(certs) == 0 {
continue
}
tag := strings.TrimSpace(in.Tag)
if tag == "" {
tag = fmt.Sprintf("inbound-%d", i+1)
}
if len(certs) > 0 && strings.TrimSpace(certs[0].CertificateFile) != "" {
out = append(out, xrayCertRef{tag: tag, certFile: certs[0].CertificateFile, keyFile: certs[0].KeyFile})
continue
}
if security == "tls" && strings.TrimSpace(fallbackCert) != "" {
out = append(out, xrayCertRef{tag: tag + " (herda do TLS forwarder)", certFile: fallbackCert, keyFile: fallbackKey})
}
}
return out
}
func tlsCertDisplayName(certFile string) string {
dir := filepath.Base(filepath.Dir(certFile))
if dir == "" || dir == "." || dir == string(filepath.Separator) {
return filepath.Base(certFile)
}
if dir == "live" || dir == "certs" {
return filepath.Base(certFile)
}
return dir
}
func tlsKeyTypeName(key interface{}) string {
switch k := key.(type) {
case *rsa.PrivateKey:
return fmt.Sprintf("RSA %d", k.N.BitLen())
case *ecdsa.PrivateKey:
return "ECDSA " + k.Curve.Params().Name
case ed25519.PrivateKey:
return "Ed25519"
}
return ""
}
func parsePEMCertChain(data []byte) ([]*x509.Certificate, error) {
var chain []*x509.Certificate
rest := data
for {
var block *pem.Block
block, rest = pem.Decode(rest)
if block == nil {
break
}
if block.Type != "CERTIFICATE" {
continue
}
crt, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
chain = append(chain, crt)
}
if len(chain) == 0 {
return nil, fmt.Errorf("no CERTIFICATE block found")
}
return chain, nil
}
func certDomains(leaf *x509.Certificate) []string {
seen := map[string]bool{}
out := make([]string, 0, len(leaf.DNSNames)+len(leaf.IPAddresses)+1)
for _, d := range leaf.DNSNames {
if d = strings.TrimSpace(d); d != "" && !seen[d] {
seen[d] = true
out = append(out, d)
}
}
for _, ip := range leaf.IPAddresses {
s := ip.String()
if !seen[s] {
seen[s] = true
out = append(out, s)
}
}
if len(out) == 0 && strings.TrimSpace(leaf.Subject.CommonName) != "" {
out = append(out, strings.TrimSpace(leaf.Subject.CommonName))
}
return out
}
func describeTLSCert(ref *tlsCertRef) tlsCertInfo {
info := tlsCertInfo{
Name: tlsCertDisplayName(ref.certFile),
CertFile: ref.certFile,
KeyFile: ref.keyFile,
Managed: ref.managed,
Domains: []string{},
UsedBy: ref.usage,
}
if info.UsedBy == nil {
info.UsedBy = []tlsCertUsage{}
}
st, err := os.Stat(ref.certFile)
if err != nil {
info.Error = "arquivo não encontrado"
return info
}
info.Exists = true
info.Modified = st.ModTime().UTC().Format(time.RFC3339)
certPEM, err := os.ReadFile(ref.certFile)
if err != nil {
info.Error = "leitura do certificado: " + err.Error()
return info
}
chain, err := parsePEMCertChain(certPEM)
if err != nil {
info.Error = "certificado inválido: " + err.Error()
return info
}
leaf := chain[0]
info.ChainLen = len(chain)
info.Subject = leaf.Subject.CommonName
info.Issuer = leaf.Issuer.CommonName
if info.Issuer == "" && len(leaf.Issuer.Organization) > 0 {
info.Issuer = leaf.Issuer.Organization[0]
}
info.Domains = certDomains(leaf)
info.NotBefore = leaf.NotBefore.UTC().Format(time.RFC3339)
info.NotAfter = leaf.NotAfter.UTC().Format(time.RFC3339)
info.SelfSigned = string(leaf.RawIssuer) == string(leaf.RawSubject)
now := time.Now()
info.Expired = now.After(leaf.NotAfter)
info.DaysLeft = int(leaf.NotAfter.Sub(now).Hours() / 24)
info.Expiring = !info.Expired && info.DaysLeft <= tlsCertExpiryWarnDays
if ref.keyFile != "" {
keyPEM, err := os.ReadFile(ref.keyFile)
if err != nil {
info.Error = "leitura da chave: " + err.Error()
return info
}
pair, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
info.Error = "a chave privada não corresponde ao certificado"
return info
}
info.KeyOK = true
info.KeyType = tlsKeyTypeName(pair.PrivateKey)
} else {
info.Error = "nenhuma chave privada associada"
}
return info
}
// handleTLSCertList returns every certificate this node uses, with expiry and
// the listeners/inbounds that serve it.
func handleTLSCertList(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
refs := collectTLSCertRefs().list()
out := make([]tlsCertInfo, 0, len(refs))
for _, ref := range refs {
out = append(out, describeTLSCert(ref))
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"certs_dir": tlsCertsDir,
"certs": out,
})
}
type tlsCertUpdateRequest struct {
// Name creates or replaces a panel-managed certificate under
// /opt/sshpanel/certs/<name>/. Ignored when CertFile is set.
Name string `json:"name"`
// CertFile/KeyFile target an existing certificate in place so every
// reference to those paths keeps working after the renewal.
CertFile string `json:"cert_file"`
KeyFile string `json:"key_file"`
// Fullchain/Privkey hold the PEM text. cert/key are accepted as aliases.
Fullchain string `json:"fullchain"`
Privkey string `json:"privkey"`
Cert string `json:"cert"`
Key string `json:"key"`
Reload *bool `json:"reload"`
Force bool `json:"force"`
}
type tlsCertReloadResult struct {
TLSForwarders []string `json:"tls_forwarders"`
XrayInbounds []string `json:"xray_inbounds"`
XrayRestarted bool `json:"xray_restarted"`
}
func normalizeTLSFilePath(raw string) (string, error) {
p := strings.TrimSpace(raw)
if p == "" {
return "", fmt.Errorf("caminho vazio")
}
if strings.ContainsAny(p, "\x00\r\n") {
return "", fmt.Errorf("caminho inválido")
}
if !filepath.IsAbs(p) {
return "", fmt.Errorf("o caminho precisa ser absoluto")
}
return filepath.Clean(p), nil
}
func normalizePEMText(raw string) string {
s := strings.ReplaceAll(strings.TrimSpace(raw), "\r\n", "\n")
s = strings.ReplaceAll(s, "\r", "\n")
if s == "" {
return ""
}
return s + "\n"
}
// resolveTLSCertTarget decides which files the new PEM material is written to
// and rejects paths that are neither panel-managed nor already referenced by the
// running configuration. Without that check this endpoint would be an arbitrary
// root file-write primitive.
func resolveTLSCertTarget(req tlsCertUpdateRequest) (certFile, keyFile string, warnings []string, err error) {
if strings.TrimSpace(req.CertFile) != "" {
certFile, err = normalizeTLSFilePath(req.CertFile)
if err != nil {
return "", "", nil, err
}
refs := collectTLSCertRefs()
var known *tlsCertRef
for _, ref := range refs.list() {
if samePathRef(ref.certFile, certFile) {
known = ref
break
}
}
if known == nil && !isUnderTLSCertsDir(certFile) {
return "", "", nil, fmt.Errorf("caminho não gerenciado pelo painel: use um certificado já referenciado na configuração ou informe um nome para armazenar em %s", tlsCertsDir)
}
if strings.TrimSpace(req.KeyFile) != "" {
keyFile, err = normalizeTLSFilePath(req.KeyFile)
if err != nil {
return "", "", nil, err
}
} else if known != nil && known.keyFile != "" {
keyFile = known.keyFile
} else {
keyFile = filepath.Join(filepath.Dir(certFile), tlsKeyFileName)
}
if !isUnderTLSCertsDir(keyFile) {
keyKnown := known != nil && samePathRef(known.keyFile, keyFile)
if !keyKnown && filepath.Dir(keyFile) != filepath.Dir(certFile) {
return "", "", nil, fmt.Errorf("a chave precisa estar na mesma pasta do certificado ou já estar referenciada na configuração")
}
}
return certFile, keyFile, warnings, nil
}
name, nameErr := normalizeTLSStoreName(req.Name)
if nameErr != nil {
return "", "", nil, fmt.Errorf("informe cert_file de um certificado existente ou um nome para armazenar: %v", nameErr)
}
dir := filepath.Join(tlsCertsDir, name)
return filepath.Join(dir, tlsCertFileName), filepath.Join(dir, tlsKeyFileName), warnings, nil
}
// writeTLSMaterial replaces path with data, keeping a .bak copy of the previous
// content and preserving the existing file mode. Symlinked targets (certbot
// layout) are followed so the link structure survives the update.
func writeTLSMaterial(path string, data []byte, defaultMode os.FileMode) (string, []string, error) {
var warnings []string
target := path
if lst, err := os.Lstat(path); err == nil && lst.Mode()&os.ModeSymlink != 0 {
if resolved, err := filepath.EvalSymlinks(path); err == nil {
target = resolved
warnings = append(warnings, fmt.Sprintf("%s é um link para %s; o conteúdo real foi substituído", path, resolved))
}
}
mode := defaultMode
if st, err := os.Stat(target); err == nil {
mode = st.Mode().Perm()
if old, err := os.ReadFile(target); err == nil {
if err := writeFileAtomic(target+".bak", old, mode); err != nil {
warnings = append(warnings, "não foi possível gravar backup de "+filepath.Base(target)+": "+err.Error())
}
}
}
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return target, warnings, err
}
if err := writeFileAtomic(target, data, mode); err != nil {
return target, warnings, err
}
return target, warnings, nil
}
// handleTLSCertUpdate replaces a certificate's fullchain + private key and
// reloads whatever serves it, so a renewal takes effect without touching any
// other configuration.
func handleTLSCertUpdate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxTLSCertRequestBody)
var req tlsCertUpdateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "corpo inválido: "+err.Error(), http.StatusBadRequest)
return
}
if strings.TrimSpace(req.Fullchain) == "" {
req.Fullchain = req.Cert
}
if strings.TrimSpace(req.Privkey) == "" {
req.Privkey = req.Key
}
certPEM := normalizePEMText(req.Fullchain)
keyPEM := normalizePEMText(req.Privkey)
if certPEM == "" || keyPEM == "" {
http.Error(w, "fullchain (certificado) e privkey (chave privada) são obrigatórios", http.StatusBadRequest)
return
}
if len(certPEM) > maxTLSPEMBytes || len(keyPEM) > maxTLSPEMBytes {
http.Error(w, "certificado ou chave muito grandes", http.StatusRequestEntityTooLarge)
return
}
pair, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM))
if err != nil || len(pair.Certificate) == 0 {
http.Error(w, "certificado e chave privada inválidos ou não correspondentes", http.StatusBadRequest)
return
}
chain, err := parsePEMCertChain([]byte(certPEM))
if err != nil {
http.Error(w, "certificado inválido: "+err.Error(), http.StatusBadRequest)
return
}
leaf := chain[0]
now := time.Now()
if now.After(leaf.NotAfter) && !req.Force {
http.Error(w, fmt.Sprintf("este certificado expirou em %s; envie force=true para gravar mesmo assim",
leaf.NotAfter.UTC().Format("2006-01-02")), http.StatusBadRequest)
return
}
certFile, keyFile, warnings, err := resolveTLSCertTarget(req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(chain) < 2 && !leaf.IsCA && string(leaf.RawIssuer) != string(leaf.RawSubject) {
warnings = append(warnings, "o PEM enviado contém apenas o certificado final; cole o fullchain.pem completo para evitar erros de cadeia em alguns clientes")
}
if now.Before(leaf.NotBefore) {
warnings = append(warnings, "o certificado só é válido a partir de "+leaf.NotBefore.UTC().Format("2006-01-02 15:04")+" UTC")
}
if now.After(leaf.NotAfter) {
warnings = append(warnings, "certificado já expirado — gravado por causa de force=true")
}
// Domain mismatch is usually a wrong paste, but a domain change can be
// intentional, so it is reported rather than blocked.
if oldPEM, err := os.ReadFile(certFile); err == nil {
if oldChain, err := parsePEMCertChain(oldPEM); err == nil {
oldDomains, newDomains := certDomains(oldChain[0]), certDomains(leaf)
if strings.Join(oldDomains, ",") != strings.Join(newDomains, ",") {
warnings = append(warnings, fmt.Sprintf("os domínios mudaram: antes %s, agora %s",
strings.Join(oldDomains, ", "), strings.Join(newDomains, ", ")))
}
}
}
writtenCert, certWarn, err := writeTLSMaterial(certFile, []byte(certPEM), 0o600)
warnings = append(warnings, certWarn...)
if err != nil {
http.Error(w, "gravar certificado: "+err.Error(), http.StatusInternalServerError)
return
}
writtenKey, keyWarn, err := writeTLSMaterial(keyFile, []byte(keyPEM), 0o600)
warnings = append(warnings, keyWarn...)
if err != nil {
http.Error(w, "gravar chave: "+err.Error(), http.StatusInternalServerError)
return
}
log.Printf("tls: certificate updated cert=%s key=%s cn=%q not_after=%s",
writtenCert, writtenKey, leaf.Subject.CommonName, leaf.NotAfter.UTC().Format(time.RFC3339))
reload := tlsCertReloadResult{TLSForwarders: []string{}, XrayInbounds: []string{}}
if req.Reload == nil || *req.Reload {
var reloadWarn []string
reload, reloadWarn = reloadTLSCertConsumers(certFile, keyFile)
warnings = append(warnings, reloadWarn...)
}
info := describeTLSCert(&tlsCertRef{
certFile: certFile,
keyFile: keyFile,
managed: isUnderTLSCertsDir(certFile),
usage: certUsageFor(certFile, keyFile),
})
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"cert_file": certFile,
"key_file": keyFile,
"cert": info,
"reloaded": reload,
"warnings": warnings,
})
}
func certUsageFor(certFile, keyFile string) []tlsCertUsage {
for _, ref := range collectTLSCertRefs().list() {
if samePathRef(ref.certFile, certFile) {
return ref.usage
}
}
return nil
}
// reloadTLSCertConsumers rebinds the TLS forwarders that serve the replaced
// certificate and restarts Xray when one of its inbounds uses it. Certificates
// are read once when a listener is created, so nothing short of rebinding picks
// up new material. Established connections are not owned by the listeners and
// keep running.
func reloadTLSCertConsumers(certFile, keyFile string) (tlsCertReloadResult, []string) {
result := tlsCertReloadResult{TLSForwarders: []string{}, XrayInbounds: []string{}}
var warnings []string
gc := getGlobalCfg()
var fallbackCert, fallbackKey string
if gc != nil {
for _, fwd := range gc.TLSForwarders {
if strings.TrimSpace(fwd.CertFile) != "" {
fallbackCert, fallbackKey = fwd.CertFile, fwd.KeyFile
break
}
}
var affected []string
for _, fwd := range gc.TLSForwarders {
if samePathRef(fwd.CertFile, certFile) || samePathRef(fwd.KeyFile, keyFile) {
if listen := strings.TrimSpace(fwd.Listen); listen != "" {
affected = append(affected, listen)
}
}
}
if len(affected) > 0 && tlsPool != nil {
tlsPool.Drop(affected, "certificate updated")
for _, e := range tlsPool.Sync(gc.TLSForwarders) {
warnings = append(warnings, fmt.Sprintf("recarregar TLS forwarder: %v", e))
}
for _, addr := range affected {
if tlsPool.Has(addr) {
result.TLSForwarders = append(result.TLSForwarders, addr)
} else {
warnings = append(warnings, "o TLS forwarder "+addr+" não voltou a escutar; verifique os logs")
}
}
}
}
for _, u := range xrayInboundCertUsage(fallbackCert, fallbackKey) {
if samePathRef(u.certFile, certFile) || samePathRef(u.keyFile, keyFile) {
result.XrayInbounds = append(result.XrayInbounds, u.tag)
}
}
if len(result.XrayInbounds) > 0 && xrayMgr != nil {
st := xrayMgr.Status()
if st.Enabled && st.Running {
if err := xrayMgr.Restart(); err != nil {
warnings = append(warnings, fmt.Sprintf("reiniciar Xray: %v", err))
} else {
result.XrayRestarted = true
}
} else if st.Enabled {
warnings = append(warnings, "o Xray usa este certificado mas não está em execução")
}
}
return result, warnings
}
+306
View File
@@ -0,0 +1,306 @@
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"math/big"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// makeTestCertPair returns PEM cert/key material for the given domain.
func makeTestCertPair(t *testing.T, domain string, notBefore, notAfter time.Time) (certPEM, keyPEM string) {
t.Helper()
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("keygen: %v", err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano()),
Subject: pkix.Name{CommonName: domain},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{domain},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
if err != nil {
t.Fatalf("certgen: %v", err)
}
keyDER, err := x509.MarshalECPrivateKey(priv)
if err != nil {
t.Fatalf("marshal key: %v", err)
}
certPEM = string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
keyPEM = string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}))
return certPEM, keyPEM
}
func useTempCertsDir(t *testing.T) string {
t.Helper()
dir := t.TempDir()
old := tlsCertsDir
tlsCertsDir = dir
t.Cleanup(func() { tlsCertsDir = old })
oldCfg := getGlobalCfg()
t.Cleanup(func() { setGlobalCfg(oldCfg) })
return dir
}
func postCertUpdate(t *testing.T, body map[string]interface{}) *httptest.ResponseRecorder {
t.Helper()
raw, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/tls/certs/update", strings.NewReader(string(raw)))
rec := httptest.NewRecorder()
handleTLSCertUpdate(rec, req)
return rec
}
func TestCertUpdateStoresNamedCertAndReportsExpiry(t *testing.T) {
dir := useTempCertsDir(t)
certPEM, keyPEM := makeTestCertPair(t, "panel.example.com", time.Now().Add(-time.Hour), time.Now().Add(30*24*time.Hour))
rec := postCertUpdate(t, map[string]interface{}{
"name": "panel-example",
"fullchain": certPEM,
"privkey": keyPEM,
"reload": false,
})
if rec.Code != http.StatusOK {
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
}
var resp struct {
CertFile string `json:"cert_file"`
KeyFile string `json:"key_file"`
Cert tlsCertInfo `json:"cert"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
wantCert := filepath.Join(dir, "panel-example", tlsCertFileName)
if filepath.Clean(resp.CertFile) != wantCert {
t.Fatalf("cert_file = %q, want %q", resp.CertFile, wantCert)
}
if !resp.Cert.KeyOK {
t.Fatalf("expected key to match certificate: %+v", resp.Cert)
}
if resp.Cert.Expired || resp.Cert.DaysLeft < 25 {
t.Fatalf("unexpected expiry data: %+v", resp.Cert)
}
if len(resp.Cert.Domains) != 1 || resp.Cert.Domains[0] != "panel.example.com" {
t.Fatalf("domains = %v", resp.Cert.Domains)
}
data, err := os.ReadFile(wantCert)
if err != nil || !strings.Contains(string(data), "BEGIN CERTIFICATE") {
t.Fatalf("cert not written: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, "panel-example", tlsKeyFileName)); err != nil {
t.Fatalf("key not written: %v", err)
}
}
func TestCertUpdateReplacesInPlaceAndKeepsBackup(t *testing.T) {
dir := useTempCertsDir(t)
oldCert, oldKey := makeTestCertPair(t, "old.example.com", time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
if rec := postCertUpdate(t, map[string]interface{}{
"name": "renew-me", "fullchain": oldCert, "privkey": oldKey, "reload": false,
}); rec.Code != http.StatusOK {
t.Fatalf("seed failed: %s", rec.Body.String())
}
certFile := filepath.Join(dir, "renew-me", tlsCertFileName)
keyFile := filepath.Join(dir, "renew-me", tlsKeyFileName)
newCert, newKey := makeTestCertPair(t, "new.example.com", time.Now().Add(-time.Hour), time.Now().Add(90*24*time.Hour))
rec := postCertUpdate(t, map[string]interface{}{
"cert_file": certFile, "key_file": keyFile,
"fullchain": newCert, "privkey": newKey, "reload": false,
})
if rec.Code != http.StatusOK {
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
}
var resp struct {
Cert tlsCertInfo `json:"cert"`
Warnings []string `json:"warnings"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp.Cert.Domains[0] != "new.example.com" {
t.Fatalf("cert was not replaced: %+v", resp.Cert)
}
backup, err := os.ReadFile(certFile + ".bak")
if err != nil {
t.Fatalf("no backup written: %v", err)
}
if strings.TrimSpace(string(backup)) != strings.TrimSpace(oldCert) {
t.Fatal("backup does not hold the previous certificate")
}
if _, err := os.Stat(keyFile + ".bak"); err != nil {
t.Fatalf("no key backup: %v", err)
}
joined := strings.Join(resp.Warnings, " | ")
if !strings.Contains(joined, "domínios mudaram") {
t.Fatalf("expected a domain-change warning, got %q", joined)
}
}
func TestCertUpdateRejectsBadInput(t *testing.T) {
dir := useTempCertsDir(t)
certPEM, keyPEM := makeTestCertPair(t, "a.example.com", time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
_, otherKey := makeTestCertPair(t, "b.example.com", time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
expiredCert, expiredKey := makeTestCertPair(t, "old.example.com", time.Now().Add(-48*time.Hour), time.Now().Add(-time.Hour))
// Absolute, but neither panel-managed nor referenced by the configuration.
unmanaged := t.TempDir()
cases := []struct {
name string
body map[string]interface{}
want string
}{
{"missing key", map[string]interface{}{"name": "x", "fullchain": certPEM}, "obrigatórios"},
{"mismatched pair", map[string]interface{}{"name": "x", "fullchain": certPEM, "privkey": otherKey}, "não correspondentes"},
{"expired without force", map[string]interface{}{"name": "x", "fullchain": expiredCert, "privkey": expiredKey}, "expirou"},
{"unmanaged path", map[string]interface{}{
"cert_file": filepath.Join(unmanaged, "cert.pem"),
"key_file": filepath.Join(unmanaged, "key.pem"),
"fullchain": certPEM, "privkey": keyPEM,
}, "não gerenciado"},
{"relative path", map[string]interface{}{"cert_file": "certs/cert.pem", "fullchain": certPEM, "privkey": keyPEM}, "absoluto"},
{"bad name", map[string]interface{}{"name": "../escape", "fullchain": certPEM, "privkey": keyPEM}, "nome"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec := postCertUpdate(t, tc.body)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status %d, want 400 (body %s)", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), tc.want) {
t.Fatalf("body %q does not mention %q", rec.Body.String(), tc.want)
}
})
}
if entries, err := os.ReadDir(dir); err == nil && len(entries) != 0 {
t.Fatalf("rejected requests wrote %d entries to the certs dir", len(entries))
}
}
func TestCertUpdateForceAcceptsExpiredCert(t *testing.T) {
useTempCertsDir(t)
expiredCert, expiredKey := makeTestCertPair(t, "old.example.com", time.Now().Add(-48*time.Hour), time.Now().Add(-time.Hour))
rec := postCertUpdate(t, map[string]interface{}{
"name": "forced", "fullchain": expiredCert, "privkey": expiredKey, "reload": false, "force": true,
})
if rec.Code != http.StatusOK {
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
}
var resp struct {
Cert tlsCertInfo `json:"cert"`
Warnings []string `json:"warnings"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if !resp.Cert.Expired {
t.Fatal("expected the stored certificate to be reported as expired")
}
if !strings.Contains(strings.Join(resp.Warnings, " | "), "expirado") {
t.Fatalf("expected an expiry warning, got %v", resp.Warnings)
}
}
// A certificate referenced only by the running config (for example a certbot
// path outside the panel directory) must still be updatable in place, because
// that is what makes a renewal invisible to the rest of the configuration.
func TestCertUpdateAllowsPathReferencedByConfig(t *testing.T) {
useTempCertsDir(t)
external := t.TempDir()
certFile := filepath.Join(external, "fullchain.pem")
keyFile := filepath.Join(external, "privkey.pem")
oldCert, oldKey := makeTestCertPair(t, "tunnel.example.com", time.Now().Add(-time.Hour), time.Now().Add(24*time.Hour))
if err := os.WriteFile(certFile, []byte(oldCert), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(keyFile, []byte(oldKey), 0o600); err != nil {
t.Fatal(err)
}
setGlobalCfg(&Config{TLSForwarders: []TLSForwarderConfig{{
Listen: "0.0.0.0:8443", CertFile: certFile, KeyFile: keyFile,
}}})
newCert, newKey := makeTestCertPair(t, "tunnel.example.com", time.Now().Add(-time.Hour), time.Now().Add(60*24*time.Hour))
rec := postCertUpdate(t, map[string]interface{}{
"cert_file": certFile, "key_file": keyFile,
"fullchain": newCert, "privkey": newKey, "reload": false,
})
if rec.Code != http.StatusOK {
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
}
stored, err := os.ReadFile(certFile)
if err != nil {
t.Fatal(err)
}
if strings.TrimSpace(string(stored)) != strings.TrimSpace(newCert) {
t.Fatal("external certificate path was not updated")
}
var resp struct {
Cert tlsCertInfo `json:"cert"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if len(resp.Cert.UsedBy) != 1 || resp.Cert.UsedBy[0].Ref != "0.0.0.0:8443" {
t.Fatalf("expected the TLS forwarder to be reported as consumer, got %+v", resp.Cert.UsedBy)
}
}
func TestTLSCertListReportsConfiguredAndManagedCerts(t *testing.T) {
dir := useTempCertsDir(t)
certPEM, keyPEM := makeTestCertPair(t, "listed.example.com", time.Now().Add(-time.Hour), time.Now().Add(10*24*time.Hour))
if err := os.MkdirAll(filepath.Join(dir, "listed"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "listed", tlsCertFileName), []byte(certPEM), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "listed", tlsKeyFileName), []byte(keyPEM), 0o600); err != nil {
t.Fatal(err)
}
setGlobalCfg(&Config{})
req := httptest.NewRequest(http.MethodGet, "/api/tls/certs", nil)
rec := httptest.NewRecorder()
handleTLSCertList(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
}
var resp struct {
Certs []tlsCertInfo `json:"certs"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if len(resp.Certs) != 1 {
t.Fatalf("expected 1 cert, got %d (%+v)", len(resp.Certs), resp.Certs)
}
got := resp.Certs[0]
if got.Name != "listed" || !got.Managed || !got.KeyOK || !got.SelfSigned {
t.Fatalf("unexpected cert info: %+v", got)
}
if !got.Expiring || got.Expired {
t.Fatalf("a cert expiring in 10 days should be flagged as expiring: %+v", got)
}
}
+263
View File
@@ -0,0 +1,263 @@
package main
// This file provides the in-memory connection that carries a tunnelled session
// into this process's own SSH server.
//
// The obvious choice, net.Pipe, is unbuffered: every Write blocks until the
// peer Reads the same bytes. That couples the two sides in lock step, so a
// transport goroutine that is momentarily writing cannot also be draining, and
// each direction pays a scheduler round trip per write. A small buffer in each
// direction removes both problems and matches how a real TCP socket behaves,
// which is what the SSH server on the other end is written against.
import (
"errors"
"io"
"net"
"os"
"sync"
"time"
)
// tunnelPipeBuffer is the per-direction buffer, chosen to hold a full SSH
// handshake plus a couple of maximum-size packets without blocking. It bounds
// memory: two of these per tunnelled session, and nothing grows past them.
const tunnelPipeBuffer = 256 * 1024
// tunnelPipe is one direction of the connection: a bounded byte queue with
// deadline-aware blocking reads and writes.
type tunnelPipe struct {
mu sync.Mutex
data []byte
offset int
max int
// signal is closed and replaced whenever the queue changes, so waiters can
// select on it alongside a deadline. This mirrors how the transports in
// this codebase already signal readiness.
signal chan struct{}
closed bool
}
func newTunnelPipe(max int) *tunnelPipe {
return &tunnelPipe{max: max, signal: make(chan struct{})}
}
// broadcastLocked wakes every waiter. The caller must hold mu.
func (p *tunnelPipe) broadcastLocked() {
close(p.signal)
p.signal = make(chan struct{})
}
func (p *tunnelPipe) availableLocked() int { return len(p.data) - p.offset }
// compactLocked reclaims the consumed prefix once it is worth the copy.
func (p *tunnelPipe) compactLocked() {
if p.offset == 0 {
return
}
if p.offset == len(p.data) {
p.data = p.data[:0]
p.offset = 0
return
}
if p.offset >= p.max/2 {
copy(p.data, p.data[p.offset:])
p.data = p.data[:len(p.data)-p.offset]
p.offset = 0
}
}
// write copies data into the queue, blocking while it is full. It returns the
// number of bytes accepted, which is all of them unless the pipe closed or the
// deadline fired.
func (p *tunnelPipe) write(data []byte, deadline func() time.Time) (int, error) {
written := 0
for len(data) > 0 {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return written, io.ErrClosedPipe
}
p.compactLocked()
room := p.max - p.availableLocked()
if room > 0 {
if room > len(data) {
room = len(data)
}
p.data = append(p.data, data[:room]...)
data = data[room:]
written += room
p.broadcastLocked()
p.mu.Unlock()
continue
}
wait := p.signal
p.mu.Unlock()
if err := waitWithDeadline(wait, deadline); err != nil {
return written, err
}
}
return written, nil
}
// read copies out whatever is queued, blocking until at least one byte is
// available, the pipe closes, or the deadline fires.
func (p *tunnelPipe) read(out []byte, deadline func() time.Time) (int, error) {
if len(out) == 0 {
return 0, nil
}
for {
p.mu.Lock()
if available := p.availableLocked(); available > 0 {
n := copy(out, p.data[p.offset:])
p.offset += n
p.compactLocked()
p.broadcastLocked()
p.mu.Unlock()
return n, nil
}
if p.closed {
p.mu.Unlock()
return 0, io.EOF
}
wait := p.signal
p.mu.Unlock()
if err := waitWithDeadline(wait, deadline); err != nil {
return 0, err
}
}
}
// close marks the direction finished. Queued bytes stay readable so a peer can
// drain what was already sent, matching how a closed TCP socket behaves.
func (p *tunnelPipe) close() {
p.mu.Lock()
if !p.closed {
p.closed = true
p.broadcastLocked()
}
p.mu.Unlock()
}
// waitWithDeadline blocks until the pipe signals, or the deadline passes.
func waitWithDeadline(signal <-chan struct{}, deadline func() time.Time) error {
at := deadline()
if at.IsZero() {
<-signal
return nil
}
delay := time.Until(at)
if delay <= 0 {
return os.ErrDeadlineExceeded
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-signal:
return nil
case <-timer.C:
return os.ErrDeadlineExceeded
}
}
// tunnelConn is one end of a buffered in-memory connection. It satisfies
// net.Conn, deadlines included, because the SSH server relies on
// SetReadDeadline to bound an unfinished handshake.
type tunnelConn struct {
recv *tunnelPipe
send *tunnelPipe
addr transportAddr
deadlineMu sync.RWMutex
readDeadline time.Time
writeDeadline time.Time
closeOnce sync.Once
}
// newTunnelConnPair returns the two ends of a buffered connection. Bytes
// written to one end are readable from the other.
func newTunnelConnPair(label string, buffer int) (*tunnelConn, *tunnelConn) {
if buffer <= 0 {
buffer = tunnelPipeBuffer
}
toServer := newTunnelPipe(buffer)
toClient := newTunnelPipe(buffer)
addr := transportAddr(label)
client := &tunnelConn{recv: toClient, send: toServer, addr: addr}
server := &tunnelConn{recv: toServer, send: toClient, addr: addr}
return client, server
}
func (c *tunnelConn) Read(p []byte) (int, error) {
return c.recv.read(p, c.currentReadDeadline)
}
func (c *tunnelConn) Write(p []byte) (int, error) {
n, err := c.send.write(p, c.currentWriteDeadline)
if errors.Is(err, io.ErrClosedPipe) && n < len(p) {
return n, io.ErrClosedPipe
}
return n, err
}
// Close shuts both directions. The peer's pending reads drain what was already
// queued and then see EOF.
func (c *tunnelConn) Close() error {
c.closeOnce.Do(func() {
c.send.close()
c.recv.close()
})
return nil
}
func (c *tunnelConn) LocalAddr() net.Addr { return c.addr }
func (c *tunnelConn) RemoteAddr() net.Addr { return c.addr }
func (c *tunnelConn) SetDeadline(t time.Time) error {
c.deadlineMu.Lock()
c.readDeadline = t
c.writeDeadline = t
c.deadlineMu.Unlock()
c.wakeWaiters()
return nil
}
func (c *tunnelConn) SetReadDeadline(t time.Time) error {
c.deadlineMu.Lock()
c.readDeadline = t
c.deadlineMu.Unlock()
c.wakeWaiters()
return nil
}
func (c *tunnelConn) SetWriteDeadline(t time.Time) error {
c.deadlineMu.Lock()
c.writeDeadline = t
c.deadlineMu.Unlock()
c.wakeWaiters()
return nil
}
// wakeWaiters re-evaluates blocked readers and writers so a deadline set while
// they are parked takes effect instead of being seen only on the next wakeup.
func (c *tunnelConn) wakeWaiters() {
c.recv.mu.Lock()
c.recv.broadcastLocked()
c.recv.mu.Unlock()
c.send.mu.Lock()
c.send.broadcastLocked()
c.send.mu.Unlock()
}
func (c *tunnelConn) currentReadDeadline() time.Time {
c.deadlineMu.RLock()
defer c.deadlineMu.RUnlock()
return c.readDeadline
}
func (c *tunnelConn) currentWriteDeadline() time.Time {
c.deadlineMu.RLock()
defer c.deadlineMu.RUnlock()
return c.writeDeadline
}
+223
View File
@@ -0,0 +1,223 @@
package main
// This file lets the tunnel transports share the ports the panel already owns:
// the HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080)
// and the TLS forwarders (normally 443).
//
// It works because the protocols on these ports open in mutually incompatible
// ways. A BHTTP frame starts with its mode number (0..5). A BTUN session starts
// with the fixed ASCII marker "DTUNNEL/1.1 CLIENT_HELLO". SSH starts with "SSH-"
// and an HTTP request or status line starts with a method or version letter.
// Each transport's own package owns the check for its wire format, so the rules
// live next to the protocol they describe.
//
// Nothing is ever consumed on a negative verdict: the bytes stay in the
// returned reader, and the caller continues with its normal handling as if this
// file did not exist.
import (
"bufio"
"encoding/binary"
"net"
"time"
"shell2/internal/bhttp"
"shell2/internal/btun"
"shell2/internal/hcr"
)
// tunnelSniffTimeout bounds how long a shared listener waits for a client's
// first bytes. Every protocol here speaks immediately on connect, so a client
// that says nothing for this long is handed to the normal HTTP/SSH path rather
// than being held any longer.
const tunnelSniffTimeout = 3 * time.Second
// tunnelSharedReaderSize must hold the largest prefix any sniff can ask for.
const tunnelSharedReaderSize = bhttp.SniffLimit + 64
// tunnelShareEnabled reports whether any transport wants the shared ports, so
// the listeners can skip all of this when none do.
func tunnelShareEnabled() bool {
return bhttpShareEnabled() || btunShareEnabled() || hcrShareEnabled()
}
// tunnelTakeSharedConn inspects the front of a connection that arrived on a
// port owned by another protocol and, when it belongs to a tunnel transport,
// serves it to completion.
//
// It returns the reader to keep using and whether the connection was consumed.
// When it returns false the caller continues with its normal handling, and the
// returned reader holds every byte that was inspected.
func tunnelTakeSharedConn(conn net.Conn, reader *bufio.Reader) (*bufio.Reader, bool) {
if reader == nil {
reader = bufio.NewReaderSize(conn, tunnelSharedReaderSize)
}
bhttpOn := bhttpShareEnabled()
btunOn := btunShareEnabled()
hcrOn := hcrShareEnabled()
if !bhttpOn && !btunOn && !hcrOn {
return reader, false
}
// The sniff needs its own deadline: the caller has not set one yet, and a
// client that connects without sending must not wedge this goroutine.
_ = conn.SetReadDeadline(time.Now().Add(tunnelSniffTimeout))
defer func() { _ = conn.SetReadDeadline(time.Time{}) }()
// BTUN is checked first because its marker is a fixed string that either
// matches from the first byte or does not. The two transports cannot both
// claim a connection: a BHTTP frame opens with a byte below 6 and the BTUN
// marker opens with 'D'.
if btunOn && tunnelSniff(reader, btunSniffStep) {
return reader, btunServeShared(conn, reader)
}
if hcrOn && tunnelSniff(reader, hcrSniffStep) {
return reader, hcrServeShared(conn, reader)
}
if bhttpOn && tunnelSniff(reader, bhttpSniffStep) {
return reader, bhttpServeShared(conn, reader)
}
return reader, false
}
// sniffStep inspects the bytes peeked so far. It returns the protocol's verdict
// and, when undecided, how many bytes to peek before asking again.
type sniffStep func(peeked []byte) (verdict int, want int)
// The verdicts a sniffStep may return, shared by both transports.
const (
sniffNo = iota
sniffMore
sniffYes
)
// tunnelSniff runs one protocol's check, peeking progressively so a protocol
// that is rejected on its first byte costs exactly one byte of lookahead.
func tunnelSniff(reader *bufio.Reader, step sniffStep) bool {
want := 1
for {
peeked, err := reader.Peek(want)
verdict, next := sniffNo, want
if len(peeked) > 0 {
verdict, next = step(peeked)
}
switch {
case verdict == sniffYes:
return true
case verdict == sniffNo:
return false
case err != nil:
// Not enough bytes arrived to decide, so this is not the protocol
// as far as this listener is concerned.
return false
case next <= len(peeked):
// A step that cannot make progress would loop forever.
return false
}
want = next
}
}
// btunSniffStep matches the fixed BTUN client hello.
func btunSniffStep(peeked []byte) (int, int) {
switch btun.SniffClientHello(peeked) {
case btun.VerdictYes:
return sniffYes, 0
case btun.VerdictMore:
return sniffMore, btun.SniffLimit
}
return sniffNo, 0
}
// bhttpSniffStep matches a BHTTP frame: the header first, then the payload the
// header declares, which is where the magic strings that settle it live.
func bhttpSniffStep(peeked []byte) (int, int) {
switch bhttp.SniffFrame(peeked) {
case bhttp.VerdictYes:
return sniffYes, 0
case bhttp.VerdictMore:
if len(peeked) < bhttp.HeaderSize {
return sniffMore, bhttp.HeaderSize
}
want := bhttp.HeaderSize + int(binary.BigEndian.Uint32(peeked[25:29]))
if want > bhttp.SniffLimit {
want = bhttp.SniffLimit
}
return sniffMore, want
}
return sniffNo, 0
}
// hcrSniffStep matches an HCR request: its opcode, then its fixed version byte,
// then the full 62-byte header. A BHTTP frame whose session byte is not 0x01 is
// rejected at two bytes, so it never waits for 62 bytes.
func hcrSniffStep(peeked []byte) (int, int) {
switch hcr.SniffFrame(peeked) {
case hcr.VerdictYes:
return sniffYes, 0
case hcr.VerdictMore:
if len(peeked) < 2 {
return sniffMore, 2
}
return sniffMore, hcr.RequestHeaderSize
}
return sniffNo, 0
}
// hcrServeShared hands an identified connection to the running HCR server.
func hcrServeShared(conn net.Conn, reader *bufio.Reader) bool {
hcrMu.Lock()
server := hcrServer
ctx := hcrCtx
hcrMu.Unlock()
if server == nil || ctx == nil {
return false
}
// The engine's own debug log records the session; no extra line here.
server.ServeConn(ctx, &bufferedConn{Conn: conn, r: reader})
return true
}
// bhttpServeShared hands an identified connection to the running BHTTP server.
func bhttpServeShared(conn net.Conn, reader *bufio.Reader) bool {
bhttpMu.Lock()
server := bhttpServer
bhttpMu.Unlock()
if server == nil {
return false
}
if bhttpLogConnections() {
bhttpLog.Printf("shared port: %s -> %s handed to BHTTP", conn.RemoteAddr(), conn.LocalAddr())
}
// The inspected bytes live in the reader, so the server has to read through
// it rather than from the socket.
server.ServeConn(&bufferedConn{Conn: conn, r: reader})
return true
}
// btunServeShared hands an identified connection to the running BTUN server.
func btunServeShared(conn net.Conn, reader *bufio.Reader) bool {
btunMu.Lock()
server := btunServer
btunMu.Unlock()
if server == nil {
return false
}
if btunLogConnections() {
btunLog.Printf("shared port: %s -> %s handed to BTUN", conn.RemoteAddr(), conn.LocalAddr())
}
server.ServeConn(&bufferedConn{Conn: conn, r: reader})
return true
}
func bhttpLogConnections() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.BHTTP != nil && globalCfg.BHTTP.LogConnections
}
func btunLogConnections() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.BTUN != nil && globalCfg.BTUN.LogConnections
}
+685
View File
@@ -0,0 +1,685 @@
package main
// This file embeds the UDP gateway (udpgw) service into the main
// application. The original udpgw program (public domain) accepts a
// TCP connection, then forwards framed UDP datagrams to arbitrary
// destinations and demultiplexes replies back to the originating
// connection. Here we expose the same functionality via a
// configuration key in config.json. When enabled, the server binds
// to the provided Listen address (or the default 0.0.0.0:7400 if
// unspecified) and handles each client in its own goroutine. The
// gateway runs entirely in‑process and behaves like the standalone
// badvpn-udpgw daemon.
import (
"bufio"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
"strings"
"sync"
"time"
)
// Safe ceilings applied regardless of config, so oversized values left in an
// existing config.json cannot bloat per-client memory at scale.
const (
udpgwSocketBufferMax = 512 * 1024 // per-client UDP socket buffer (kernel memory)
udpgwWriteChanMax = 1024 // per-client reply queue slots
udpgwDefaultMaxClients = 10000 // total concurrent client cap
)
var (
udpgwMu sync.Mutex
udpgwLn net.Listener
udpgwClients = make(map[net.Conn]struct{})
// udpgwClientLimit is the max concurrent clients (0 = unlimited). Set when
// the listener starts and read on every accept, all under udpgwMu.
udpgwClientLimit int
// udpgwClientsRejected counts clients turned away at the cap, for logging
// and future stats. Guarded by udpgwMu.
udpgwClientsRejected int64
udpgwAutoMu sync.Mutex
udpgwAutoCancel context.CancelFunc
)
// stopUDPGW closes the active UDPGW listener, all active UDPGW client TCP
// sockets, and the optional auto-restart watchdog. It is a no-op if UDPGW is
// not running.
func stopUDPGW() {
stopUDPGWAutoRestart()
stopUDPGWInstance()
}
func stopUDPGWInstance() {
udpgwMu.Lock()
defer udpgwMu.Unlock()
if udpgwLn != nil {
_ = udpgwLn.Close()
udpgwLn = nil
}
for conn := range udpgwClients {
_ = conn.Close()
delete(udpgwClients, conn)
}
}
func stopUDPGWAutoRestart() {
udpgwAutoMu.Lock()
defer udpgwAutoMu.Unlock()
if udpgwAutoCancel != nil {
udpgwAutoCancel()
udpgwAutoCancel = nil
}
}
func registerUDPGWClient(conn net.Conn) bool {
udpgwMu.Lock()
defer udpgwMu.Unlock()
if udpgwLn == nil {
_ = conn.Close()
return false
}
// Reject past the hard client cap so a surge cannot exhaust memory.
if udpgwClientLimit > 0 && len(udpgwClients) >= udpgwClientLimit {
udpgwClientsRejected++
rejected := udpgwClientsRejected
_ = conn.Close()
// Log the first rejection and then every 1000th to avoid log spam.
if rejected == 1 || rejected%1000 == 0 {
log.Printf("udpgw: client cap reached (%d); rejected %d client(s) so far", udpgwClientLimit, rejected)
}
return false
}
udpgwClients[conn] = struct{}{}
return true
}
func unregisterUDPGWClient(conn net.Conn) {
udpgwMu.Lock()
delete(udpgwClients, conn)
udpgwMu.Unlock()
}
func udpgwRunning() bool {
udpgwMu.Lock()
defer udpgwMu.Unlock()
return udpgwLn != nil
}
// startUDPGW starts the integrated UDP gateway if cfg is non‑nil and
// cfg.Listen is non‑empty. It applies default values to any zero
// configuration fields and converts duration strings to time.Duration.
// The server runs in a goroutine; any fatal errors are logged and
// prevent the gateway from starting, but do not terminate the main
// process.
func startUDPGW(cfg *UDPGWConfig) error {
if cfg == nil {
return nil
}
stopUDPGWAutoRestart()
if err := startUDPGWInstance(cfg); err != nil {
return err
}
startUDPGWAutoRestart(cfg)
return nil
}
func startUDPGWInstance(cfg *UDPGWConfig) error {
if cfg == nil {
return nil
}
// Default the listen address to the standalone default (0.0.0.0:7400) if
// unspecified. This matches the behaviour of the original
// badvpn-udpgw program, which listens on all interfaces by default.
listenAddr := cfg.Listen
if listenAddr == "" {
listenAddr = defaultUDPGWListen
}
cfg.Listen = listenAddr
// Apply defaults for numeric fields if zero.
c := &internalUDPGWConfig{}
c.listen = listenAddr
if cfg.MaxFrame > 0 {
c.maxFrame = cfg.MaxFrame
} else {
c.maxFrame = 64 * 1024
}
c.debug = cfg.Debug
if cfg.HexdumpN > 0 {
c.hexdumpN = cfg.HexdumpN
} else {
c.hexdumpN = 64
}
// Per-client outgoing frame queue. A large queue costs ~24 B/slot of heap
// per client even when empty; at thousands of clients that adds up. UDP is
// lossy by nature, so a smaller queue that drops under backpressure is fine.
// The value is clamped to udpgwWriteChanMax so an oversized value left in an
// old config.json is ignored; only smaller custom values are honored.
c.writeChan = udpgwWriteChanMax
if cfg.WriteChan > 0 && cfg.WriteChan < udpgwWriteChanMax {
c.writeChan = cfg.WriteChan
}
c.udpBindIP = cfg.UDPBindIP
// Per-client UDP socket buffers are KERNEL memory, allocated per connected
// client. 8 MB per socket is fine for a single process-wide listener, but
// here every tunnel user gets its own socket, so a large value multiplied by
// thousands of clients can exhaust kernel memory (especially if
// net.core.rmem_max was raised for DNSTT). Clamp to udpgwSocketBufferMax so
// old large config values are ignored; only smaller custom values are used.
c.udpRBuf = udpgwSocketBufferMax
if cfg.UDPRBuf > 0 && cfg.UDPRBuf < udpgwSocketBufferMax {
c.udpRBuf = cfg.UDPRBuf
}
c.udpWBuf = udpgwSocketBufferMax
if cfg.UDPWBuf > 0 && cfg.UDPWBuf < udpgwSocketBufferMax {
c.udpWBuf = cfg.UDPWBuf
}
// Parse durations with fallback defaults.
if cfg.MapTTL != "" {
if d, err := time.ParseDuration(cfg.MapTTL); err == nil {
c.mapTTL = d
} else {
log.Printf("udpgw: invalid map_ttl %q: %v; using default 90s", cfg.MapTTL, err)
c.mapTTL = 90 * time.Second
}
} else {
c.mapTTL = 90 * time.Second
}
if cfg.ReapEvery != "" {
if d, err := time.ParseDuration(cfg.ReapEvery); err == nil {
c.reapEvery = d
} else {
log.Printf("udpgw: invalid reap_every %q: %v; using default 10s", cfg.ReapEvery, err)
c.reapEvery = 10 * time.Second
}
} else {
c.reapEvery = 10 * time.Second
}
// Idle timeout for TCP clients.
if cfg.IdleTimeout != "" {
if d, err := time.ParseDuration(cfg.IdleTimeout); err == nil {
c.idleTimeout = d
} else {
log.Printf("udpgw: invalid idle_timeout %q: %v; using default 2m", cfg.IdleTimeout, err)
c.idleTimeout = 2 * time.Minute
}
} else {
c.idleTimeout = 2 * time.Minute
}
// Per-client logical connID cap.
if cfg.MaxClientConns > 0 {
c.maxClientConns = cfg.MaxClientConns
} else {
c.maxClientConns = 10
}
// Per-client destination mapping cap.
if cfg.MaxMapEntries > 0 {
c.maxMapEntries = cfg.MaxMapEntries
} else {
c.maxMapEntries = 32768
}
// Total concurrent client cap. New clients past this are rejected so a
// surge (e.g. well past normal load) cannot exhaust memory and crash.
if cfg.MaxClients > 0 {
c.maxClients = cfg.MaxClients
} else {
c.maxClients = udpgwDefaultMaxClients
}
// Start listening.
ln, err := net.Listen("tcp", c.listen)
if err != nil {
log.Printf("udpgw: listen failed on %s: %v", c.listen, err)
return fmt.Errorf("udpgw: listen failed on %s: %w", c.listen, err)
}
// Register as the active listener so stopUDPGW can close it, and publish
// the current client cap so registerUDPGWClient can enforce it.
udpgwMu.Lock()
if udpgwLn != nil {
_ = udpgwLn.Close()
}
udpgwLn = ln
udpgwClientLimit = c.maxClients
udpgwMu.Unlock()
if c.debug {
log.Printf("udpgw: listening on %s", c.listen)
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
log.Printf("udpgw: accept error: %v", err)
continue
}
if !registerUDPGWClient(conn) {
continue
}
go func(client net.Conn) {
defer unregisterUDPGWClient(client)
handleUDPGWClient(client, c)
}(conn)
}
}()
return nil
}
func startUDPGWAutoRestart(cfg *UDPGWConfig) {
interval := udpgwAutoRestartInterval(cfg)
if interval <= 0 {
return
}
grace := udpgwAutoRestartGrace(cfg)
cfgCopy := *cfg
ctx, cancel := context.WithCancel(context.Background())
udpgwAutoMu.Lock()
if udpgwAutoCancel != nil {
udpgwAutoCancel()
}
udpgwAutoCancel = cancel
udpgwAutoMu.Unlock()
go func() {
t := time.NewTicker(interval)
defer t.Stop()
log.Printf("udpgw: auto restart enabled: interval=%s grace=%s mode=hard", interval, grace)
for {
select {
case <-ctx.Done():
return
case <-t.C:
log.Printf("udpgw: auto restart: stopping listener and connected clients")
stopUDPGWInstance()
if !sleepOrContextDone(ctx, grace) {
return
}
for attempt := 1; ; attempt++ {
if err := startUDPGWInstance(&cfgCopy); err != nil {
log.Printf("udpgw: auto restart: start attempt %d failed: %v", attempt, err)
if !sleepOrContextDone(ctx, 10*time.Second) {
return
}
continue
}
log.Printf("udpgw: auto restart: listener and client handler restarted")
break
}
}
}
}()
}
func udpgwAutoRestartInterval(cfg *UDPGWConfig) time.Duration {
if cfg == nil {
return 0
}
raw := strings.TrimSpace(cfg.AutoRestartInterval)
if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") {
return 0
}
d, err := time.ParseDuration(raw)
if err != nil {
log.Printf("udpgw: auto restart disabled: invalid interval %q: %v", raw, err)
return 0
}
if d < time.Minute {
log.Printf("udpgw: auto restart disabled: interval %q is below minimum 1m", raw)
return 0
}
return d
}
func udpgwAutoRestartGrace(cfg *UDPGWConfig) time.Duration {
if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" {
return 2 * time.Second
}
d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace))
if err != nil || d < 0 {
log.Printf("udpgw: auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace)
return 2 * time.Second
}
if d > time.Minute {
return time.Minute
}
return d
}
// internalUDPGWConfig mirrors the exported UDPGWConfig but with
// time.Duration fields for TTL and reaper intervals. It does not
// embed JSON tags because it is not exposed to the user.
type internalUDPGWConfig struct {
listen string
maxFrame int
debug bool
hexdumpN int
writeChan int
udpBindIP string
udpRBuf int
udpWBuf int
mapTTL time.Duration
reapEvery time.Duration
idleTimeout time.Duration
maxClientConns int
maxMapEntries int
maxClients int
}
// udpDestKey identifies a destination IPv4:port for the UDP gateway. A
// mapping of this key to a connID+x byte is kept per client so
// replies can be routed correctly. Each client maintains its own map
// of udpDestKey->udpMapVal entries.
type udpDestKey struct {
ip [4]byte
port uint16
}
// udpMapVal stores the mapping from udpDestKey to connID, the x byte and the
// expiration time.
type udpMapVal struct {
connID uint16
x byte
exp time.Time
}
// handleUDPGWClient manages a single TCP client connection to the UDP
// gateway. It creates a per‑client UDP socket, reads frames from the
// TCP connection, sends UDP datagrams to the requested destination,
// maintains a mapping of udpDestKey->udpMapVal for routing replies, and
// writes reply frames back over the TCP connection. When the client
// disconnects or an error occurs, all goroutines are terminated and the
// UDP socket is closed.
func handleUDPGWClient(conn net.Conn, c *internalUDPGWConfig) {
defer conn.Close()
remote := conn.RemoteAddr().String()
if c.debug {
log.Printf("udpgw: client connected: %s", remote)
}
// Lower latency for interactive applications by disabling Nagle.
if tcp, ok := conn.(*net.TCPConn); ok {
_ = tcp.SetNoDelay(true)
}
// 32 KiB is ample for reading length-prefixed UDPGW frames (which are
// MTU-sized in practice). bufio serves reads larger than its buffer by
// reading straight into the caller's slice, so max-frame reads still work.
// The old 256 KiB buffer wasted ~224 KiB of heap per connected client.
br := bufio.NewReaderSize(conn, 32*1024)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Bind a UDP socket for this client. Use cfg.udpBindIP if provided.
var laddr *net.UDPAddr
if c.udpBindIP != "" {
ip := net.ParseIP(c.udpBindIP)
if ip != nil {
laddr = &net.UDPAddr{IP: ip, Port: 0}
} else {
log.Printf("udpgw[%s]: invalid udp_bind IP %q", remote, c.udpBindIP)
return
}
}
udpConn, err := net.ListenUDP("udp", laddr)
if err != nil {
log.Printf("udpgw[%s]: UDP listen failed: %v", remote, err)
return
}
defer udpConn.Close()
_ = udpConn.SetReadBuffer(c.udpRBuf)
_ = udpConn.SetWriteBuffer(c.udpWBuf)
// Channel to queue outgoing frames back to the client.
writeCh := make(chan []byte, c.writeChan)
done := make(chan struct{})
go func() {
defer close(done)
for {
select {
case <-ctx.Done():
return
case b := <-writeCh:
if len(b) == 0 {
continue
}
// If the client stops reading, don't block forever.
_ = conn.SetWriteDeadline(time.Now().Add(30 * time.Second))
_, err := conn.Write(b)
if err != nil {
cancel()
return
}
}
}
}()
// Destination -> connID+x mapping and active connID tracking per TCP client.
var mu sync.Mutex
destToConn := make(map[udpDestKey]udpMapVal)
connIDLastSeen := make(map[uint16]time.Time)
// Start a reaper goroutine to purge expired mappings.
// Uses ctx instead of a separate stopReaper channel so that cancellation
// is always uniform: any exit path that calls cancel() (error, disconnect,
// idle timeout, panic-deferred cancel) also stops the reaper.
go func() {
t := time.NewTicker(c.reapEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
now := time.Now()
mu.Lock()
for k, v := range destToConn {
if now.After(v.exp) {
delete(destToConn, k)
}
}
for id, lastSeen := range connIDLastSeen {
if now.Sub(lastSeen) > c.mapTTL {
delete(connIDLastSeen, id)
}
}
mu.Unlock()
}
}
}()
// Goroutine to read UDP replies and write framed responses back.
go func() {
buf := make([]byte, 65535)
for {
n, from, err := udpConn.ReadFromUDP(buf)
if err != nil {
return
}
if n <= 0 {
continue
}
ip4 := from.IP.To4()
if ip4 == nil {
// IPv6 replies are dropped because framing only supports IPv4.
continue
}
k := udpDestKey{port: uint16(from.Port)}
copy(k.ip[:], ip4)
mu.Lock()
v, ok := destToConn[k]
mu.Unlock()
if !ok || time.Now().After(v.exp) {
if c.debug {
log.Printf("udpgw[%s]: dropping %dB from %s (no mapping)", remote, n, from.String())
}
continue
}
// Avoid unbounded memory growth: if the client is slow and the
// write queue is full, drop replies rather than allocating more.
if len(writeCh) == cap(writeCh) {
if c.debug {
log.Printf("udpgw[%s]: drop UDP reply %dB from %s (write queue full)", remote, n, from.String())
}
continue
}
frame := udpgwBuildFrame(v.connID, v.x, k.ip, k.port, buf[:n])
select {
case <-ctx.Done():
return
case writeCh <- frame:
default:
// Race with another sender filling the channel.
}
if c.debug {
log.Printf("udpgw[%s]: UDP<- %dB from %s -> connID=%d x=0x%02x", remote, n, from.String(), v.connID, v.x)
}
}
}()
// Main loop: read frames from TCP, update mapping and send UDP.
for {
// Close idle TCP clients to avoid leaking goroutines.
if c.idleTimeout > 0 {
_ = conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
}
payload, err := udpgwReadPayload(br, c.maxFrame)
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Timeout() {
if c.debug {
log.Printf("udpgw[%s]: idle timeout (%s); closing", remote, c.idleTimeout)
}
}
if err == io.EOF {
if c.debug {
log.Printf("udpgw: client disconnected: %s", remote)
}
} else {
log.Printf("udpgw[%s]: read error: %v", remote, err)
}
cancel()
_ = conn.Close()
<-done
return
}
// payload: connID(2) + X(1) + dstIPv4(4) + dstPort(2) + data
if len(payload) < 2+1+4+2 {
if c.debug {
log.Printf("udpgw[%s]: too short payload %dB", remote, len(payload))
}
continue
}
connID := binary.BigEndian.Uint16(payload[0:2])
x := payload[2]
var dstIP [4]byte
copy(dstIP[:], payload[3:7])
dstPort := binary.BigEndian.Uint16(payload[7:9])
data := payload[9:]
if c.debug {
log.Printf("udpgw[%s]: RX connID=%d dst=%d.%d.%d.%d:%d x=0x%02x len=%d", remote, connID, dstIP[0], dstIP[1], dstIP[2], dstIP[3], dstPort, x, len(data))
}
// Enforce a per-client logical session cap using udpgw connID.
k := udpDestKey{ip: dstIP, port: dstPort}
now := time.Now()
mu.Lock()
// Step 1: evict TTL-expired connIDs first.
for id, lastSeen := range connIDLastSeen {
if now.Sub(lastSeen) > c.mapTTL {
delete(connIDLastSeen, id)
}
}
// Step 2: if the connID is new and we are still at or above the cap
// after TTL eviction, evict the single oldest entry to make room.
// This prevents a client rotating connIDs faster than mapTTL from
// bypassing maxClientConns and growing the map indefinitely.
if _, alreadyKnown := connIDLastSeen[connID]; !alreadyKnown && c.maxClientConns > 0 && len(connIDLastSeen) >= c.maxClientConns {
// Find and remove the oldest connID seen.
var oldestID uint16
var oldestTime time.Time
first := true
for id, lastSeen := range connIDLastSeen {
if first || lastSeen.Before(oldestTime) {
oldestID = id
oldestTime = lastSeen
first = false
}
}
delete(connIDLastSeen, oldestID)
if c.debug {
log.Printf("udpgw[%s]: connID cap reached (%d); evicted oldest connID=%d to admit connID=%d", remote, c.maxClientConns, oldestID, connID)
}
}
connIDLastSeen[connID] = now
// Update the mapping (bounded to protect memory).
if c.maxMapEntries > 0 && len(destToConn) >= c.maxMapEntries {
// First, purge expired entries.
for dk, dv := range destToConn {
if now.After(dv.exp) {
delete(destToConn, dk)
}
}
// If still too large, evict arbitrary entries until we're under the cap.
if len(destToConn) >= c.maxMapEntries {
evict := (len(destToConn) - c.maxMapEntries) + 1
for dk := range destToConn {
delete(destToConn, dk)
evict--
if evict <= 0 {
break
}
}
if c.debug {
log.Printf("udpgw[%s]: mapping cap reached; evicted entries, size=%d", remote, len(destToConn))
}
}
}
destToConn[k] = udpMapVal{connID: connID, x: x, exp: now.Add(c.mapTTL)}
mu.Unlock()
// Send the UDP datagram.
raddr := &net.UDPAddr{IP: net.IP(dstIP[:]), Port: int(dstPort)}
_, err = udpConn.WriteToUDP(data, raddr)
if err != nil {
if c.debug {
log.Printf("udpgw[%s]: UDP write failed to %s: %v", remote, raddr.String(), err)
}
continue
}
if c.debug {
log.Printf("udpgw[%s]: UDP-> %dB to %s", remote, len(data), raddr.String())
}
}
}
// udpgwReadPayload reads a length‑prefixed payload from r. The length
// prefix is a little‑endian uint16. Payloads larger than max cause an
// error.
func udpgwReadPayload(r *bufio.Reader, max int) ([]byte, error) {
var lenBuf [2]byte
if _, err := io.ReadFull(r, lenBuf[:]); err != nil {
return nil, err
}
n := int(binary.LittleEndian.Uint16(lenBuf[:]))
if n <= 0 || n > max {
return nil, fmt.Errorf("udpgw: invalid frame length %d", n)
}
b := make([]byte, n)
if _, err := io.ReadFull(r, b); err != nil {
return nil, err
}
return b, nil
}
// udpgwBuildFrame constructs a reply frame for the client. The frame
// consists of a little‑endian length prefix, then connID (big endian),
// x byte, source IPv4, source port, and the data.
func udpgwBuildFrame(connID uint16, x byte, ip [4]byte, port uint16, data []byte) []byte {
payloadLen := 2 + 1 + 4 + 2 + len(data)
out := make([]byte, 2+payloadLen)
binary.LittleEndian.PutUint16(out[0:2], uint16(payloadLen))
binary.BigEndian.PutUint16(out[2:4], connID)
out[4] = x
copy(out[5:9], ip[:])
binary.BigEndian.PutUint16(out[9:11], port)
copy(out[11:], data)
return out
}
+614
View File
@@ -0,0 +1,614 @@
#!/bin/bash
# Update the DragonCoreSSH CLI from a local extracted release.
#
# Preserved:
# - /opt/sshpanel/.env
# - /opt/sshpanel/config.json
# - /opt/sshpanel/xray_config.json
# - SSH keys, certs, logs, database, users
#
# Usage:
# sudo bash /opt/sshpanel/update.sh
# sudo bash update.sh
#
# Run from an extracted DragonCoreSSH-CLI source directory to apply that release.
# Installed /opt/sshpanel/update.sh rebuilds the cached CLI source.
set -euo pipefail
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info() { echo -e "${GREEN}[+]${NC} $*"; }
warn() { echo -e "${YELLOW}[!]${NC} $*"; }
error() { echo -e "${RED}[x]${NC} $*"; exit 1; }
# Config
INSTALL_DIR="${INSTALL_DIR:-/opt/sshpanel}"
SERVICE_NAME="${SERVICE_NAME:-sshpanel}"
LOG_TMPFS_SIZE="${LOG_TMPFS_SIZE:-15m}"
PANEL_LOG_MAX_BYTES="${PANEL_LOG_MAX_BYTES:-1048576}"
REPO_URL="local-cli-source"
UPDATE_REF="${UPDATE_REF:-}"
SOURCE_CACHE_DIR="${SOURCE_CACHE_DIR:-${INSTALL_DIR}/source}"
MKDIR_BIN="$(command -v mkdir 2>/dev/null || true)"
[[ -n "$MKDIR_BIN" ]] || MKDIR_BIN="/bin/mkdir"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_DIR=""
RESTART_NEEDED=false
BUILD_COMMIT=""
BUILD_BRANCH=""
BUILD_TIME=""
BUILD_REPO_URL=""
[[ $EUID -ne 0 ]] && error "Run as root: sudo bash $0"
# Cross-distro helpers -------------------------------------------------------
PKG_MANAGER=""
UPDATE_DEPS=()
SYSTEMCTL_BIN=""
SH_BIN="$(command -v sh 2>/dev/null || echo /bin/sh)"
MOUNT_BIN="$(command -v mount 2>/dev/null || echo /bin/mount)"
MOUNTPOINT_BIN="$(command -v mountpoint 2>/dev/null || echo /usr/bin/mountpoint)"
TOUCH_BIN="$(command -v touch 2>/dev/null || echo /usr/bin/touch)"
CHMOD_BIN="$(command -v chmod 2>/dev/null || echo /usr/bin/chmod)"
require_systemd() {
SYSTEMCTL_BIN="$(command -v systemctl 2>/dev/null || true)"
if [[ -z "$SYSTEMCTL_BIN" ]]; then
error "systemd was not found. This updater supports Linux distributions that use systemd for services."
fi
}
detect_pkg_manager() {
if command -v apt-get >/dev/null 2>&1; then
PKG_MANAGER="apt"
elif command -v dnf >/dev/null 2>&1; then
PKG_MANAGER="dnf"
elif command -v yum >/dev/null 2>&1; then
PKG_MANAGER="yum"
elif command -v zypper >/dev/null 2>&1; then
PKG_MANAGER="zypper"
elif command -v pacman >/dev/null 2>&1; then
PKG_MANAGER="pacman"
elif command -v apk >/dev/null 2>&1; then
PKG_MANAGER="apk"
else
error "No supported package manager found. Supported: apt, dnf, yum, zypper, pacman, apk."
fi
}
set_update_deps() {
case "$PKG_MANAGER" in
apt)
UPDATE_DEPS=(git rsync wget ca-certificates python3 gcc make tar gzip)
;;
dnf|yum)
UPDATE_DEPS=(git rsync wget ca-certificates python3 gcc make tar gzip)
;;
zypper)
UPDATE_DEPS=(git rsync wget ca-certificates python3 gcc make tar gzip)
;;
pacman)
UPDATE_DEPS=(git rsync wget ca-certificates python gcc make tar gzip)
;;
apk)
UPDATE_DEPS=(git rsync wget ca-certificates python3 gcc make tar gzip)
;;
esac
}
pkg_update() {
case "$PKG_MANAGER" in
apt) apt-get update -qq ;;
dnf) dnf makecache -q ;;
yum) yum makecache -q ;;
zypper) zypper --non-interactive refresh ;;
pacman) pacman -Sy --noconfirm ;;
apk) apk update ;;
esac
}
pkg_install() {
case "$PKG_MANAGER" in
apt) DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@" ;;
dnf) dnf install -y "$@" ;;
yum) yum install -y "$@" ;;
zypper) zypper --non-interactive install -y "$@" ;;
pacman) pacman -S --noconfirm --needed "$@" ;;
apk) apk add --no-cache "$@" ;;
esac
}
ensure_update_dependencies() {
local missing=false cmd
for cmd in git rsync wget tar gzip gcc make; do
if ! command -v "$cmd" >/dev/null 2>&1; then
missing=true
fi
done
if ! command -v python3 >/dev/null 2>&1; then
missing=true
fi
if $missing; then
warn "One or more updater dependencies are missing. Installing them with $PKG_MANAGER..."
pkg_update
pkg_install "${UPDATE_DEPS[@]}"
fi
if ! command -v python3 >/dev/null 2>&1 && command -v python >/dev/null 2>&1; then
ln -sf "$(command -v python)" /usr/local/bin/python3 2>/dev/null || true
fi
}
echo -e "\n${GREEN}==========================================${NC}"
echo -e "${GREEN} DragonCoreSSH / SSH Panel Updater ${NC}"
echo -e "${GREEN}==========================================${NC}\n"
# Helpers
need_cmd() {
command -v "$1" >/dev/null 2>&1 || error "Required command not found: $1"
}
ensure_log_tmpfs_mount() {
local log_dir="${INSTALL_DIR}/logs"
local opts="rw,nosuid,nodev,noexec,noatime,nofail,size=${LOG_TMPFS_SIZE},mode=0755"
local tmp_fstab
mkdir -p "$log_dir"
if [[ -f /etc/fstab ]]; then
cp /etc/fstab "/etc/fstab.sshpanel.bak.$(date +%s)" 2>/dev/null || true
tmp_fstab="$(mktemp)"
awk -v mp="$log_dir" '!(($1 == "tmpfs") && ($2 == mp) && ($3 == "tmpfs")) {print}' /etc/fstab > "$tmp_fstab"
printf 'tmpfs %s tmpfs %s 0 0\n' "$log_dir" "$opts" >> "$tmp_fstab"
cat "$tmp_fstab" > /etc/fstab
rm -f "$tmp_fstab"
info " Log RAM disk automount saved in /etc/fstab: $log_dir (${LOG_TMPFS_SIZE})"
else
warn " /etc/fstab not found; service startup fallback will mount $log_dir as tmpfs"
fi
"${SYSTEMCTL_BIN:-systemctl}" daemon-reload >/dev/null 2>&1 || true
if command -v mountpoint >/dev/null 2>&1 && mountpoint -q "$log_dir"; then
mount -o "remount,size=${LOG_TMPFS_SIZE},mode=0755" "$log_dir" >/dev/null 2>&1 || true
else
mount "$log_dir" >/dev/null 2>&1 || mount -t tmpfs -o "size=${LOG_TMPFS_SIZE},mode=0755" tmpfs "$log_dir" >/dev/null 2>&1 || \
warn " Could not mount $log_dir as tmpfs now; service startup fallback will try again"
fi
touch "$log_dir/panel.log" >/dev/null 2>&1 || true
chmod 0644 "$log_dir/panel.log" >/dev/null 2>&1 || true
}
install_git_if_missing() {
if command -v git >/dev/null 2>&1; then
return 0
fi
warn "git is not installed. Trying to install it..."
pkg_update
pkg_install git ca-certificates
}
remote_default_branch() {
local branch
branch="$(git ls-remote --symref "$REPO_URL" HEAD 2>/dev/null | awk '/^ref:/ {sub("refs/heads/", "", $2); print $2; exit}')"
if [[ -n "$branch" ]]; then
printf '%s\n' "$branch"
else
printf 'main\n'
fi
}
prepare_source_from_git() {
SOURCE_DIR="${SOURCE_DIR:-$SCRIPT_DIR}"
if [[ ! -f "$SOURCE_DIR/go.mod" ]]; then
SOURCE_DIR="$SOURCE_CACHE_DIR"
fi
info "[1/7] Using local CLI source: $SOURCE_DIR"
[[ -f "$SOURCE_DIR/go.mod" ]] || error "go.mod not found; run update.sh from an extracted CLI release"
[[ -f "$SOURCE_DIR/dragoncore_cli.py" ]] || error "Source is missing dragoncore_cli.py"
}
install_go_if_needed() {
local go_version machine goarch go_url current_go need_go
go_version="$(awk '$1 == "go" {print $2; exit}' "$SOURCE_DIR/go.mod" 2>/dev/null || echo "1.22.5")"
need_go=true
info "[2/7] Checking Go toolchain..."
info " Required Go: $go_version"
if command -v go >/dev/null 2>&1; then
current_go="$(go version 2>/dev/null | awk '{print $3}' | sed 's/go//')"
if [[ "$(printf '%s\n' "$go_version" "$current_go" | sort -V | head -1)" == "$go_version" ]]; then
info " Go $current_go already installed."
need_go=false
fi
fi
if $need_go; then
machine="$(uname -m)"
case "$machine" in
x86_64) goarch="amd64" ;;
aarch64) goarch="arm64" ;;
armv7l) goarch="armv6l" ;;
*) goarch="amd64" ;;
esac
go_url="https://go.dev/dl/go${go_version}.linux-${goarch}.tar.gz"
info " Downloading Go ${go_version} (${goarch})..."
need_cmd wget
wget -q --show-progress -O /tmp/go.tar.gz "$go_url"
rm -rf /usr/local/go
tar -C /usr/local -xzf /tmp/go.tar.gz
rm -f /tmp/go.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' > /etc/profile.d/go.sh
chmod +x /etc/profile.d/go.sh
fi
export PATH=$PATH:/usr/local/go/bin
go version
}
build_binary() {
info "[3/7] Building new sshpanel binary..."
cd "$SOURCE_DIR"
export GOPATH=/tmp/gopath_sshpanel
export GOCACHE=/tmp/gocache_sshpanel
BUILD_COMMIT="$(git -C "$SOURCE_DIR" rev-parse HEAD 2>/dev/null || true)"
BUILD_BRANCH="${UPDATE_REF:-$(git -C "$SOURCE_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || true)}"
BUILD_TIME="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
BUILD_REPO_URL="DragonCoreSSH-CLI local release"
[[ -n "$BUILD_COMMIT" ]] || BUILD_COMMIT="unknown"
[[ -n "$BUILD_BRANCH" && "$BUILD_BRANCH" != "HEAD" ]] || BUILD_BRANCH="main"
go mod download
go mod tidy
go build -ldflags="-s -w -X main.buildCommit=$BUILD_COMMIT -X main.buildBranch=$BUILD_BRANCH -X main.buildTime=$BUILD_TIME" -o /tmp/sshpanel_new .
info " Build commit: $BUILD_COMMIT ($BUILD_BRANCH)"
info " Build complete."
}
stop_service() {
info "[4/7] Stopping service..."
if "$SYSTEMCTL_BIN" is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
"$SYSTEMCTL_BIN" stop "$SERVICE_NAME"
RESTART_NEEDED=true
info " $SERVICE_NAME stopped."
else
RESTART_NEEDED=false
warn " $SERVICE_NAME was not running."
fi
}
copy_optional_script() {
local name mode
name="$1"
mode="$2"
if [[ -f "$SOURCE_DIR/$name" ]]; then
cp "$SOURCE_DIR/$name" "$INSTALL_DIR/$name"
chmod "$mode" "$INSTALL_DIR/$name"
info " Updated $name"
fi
}
apply_update() {
info "[5/7] Applying update..."
mkdir -p "$INSTALL_DIR/logs" "$INSTALL_DIR/certs"
ensure_log_tmpfs_mount
if [[ -f "$INSTALL_DIR/sshpanel" ]]; then
cp "$INSTALL_DIR/sshpanel" "$INSTALL_DIR/sshpanel.bak"
info " Old binary backed up to $INSTALL_DIR/sshpanel.bak"
fi
mv /tmp/sshpanel_new "$INSTALL_DIR/sshpanel"
chmod 755 "$INSTALL_DIR/sshpanel"
info " Binary updated."
printf '%s\n' "$BUILD_COMMIT" > "$INSTALL_DIR/.installed_commit"
printf '%s\n' "$BUILD_BRANCH" > "$INSTALL_DIR/.installed_branch"
printf '%s\n' "$BUILD_TIME" > "$INSTALL_DIR/.installed_build_time"
printf '%s\n' "$BUILD_REPO_URL" > "$INSTALL_DIR/.installed_repo_url"
chmod 0644 "$INSTALL_DIR/.installed_commit" "$INSTALL_DIR/.installed_branch" "$INSTALL_DIR/.installed_build_time"
chmod 0600 "$INSTALL_DIR/.installed_repo_url"
info " Build metadata updated."
install -m 700 "$SOURCE_DIR/dragoncore_cli.py" "$INSTALL_DIR/dragoncore_cli.py"
ln -sfn "$INSTALL_DIR/dragoncore_cli.py" /usr/local/bin/dragoncore
if [[ ( -e /usr/local/bin/menu || -L /usr/local/bin/menu ) && "$(readlink -f /usr/local/bin/menu 2>/dev/null || true)" != "$INSTALL_DIR/dragoncore_cli.py" ]]; then
MENU_BACKUP="/usr/local/bin/menu.backup.$(date +%s%N)"
mv /usr/local/bin/menu "$MENU_BACKUP"
warn " Previous menu command saved to $MENU_BACKUP"
fi
ln -sfn "$INSTALL_DIR/dragoncore_cli.py" /usr/local/bin/menu
info " DragonCoreSSH CLI updated."
copy_optional_script "update.sh" 700
copy_optional_script "install.sh" 700
# Keep a local copy of the latest source for easier support and future updates.
if [[ "$SOURCE_DIR" != "$SOURCE_CACHE_DIR" ]]; then
mkdir -p "$SOURCE_CACHE_DIR"
rsync -a --delete --exclude '.git' "$SOURCE_DIR/" "$SOURCE_CACHE_DIR/"
info " Source files copied to $SOURCE_CACHE_DIR"
fi
[[ -f "$INSTALL_DIR/banner.txt" ]] || touch "$INSTALL_DIR/banner.txt"
}
patch_configs() {
info "[6/7] Patching config files without overwriting user settings..."
local cfg xcfg
cfg="$INSTALL_DIR/config.json"
xcfg="$INSTALL_DIR/xray_config.json"
native_xcfg="$INSTALL_DIR/xray_native_config.json"
if [[ ! -f "$native_xcfg" && -f "$xcfg" ]]; then
cp -f "$xcfg" "$native_xcfg"
chmod 600 "$native_xcfg" || true
info " Created independent native Xray config: $native_xcfg"
fi
if [[ -f "$cfg" ]]; then
python3 - "$cfg" <<'PYEOF'
import ipaddress, json, sys
path = sys.argv[1]
try:
with open(path) as f:
d = json.load(f)
except Exception as e:
print(f"[!] Could not parse {path}: {e}")
sys.exit(0)
changed = False
if 'banner_file' not in d:
d['banner_file'] = '/opt/sshpanel/banner.txt'
changed = True
local_ssh = str(d.get('local_ssh_listen') or '').strip()
local_ssh_valid = False
try:
if local_ssh.startswith('['):
end = local_ssh.index(']')
host = local_ssh[1:end]
if local_ssh[end + 1:end + 2] != ':':
raise ValueError('missing port')
port = int(local_ssh[end + 2:])
else:
host, port_text = local_ssh.rsplit(':', 1)
port = int(port_text)
local_ssh_valid = ipaddress.ip_address(host).is_loopback and 1 <= port <= 65535
except (ValueError, IndexError):
pass
if not local_ssh_valid:
d['local_ssh_listen'] = '127.0.0.1:2222'
changed = True
x = d.get('xray')
if isinstance(x, dict):
mode = str(x.get('mode') or '').strip().lower()
if mode not in ('native', 'external'):
x['mode'] = 'native'
x['native'] = True
changed = True
elif mode == 'native' and x.get('native') is not True:
x['native'] = True
changed = True
elif mode == 'external' and x.get('native') is not False:
x['native'] = False
changed = True
x.setdefault('bin_path', '/opt/sshpanel/xray')
x.setdefault('config_file', '/opt/sshpanel/xray_config.json')
x.setdefault('native_config_file', '/opt/sshpanel/xray_native_config.json')
if changed:
with open(path, 'w') as f:
json.dump(d, f, indent=2)
f.write('\n')
PYEOF
info " config.json checked."
fi
if [[ -f "$xcfg" ]] && grep -q '"geoip:private"' "$xcfg" 2>/dev/null; then
python3 - "$xcfg" <<'PYEOF'
import json, sys
path = sys.argv[1]
try:
with open(path) as f:
d = json.load(f)
except Exception as e:
print(f"[!] Could not parse {path}: {e}")
sys.exit(0)
routing = d.get('routing', {})
rules = routing.get('rules', [])
new_rules = [r for r in rules if 'geoip:private' not in r.get('ip', [])]
if new_rules != rules:
if new_rules:
d.setdefault('routing', {})['rules'] = new_rules
else:
d.pop('routing', None)
with open(path, 'w') as f:
json.dump(d, f, indent=2)
f.write('\n')
PYEOF
info " Removed geoip:private routing rule from xray_config.json"
fi
}
dnstt_redirect_is_enabled() {
# Updates must not resurrect this service when an admin intentionally
# disabled/removed it because it can break ip6tables on some machines.
local unit="sshpanel-dnstt-redirect.service"
if "$SYSTEMCTL_BIN" is-enabled --quiet "$unit" 2>/dev/null; then
return 0
fi
return 1
}
write_sshpanel_systemd_override() {
local include_dnstt_redirect="${1:-false}"
mkdir -p /etc/systemd/system/sshpanel.service.d
{
echo "[Unit]"
if [[ "$include_dnstt_redirect" == "true" ]]; then
echo "Wants=sshpanel-dnstt-redirect.service"
echo "After=local-fs.target sshpanel-dnstt-redirect.service"
else
echo "After=local-fs.target"
fi
echo
echo "[Service]"
echo "Environment=PANEL_LOG_FILE=${INSTALL_DIR}/logs/panel.log"
echo "Environment=PANEL_LOG_MAX_BYTES=${PANEL_LOG_MAX_BYTES}"
echo "LimitNOFILE=1048576"
echo "ExecStartPre="
echo "ExecStartPre=${MKDIR_BIN} -p ${INSTALL_DIR}/logs"
echo "ExecStartPre=${SH_BIN} -c '${MOUNTPOINT_BIN} -q ${INSTALL_DIR}/logs || ${MOUNT_BIN} -t tmpfs -o size=${LOG_TMPFS_SIZE},mode=0755 tmpfs ${INSTALL_DIR}/logs || true'"
echo "ExecStartPre=${SH_BIN} -c '${TOUCH_BIN} ${INSTALL_DIR}/logs/panel.log && ${CHMOD_BIN} 0644 ${INSTALL_DIR}/logs/panel.log || true'"
echo "StandardOutput=journal"
echo "StandardError=journal"
} > /etc/systemd/system/sshpanel.service.d/override.conf
}
ensure_dnstt_redirect() {
if ! dnstt_redirect_is_enabled; then
warn " sshpanel-dnstt-redirect is disabled or removed; update will not recreate or enable it."
write_sshpanel_systemd_override false
"$SYSTEMCTL_BIN" daemon-reload
return 0
fi
info " Ensuring DNSTT DNS redirect service exists..."
cat > /usr/local/sbin/sshpanel-dnstt-redirect.sh <<'EOS'
#!/bin/bash
set -euo pipefail
DNS_UPSTREAM="${DNS_UPSTREAM:-1.1.1.1}"
DNSTT_PORT="${DNSTT_PORT:-5300}"
if command -v systemctl >/dev/null 2>&1; then
systemctl disable --now systemd-resolved.service >/dev/null 2>&1 || true
fi
rm -f /etc/resolv.conf
printf 'nameserver %s\n' "$DNS_UPSTREAM" > /etc/resolv.conf
if command -v ufw >/dev/null 2>&1; then
ufw allow 53/udp >/dev/null 2>&1 || true
fi
if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
firewall-cmd --permanent --add-port=53/udp >/dev/null 2>&1 || true
firewall-cmd --reload >/dev/null 2>&1 || true
fi
add_iptables_rule() {
local bin="$1" chain="$2"
"$bin" -t nat -C "$chain" -p udp --dport 53 -j REDIRECT --to-ports "$DNSTT_PORT" 2>/dev/null \
|| "$bin" -t nat -A "$chain" -p udp --dport 53 -j REDIRECT --to-ports "$DNSTT_PORT"
}
if command -v iptables >/dev/null 2>&1; then
add_iptables_rule iptables PREROUTING
fi
if command -v ip6tables >/dev/null 2>&1; then
add_iptables_rule ip6tables PREROUTING || true
fi
if ! command -v iptables >/dev/null 2>&1 && command -v nft >/dev/null 2>&1; then
nft add table inet sshpanel_nat 2>/dev/null || true
nft 'add chain inet sshpanel_nat prerouting { type nat hook prerouting priority dstnat; policy accept; }' 2>/dev/null || true
nft list chain inet sshpanel_nat prerouting 2>/dev/null | grep -q "udp dport 53 redirect to :$DNSTT_PORT" \
|| nft add rule inet sshpanel_nat prerouting udp dport 53 redirect to :"$DNSTT_PORT"
fi
EOS
chmod +x /usr/local/sbin/sshpanel-dnstt-redirect.sh
cat > /etc/systemd/system/sshpanel-dnstt-redirect.service <<'EOF2'
[Unit]
Description=SSH Panel DNSTT DNS redirect (UDP 53 to 5300)
After=network.target
Before=sshpanel.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/sshpanel-dnstt-redirect.sh
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
EOF2
write_sshpanel_systemd_override true
"$SYSTEMCTL_BIN" daemon-reload
"$SYSTEMCTL_BIN" enable --now sshpanel-dnstt-redirect.service || warn "DNSTT redirect service failed. Check: journalctl -u sshpanel-dnstt-redirect -e"
}
restart_service() {
info "[7/7] Restarting service..."
ensure_dnstt_redirect
if $RESTART_NEEDED; then
info " Starting $SERVICE_NAME after update..."
else
warn " $SERVICE_NAME was not running before update; starting it now."
fi
"$SYSTEMCTL_BIN" start "$SERVICE_NAME"
sleep 2
if "$SYSTEMCTL_BIN" is-active --quiet "$SERVICE_NAME"; then
info " $SERVICE_NAME is running."
else
warn " $SERVICE_NAME failed to start. Check logs:"
warn " journalctl -u $SERVICE_NAME -n 50 --no-pager"
if [[ -f "$INSTALL_DIR/sshpanel.bak" ]]; then
warn " Restore command:"
warn " cp $INSTALL_DIR/sshpanel.bak $INSTALL_DIR/sshpanel && systemctl start $SERVICE_NAME"
fi
exit 1
fi
}
# Pre-flight
info "[0/7] Pre-flight checks..."
require_systemd
detect_pkg_manager
set_update_deps
ensure_update_dependencies
[[ -d "$INSTALL_DIR" ]] || error "Install dir $INSTALL_DIR not found. Run install.sh first."
[[ -f "$INSTALL_DIR/.env" ]] || error "$INSTALL_DIR/.env not found. Run install.sh first."
need_cmd python3
need_cmd rsync
need_cmd wget
info " Install dir : $INSTALL_DIR"
info " Cache dir : $SOURCE_CACHE_DIR"
info " Package manager : $PKG_MANAGER"
info " Service manager : systemd"
prepare_source_from_git
install_go_if_needed
build_binary
stop_service
apply_update
patch_configs
restart_service
echo ""
echo -e "${GREEN}==========================================${NC}"
echo -e "${GREEN} Update complete! ${NC}"
echo -e "${GREEN}==========================================${NC}"
echo ""
echo -e " Updated from: ${YELLOW}${REPO_URL}${NC}"
echo -e " Source ref : ${YELLOW}${UPDATE_REF}${NC}"
echo -e " Source cache: ${YELLOW}${SOURCE_CACHE_DIR}${NC}"
echo -e " Logs : ${YELLOW}journalctl -u ${SERVICE_NAME} -f${NC}"
echo -e " ${YELLOW}tail -f ${INSTALL_DIR}/logs/panel.log${NC}"
echo -e " Backup : ${YELLOW}${INSTALL_DIR}/sshpanel.bak${NC}"
echo ""
echo -e "${YELLOW}Updated:${NC}"
echo -e " - sshpanel binary"
echo -e " - DragonCoreSSH CLI and API"
echo -e " - update.sh / install.sh / helper scripts when available"
echo ""
echo -e "${YELLOW}Preserved:${NC}"
echo -e " - .env"
echo -e " - config.json"
echo -e " - xray_config.json"
echo -e " - SSH keys, certs, logs, database and users"
echo ""
+259
View File
@@ -0,0 +1,259 @@
package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/url"
"os"
"os/exec"
"runtime/debug"
"strings"
"sync"
"time"
)
const (
defaultUpdateRepoURL = "https://git.dr2.site/penguinehis/DragonCoreSSH-NewWEB.git"
defaultUpdateBranch = "main"
updateStatusCacheTTL = 5 * time.Minute
updateCheckTimeout = 12 * time.Second
)
// These values are injected by install.sh/update.sh with -ldflags. The
// runtime/debug fallback keeps the endpoint useful for normal git builds.
var (
buildCommit = ""
buildBranch = ""
buildTime = ""
buildRepoURL = ""
)
type updateStatusResponse struct {
Status string `json:"status"`
UpToDate bool `json:"up_to_date"`
UpdateAvailable bool `json:"update_available"`
LocalModified bool `json:"local_modified"`
CurrentCommit string `json:"current_commit,omitempty"`
CurrentCommitShort string `json:"current_commit_short,omitempty"`
LatestCommit string `json:"latest_commit,omitempty"`
LatestCommitShort string `json:"latest_commit_short,omitempty"`
Branch string `json:"branch"`
BuildTime string `json:"build_time,omitempty"`
RepoURL string `json:"repo_url"`
RepoWebURL string `json:"repo_web_url"`
CheckedAt string `json:"checked_at"`
Cached bool `json:"cached"`
Error string `json:"error,omitempty"`
}
var updateStatusCache struct {
sync.Mutex
checkedAt time.Time
response updateStatusResponse
}
func handleUpdateStatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
_ = json.NewEncoder(w).Encode(map[string]string{"error": "method not allowed"})
return
}
force := r.URL.Query().Get("refresh") == "1"
resp := getUpdateStatus(r.Context(), force)
_ = json.NewEncoder(w).Encode(resp)
}
func getUpdateStatus(parent context.Context, force bool) updateStatusResponse {
updateStatusCache.Lock()
defer updateStatusCache.Unlock()
if !force && !updateStatusCache.checkedAt.IsZero() && time.Since(updateStatusCache.checkedAt) < updateStatusCacheTTL {
resp := updateStatusCache.response
resp.Cached = true
return resp
}
resp := checkRemoteUpdate(parent)
updateStatusCache.checkedAt = time.Now()
updateStatusCache.response = resp
return resp
}
func checkRemoteUpdate(parent context.Context) updateStatusResponse {
repoURL := firstNonEmptyTrimmed(
strings.TrimSpace(os.Getenv("DRAGON_UPDATE_REPO_URL")),
readSingleLineFile("/opt/sshpanel/.installed_repo_url"),
strings.TrimSpace(buildRepoURL),
defaultUpdateRepoURL,
)
branch := firstNonEmptyTrimmed(
strings.TrimSpace(os.Getenv("DRAGON_UPDATE_BRANCH")),
strings.TrimSpace(buildBranch),
readSingleLineFile("/opt/sshpanel/.installed_branch"),
defaultUpdateBranch,
)
currentCommit, localModified, resolvedBuildTime := resolveCurrentBuildInfo()
if resolvedBuildTime == "" {
resolvedBuildTime = readSingleLineFile("/opt/sshpanel/.installed_build_time")
}
if currentCommit == "" {
currentCommit = normalizeGitCommit(readSingleLineFile("/opt/sshpanel/.installed_commit"))
}
now := time.Now().UTC().Format(time.RFC3339)
resp := updateStatusResponse{
Status: "unknown",
CurrentCommit: currentCommit,
CurrentCommitShort: shortCommit(currentCommit),
Branch: branch,
BuildTime: resolvedBuildTime,
RepoURL: safeRepoURL(repoURL),
RepoWebURL: repoWebURL(repoURL),
CheckedAt: now,
LocalModified: localModified,
}
ctx, cancel := context.WithTimeout(parent, updateCheckTimeout)
defer cancel()
latestCommit, err := queryRemoteCommit(ctx, repoURL, branch)
if err != nil {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
resp.Error = "remote update check timed out"
} else {
resp.Error = "could not read the remote Git branch"
}
return resp
}
resp.LatestCommit = latestCommit
resp.LatestCommitShort = shortCommit(latestCommit)
if currentCommit == "" {
resp.Error = "current build commit is unavailable"
return resp
}
resp.Status, resp.UpToDate, resp.UpdateAvailable = classifyUpdateStatus(currentCommit, latestCommit, localModified)
return resp
}
func classifyUpdateStatus(currentCommit, latestCommit string, localModified bool) (status string, upToDate bool, updateAvailable bool) {
if currentCommit == "" || latestCommit == "" {
return "unknown", false, false
}
if strings.EqualFold(currentCommit, latestCommit) {
if localModified {
return "local_changes", false, false
}
return "up_to_date", true, false
}
return "update_available", false, true
}
func queryRemoteCommit(ctx context.Context, repoURL, branch string) (string, error) {
cmd := exec.CommandContext(ctx, "git", "ls-remote", "--exit-code", "--heads", repoURL, "refs/heads/"+branch)
cmd.Env = append(os.Environ(),
"GIT_TERMINAL_PROMPT=0",
"GIT_ASKPASS=/bin/false",
)
out, err := cmd.Output()
if err != nil {
return "", err
}
fields := strings.Fields(string(out))
if len(fields) < 2 {
return "", errors.New("invalid git ls-remote response")
}
commit := normalizeGitCommit(fields[0])
if commit == "" {
return "", errors.New("invalid remote commit")
}
return commit, nil
}
func resolveCurrentBuildInfo() (commit string, modified bool, builtAt string) {
commit = normalizeGitCommit(buildCommit)
builtAt = strings.TrimSpace(buildTime)
info, ok := debug.ReadBuildInfo()
if !ok {
return commit, false, builtAt
}
for _, setting := range info.Settings {
switch setting.Key {
case "vcs.revision":
if commit == "" {
commit = normalizeGitCommit(setting.Value)
}
case "vcs.modified":
modified = strings.EqualFold(setting.Value, "true")
case "vcs.time":
if builtAt == "" {
builtAt = strings.TrimSpace(setting.Value)
}
}
}
return commit, modified, builtAt
}
func normalizeGitCommit(value string) string {
value = strings.TrimSpace(value)
if strings.EqualFold(value, "unknown") || len(value) < 7 || len(value) > 64 {
return ""
}
for _, r := range value {
if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')) {
return ""
}
}
return strings.ToLower(value)
}
func shortCommit(commit string) string {
if len(commit) <= 12 {
return commit
}
return commit[:12]
}
func readSingleLineFile(path string) string {
data, err := os.ReadFile(path)
if err != nil {
return ""
}
line := strings.TrimSpace(string(data))
if idx := strings.IndexByte(line, '\n'); idx >= 0 {
line = strings.TrimSpace(line[:idx])
}
return line
}
func firstNonEmptyTrimmed(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return strings.TrimSpace(value)
}
}
return ""
}
func safeRepoURL(raw string) string {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil {
return strings.TrimSpace(raw)
}
u.User = nil
return u.String()
}
func repoWebURL(raw string) string {
value := safeRepoURL(raw)
return strings.TrimSuffix(value, ".git")
}
+73
View File
@@ -0,0 +1,73 @@
package main
import (
"context"
"os"
"path/filepath"
"runtime"
"testing"
)
func TestNormalizeGitCommit(t *testing.T) {
valid := "CF49340B9A1234567890ABCDEF1234567890ABCD"
got := normalizeGitCommit(valid)
want := "cf49340b9a1234567890abcdef1234567890abcd"
if got != want {
t.Fatalf("normalizeGitCommit() = %q, want %q", got, want)
}
for _, value := range []string{"", "unknown", "xyz1234", "123 4567", "123456"} {
if got := normalizeGitCommit(value); got != "" {
t.Fatalf("normalizeGitCommit(%q) = %q, want empty", value, got)
}
}
}
func TestClassifyUpdateStatus(t *testing.T) {
const current = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
const latest = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
status, upToDate, updateAvailable := classifyUpdateStatus(current, current, false)
if status != "up_to_date" || !upToDate || updateAvailable {
t.Fatalf("same clean commit classified as %q, upToDate=%v updateAvailable=%v", status, upToDate, updateAvailable)
}
status, upToDate, updateAvailable = classifyUpdateStatus(current, current, true)
if status != "local_changes" || upToDate || updateAvailable {
t.Fatalf("modified commit classified as %q, upToDate=%v updateAvailable=%v", status, upToDate, updateAvailable)
}
status, upToDate, updateAvailable = classifyUpdateStatus(current, latest, false)
if status != "update_available" || upToDate || !updateAvailable {
t.Fatalf("different commit classified as %q, upToDate=%v updateAvailable=%v", status, upToDate, updateAvailable)
}
}
func TestRepoWebURLRemovesCredentialsAndGitSuffix(t *testing.T) {
got := repoWebURL("https://user:secret@git.example.test/owner/repo.git")
want := "https://git.example.test/owner/repo"
if got != want {
t.Fatalf("repoWebURL() = %q, want %q", got, want)
}
}
func TestQueryRemoteCommit(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script git stub is Unix-specific")
}
const want = "cf49340b9a1234567890abcdef1234567890abcd"
dir := t.TempDir()
gitPath := filepath.Join(dir, "git")
script := "#!/bin/sh\nprintf '%s\\trefs/heads/main\\n' '" + want + "'\n"
if err := os.WriteFile(gitPath, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
got, err := queryRemoteCommit(context.Background(), "https://git.example.test/owner/repo.git", "main")
if err != nil {
t.Fatalf("queryRemoteCommit() error = %v", err)
}
if got != want {
t.Fatalf("queryRemoteCommit() = %q, want %q", got, want)
}
}
+366
View File
@@ -0,0 +1,366 @@
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"strconv"
"sync"
"time"
)
type IfaceUsageDelta struct {
Iface string
RxBytes uint64
TxBytes uint64
At time.Time
}
var ifaceUsagePending = struct {
mu sync.Mutex
m map[string]ifaceCounters
}{m: make(map[string]ifaceCounters)}
func addPendingIfaceUsage(iface string, rxBytes, txBytes uint64) {
if isIgnoredInterface(iface) || (rxBytes == 0 && txBytes == 0) {
return
}
ifaceUsagePending.mu.Lock()
defer ifaceUsagePending.mu.Unlock()
p := ifaceUsagePending.m[iface]
p.RxBytes += rxBytes
p.TxBytes += txBytes
ifaceUsagePending.m[iface] = p
}
func flushPendingIfaceUsage(at time.Time) []IfaceUsageDelta {
ifaceUsagePending.mu.Lock()
defer ifaceUsagePending.mu.Unlock()
if len(ifaceUsagePending.m) == 0 {
return nil
}
deltas := make([]IfaceUsageDelta, 0, len(ifaceUsagePending.m))
for iface, ctrs := range ifaceUsagePending.m {
if isIgnoredInterface(iface) {
continue
}
deltas = append(deltas, IfaceUsageDelta{Iface: iface, RxBytes: ctrs.RxBytes, TxBytes: ctrs.TxBytes, At: at})
}
ifaceUsagePending.m = make(map[string]ifaceCounters)
return deltas
}
func restorePendingIfaceUsage(deltas []IfaceUsageDelta) {
ifaceUsagePending.mu.Lock()
defer ifaceUsagePending.mu.Unlock()
for _, d := range deltas {
if isIgnoredInterface(d.Iface) {
continue
}
p := ifaceUsagePending.m[d.Iface]
p.RxBytes += d.RxBytes
p.TxBytes += d.TxBytes
ifaceUsagePending.m[d.Iface] = p
}
}
func clearPendingIfaceUsage() {
ifaceUsagePending.mu.Lock()
ifaceUsagePending.m = make(map[string]ifaceCounters)
ifaceUsagePending.mu.Unlock()
}
type VnstatUsageRow struct {
Iface string `json:"iface"`
Period string `json:"period"`
RxBytes uint64 `json:"rx_bytes"`
TxBytes uint64 `json:"tx_bytes"`
TotalBytes uint64 `json:"total_bytes"`
}
type VnstatDTO struct {
Daily []VnstatUsageRow `json:"daily"`
Monthly []VnstatUsageRow `json:"monthly"`
UpdatedAt time.Time `json:"updated_at"`
TodayPeriod string `json:"today_period"`
MonthPeriod string `json:"month_period"`
TodayTotalBytes uint64 `json:"today_total_bytes"`
MonthTotalBytes uint64 `json:"month_total_bytes"`
InterfaceCount int `json:"interface_count"`
}
func (s *Store) EnsureIfaceUsageTables(ctx context.Context) error {
stmts := []string{
`CREATE TABLE IF NOT EXISTS ssh_iface_daily_usage (
usage_date DATE NOT NULL,
iface TEXT NOT NULL,
rx_bytes BIGINT NOT NULL DEFAULT 0,
tx_bytes BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (usage_date, iface)
)`,
`CREATE TABLE IF NOT EXISTS ssh_iface_monthly_usage (
month_start DATE NOT NULL,
iface TEXT NOT NULL,
rx_bytes BIGINT NOT NULL DEFAULT 0,
tx_bytes BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (month_start, iface)
)`,
}
for _, stmt := range stmts {
if _, err := s.db.ExecContext(ctx, stmt); err != nil {
return err
}
}
return nil
}
func (s *Store) UpsertIfaceUsageDeltas(ctx context.Context, deltas []IfaceUsageDelta) error {
if len(deltas) == 0 {
return nil
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for _, d := range deltas {
if isIgnoredInterface(d.Iface) || (d.RxBytes == 0 && d.TxBytes == 0) {
continue
}
at := d.At
if at.IsZero() {
at = time.Now()
}
day := at.Format("2006-01-02")
month := time.Date(at.Year(), at.Month(), 1, 0, 0, 0, 0, at.Location()).Format("2006-01-02")
if _, err := tx.ExecContext(ctx, `
INSERT INTO ssh_iface_daily_usage (usage_date, iface, rx_bytes, tx_bytes, updated_at)
VALUES ($1, $2, $3, $4, NOW())
ON CONFLICT (usage_date, iface) DO UPDATE
SET rx_bytes = ssh_iface_daily_usage.rx_bytes + EXCLUDED.rx_bytes,
tx_bytes = ssh_iface_daily_usage.tx_bytes + EXCLUDED.tx_bytes,
updated_at = NOW()`,
day, d.Iface, d.RxBytes, d.TxBytes); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO ssh_iface_monthly_usage (month_start, iface, rx_bytes, tx_bytes, updated_at)
VALUES ($1, $2, $3, $4, NOW())
ON CONFLICT (month_start, iface) DO UPDATE
SET rx_bytes = ssh_iface_monthly_usage.rx_bytes + EXCLUDED.rx_bytes,
tx_bytes = ssh_iface_monthly_usage.tx_bytes + EXCLUDED.tx_bytes,
updated_at = NOW()`,
month, d.Iface, d.RxBytes, d.TxBytes); err != nil {
return err
}
}
return tx.Commit()
}
func (s *Store) LoadIfaceUsage(ctx context.Context, days, months int) (VnstatDTO, error) {
if days <= 0 || days > 366 {
days = 31
}
if months <= 0 || months > 60 {
months = 12
}
now := time.Now()
todayPeriod := now.Format("2006-01-02")
monthPeriod := now.Format("2006-01")
out := VnstatDTO{UpdatedAt: now, TodayPeriod: todayPeriod, MonthPeriod: monthPeriod}
ifaceSet := make(map[string]struct{})
dailyRows, err := s.db.QueryContext(ctx, `
SELECT iface, usage_date::text, rx_bytes, tx_bytes
FROM ssh_iface_daily_usage
WHERE usage_date >= CURRENT_DATE - $1::int
AND iface <> 'lo'
ORDER BY usage_date DESC, iface ASC`, days-1)
if err != nil {
return out, err
}
defer dailyRows.Close()
for dailyRows.Next() {
var r VnstatUsageRow
if err := dailyRows.Scan(&r.Iface, &r.Period, &r.RxBytes, &r.TxBytes); err != nil {
return out, err
}
r.TotalBytes = r.RxBytes + r.TxBytes
out.Daily = append(out.Daily, r)
ifaceSet[r.Iface] = struct{}{}
if r.Period == todayPeriod {
out.TodayTotalBytes += r.TotalBytes
}
}
if err := dailyRows.Err(); err != nil {
return out, err
}
monthlyRows, err := s.db.QueryContext(ctx, `
SELECT iface, to_char(month_start, 'YYYY-MM') AS period, rx_bytes, tx_bytes
FROM ssh_iface_monthly_usage
WHERE month_start >= (date_trunc('month', CURRENT_DATE)::date - ($1::int * INTERVAL '1 month'))
AND iface <> 'lo'
ORDER BY month_start DESC, iface ASC`, months-1)
if err != nil {
return out, err
}
defer monthlyRows.Close()
for monthlyRows.Next() {
var r VnstatUsageRow
if err := monthlyRows.Scan(&r.Iface, &r.Period, &r.RxBytes, &r.TxBytes); err != nil {
return out, err
}
r.TotalBytes = r.RxBytes + r.TxBytes
out.Monthly = append(out.Monthly, r)
ifaceSet[r.Iface] = struct{}{}
if r.Period == monthPeriod {
out.MonthTotalBytes += r.TotalBytes
}
}
if err := monthlyRows.Err(); err != nil {
return out, err
}
out.InterfaceCount = len(ifaceSet)
return out, nil
}
func (s *Store) ResetIfaceUsage(ctx context.Context) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `TRUNCATE TABLE ssh_iface_daily_usage, ssh_iface_monthly_usage`); err != nil {
return err
}
return tx.Commit()
}
func (s *Store) ReplaceIfaceTotals(ctx context.Context, rows []IfaceTotals) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `DELETE FROM ssh_iface_totals`); err != nil {
return err
}
for _, r := range rows {
if isIgnoredInterface(r.Iface) {
continue
}
resetAt := r.ResetAt
if resetAt.IsZero() {
resetAt = time.Now()
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO ssh_iface_totals (iface, total_rx_bytes, total_tx_bytes, last_kernel_rx_bytes, last_kernel_tx_bytes, updated_at, reset_at)
VALUES ($1, $2, $3, $4, $5, NOW(), $6)`,
r.Iface, r.TotalRxBytes, r.TotalTxBytes, r.LastKernelRxBytes, r.LastKernelTxBytes, resetAt); err != nil {
return err
}
}
return tx.Commit()
}
func handleVnstat(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if store == nil {
http.Error(w, "database not configured", http.StatusServiceUnavailable)
return
}
days := parsePositiveInt(r.URL.Query().Get("days"), 31)
months := parsePositiveInt(r.URL.Query().Get("months"), 12)
data, err := store.LoadIfaceUsage(r.Context(), days, months)
if err != nil {
log.Printf("failed to load vnstat usage: %v", err)
http.Error(w, "db error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(data)
}
}
func handleVnstatReset(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if store == nil {
http.Error(w, "database not configured", http.StatusServiceUnavailable)
return
}
if err := store.ResetIfaceUsage(r.Context()); err != nil {
log.Printf("failed to reset vnstat usage: %v", err)
http.Error(w, "db error", http.StatusInternalServerError)
return
}
clearPendingIfaceUsage()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
}
}
func handleResetInterfaceStats(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if store == nil || ifaceTotalsMgr == nil {
http.Error(w, "interface totals persistence not configured", http.StatusServiceUnavailable)
return
}
netMap, err := readNetDev()
if err != nil {
log.Printf("failed to read interfaces for reset: %v", err)
http.Error(w, "failed to read interfaces", http.StatusInternalServerError)
return
}
rows := ifaceTotalsMgr.ResetAllToKernel(netMap)
if err := store.ReplaceIfaceTotals(r.Context(), rows); err != nil {
log.Printf("failed to reset interface totals: %v", err)
http.Error(w, "db error", http.StatusInternalServerError)
return
}
stats := getCurrentStats()
for i := range stats.Interfaces {
stats.Interfaces[i].RxBytes = 0
stats.Interfaces[i].TxBytes = 0
}
setCurrentStats(stats)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
}
}
func parsePositiveInt(raw string, fallback int) int {
if raw == "" {
return fallback
}
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 {
return fallback
}
return n
}
+432
View File
@@ -0,0 +1,432 @@
package main
import (
"context"
"database/sql"
"log"
"time"
)
// XrayClientMeta holds metadata stored in PostgreSQL for an Xray client.
// Xray's own config only stores uuid/email/level; expiry, display name,
// reseller owner, and connection policy live here.
type XrayClientMeta struct {
UUID string
Name string
Email string
InboundTag string
OwnerUsername string
ExpiresAt *time.Time
MaxConns int
DataQuotaBytes int64
QuotaAction string
QuotaThrottleMbps int
CreatedAt time.Time
TotalUplinkBytes int64
TotalDownlinkBytes int64
LastActive *time.Time
ActiveConnections int
}
func (s *Store) EnsureXrayClientsSchema(ctx context.Context) error {
stmts := []string{
`CREATE TABLE IF NOT EXISTS xray_clients (
uuid TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
inbound_tag TEXT NOT NULL DEFAULT '',
owner_username TEXT NOT NULL DEFAULT '',
expires_at TIMESTAMPTZ,
max_conns INT NOT NULL DEFAULT 0,
data_quota_bytes BIGINT NOT NULL DEFAULT 0,
quota_action TEXT NOT NULL DEFAULT 'block',
quota_throttle_mbps INT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
total_uplink_bytes BIGINT NOT NULL DEFAULT 0,
total_downlink_bytes BIGINT NOT NULL DEFAULT 0,
last_active TIMESTAMPTZ,
active_connections INT NOT NULL DEFAULT 0
)`,
`ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS owner_username TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS data_quota_bytes BIGINT NOT NULL DEFAULT 0`,
`ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS quota_action TEXT NOT NULL DEFAULT 'block'`,
`ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS quota_throttle_mbps INT NOT NULL DEFAULT 1`,
`ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS total_uplink_bytes BIGINT NOT NULL DEFAULT 0`,
`ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS total_downlink_bytes BIGINT NOT NULL DEFAULT 0`,
`ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS last_active TIMESTAMPTZ`,
`ALTER TABLE xray_clients ADD COLUMN IF NOT EXISTS active_connections INT NOT NULL DEFAULT 0`,
}
for _, stmt := range stmts {
if _, err := s.db.ExecContext(ctx, stmt); err != nil {
return err
}
}
return nil
}
func (s *Store) UpsertXrayClientMeta(ctx context.Context, m XrayClientMeta) error {
var expiresAt interface{}
if m.ExpiresAt != nil {
expiresAt = *m.ExpiresAt
}
_, err := s.db.ExecContext(ctx, `
INSERT INTO xray_clients (uuid, name, email, inbound_tag, owner_username, expires_at, max_conns, data_quota_bytes, quota_action, quota_throttle_mbps)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (uuid) DO UPDATE SET
name = EXCLUDED.name,
email = EXCLUDED.email,
inbound_tag = CASE WHEN EXCLUDED.inbound_tag <> '' THEN EXCLUDED.inbound_tag ELSE xray_clients.inbound_tag END,
owner_username = CASE WHEN EXCLUDED.owner_username <> '' THEN EXCLUDED.owner_username ELSE xray_clients.owner_username END,
expires_at = EXCLUDED.expires_at,
max_conns = EXCLUDED.max_conns,
data_quota_bytes = EXCLUDED.data_quota_bytes,
quota_action = EXCLUDED.quota_action,
quota_throttle_mbps = EXCLUDED.quota_throttle_mbps`,
m.UUID, m.Name, m.Email, m.InboundTag, m.OwnerUsername, expiresAt, m.MaxConns,
m.DataQuotaBytes, normalizeQuotaAction(m.QuotaAction), quotaThrottleMbpsOrDefault(m.QuotaThrottleMbps))
return err
}
func (s *Store) GetXrayClientMeta(ctx context.Context, uuid string) (*XrayClientMeta, error) {
m := &XrayClientMeta{}
var expiresAt sql.NullTime
var lastActive sql.NullTime
err := s.db.QueryRowContext(ctx, `
SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns,
COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at,
COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0)
FROM xray_clients WHERE uuid = $1`, uuid).
Scan(&m.UUID, &m.Name, &m.Email, &m.InboundTag, &m.OwnerUsername, &expiresAt, &m.MaxConns,
&m.DataQuotaBytes, &m.QuotaAction, &m.QuotaThrottleMbps, &m.CreatedAt,
&m.TotalUplinkBytes, &m.TotalDownlinkBytes, &lastActive, &m.ActiveConnections)
if err != nil {
return nil, err
}
if expiresAt.Valid {
m.ExpiresAt = &expiresAt.Time
}
if lastActive.Valid {
m.LastActive = &lastActive.Time
}
return m, nil
}
func (s *Store) DeleteXrayClientMeta(ctx context.Context, uuid string) error {
// Serialize deletion with the native stats flusher. Otherwise a batch that
// was swapped out just before DELETE could finish afterward and, if the same
// UUID is recreated quickly, apply stale traffic/active deltas to the new row.
xrayMgr.nativeTrafficPersistMu.Lock()
defer xrayMgr.nativeTrafficPersistMu.Unlock()
_, err := s.db.ExecContext(ctx, `DELETE FROM xray_clients WHERE uuid = $1`, uuid)
if err == nil {
xrayMgr.removeNativeQuotaPolicy(uuid)
}
return err
}
func (s *Store) ListAllXrayClients(ctx context.Context) ([]*XrayClientMeta, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns,
COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at,
COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0)
FROM xray_clients ORDER BY created_at DESC`)
if err != nil {
return nil, err
}
defer rows.Close()
return scanXrayClientMetaRows(rows)
}
func (s *Store) ListXrayClientsByOwner(ctx context.Context, ownerUsername string) ([]*XrayClientMeta, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns,
COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at,
COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0)
FROM xray_clients WHERE owner_username = $1 ORDER BY created_at DESC`, ownerUsername)
if err != nil {
return nil, err
}
defer rows.Close()
return scanXrayClientMetaRows(rows)
}
func (s *Store) CountXrayClientsByOwner(ctx context.Context, ownerUsername string) (int, error) {
var n int
err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM xray_clients WHERE owner_username = $1`, ownerUsername).Scan(&n)
return n, err
}
func (s *Store) ListExpiredXrayClients(ctx context.Context) ([]*XrayClientMeta, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns,
COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at,
COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0)
FROM xray_clients WHERE expires_at IS NOT NULL AND expires_at <= NOW()`)
if err != nil {
return nil, err
}
defer rows.Close()
return scanXrayClientMetaRows(rows)
}
func scanXrayClientMetaRows(rows *sql.Rows) ([]*XrayClientMeta, error) {
var out []*XrayClientMeta
for rows.Next() {
m := &XrayClientMeta{}
var expiresAt sql.NullTime
var lastActive sql.NullTime
if err := rows.Scan(&m.UUID, &m.Name, &m.Email, &m.InboundTag, &m.OwnerUsername, &expiresAt, &m.MaxConns,
&m.DataQuotaBytes, &m.QuotaAction, &m.QuotaThrottleMbps, &m.CreatedAt,
&m.TotalUplinkBytes, &m.TotalDownlinkBytes, &lastActive, &m.ActiveConnections); err != nil {
return nil, err
}
if expiresAt.Valid {
m.ExpiresAt = &expiresAt.Time
}
if lastActive.Valid {
m.LastActive = &lastActive.Time
}
out = append(out, m)
}
return out, rows.Err()
}
// ResetXrayActiveConnections clears stale online counters after the panel starts.
// Native mode then increments/decrements active_connections for real live streams.
func (s *Store) ResetXrayActiveConnections(ctx context.Context) error {
_, err := s.db.ExecContext(ctx, `UPDATE xray_clients SET active_connections = 0`)
return err
}
// AddXrayClientTrafficBatch persists native-emulator traffic deltas. It keeps
// totals in PostgreSQL so bandwidth remains visible after panel restarts.
func (s *Store) AddXrayClientTrafficBatch(ctx context.Context, deltas map[string]xrayPendingTraffic) error {
if len(deltas) == 0 {
return nil
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
stmt, err := tx.PrepareContext(ctx, `
UPDATE xray_clients SET
email = CASE WHEN email = '' AND $2 <> '' THEN $2 ELSE email END,
name = CASE WHEN name = '' AND $2 <> '' THEN $2 ELSE name END,
total_uplink_bytes = GREATEST(total_uplink_bytes + GREATEST($3::BIGINT, 0), 0),
total_downlink_bytes = GREATEST(total_downlink_bytes + GREATEST($4::BIGINT, 0), 0),
last_active = NOW()
WHERE uuid = $1`)
if err != nil {
_ = tx.Rollback()
return err
}
defer stmt.Close()
for uuid, d := range deltas {
if uuid == "" || (d.Uplink == 0 && d.Downlink == 0) {
continue
}
if _, err := stmt.ExecContext(ctx, uuid, d.Email, d.Uplink, d.Downlink); err != nil {
_ = tx.Rollback()
return err
}
}
return tx.Commit()
}
// AddXrayClientActiveBatch persists native online-counter deltas without
// launching a database goroutine/query for every connect and disconnect.
func (s *Store) AddXrayClientActiveBatch(ctx context.Context, deltas map[string]xrayPendingActive) error {
if len(deltas) == 0 {
return nil
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
stmt, err := tx.PrepareContext(ctx, `
UPDATE xray_clients SET
email = CASE WHEN email = '' AND $2 <> '' THEN $2 ELSE email END,
name = CASE WHEN name = '' AND $2 <> '' THEN $2 ELSE name END,
last_active = CASE WHEN $4::BOOLEAN THEN NOW() ELSE last_active END,
active_connections = GREATEST(active_connections + $3::INT, 0)
WHERE uuid = $1`)
if err != nil {
_ = tx.Rollback()
return err
}
defer stmt.Close()
for uuid, d := range deltas {
if uuid == "" || (d.Delta == 0 && !d.Connected) {
continue
}
if _, err := stmt.ExecContext(ctx, uuid, d.Email, d.Delta, d.Connected); err != nil {
_ = tx.Rollback()
return err
}
}
return tx.Commit()
}
func countOwnedXrayClients(ctx context.Context, store *Store, ownerUsername string) int {
if store == nil || ownerUsername == "" {
return 0
}
n, err := store.CountXrayClientsByOwner(ctx, ownerUsername)
if err != nil {
log.Printf("count xray clients for %s: %v", ownerUsername, err)
return 0
}
return n
}
func countOwnedQuota(ctx context.Context, store *Store, ownerUsername string) int {
return countOwnedUsers(ownerUsername) + countOwnedXrayClients(ctx, store, ownerUsername)
}
func removeOwnerXrayClients(ctx context.Context, store *Store, ownerUsername string) {
if store == nil || ownerUsername == "" {
return
}
clients, err := store.ListXrayClientsByOwner(ctx, ownerUsername)
if err != nil {
log.Printf("xray owner cleanup: list %s: %v", ownerUsername, err)
return
}
needRestart := false
for _, m := range clients {
if m.InboundTag != "" {
if err := xrayMgr.RemoveXrayClient(m.InboundTag, m.UUID); err != nil {
log.Printf("xray owner cleanup: remove %s from %s: %v", m.UUID, m.InboundTag, err)
} else {
needRestart = true
}
}
if err := store.DeleteXrayClientMeta(ctx, m.UUID); err != nil {
log.Printf("xray owner cleanup: delete meta %s: %v", m.UUID, err)
}
}
if needRestart {
xrayMgr.restartIfExternalRunning()
}
}
// suspendOwnerXrayClients revokes transport access while preserving metadata,
// expiry, traffic and quota. This makes reseller suspension/renewal reversible.
func suspendOwnerXrayClients(ctx context.Context, store *Store, ownerUsername string) {
if store == nil || ownerUsername == "" {
return
}
clients, err := store.ListXrayClientsByOwner(ctx, ownerUsername)
if err != nil {
log.Printf("xray owner suspension: list %s: %v", ownerUsername, err)
return
}
changed := false
for _, m := range clients {
xrayMgr.disconnectNativeClient(m.UUID)
if m.InboundTag == "" {
continue
}
if err := xrayMgr.RemoveXrayClient(m.InboundTag, m.UUID); err != nil {
log.Printf("xray owner suspension: remove %s from %s: %v", m.UUID, m.InboundTag, err)
continue
}
changed = true
}
if changed {
xrayMgr.restartIfExternalRunning()
}
}
// restoreOwnerXrayClients reactivates non-expired clients after reseller renewal.
func restoreOwnerXrayClients(ctx context.Context, store *Store, ownerUsername string) {
if store == nil || ownerUsername == "" {
return
}
clients, err := store.ListXrayClientsByOwner(ctx, ownerUsername)
if err != nil {
log.Printf("xray owner restore: list %s: %v", ownerUsername, err)
return
}
now := time.Now()
changed := false
for _, m := range clients {
if m.InboundTag == "" || (m.ExpiresAt != nil && !m.ExpiresAt.After(now)) {
continue
}
email := m.Email
if email == "" {
email = m.UUID
}
if err := xrayMgr.EnsureXrayClient(m.InboundTag, m.UUID, email); err != nil {
log.Printf("xray owner restore: add %s to %s: %v", m.UUID, m.InboundTag, err)
continue
}
xrayMgr.setNativeQuotaPolicy(m)
changed = true
}
if changed {
xrayMgr.restartIfExternalRunning()
}
}
// startXrayClientExpiryChecker runs a background goroutine that removes expired
// Xray clients from both the config file and the database every 5 minutes.
func startXrayClientExpiryChecker(store *Store) {
if store == nil {
return
}
go func() {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for range ticker.C {
expireXrayClientsOnce(store)
}
}()
}
func expireXrayClientsOnce(store *Store) {
if store == nil {
return
}
ctx := context.Background()
expired, err := store.ListExpiredXrayClients(ctx)
if err != nil {
log.Printf("xray expiry checker: list error: %v", err)
return
}
needRestart := false
for _, m := range expired {
tag := m.InboundTag
xrayMgr.disconnectNativeClient(m.UUID)
if tag != "" {
if err := xrayMgr.RemoveXrayClient(tag, m.UUID); err != nil {
log.Printf("xray expiry: remove %s from %s: %v", m.UUID, tag, err)
} else {
needRestart = true
}
}
if err := store.DeleteXrayClientMeta(ctx, m.UUID); err != nil {
log.Printf("xray expiry: delete meta %s: %v", m.UUID, err)
}
log.Printf("xray expiry: removed expired client %q (%s) from inbound %s", m.Name, m.UUID, tag)
}
if needRestart {
xrayMgr.restartIfExternalRunning()
}
}
// ResetXrayClientTraffic clears a client's persistent usage without removing
// the account or changing its expiry/quota policy.
func (s *Store) ResetXrayClientTraffic(ctx context.Context, uuid string) error {
if s == nil || uuid == "" {
return nil
}
_, err := s.db.ExecContext(ctx, `
UPDATE xray_clients SET
total_uplink_bytes = 0,
total_downlink_bytes = 0,
last_active = NULL
WHERE uuid = $1`, uuid)
return err
}
+145
View File
@@ -0,0 +1,145 @@
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"strings"
)
// EnsureXrayConfigSchema creates the DB table used as the canonical store for
// Xray JSON configs. The config_file path is used as a stable key so local and
// remote nodes can keep independent configs in the same database if needed.
func (s *Store) EnsureXrayConfigSchema(ctx context.Context) error {
stmts := []string{
`CREATE TABLE IF NOT EXISTS xray_configs (
config_key TEXT PRIMARY KEY,
config_json JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`,
`ALTER TABLE xray_configs ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()`,
}
for _, stmt := range stmts {
if _, err := s.db.ExecContext(ctx, stmt); err != nil {
return err
}
}
return nil
}
func (s *Store) GetXrayConfig(ctx context.Context, configKey string) ([]byte, bool, error) {
if configKey == "" {
configKey = "default"
}
var raw string
err := s.db.QueryRowContext(ctx, `SELECT config_json::text FROM xray_configs WHERE config_key = $1`, configKey).Scan(&raw)
if err != nil {
if err == sql.ErrNoRows {
return nil, false, nil
}
return nil, false, err
}
if !json.Valid([]byte(raw)) {
return nil, false, fmt.Errorf("stored Xray config %q is not valid JSON", configKey)
}
return []byte(raw), true, nil
}
func (s *Store) UpsertXrayConfig(ctx context.Context, configKey string, data []byte) error {
if configKey == "" {
configKey = "default"
}
if !json.Valid(data) {
return fmt.Errorf("invalid Xray JSON config")
}
_, err := s.db.ExecContext(ctx, `
INSERT INTO xray_configs (config_key, config_json, updated_at)
VALUES ($1, $2::jsonb, NOW())
ON CONFLICT (config_key) DO UPDATE SET
config_json = EXCLUDED.config_json,
updated_at = NOW()`, configKey, string(data))
return err
}
func (s *Store) ListXrayClientsByInbound(ctx context.Context, inboundTag string) ([]*XrayClientMeta, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT uuid, name, email, inbound_tag, COALESCE(owner_username, ''), expires_at, max_conns,
COALESCE(data_quota_bytes, 0), COALESCE(quota_action, 'block'), COALESCE(quota_throttle_mbps, 1), created_at,
COALESCE(total_uplink_bytes, 0), COALESCE(total_downlink_bytes, 0), last_active, COALESCE(active_connections, 0)
FROM xray_clients WHERE inbound_tag = $1 ORDER BY created_at DESC`, inboundTag)
if err != nil {
return nil, err
}
defer rows.Close()
return scanXrayClientMetaRows(rows)
}
// ImportXrayClientsFromConfig mirrors client UUIDs found in an existing Xray
// JSON config into xray_clients. This lets native mode inherit users from the
// external Xray config and keeps the DB as the hot-reloadable client index.
// It intentionally preserves owner/expiry/quota fields for existing rows.
func (s *Store) ImportXrayClientsFromConfig(ctx context.Context, data []byte) (int, error) {
if s == nil || len(data) == 0 {
return 0, nil
}
var cfg struct {
Inbounds []struct {
Tag string `json:"tag"`
Protocol string `json:"protocol"`
Settings struct {
Clients []struct {
ID string `json:"id"`
Password string `json:"password"`
Email string `json:"email"`
} `json:"clients"`
Users []struct {
ID string `json:"id"`
Password string `json:"password"`
Email string `json:"email"`
} `json:"users"`
} `json:"settings"`
} `json:"inbounds"`
}
if err := json.Unmarshal(data, &cfg); err != nil {
return 0, err
}
imported := 0
for _, ib := range cfg.Inbounds {
proto := strings.ToLower(strings.TrimSpace(ib.Protocol))
if proto != "vless" && proto != "vmess" && proto != "trojan" {
continue
}
inboundTag := strings.TrimSpace(ib.Tag)
configClients := ib.Settings.Clients
if len(ib.Settings.Users) > 0 {
configClients = append(configClients, ib.Settings.Users...)
}
for _, c := range configClients {
uuid := strings.TrimSpace(c.ID)
if uuid == "" {
uuid = strings.TrimSpace(c.Password)
}
if uuid == "" {
continue
}
email := strings.TrimSpace(c.Email)
if email == "" {
email = uuid
}
_, err := s.db.ExecContext(ctx, `
INSERT INTO xray_clients (uuid, name, email, inbound_tag)
VALUES ($1, $2, $3, $4)
ON CONFLICT (uuid) DO UPDATE SET
email = CASE WHEN xray_clients.email = '' THEN EXCLUDED.email ELSE xray_clients.email END,
name = CASE WHEN xray_clients.name = '' THEN EXCLUDED.name ELSE xray_clients.name END,
inbound_tag = CASE WHEN EXCLUDED.inbound_tag <> '' THEN EXCLUDED.inbound_tag ELSE xray_clients.inbound_tag END`,
uuid, email, email, inboundTag)
if err != nil {
return imported, err
}
imported++
}
}
return imported, nil
}
+3108
View File
File diff suppressed because it is too large Load Diff
+1513
View File
File diff suppressed because it is too large Load Diff
+1123
View File
File diff suppressed because it is too large Load Diff
+276
View File
@@ -0,0 +1,276 @@
package main
import (
"net"
"runtime/debug"
"sync"
"sync/atomic"
"time"
)
const nativeOverloadBackoff = 10 * time.Millisecond
// xrayRecover prevents a bad client packet, closed HTTP stream, or mux/session
// race from taking down the whole sshpanel process. A panic should only kill the
// current native Xray connection/session and must always leave a visible stack
// trace in /api/xray/logs and journald.
func xrayRecover(where string) {
if r := recover(); r != nil {
xrayLogf("native xray: panic recovered in %s: %v\n%s", where, r, debug.Stack())
}
}
func xrayGo(where string, fn func()) {
go func() {
defer xrayRecover(where)
fn()
}()
}
func init() {
// Direct native-inbound tests and embedders may run an accept loop without
// the singleton server start method. Production stop() flips this to false.
nativeTransportAccepting.Store(true)
}
var (
nativeTransportConnections atomic.Int64
nativeXHTTPSessions atomic.Int64
nativeXHTTPRequests atomic.Int64
nativeClientConnsRejected atomic.Int64
nativePreAuthRejected atomic.Int64
nativeXHTTPRejected atomic.Int64
nativeTransportAccepting atomic.Bool
nativeTransportRegistry = struct {
sync.Mutex
conns map[*nativeCountedConn]struct{}
}{conns: make(map[*nativeCountedConn]struct{})}
)
// acquireNativeCounter tracks a counted resource and returns an exactly-once
// release function. Limits here are simultaneous resource-safety windows, not
// traffic-volume or request-rate ceilings.
func acquireNativeCounter(active *atomic.Int64, limit int) (func(), bool) {
for {
current := active.Load()
if limit > 0 && current >= int64(limit) {
return nil, false
}
if active.CompareAndSwap(current, current+1) {
var once sync.Once
return func() {
once.Do(func() {
if active.Add(-1) < 0 {
active.Store(0)
}
})
}, true
}
}
}
func shouldLogNativeSample(counter *atomic.Int64) (n int64, ok bool) {
n = counter.Add(1)
// Keep attacks visible without allowing logging itself to become a CPU/disk
// amplifier. The first event and one event per 1024 repetitions are logged.
return n, n == 1 || n%1024 == 0
}
func logNativeLimitRejection(kind string, rejected *atomic.Int64, limit int) {
n, ok := shouldLogNativeSample(rejected)
if ok {
xrayLogf("native xray: rejected %s at safety limit=%d (rejected=%d)", kind, limit, n)
}
}
func logNativeClientLimitRejection(email string, limit int) {
n, ok := shouldLogNativeSample(&nativeClientConnsRejected)
if ok {
xrayLogf("native xray: rejected authenticated user %s at max_conns=%d (rejected=%d)", email, limit, n)
}
}
func logNativePreAuthRejection(format string, args ...interface{}) {
if _, ok := shouldLogNativeSample(&nativePreAuthRejected); ok {
xrayLogf(format, args...)
}
}
func acquireNativeTransportConnection() (func(), bool) {
return acquireNativeCounter(&nativeTransportConnections, nativeTransportConnectionLimit())
}
func acquireNativeXHTTPSession() (func(), bool) {
return acquireNativeCounter(&nativeXHTTPSessions, nativeXHTTPSessionLimit())
}
func acquireNativeXHTTPRequest() (func(), bool) {
return acquireNativeCounter(&nativeXHTTPRequests, nativeXHTTPRequestLimit())
}
func configureNativeTransportSocket(c net.Conn) {
if tc, ok := c.(*net.TCPConn); ok {
_ = tc.SetKeepAlive(true)
_ = tc.SetKeepAlivePeriod(30 * time.Second)
_ = tc.SetNoDelay(true)
}
}
// nativeCountedConn releases its global transport slot and unregisters itself
// exactly once, even when several tunnel paths race to close the same socket.
type nativeCountedConn struct {
net.Conn
release func()
onClose func()
closeOnce sync.Once
closeErr error
}
func (c *nativeCountedConn) Close() error {
c.closeOnce.Do(func() {
c.closeErr = c.Conn.Close()
if c.release != nil {
c.release()
}
if c.onClose != nil {
c.onClose()
}
})
return c.closeErr
}
// wrapNativeTransportConn applies only the global counter. It is useful for
// focused tests and for callers that own connection lifetime themselves.
func wrapNativeTransportConn(c net.Conn) (net.Conn, bool) {
if c == nil {
return nil, false
}
configureNativeTransportSocket(c)
release, ok := acquireNativeTransportConnection()
if !ok {
_ = c.Close()
return nil, false
}
return &nativeCountedConn{Conn: c, release: release}, true
}
// wrapTrackedNativeTransportConn additionally registers the accepted socket so
// stopping/restarting native Xray closes established raw, WebSocket, TLS, HTTP/1
// and HTTP/2 transports instead of leaving tunnel goroutines alive.
func wrapTrackedNativeTransportConn(c net.Conn) (net.Conn, bool) {
if c == nil {
return nil, false
}
configureNativeTransportSocket(c)
if !nativeTransportAccepting.Load() {
_ = c.Close()
return nil, false
}
release, ok := acquireNativeTransportConnection()
if !ok {
_ = c.Close()
return nil, false
}
return registerTrackedNativeTransportConn(c, release)
}
// registerTrackedNativeTransportConn finishes registration when the caller has
// already reserved a transport slot. Keeping reservation and Accept separate is
// what lets the production listener apply kernel/socket backpressure instead of
// accepting and immediately resetting connections at capacity.
func registerTrackedNativeTransportConn(c net.Conn, release func()) (net.Conn, bool) {
counted := &nativeCountedConn{Conn: c, release: release}
counted.onClose = func() {
nativeTransportRegistry.Lock()
delete(nativeTransportRegistry.conns, counted)
nativeTransportRegistry.Unlock()
}
nativeTransportRegistry.Lock()
if !nativeTransportAccepting.Load() {
nativeTransportRegistry.Unlock()
_ = counted.Close()
return nil, false
}
nativeTransportRegistry.conns[counted] = struct{}{}
nativeTransportRegistry.Unlock()
return counted, true
}
// waitWrapTrackedNativeTransportConn is used by raw native accept loops. Waiting
// here, before another connection is admitted to the protocol handler, applies
// socket/kernel backpressure instead of creating an unbounded goroutine backlog.
func waitWrapTrackedNativeTransportConn(c net.Conn) (net.Conn, bool) {
if c == nil {
return nil, false
}
configureNativeTransportSocket(c)
for nativeTransportAccepting.Load() {
release, ok := acquireNativeTransportConnection()
if ok {
return registerTrackedNativeTransportConn(c, release)
}
time.Sleep(nativeOverloadBackoff)
}
_ = c.Close()
return nil, false
}
func beginNativeTransportAccepting() {
nativeTransportAccepting.Store(true)
}
func stopNativeTransportAccepting() {
nativeTransportAccepting.Store(false)
}
func closeAllNativeTransportConnections() {
nativeTransportRegistry.Lock()
conns := make([]*nativeCountedConn, 0, len(nativeTransportRegistry.conns))
for c := range nativeTransportRegistry.conns {
conns = append(conns, c)
}
nativeTransportRegistry.Unlock()
for _, c := range conns {
_ = c.Close()
}
}
// nativeTrackingListener registers every accepted XHTTP socket so a live
// stop/reload can close it. It reserves capacity before Accept so overload stays
// in the kernel accept queue rather than allocating more Go handlers.
type nativeTrackingListener struct {
net.Listener
}
func (l nativeTrackingListener) Accept() (net.Conn, error) {
for {
release, ok := acquireNativeTransportConnection()
if !ok {
// Unlimited admission can only fail if this implementation changes. Avoid
// accepting and resetting a socket if that ever happens.
time.Sleep(nativeOverloadBackoff)
continue
}
c, err := l.Listener.Accept()
if err != nil {
release()
return nil, err
}
configureNativeTransportSocket(c)
if counted, ok := registerTrackedNativeTransportConn(c, release); ok {
return counted, nil
}
// Shutdown may race Accept. Registration closes the socket and releases the
// slot; the next Accept observes the listener close.
time.Sleep(nativeOverloadBackoff)
}
}
func trackNativeListener(ln net.Listener) net.Listener {
if ln == nil {
return nil
}
return nativeTrackingListener{Listener: ln}
}
+1147
View File
File diff suppressed because it is too large Load Diff
+139
View File
@@ -0,0 +1,139 @@
package main
import (
"runtime"
"sync/atomic"
"time"
)
type XrayNativeTuning struct {
RuntimeGOMAXPROCS int `json:"runtime_gomaxprocs,omitempty"`
MuxGlobalSessions int `json:"mux_global_sessions,omitempty"`
MaxConcurrentConnections int `json:"max_concurrent_connections,omitempty"`
MaxConcurrentXHTTPRequests int `json:"max_concurrent_xhttp_requests,omitempty"`
XHTTPMaxSessions int `json:"xhttp_max_sessions,omitempty"`
TracePackets bool `json:"trace_packets,omitempty"`
}
const (
defaultNativeRuntimeGOMAXPROCS = 0
defaultNativeMuxGlobalSessions = 32768
// Transport sockets, XHTTP requests, and XHTTP sessions are VPN traffic, not
// website requests. Keep the legacy JSON fields for config compatibility, but
// always normalize them to unlimited. Actual resource protection is provided by
// socket/HTTP flow control and the bounded byte queues in xray_xhttp.go.
defaultNativeMaxConnections = -1
defaultNativeMaxXHTTPRequests = -1
fixedNativeMuxMaxSessions = 64
fixedNativeMuxUDPIdleMS = 120000
fixedNativeMuxUDPReadBuffer = 256 * 1024
fixedNativeMuxUDPWriteBuffer = 256 * 1024
defaultNativeXHTTPMaxSessions = -1
// Packet-up posts are also protected by byte budgets in xray_xhttp.go. Keep
// the default reorder queue modest so thousands of unauthenticated sessions
// cannot consume large amounts of memory merely by allocating empty channel
// buffers. Operators may request more, up to the hard cap enforced there.
defaultNativeXHTTPBufferedPosts = 64
// These are simultaneous resource-safety windows, not request-rate limits.
// They are deliberately far above the expected 6-8K connected-user load, but
// finite so a reconnect storm, broken CDN, or hostile client cannot retain an
// unbounded number of sockets, HTTP handlers, sessions, and goroutine stacks.
// Transport Accept waits at capacity (kernel backpressure); XHTTP overloads
// receive 503 rather than the web-rate-limit semantics of 429.
fixedNativeMaxTransportConnections = 65536
fixedNativeMaxXHTTPRequests = 65536
fixedNativeMaxXHTTPSessions = 65536
fixedNativeHTTP2ConcurrentStreams = 4096
fixedNativeXHTTPWriteTimeoutMS = 60 * 1000
// Backstop reaper for connected XHTTP VPN sessions. The stream-down GET's
// request context is the primary lifetime owner, but behind a CDN that context
// frequently never fires when a client silently drops (mobile networks, CDN
// connection pooling, half-open TCP). When it doesn't, an idle SSH backend
// never errors either, so the session, its goroutines, socket/fd, and SSH
// connection leak until the whole process restarts. That accumulation is what
// drove the recurring XHTTP 502s that only a reboot cleared: the origin slowly
// ran out of fds/memory and could no longer serve new stream-down GETs.
//
// This sweeper only ever reaps sessions with genuinely stale lastSeen. lastSeen
// is refreshed on every successful read OR write via nativeXHTTPConn.onActivity,
// so any tunnel still passing data or keepalives is never touched -- only a
// session with zero bytes in BOTH directions for the full window (i.e. one that
// looks dead) is closed. 20 minutes is generous enough not to disturb a
// genuinely idle-but-alive tunnel while still bounding resource growth under
// heavy 6-8K-user churn. Zero disables the connected-session sweeper.
fixedNativeXHTTPIdleMS = 20 * 60 * 1000
)
var (
nativeTuneRuntimeGOMAXPROCS atomic.Int64
nativeTuneMuxGlobalSessions atomic.Int64
nativeTuneTracePackets atomic.Bool
)
func init() {
applyNativeXrayTuning(nil)
}
func normalizeNativeXrayTuning(t *XrayNativeTuning) XrayNativeTuning {
if t == nil {
t = &XrayNativeTuning{}
}
out := *t
if out.RuntimeGOMAXPROCS < 0 {
out.RuntimeGOMAXPROCS = defaultNativeRuntimeGOMAXPROCS
}
if out.MuxGlobalSessions <= 0 {
out.MuxGlobalSessions = defaultNativeMuxGlobalSessions
}
// Ignore every old positive/zero admission ceiling. This migration is
// deliberately unconditional so upgrading an existing server immediately
// removes the old 4K/8K/32K web-style caps without requiring a panel save.
out.MaxConcurrentConnections = defaultNativeMaxConnections
out.MaxConcurrentXHTTPRequests = defaultNativeMaxXHTTPRequests
out.XHTTPMaxSessions = defaultNativeXHTTPMaxSessions
return out
}
func applyNativeXrayTuning(t *XrayNativeTuning) XrayNativeTuning {
out := normalizeNativeXrayTuning(t)
gomax := out.RuntimeGOMAXPROCS
if gomax <= 0 {
gomax = runtime.NumCPU()
}
if gomax < 1 {
gomax = 1
}
runtime.GOMAXPROCS(gomax)
nativeTuneRuntimeGOMAXPROCS.Store(int64(gomax))
nativeTuneMuxGlobalSessions.Store(int64(out.MuxGlobalSessions))
nativeTuneTracePackets.Store(out.TracePackets)
return out
}
func nativeRuntimeGOMAXPROCS() int { return int(nativeTuneRuntimeGOMAXPROCS.Load()) }
func nativeMuxGlobalSessionLimit() int { return int(nativeTuneMuxGlobalSessions.Load()) }
func nativeTracePacketsEnabled() bool { return nativeTuneTracePackets.Load() }
func nativeMuxMaxSessionLimit() int { return fixedNativeMuxMaxSessions }
func nativeMuxUDPReadBufferSize() int { return fixedNativeMuxUDPReadBuffer }
func nativeMuxUDPWriteBufferSize() int { return fixedNativeMuxUDPWriteBuffer }
func nativeXHTTPBufferedPostLimit() int { return defaultNativeXHTTPBufferedPosts }
func nativeHTTP2MaxConcurrentStreams() uint32 {
return fixedNativeHTTP2ConcurrentStreams
}
func nativeTransportConnectionLimit() int { return fixedNativeMaxTransportConnections }
func nativeXHTTPRequestLimit() int { return fixedNativeMaxXHTTPRequests }
func nativeXHTTPSessionLimit() int { return fixedNativeMaxXHTTPSessions }
func nativeXHTTPWriteTimeout() time.Duration {
return fixedNativeXHTTPWriteTimeoutMS * time.Millisecond
}
func nativeMuxUDPIdleTimeout() time.Duration {
return fixedNativeMuxUDPIdleMS * time.Millisecond
}
func nativeXHTTPIdleTimeout() time.Duration {
return fixedNativeXHTTPIdleMS * time.Millisecond
}
+421
View File
@@ -0,0 +1,421 @@
package main
import (
"context"
"encoding/binary"
"fmt"
"io"
"net"
"sync"
"time"
"golang.org/x/time/rate"
)
const (
nativeUDPMaxPacket = 65535
nativeUDPBufferSize = 64 * 1024
nativeUDPIdle = 2 * time.Minute
)
// nativeVLESSUDPTunnel implements VLESS UDP-over-stream framing for a normal
// VLESS CommandUDP request. Xray uses classic 2-byte length-prefixed packets
// for this command. Do not auto-detect XUDP here: real DNS queries often have
// bytes 2/3 equal to 0x01/0x00, which looked like our old loose XUDP metadata
// check and caused the server to block waiting for a fake second payload.
// XUDP belongs to VLESS CommandMux and is handled separately when Mux support
// is implemented.
func nativeVLESSUDPTunnel(client io.ReadWriteCloser, backend net.Conn, uuid, email string, quotaState *xrayNativeQuotaState, up, down *rate.Limiter) {
defer xrayRecover(fmt.Sprintf("native xray VLESS UDP tunnel user=%s", email))
upMeter := newTrafficMeter(uuid, email, true, quotaState)
downMeter := newTrafficMeter(uuid, email, false, quotaState)
var wg sync.WaitGroup
var closeOnce sync.Once
ctx, cancel := context.WithCancel(context.Background())
closeAll := func() {
closeOnce.Do(func() {
cancel()
_ = backend.Close()
_ = client.Close()
})
}
wg.Add(1)
xrayGo("native xray VLESS UDP uplink", func() {
defer wg.Done()
defer closeAll()
for {
payload, err := readVLESSLengthPacket(client)
if err != nil {
if err != io.EOF {
xrayLogf("native xray: VLESS UDP client read failed: %v", err)
}
return
}
if len(payload) == 0 {
continue
}
if err := waitNativeRate(ctx, up, len(payload)); err != nil {
return
}
quotaReservation, err := reserveNativePacketQuota(upMeter, len(payload))
if err != nil {
return
}
if err := quotaReservation.wait(ctx); err != nil {
return
}
n, err := backend.Write(payload)
quotaReservation.finish(n)
if err != nil {
xrayLogf("native xray: VLESS UDP backend write failed: %v", err)
return
}
}
})
wg.Add(1)
xrayGo("native xray VLESS UDP downlink", func() {
defer wg.Done()
defer closeAll()
buf := make([]byte, nativeUDPBufferSize)
for {
_ = backend.SetReadDeadline(time.Now().Add(nativeUDPIdle))
n, err := backend.Read(buf)
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Timeout() {
return
}
if err != io.EOF {
xrayLogf("native xray: VLESS UDP backend read failed: %v", err)
}
return
}
if n <= 0 {
continue
}
if err := waitNativeRate(ctx, down, n); err != nil {
return
}
quotaReservation, err := reserveNativePacketQuota(downMeter, n)
if err != nil {
return
}
if err := quotaReservation.wait(ctx); err != nil {
return
}
if err := writeVLESSLengthPacket(client, buf[:n]); err != nil {
quotaReservation.finish(0)
xrayLogf("native xray: VLESS UDP client write failed: %v", err)
return
}
quotaReservation.finish(n)
}
})
wg.Wait()
upMeter.flush()
downMeter.flush()
closeAll()
}
type vlessUDPPacketCodec struct {
mu sync.RWMutex
decided bool
xudp bool
}
func (c *vlessUDPPacketCodec) setXUDP(v bool) {
c.mu.Lock()
if !c.decided {
c.decided = true
c.xudp = v
}
c.mu.Unlock()
}
func (c *vlessUDPPacketCodec) useXUDP() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.decided && c.xudp
}
func (c *vlessUDPPacketCodec) Read(r io.Reader) ([]byte, error) {
if c.useXUDP() {
return readVLESSXUDPPacket(r)
}
return c.readAuto(r)
}
func (c *vlessUDPPacketCodec) Write(w io.Writer, payload []byte) error {
if c.useXUDP() {
return writeVLESSXUDPPacket(w, payload)
}
return writeVLESSLengthPacket(w, payload)
}
func (c *vlessUDPPacketCodec) readAuto(r io.Reader) ([]byte, error) {
var lenBuf [2]byte
if _, err := io.ReadFull(r, lenBuf[:]); err != nil {
return nil, err
}
n := int(binary.BigEndian.Uint16(lenBuf[:]))
if n == 0 {
c.setXUDP(false)
return []byte{}, nil
}
if n > nativeUDPMaxPacket {
return nil, fmt.Errorf("udp packet too large: %d", n)
}
// XUDP starts with a metadata frame length, not a payload length. Metadata is
// small and has command/option bytes at offsets 2/3 after the two-byte mux ID.
// Read a possible metadata frame once and fall back to normal length-prefixed
// UDP if it does not match the XUDP shape. This lets the native emulator work
// with clients whose default packet encoding is xudp while preserving classic
// VLESS UDP framing.
if n >= 4 && n <= 512 {
candidate := make([]byte, n)
if _, err := io.ReadFull(r, candidate); err != nil {
return nil, err
}
if isVLESSXUDPMetadata(candidate) {
c.setXUDP(true)
return readVLESSXUDPPayloadAfterMeta(r, candidate)
}
c.setXUDP(false)
return candidate, nil
}
c.setXUDP(false)
pkt := make([]byte, n)
_, err := io.ReadFull(r, pkt)
return pkt, err
}
func readVLESSLengthPacket(r io.Reader) ([]byte, error) {
var lenBuf [2]byte
if _, err := io.ReadFull(r, lenBuf[:]); err != nil {
return nil, err
}
n := int(binary.BigEndian.Uint16(lenBuf[:]))
if n == 0 {
return []byte{}, nil
}
if n > nativeUDPMaxPacket {
return nil, fmt.Errorf("udp packet too large: %d", n)
}
pkt := make([]byte, n)
_, err := io.ReadFull(r, pkt)
return pkt, err
}
func writeVLESSLengthPacket(w io.Writer, payload []byte) error {
if len(payload) > nativeUDPMaxPacket {
return fmt.Errorf("udp packet too large: %d", len(payload))
}
// One Write is important for XHTTP because the response writer flushes once per
// Write. Two writes per UDP packet doubles flush/syscall pressure.
frame := make([]byte, 0, 2+len(payload))
frame = appendUint16(frame, uint16(len(payload)))
frame = append(frame, payload...)
_, err := w.Write(frame)
return err
}
func isVLESSXUDPMetadata(meta []byte) bool {
if len(meta) < 4 {
return false
}
cmd := meta[2]
opt := meta[3]
if cmd != 1 && cmd != 2 && cmd != 4 { // New, Keep, End/discard
return false
}
return opt == 0 || opt == 1
}
func readVLESSXUDPPacket(r io.Reader) ([]byte, error) {
for {
var lenBuf [2]byte
if _, err := io.ReadFull(r, lenBuf[:]); err != nil {
return nil, err
}
n := int(binary.BigEndian.Uint16(lenBuf[:]))
if n < 4 || n > 512 {
return nil, fmt.Errorf("bad xudp metadata length: %d", n)
}
meta := make([]byte, n)
if _, err := io.ReadFull(r, meta); err != nil {
return nil, err
}
if !isVLESSXUDPMetadata(meta) {
return nil, fmt.Errorf("bad xudp metadata command/option")
}
payload, err := readVLESSXUDPPayloadAfterMeta(r, meta)
if err != nil {
return nil, err
}
if payload != nil {
return payload, nil
}
}
}
func readVLESSXUDPPayloadAfterMeta(r io.Reader, meta []byte) ([]byte, error) {
if len(meta) < 4 {
return nil, io.ErrUnexpectedEOF
}
if meta[2] == 4 { // discard/end marker
return nil, nil
}
if meta[3] != 1 { // no payload attached
return nil, nil
}
var lenBuf [2]byte
if _, err := io.ReadFull(r, lenBuf[:]); err != nil {
return nil, err
}
n := int(binary.BigEndian.Uint16(lenBuf[:]))
if n == 0 {
return []byte{}, nil
}
if n > nativeUDPMaxPacket {
return nil, fmt.Errorf("xudp payload too large: %d", n)
}
pkt := make([]byte, n)
_, err := io.ReadFull(r, pkt)
return pkt, err
}
func writeVLESSXUDPPacket(w io.Writer, payload []byte) error {
if len(payload) > nativeUDPMaxPacket {
return fmt.Errorf("udp packet too large: %d", len(payload))
}
// Metadata length 4, mux session id 0, command Keep, option payload-present.
// This is accepted by Xray's xudp.PacketReader for responses when the UDP
// destination is already known from the request header.
var header [8]byte
binary.BigEndian.PutUint16(header[0:2], 4)
header[2] = 0
header[3] = 0
header[4] = 2 // Keep
header[5] = 1 // Opt: payload follows
binary.BigEndian.PutUint16(header[6:8], uint16(len(payload)))
if _, err := w.Write(header[:]); err != nil {
return err
}
_, err := w.Write(payload)
return err
}
// nativeVMessUDPTunnel maps one VMess body chunk to one UDP datagram. VMess AEAD
// chunking already preserves packet boundaries, so no extra VLESS length prefix
// is added inside the encrypted body.
func nativeVMessUDPTunnel(client nativeVMessStream, backend net.Conn, uuid, email string, quotaState *xrayNativeQuotaState, up, down *rate.Limiter) {
defer xrayRecover(fmt.Sprintf("native xray VMess UDP tunnel user=%s", email))
upMeter := newTrafficMeter(uuid, email, true, quotaState)
downMeter := newTrafficMeter(uuid, email, false, quotaState)
var wg sync.WaitGroup
var closeOnce sync.Once
ctx, cancel := context.WithCancel(context.Background())
closeAll := func() {
closeOnce.Do(func() {
cancel()
_ = backend.Close()
_ = client.Close()
})
}
wg.Add(1)
xrayGo("native xray VMess UDP uplink", func() {
defer wg.Done()
defer closeAll()
for {
pkt, err := client.ReadPacket()
if err != nil {
if err != io.EOF {
xrayLogf("native xray: VMess UDP client read failed: %v", err)
}
return
}
if len(pkt) == 0 {
continue
}
if err := waitNativeRate(ctx, up, len(pkt)); err != nil {
return
}
quotaReservation, err := reserveNativePacketQuota(upMeter, len(pkt))
if err != nil {
return
}
if err := quotaReservation.wait(ctx); err != nil {
return
}
n, err := backend.Write(pkt)
quotaReservation.finish(n)
if err != nil {
xrayLogf("native xray: VMess UDP backend write failed: %v", err)
return
}
}
})
wg.Add(1)
xrayGo("native xray VMess UDP downlink", func() {
defer wg.Done()
defer closeAll()
buf := make([]byte, nativeUDPBufferSize)
for {
_ = backend.SetReadDeadline(time.Now().Add(nativeUDPIdle))
n, err := backend.Read(buf)
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Timeout() {
return
}
if err != io.EOF {
xrayLogf("native xray: VMess UDP backend read failed: %v", err)
}
return
}
if n <= 0 {
continue
}
if err := waitNativeRate(ctx, down, n); err != nil {
return
}
quotaReservation, err := reserveNativePacketQuota(downMeter, n)
if err != nil {
return
}
if err := quotaReservation.wait(ctx); err != nil {
return
}
if err := client.WritePacket(buf[:n]); err != nil {
quotaReservation.finish(0)
xrayLogf("native xray: VMess UDP client write failed: %v", err)
return
}
quotaReservation.finish(n)
}
})
wg.Wait()
upMeter.flush()
downMeter.flush()
closeAll()
}
func waitNativeRate(ctx context.Context, lim *rate.Limiter, n int) error {
if lim == nil || n <= 0 {
return nil
}
if ctx == nil {
ctx = context.Background()
}
return lim.WaitN(ctx, n)
}
+513
View File
@@ -0,0 +1,513 @@
package main
import (
"context"
"io"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
)
type xrayNativeQuotaState struct {
// trafficMu establishes a clean reset boundary. Native stream and packet
// writers hold a read lock from quota reservation through the actual write
// and metering; traffic resets take the write lock. This prevents an
// in-flight pre-reset reservation from being accounted in the new period or
// subtracting from freshly reset usage.
trafficMu sync.RWMutex
mu sync.Mutex
usedBytes int64
quotaBytes int64
action string
throttleMbps int
limiter *rate.Limiter
generation uint64
maxConns int
activeConns int
owner string
expiresAt time.Time
hasExpiry bool
connections map[io.Closer]struct{}
}
func (m *XrayManager) reloadNativeQuotaPolicies() {
if statsStore == nil {
return
}
metas, err := statsStore.ListAllXrayClients(context.Background())
if err != nil {
xrayLogf("xray native quota: load policies failed: %v", err)
return
}
next := make(map[string]*xrayNativeQuotaState, len(metas))
for _, meta := range metas {
if meta == nil || strings.TrimSpace(meta.UUID) == "" {
continue
}
next[meta.UUID] = newXrayNativeQuotaState(meta)
}
m.nativeQuotaMu.Lock()
m.nativeQuotaByUUID = next
m.nativeQuotaMu.Unlock()
}
func newXrayNativeQuotaState(meta *XrayClientMeta) *xrayNativeQuotaState {
used := meta.TotalUplinkBytes + meta.TotalDownlinkBytes
if used < 0 {
used = 0
}
return &xrayNativeQuotaState{
usedBytes: used,
quotaBytes: meta.DataQuotaBytes,
action: normalizeQuotaAction(meta.QuotaAction),
throttleMbps: quotaThrottleMbpsOrDefault(meta.QuotaThrottleMbps),
generation: 1,
maxConns: normalizeXrayMaxConns(meta.MaxConns),
owner: strings.TrimSpace(meta.OwnerUsername),
hasExpiry: meta.ExpiresAt != nil,
expiresAt: xrayExpiryValue(meta.ExpiresAt),
}
}
func xrayExpiryValue(expiry *time.Time) time.Time {
if expiry == nil {
return time.Time{}
}
return *expiry
}
func normalizeXrayMaxConns(v int) int {
if v < 0 {
return 0
}
return v
}
func (m *XrayManager) setNativeQuotaPolicy(meta *XrayClientMeta) {
if meta == nil || strings.TrimSpace(meta.UUID) == "" {
return
}
uuid := strings.TrimSpace(meta.UUID)
m.nativeQuotaMu.Lock()
if m.nativeQuotaByUUID == nil {
m.nativeQuotaByUUID = make(map[string]*xrayNativeQuotaState)
}
existing := m.nativeQuotaByUUID[uuid]
if existing == nil {
m.nativeQuotaByUUID[uuid] = newXrayNativeQuotaState(meta)
m.nativeQuotaMu.Unlock()
return
}
m.nativeQuotaMu.Unlock()
existing.mu.Lock()
existing.quotaBytes = meta.DataQuotaBytes
existing.action = normalizeQuotaAction(meta.QuotaAction)
existing.throttleMbps = quotaThrottleMbpsOrDefault(meta.QuotaThrottleMbps)
existing.maxConns = normalizeXrayMaxConns(meta.MaxConns)
existing.owner = strings.TrimSpace(meta.OwnerUsername)
existing.hasExpiry = meta.ExpiresAt != nil
existing.expiresAt = xrayExpiryValue(meta.ExpiresAt)
existing.limiter = nil
existing.mu.Unlock()
}
func (m *XrayManager) removeNativeQuotaPolicy(uuid string) {
uuid = strings.TrimSpace(uuid)
if uuid == "" {
return
}
m.nativeQuotaMu.Lock()
state := m.nativeQuotaByUUID[uuid]
delete(m.nativeQuotaByUUID, uuid)
m.nativeQuotaMu.Unlock()
closeNativeClientConnections(state)
// Do not retain failed traffic/active deltas for a client that no longer
// exists. This also bounds the pending maps during a prolonged DB outage.
m.nativeDBMu.Lock()
delete(m.nativeTrafficPending, uuid)
delete(m.nativeActivePending, uuid)
m.nativeDBMu.Unlock()
}
func (m *XrayManager) resetNativeQuotaUsage(uuid string) {
uuid = strings.TrimSpace(uuid)
m.nativeQuotaMu.RLock()
state := m.nativeQuotaByUUID[uuid]
m.nativeQuotaMu.RUnlock()
if state == nil {
return
}
state.trafficMu.Lock()
defer state.trafficMu.Unlock()
state.mu.Lock()
state.usedBytes = 0
state.limiter = nil
state.generation++
if state.generation == 0 {
state.generation = 1
}
state.mu.Unlock()
}
func (m *XrayManager) resetNativeTrafficAccounting(ctx context.Context, store *Store, uuid, email string) error {
state := m.nativeQuotaState(uuid)
if state != nil {
state.trafficMu.Lock()
defer state.trafficMu.Unlock()
state.mu.Lock()
defer state.mu.Unlock()
}
m.nativeTrafficPersistMu.Lock()
defer m.nativeTrafficPersistMu.Unlock()
// Remove this client's queued pre-reset delta while holding only the short
// map mutex. The database call may take seconds during an outage; keeping
// nativeDBMu locked across it would stall traffic/accounting updates for
// every other native user and could amplify a slow database into a goroutine
// pile-up.
m.nativeDBMu.Lock()
key := strings.TrimSpace(uuid)
var pending xrayPendingTraffic
hadPending := false
if m.nativeTrafficPending != nil {
pending, hadPending = m.nativeTrafficPending[key]
delete(m.nativeTrafficPending, key)
}
m.nativeDBMu.Unlock()
err := store.ResetXrayClientTraffic(ctx, uuid)
if err != nil && hadPending && pending.State == state {
m.nativeDBMu.Lock()
if m.nativeTrafficPending == nil {
m.nativeTrafficPending = make(map[string]xrayPendingTraffic)
}
current := m.nativeTrafficPending[key]
if current.State != nil && current.State != state {
current = xrayPendingTraffic{}
}
if current.Email == "" {
current.Email = pending.Email
}
current.Uplink += pending.Uplink
current.Downlink += pending.Downlink
current.State = state
m.nativeTrafficPending[key] = current
m.nativeDBMu.Unlock()
}
if err != nil {
return err
}
if state != nil {
state.usedBytes = 0
state.limiter = nil
state.generation++
if state.generation == 0 {
state.generation = 1
}
}
m.statsMu.Lock()
for _, key := range []string{strings.TrimSpace(email), strings.TrimSpace(uuid)} {
if key == "" {
continue
}
if runtime, ok := m.statsByEmail[key]; ok {
runtime.Uplink = 0
runtime.Downlink = 0
m.statsByEmail[key] = runtime
}
}
m.statsMu.Unlock()
return nil
}
func (m *XrayManager) nativeQuotaState(uuid string) *xrayNativeQuotaState {
m.nativeQuotaMu.RLock()
state := m.nativeQuotaByUUID[strings.TrimSpace(uuid)]
m.nativeQuotaMu.RUnlock()
return state
}
// acquireNativeClientConnection enforces the DB-backed max_conns policy across
// every native inbound and transport. The returned release function is safe to
// call more than once and keeps runtime/DB online counters in sync.
func (m *XrayManager) acquireNativeClientConnection(uuid, email string, closers ...io.Closer) (func(), *xrayNativeQuotaState, bool) {
state := m.nativeQuotaState(uuid)
var closer io.Closer
if len(closers) > 0 {
closer = closers[0]
}
if state != nil {
state.mu.Lock()
if reason := nativeClientAccessDeniedLocked(state); reason != "" {
state.mu.Unlock()
xrayLogf("native xray: rejected user %s: %s", email, reason)
return nil, state, false
}
if state.maxConns > 0 && state.activeConns >= state.maxConns {
limit := state.maxConns
state.mu.Unlock()
logNativeClientLimitRejection(email, limit)
return nil, state, false
}
state.activeConns++
if closer != nil {
if state.connections == nil {
state.connections = make(map[io.Closer]struct{})
}
state.connections[closer] = struct{}{}
}
state.mu.Unlock()
}
m.recordNativeConnect(uuid, email, state)
var once sync.Once
return func() {
once.Do(func() {
if state != nil {
state.mu.Lock()
if closer != nil {
delete(state.connections, closer)
}
if state.activeConns > 0 {
state.activeConns--
}
state.mu.Unlock()
}
m.recordNativeDisconnect(uuid, email, state)
})
}, state, true
}
func closeNativeClientConnections(state *xrayNativeQuotaState) {
if state == nil {
return
}
state.mu.Lock()
closers := make([]io.Closer, 0, len(state.connections))
for closer := range state.connections {
closers = append(closers, closer)
}
state.mu.Unlock()
for _, closer := range closers {
_ = closer.Close()
}
}
func (m *XrayManager) disconnectNativeClient(uuid string) {
closeNativeClientConnections(m.nativeQuotaState(uuid))
}
func (m *XrayManager) nativeClientAccessDenied(uuid string) string {
state := m.nativeQuotaState(uuid)
if state == nil {
return ""
}
state.mu.Lock()
reason := nativeClientAccessDeniedLocked(state)
state.mu.Unlock()
return reason
}
func nativeClientAccessDeniedLocked(state *xrayNativeQuotaState) string {
if state.hasExpiry && !state.expiresAt.After(time.Now()) {
return "expired"
}
if state.owner != "" {
if err := ownerIsActive(state.owner); err != nil {
return "owner suspended or expired"
}
}
if state.quotaBytes > 0 && normalizeQuotaAction(state.action) == quotaActionBlock && state.usedBytes >= state.quotaBytes {
return "data quota exceeded"
}
return ""
}
func (m *XrayManager) nativeQuotaBlocked(uuid string) bool {
return nativeQuotaStateBlocked(m.nativeQuotaState(uuid))
}
func nativeQuotaStateBlocked(state *xrayNativeQuotaState) bool {
if state == nil {
return false
}
state.mu.Lock()
defer state.mu.Unlock()
return state.quotaBytes > 0 && normalizeQuotaAction(state.action) == quotaActionBlock && state.usedBytes >= state.quotaBytes
}
func (m *XrayManager) reserveNativeQuota(state *xrayNativeQuotaState, requested int) (allowed int, limiter *rate.Limiter, stopAfter bool) {
if requested <= 0 {
return 0, nil, false
}
if state == nil {
return requested, nil, false
}
state.mu.Lock()
defer state.mu.Unlock()
n := int64(requested)
if state.quotaBytes <= 0 {
state.usedBytes += n
return requested, nil, false
}
if normalizeQuotaAction(state.action) == quotaActionThrottle {
previous := state.usedBytes
state.usedBytes += n
if previous+n > state.quotaBytes {
if state.limiter == nil {
bps := mbpsToBytesPerSec(quotaThrottleMbpsOrDefault(state.throttleMbps))
burst := int(bps)
if burst < copyBufSize {
burst = copyBufSize
}
state.limiter = rate.NewLimiter(rate.Limit(bps), burst)
}
return requested, state.limiter, false
}
return requested, nil, false
}
remaining := state.quotaBytes - state.usedBytes
if remaining <= 0 {
return 0, nil, true
}
take := n
if take > remaining {
take = remaining
}
state.usedBytes += take
return int(take), nil, take < n
}
func (m *XrayManager) finishNativeQuotaReservation(state *xrayNativeQuotaState, reserved, written int) {
if reserved <= 0 || written >= reserved {
return
}
if written < 0 {
written = 0
}
if state == nil {
return
}
state.mu.Lock()
state.usedBytes -= int64(reserved - written)
if state.usedBytes < 0 {
state.usedBytes = 0
}
state.mu.Unlock()
}
type xrayQuotaMeteredWriter struct {
w io.Writer
meter *trafficMeter
ctx context.Context
}
func (mw xrayQuotaMeteredWriter) Write(p []byte) (int, error) {
if mw.meter == nil {
return mw.w.Write(p)
}
state := mw.meter.state
if state != nil {
state.trafficMu.RLock()
defer state.trafficMu.RUnlock()
}
allowed, limiter, stopAfter := xrayMgr.reserveNativeQuota(state, len(p))
if allowed <= 0 {
return 0, errDataQuotaExceeded
}
if limiter != nil {
ctx := mw.ctx
if ctx == nil {
ctx = context.Background()
}
if err := limiter.WaitN(ctx, allowed); err != nil {
xrayMgr.finishNativeQuotaReservation(state, allowed, 0)
return 0, err
}
}
n, err := mw.w.Write(p[:allowed])
xrayMgr.finishNativeQuotaReservation(state, allowed, n)
if n > 0 {
mw.meter.add(n)
}
if err != nil {
return n, err
}
if stopAfter || allowed < len(p) || nativeQuotaStateBlocked(state) {
return n, errDataQuotaExceeded
}
return n, nil
}
type nativePacketQuotaReservation struct {
meter *trafficMeter
state *xrayNativeQuotaState
limiter *rate.Limiter
reserved int
finished bool
}
func reserveNativePacketQuota(meter *trafficMeter, n int) (nativePacketQuotaReservation, error) {
if meter == nil || n <= 0 {
return nativePacketQuotaReservation{}, nil
}
state := meter.state
if state != nil {
state.trafficMu.RLock()
}
allowed, limiter, stopAfter := xrayMgr.reserveNativeQuota(state, n)
if allowed != n || stopAfter {
if allowed > 0 {
xrayMgr.finishNativeQuotaReservation(state, allowed, 0)
}
if state != nil {
state.trafficMu.RUnlock()
}
return nativePacketQuotaReservation{}, errDataQuotaExceeded
}
return nativePacketQuotaReservation{
meter: meter,
state: state,
limiter: limiter,
reserved: n,
}, nil
}
func (r *nativePacketQuotaReservation) wait(ctx context.Context) error {
if r == nil || r.finished || r.limiter == nil || r.reserved <= 0 {
return nil
}
if err := waitNativeRate(ctx, r.limiter, r.reserved); err != nil {
r.finish(0)
return err
}
return nil
}
func (r *nativePacketQuotaReservation) finish(written int) {
if r == nil || r.finished {
return
}
r.finished = true
if r.meter == nil || r.reserved <= 0 {
if r.state != nil {
r.state.trafficMu.RUnlock()
}
return
}
xrayMgr.finishNativeQuotaReservation(r.state, r.reserved, written)
if written > 0 {
r.meter.add(written)
}
if r.state != nil {
r.state.trafficMu.RUnlock()
}
}
+167
View File
@@ -0,0 +1,167 @@
package main
// Shared native Xray HTTP transports are handed off before the public proxy's
// HTTP-injection cleanup writes its unsolicited SSH response. TLS is terminated
// by the panel listener, so the Xray inbound itself must use security "none".
import (
"bufio"
"bytes"
"fmt"
"net"
"strings"
"sync"
"time"
)
type sharedXrayRouter struct {
ws map[string]*nativeInbound
xhttp *nativeXHTTPListener
httpListener *sharedXrayListener
listeners []net.Listener
}
type sharedXrayListener struct {
conns chan net.Conn
done chan struct{}
once sync.Once
}
func (l *sharedXrayListener) Accept() (net.Conn, error) {
select {
case <-l.done:
return nil, net.ErrClosed
case c := <-l.conns:
return c, nil
}
}
func (l *sharedXrayListener) Close() error { l.once.Do(func() { close(l.done) }); return nil }
func (l *sharedXrayListener) Addr() net.Addr { return &net.TCPAddr{} }
func sharedXrayPath(path string) (string, error) {
if path == "" || path == "/" || !strings.HasPrefix(path, "/") ||
strings.ContainsAny(path, "?#%\\ \t\r\n") || strings.Contains(path, "//") ||
strings.Contains(path, "/./") || strings.Contains(path, "/../") ||
strings.HasSuffix(path, "/.") || strings.HasSuffix(path, "/..") {
return "", fmt.Errorf("shared Xray path must be a distinct absolute path such as /c1")
}
return strings.TrimSuffix(path, "/"), nil
}
func validateSharedXrayInbound(in nativeInboundJSON) error {
network := strings.ToLower(firstNonEmpty(in.StreamSettings.Network, "tcp"))
if network != "ws" && network != "websocket" && network != "xhttp" && network != "splithttp" {
return fmt.Errorf("shared Xray inbound %q requires WebSocket or XHTTP", in.Tag)
}
security := strings.ToLower(strings.TrimSpace(in.StreamSettings.Security))
if security != "" && security != "none" {
return fmt.Errorf("shared Xray inbound %q must use security none; the DragonCoreSSH TLS listener terminates TLS", in.Tag)
}
path := in.StreamSettings.WSSettings.Path
if network == "xhttp" || network == "splithttp" {
path = mergeNativeXHTTPSettings(in.StreamSettings.XHTTPSettings, in.StreamSettings.SplitHTTPSettings).Path
}
if _, err := sharedXrayPath(path); err != nil {
return fmt.Errorf("inbound %q: %w", in.Tag, err)
}
return nil
}
func newSharedXrayRouter(inbounds []*nativeInbound) (*sharedXrayRouter, error) {
r := &sharedXrayRouter{ws: make(map[string]*nativeInbound)}
var httpInbounds []*nativeInbound
paths := map[string]string{}
for _, ib := range inbounds {
if !ib.sharedPort { continue }
path, err := sharedXrayPath(ib.path)
if err != nil { return nil, fmt.Errorf("inbound %q: %w", ib.tag, err) }
for prior, tag := range paths {
if path == prior || strings.HasPrefix(path, prior+"/") || strings.HasPrefix(prior, path+"/") {
return nil, fmt.Errorf("shared Xray paths %s (%s) and %s (%s) overlap", prior, tag, path, ib.tag)
}
}
paths[path] = ib.tag
if ib.isXHTTP() { httpInbounds = append(httpInbounds, ib) } else { r.ws[path] = ib }
}
if len(paths) == 0 { return nil, nil }
if len(httpInbounds) > 0 {
group, err := newNativeXHTTPListener("DragonCoreSSH public ports", httpInbounds)
if err != nil { return nil, err }
r.xhttp = group
r.httpListener = &sharedXrayListener{conns: make(chan net.Conn, 128), done: make(chan struct{})}
r.listeners = []net.Listener{r.httpListener}
}
return r, nil
}
func nativeSharedEnabled() bool { return nativeXray.shared.Load() != nil }
func (r *sharedXrayRouter) takeHTTP(conn net.Conn, reader *bufio.Reader) {
select {
case <-r.httpListener.done:
_ = conn.Close()
case r.httpListener.conns <- &bufferedConn{Conn: conn, r: reader}:
default:
_ = conn.Close()
}
}
// nativeTakeSharedConn only runs before the public SSH proxy writes a response,
// or after the panel TLS handshake. Peek leaves every byte intact for the
// Xray transport and for normal SSH/injection clients on a negative match.
func nativeTakeSharedConn(conn net.Conn, reader *bufio.Reader) (*bufio.Reader, bool) {
router := nativeXray.shared.Load()
if router == nil { return reader, false }
if reader == nil { reader = bufio.NewReaderSize(conn, 16*1024) }
// SSH may wait for the server banner. Bound the first-byte wait so adding
// Xray sharing does not stall every ordinary SSH connection for three seconds.
_ = conn.SetReadDeadline(time.Now().Add(time.Second))
defer conn.SetReadDeadline(time.Time{})
first, err := reader.Peek(1)
if err != nil || len(first) == 0 || (first[0] != 'G' && first[0] != 'P' && first[0] != 'O' && first[0] != 'D') {
return reader, false
}
_ = conn.SetReadDeadline(time.Now().Add(tunnelSniffTimeout))
if first[0] == 'P' && router.xhttp != nil {
prefix, err := reader.Peek(3)
if err == nil && string(prefix) == "PRI" {
if preface, err := reader.Peek(len("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")); err == nil &&
string(preface) == "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" {
router.takeHTTP(conn, reader)
return reader, true
}
}
}
// Require a complete bounded HTTP header before trusting a path. An SSH
// payload that happens to start with 'G' must still fall through untouched.
var header []byte
for n := 4; n <= 16*1024; n++ {
peek, e := reader.Peek(n)
if len(peek) == n && bytes.Equal(peek[n-4:], []byte("\r\n\r\n")) { header = peek; break }
if e != nil { return reader, false }
}
if len(header) == 0 { return reader, false }
lineEnd := bytes.Index(header, []byte("\r\n"))
if lineEnd < 0 { return reader, false }
parts := strings.SplitN(string(header[:lineEnd]), " ", 3)
if len(parts) != 3 || !strings.HasPrefix(parts[2], "HTTP/1.") { return reader, false }
method := parts[0]
if method != "GET" && method != "POST" && method != "OPTIONS" && method != "HEAD" { return reader, false }
path := strings.SplitN(parts[1], "?", 2)[0]
path = strings.TrimSuffix(path, "/")
if ib := router.ws[path]; ib != nil && method == "GET" &&
bytes.Contains(bytes.ToLower(header), []byte("upgrade: websocket")) {
counted, ok := waitWrapTrackedNativeTransportConn(&bufferedConn{Conn: conn, r: reader})
if !ok { return reader, true }
xrayGo("native xray shared WebSocket", func() { ib.serve(counted) })
return reader, true
}
if router.xhttp != nil {
for _, ib := range router.xhttp.inbounds {
if _, ok := ib.matchXHTTPPath(path); !ok { continue }
router.takeHTTP(conn, reader)
return reader, true
}
}
return reader, false
}
+53
View File
@@ -0,0 +1,53 @@
package main
import (
"io"
"net"
"strings"
"testing"
"time"
)
func TestSharedXrayPathsRequireExplicitNonRootHTTPTransport(t *testing.T) {
for _, body := range []string{
`{"tag":"a","protocol":"vless","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"tcp"}}`,
`{"tag":"a","protocol":"vless","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"ws","wsSettings":{"path":"/"}}}`,
`{"tag":"a","protocol":"vless","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"ws","security":"tls","wsSettings":{"path":"/c1"}}}`,
} {
if err := validateNativeInboundBindings([]byte(`{"inbounds":[` + body + `]}`)); err == nil {
t.Fatalf("accepted invalid shared inbound: %s", body)
}
}
valid := []byte(`{"inbounds":[{"tag":"a","protocol":"vless","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"ws","wsSettings":{"path":"/c1"}}},{"tag":"b","protocol":"vmess","port":80,"dragoncoreSharedPort":true,"streamSettings":{"network":"xhttp","xhttpSettings":{"path":"/c2"}}}]}`)
if err := validateNativeInboundBindings(valid); err != nil { t.Fatal(err) }
overlap := strings.Replace(string(valid), "/c2", "/c1/nested", 1)
if err := validateNativeInboundBindings([]byte(overlap)); err == nil { t.Fatal("accepted overlapping shared paths") }
}
func TestSharedXraySniffPreservesHTTPBytes(t *testing.T) {
ib := &nativeInbound{tag: "x", transport: "xhttp", path: "/c1", xhttpSessions: make(map[string]*nativeXHTTPSession)}
router, err := newSharedXrayRouter([]*nativeInbound{ib})
if err != nil { t.Fatal(err) }
nativeXray.shared.Store(router)
defer nativeXray.shared.Store(nil)
defer router.httpListener.Close()
request := "OPTIONS /c1/sid HTTP/1.1\r\nHost: example.test\r\n\r\n"
client, server := net.Pipe()
defer client.Close()
defer server.Close()
done := make(chan bool, 1)
go func() { _, taken := nativeTakeSharedConn(server, nil); done <- taken }()
if _, err := io.WriteString(client, request); err != nil { t.Fatal(err) }
select {
case taken := <-done:
if !taken { t.Fatal("shared path not routed") }
case <-time.After(2*time.Second): t.Fatal("shared sniff stalled")
}
select {
case routed := <-router.httpListener.conns:
buf := make([]byte, len(request))
if _, err := io.ReadFull(routed, buf); err != nil { t.Fatal(err) }
if string(buf) != request { t.Fatalf("routed bytes changed: %q", buf) }
case <-time.After(2*time.Second): t.Fatal("XHTTP connection not queued")
}
}
+737
View File
@@ -0,0 +1,737 @@
package main
// Pure-Go VMess (AEAD) server, part of the in-process Xray emulator.
//
// This implements the modern "VMess AEAD" protocol (alterId = 0) exactly as
// spoken by current Xray/v2ray clients: AEAD-authenticated request header,
// AES-128-GCM / ChaCha20-Poly1305 chunked body with SHAKE-masked lengths,
// optional global padding and authenticated length, and the AEAD response
// header + body. Byte offsets, KDF labels and orderings follow the v2fly/xray
// reference (proxy/vmess/{aead,encoding}). Legacy MD5-auth VMess (alterId > 0)
// is intentionally not supported.
//
// TCP and UDP commands are served. Mux is intentionally not supported in the
// native emulator yet.
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"hash"
"hash/crc32"
"hash/fnv"
"io"
"log"
"net"
"sync"
"time"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/sha3"
)
// ---------- constants ----------
const vmessCmdKeyMagic = "c48619fe-8f02-49e0-b9e9-edf763e17e21"
const (
kdfSaltVMessAEADKDF = "VMess AEAD KDF"
kdfLabelAuthIDEncryptionKey = "AES Auth ID Encryption"
kdfLabelReqHeaderLenKey = "VMess Header AEAD Key_Length"
kdfLabelReqHeaderLenIV = "VMess Header AEAD Nonce_Length"
kdfLabelReqHeaderKey = "VMess Header AEAD Key"
kdfLabelReqHeaderIV = "VMess Header AEAD Nonce"
kdfLabelRespHeaderLenKey = "AEAD Resp Header Len Key"
kdfLabelRespHeaderLenIV = "AEAD Resp Header Len IV"
kdfLabelRespHeaderKey = "AEAD Resp Header Key"
kdfLabelRespHeaderIV = "AEAD Resp Header IV"
kdfLabelAuthLen = "auth_len"
)
// VMess request option flags (header byte 34).
const (
vmessOptChunkStream = 0x01
vmessOptChunkMasking = 0x04
vmessOptGlobalPadding = 0x08
vmessOptAuthenticatedLength = 0x10
)
// VMess security types (low nibble of header byte 35).
const (
vmessSecAES128GCM = 3
vmessSecChaCha20Poly1305 = 4
vmessSecNone = 5
)
// VMess commands (header byte 37).
const (
vmessCmdTCP = 1
vmessCmdUDP = 2
vmessCmdMux = 3
)
const vmessTimeWindowSeconds = 120
// ---------- KDF ("VMess AEAD KDF", nested HMAC-SHA256) ----------
type hmacCreator struct {
parent *hmacCreator
value []byte
}
func newHMAC(f func() hash.Hash, key []byte) hash.Hash {
return hmac.New(f, key)
}
func (h *hmacCreator) create() hash.Hash {
if h.parent == nil {
return newHMAC(sha256.New, h.value)
}
return newHMAC(h.parent.create, h.value)
}
func vmessKDF(key []byte, path ...string) []byte {
c := &hmacCreator{value: []byte(kdfSaltVMessAEADKDF)}
for _, p := range path {
c = &hmacCreator{value: []byte(p), parent: c}
}
h := c.create()
h.Write(key)
return h.Sum(nil)
}
func vmessKDF16(key []byte, path ...string) []byte {
return vmessKDF(key, path...)[:16]
}
// ---------- command key / crypto helpers ----------
func vmessCmdKey(uuid [16]byte) [16]byte {
h := md5.New()
h.Write(uuid[:])
h.Write([]byte(vmessCmdKeyMagic))
var out [16]byte
copy(out[:], h.Sum(nil))
return out
}
func newAESGCM(key []byte) cipher.AEAD {
block, err := aes.NewCipher(key)
if err != nil {
panic(err) // only happens on wrong key length — a programmer error
}
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err)
}
return gcm
}
// vmessChaChaKey expands a 16-byte key into the 32-byte ChaCha20 key VMess uses:
// MD5(key) || MD5(MD5(key)).
func vmessChaChaKey(key []byte) []byte {
h1 := md5.Sum(key)
h2 := md5.Sum(h1[:])
out := make([]byte, 32)
copy(out[0:16], h1[:])
copy(out[16:32], h2[:])
return out
}
func absInt64(v int64) int64 {
if v < 0 {
return -v
}
return v
}
func shakeNext(s sha3.ShakeHash) uint16 {
var b [2]byte
_, _ = s.Read(b[:])
return binary.BigEndian.Uint16(b[:])
}
// ---------- auth ID matching ----------
// matchVMess tries every VMess client's auth-ID cipher against the 16-byte
// auth ID, returning the client whose key decrypts to a CRC-valid, in-window
// timestamp. This is O(clients) AES blocks per connection.
func (ib *nativeInbound) matchVMess(authid [16]byte, now int64) *nativeXrayClient {
ib.clientMu.RLock()
defer ib.clientMu.RUnlock()
for _, c := range ib.clientsByID {
if c.authIDCipher == nil {
continue
}
var dec [16]byte
c.authIDCipher.Decrypt(dec[:], authid[:])
if crc32.ChecksumIEEE(dec[0:12]) != binary.BigEndian.Uint32(dec[12:16]) {
continue
}
t := int64(binary.BigEndian.Uint64(dec[0:8]))
if t < 0 || absInt64(t-now) > vmessTimeWindowSeconds {
continue
}
return c
}
return nil
}
// ---------- request header ----------
type vmessRequest struct {
bodyIV [16]byte
bodyKey [16]byte
respV byte
option byte
security byte
command byte
host string
port uint16
}
// openVMessHeader reads and decrypts the AEAD request header from r, given the
// user's command key and the already-read 16-byte auth ID. r must be positioned
// immediately after the auth ID.
func openVMessHeader(cmdKey [16]byte, authid [16]byte, r io.Reader) ([]byte, error) {
var lenBlock [18]byte // 2-byte length + 16-byte tag
if _, err := io.ReadFull(r, lenBlock[:]); err != nil {
return nil, err
}
var connNonce [8]byte
if _, err := io.ReadFull(r, connNonce[:]); err != nil {
return nil, err
}
aid := string(authid[:])
cn := string(connNonce[:])
lenGCM := newAESGCM(vmessKDF16(cmdKey[:], kdfLabelReqHeaderLenKey, aid, cn))
lenNonce := vmessKDF(cmdKey[:], kdfLabelReqHeaderLenIV, aid, cn)[:12]
lenPlain, err := lenGCM.Open(nil, lenNonce, lenBlock[:], authid[:])
if err != nil {
return nil, fmt.Errorf("vmess: header length decrypt: %w", err)
}
headerLen := int(binary.BigEndian.Uint16(lenPlain))
if headerLen < 38 || headerLen > 512 {
return nil, fmt.Errorf("vmess: implausible header length %d", headerLen)
}
payload := make([]byte, headerLen+16)
if _, err := io.ReadFull(r, payload); err != nil {
return nil, err
}
payGCM := newAESGCM(vmessKDF16(cmdKey[:], kdfLabelReqHeaderKey, aid, cn))
payNonce := vmessKDF(cmdKey[:], kdfLabelReqHeaderIV, aid, cn)[:12]
header, err := payGCM.Open(nil, payNonce, payload, authid[:])
if err != nil {
return nil, fmt.Errorf("vmess: header payload decrypt: %w", err)
}
return header, nil
}
// parseVMessHeader parses the decrypted request header plaintext.
func parseVMessHeader(h []byte) (vmessRequest, error) {
var req vmessRequest
if len(h) < 40 {
return req, errors.New("vmess: header too short")
}
if h[0] != 1 {
return req, fmt.Errorf("vmess: unsupported version %d", h[0])
}
copy(req.bodyIV[:], h[1:17])
copy(req.bodyKey[:], h[17:33])
req.respV = h[33]
req.option = h[34]
req.security = h[35] & 0x0f
paddingLen := int(h[35] >> 4)
req.command = h[37]
req.port = binary.BigEndian.Uint16(h[38:40])
host, next, err := parseVMessAddress(h, 40)
if err != nil {
return req, err
}
req.host = host
if next+paddingLen+4 != len(h) {
return req, fmt.Errorf("vmess: header length mismatch (addr end %d + pad %d + 4 != %d)", next, paddingLen, len(h))
}
f := fnv.New32a()
f.Write(h[:len(h)-4])
if binary.BigEndian.Uint32(h[len(h)-4:]) != f.Sum32() {
return req, errors.New("vmess: header checksum mismatch")
}
return req, nil
}
func parseVMessAddress(h []byte, off int) (host string, next int, err error) {
if off >= len(h) {
return "", 0, io.ErrUnexpectedEOF
}
atyp := h[off]
off++
switch atyp {
case atypIPv4:
if off+4 > len(h) {
return "", 0, io.ErrUnexpectedEOF
}
host = net.IP(h[off : off+4]).String()
off += 4
case atypIPv6:
if off+16 > len(h) {
return "", 0, io.ErrUnexpectedEOF
}
host = net.IP(h[off : off+16]).String()
off += 16
case atypDomain:
if off >= len(h) {
return "", 0, io.ErrUnexpectedEOF
}
l := int(h[off])
off++
if off+l > len(h) {
return "", 0, io.ErrUnexpectedEOF
}
host = string(h[off : off+l])
off += l
default:
return "", 0, fmt.Errorf("vmess: unknown address type %d", atyp)
}
return host, off, nil
}
// ---------- response header ----------
func writeVMessResponseHeader(w io.Writer, respBodyKey, respBodyIV [16]byte, respV byte) error {
header := []byte{respV, 0, 0, 0} // V echo, option 0, command 0, command-data-length 0
lenGCM := newAESGCM(vmessKDF16(respBodyKey[:], kdfLabelRespHeaderLenKey))
lenNonce := vmessKDF(respBodyIV[:], kdfLabelRespHeaderLenIV)[:12]
var lenPlain [2]byte
binary.BigEndian.PutUint16(lenPlain[:], uint16(len(header)))
lenSealed := lenGCM.Seal(nil, lenNonce, lenPlain[:], nil) // AAD nil
payGCM := newAESGCM(vmessKDF16(respBodyKey[:], kdfLabelRespHeaderKey))
payNonce := vmessKDF(respBodyIV[:], kdfLabelRespHeaderIV)[:12]
paySealed := payGCM.Seal(nil, payNonce, header, nil) // AAD nil
out := make([]byte, 0, len(lenSealed)+len(paySealed))
out = append(out, lenSealed...)
out = append(out, paySealed...)
_, err := w.Write(out)
return err
}
// ---------- authenticated-length size parser ----------
// vmessAuthLen encodes/decodes the 2-byte chunk length as an AEAD-sealed field
// (option AuthenticatedLength). It always derives its key from the *request*
// body key/IV, in both directions, per the reference.
type vmessAuthLen struct {
aead cipher.AEAD
count uint16
ivTail [10]byte
nonce [12]byte
}
func newVMessAuthLen(reqBodyKey, reqBodyIV [16]byte, chacha bool) *vmessAuthLen {
keyMat := vmessKDF16(reqBodyKey[:], kdfLabelAuthLen)
var aead cipher.AEAD
if chacha {
a, _ := chacha20poly1305.New(vmessChaChaKey(keyMat))
aead = a
} else {
aead = newAESGCM(keyMat)
}
al := &vmessAuthLen{aead: aead}
copy(al.ivTail[:], reqBodyIV[2:12])
return al
}
func (al *vmessAuthLen) nextNonce() []byte {
binary.BigEndian.PutUint16(al.nonce[0:2], al.count)
copy(al.nonce[2:12], al.ivTail[:])
al.count++
return al.nonce[:12]
}
func (al *vmessAuthLen) decode(r io.Reader) (int, error) {
var buf [18]byte
if _, err := io.ReadFull(r, buf[:]); err != nil {
return 0, err
}
plain, err := al.aead.Open(nil, al.nextNonce(), buf[:], nil)
if err != nil {
return 0, fmt.Errorf("vmess: auth-len decrypt: %w", err)
}
return int(binary.BigEndian.Uint16(plain)) + 16, nil
}
func (al *vmessAuthLen) encode(out *bytes.Buffer, size int) {
var lenPlain [2]byte
binary.BigEndian.PutUint16(lenPlain[:], uint16(size-16))
out.Write(al.aead.Seal(nil, al.nextNonce(), lenPlain[:], nil))
}
// ---------- body chunk reader/writer ----------
const vmessMaxChunk = 64*1024 + 64
type vmessChunkReader struct {
r io.Reader
aead cipher.AEAD // nil for security "none"
overhead int
ivTail [10]byte
count uint16
nonce [12]byte
shake sha3.ShakeHash // non-nil when chunk masking is enabled
authLen *vmessAuthLen // non-nil when authenticated length is enabled
globalPad bool
leftover []byte
eof bool
}
func (cr *vmessChunkReader) nextNonce() []byte {
binary.BigEndian.PutUint16(cr.nonce[0:2], cr.count)
copy(cr.nonce[2:12], cr.ivTail[:])
cr.count++
return cr.nonce[:12]
}
func (cr *vmessChunkReader) readChunk() ([]byte, error) {
// Padding length is always drawn from the SHAKE stream before the size.
pad := 0
if cr.shake != nil && cr.globalPad {
pad = int(shakeNext(cr.shake) % 64)
}
var size int
switch {
case cr.authLen != nil:
s, err := cr.authLen.decode(cr.r)
if err != nil {
return nil, err
}
size = s
case cr.shake != nil:
var b [2]byte
if _, err := io.ReadFull(cr.r, b[:]); err != nil {
return nil, err
}
size = int(shakeNext(cr.shake) ^ binary.BigEndian.Uint16(b[:]))
default:
var b [2]byte
if _, err := io.ReadFull(cr.r, b[:]); err != nil {
return nil, err
}
size = int(binary.BigEndian.Uint16(b[:]))
}
// size == overhead + pad means an empty (terminating) chunk.
if size == cr.overhead+pad {
return nil, io.EOF
}
if size < cr.overhead+pad || size > vmessMaxChunk {
return nil, fmt.Errorf("vmess: bad chunk size %d", size)
}
data := make([]byte, size)
if _, err := io.ReadFull(cr.r, data); err != nil {
return nil, err
}
sealed := data[:size-pad] // trailing pad bytes are clear-text, discarded
if cr.aead == nil {
return sealed, nil
}
plain, err := cr.aead.Open(nil, cr.nextNonce(), sealed, nil)
if err != nil {
return nil, fmt.Errorf("vmess: body decrypt: %w", err)
}
return plain, nil
}
func (cr *vmessChunkReader) Read(p []byte) (int, error) {
for len(cr.leftover) == 0 {
if cr.eof {
return 0, io.EOF
}
chunk, err := cr.readChunk()
if err == io.EOF {
cr.eof = true
return 0, io.EOF
}
if err != nil {
return 0, err
}
cr.leftover = chunk
}
n := copy(p, cr.leftover)
cr.leftover = cr.leftover[n:]
return n, nil
}
type vmessChunkWriter struct {
w io.Writer
aead cipher.AEAD
overhead int
ivTail [10]byte
count uint16
nonce [12]byte
shake sha3.ShakeHash
authLen *vmessAuthLen
globalPad bool
}
func (cw *vmessChunkWriter) nextNonce() []byte {
binary.BigEndian.PutUint16(cw.nonce[0:2], cw.count)
copy(cw.nonce[2:12], cw.ivTail[:])
cw.count++
return cw.nonce[:12]
}
func (cw *vmessChunkWriter) writeChunk(p []byte) error {
var out bytes.Buffer
pad := 0
if cw.shake != nil && cw.globalPad {
pad = int(shakeNext(cw.shake) % 64)
}
size := len(p) + cw.overhead + pad
switch {
case cw.authLen != nil:
cw.authLen.encode(&out, size)
case cw.shake != nil:
var b [2]byte
binary.BigEndian.PutUint16(b[:], shakeNext(cw.shake)^uint16(size))
out.Write(b[:])
default:
var b [2]byte
binary.BigEndian.PutUint16(b[:], uint16(size))
out.Write(b[:])
}
if cw.aead != nil {
out.Write(cw.aead.Seal(nil, cw.nextNonce(), p, nil))
} else {
out.Write(p)
}
if pad > 0 {
padBytes := make([]byte, pad)
_, _ = rand.Read(padBytes)
out.Write(padBytes)
}
_, err := cw.w.Write(out.Bytes())
return err
}
// ---------- vmessConn: net.Conn view of a decoded VMess session ----------
type nativeVMessStream interface {
net.Conn
ReadPacket() ([]byte, error)
WritePacket([]byte) error
}
type vmessConn struct {
net.Conn
reader *vmessChunkReader
writer *vmessChunkWriter
terminateOnClose bool
closeOnce sync.Once
}
func (c *vmessConn) Read(p []byte) (int, error) { return c.reader.Read(p) }
// ReadPacket returns exactly one decrypted VMess body chunk. UDP-over-VMess uses
// one VMess chunk per UDP datagram, so packet handling must bypass the streamy
// Read method that can merge/split chunks.
func (c *vmessConn) ReadPacket() ([]byte, error) { return c.reader.readChunk() }
func (c *vmessConn) WritePacket(p []byte) error { return c.writer.writeChunk(p) }
func (c *vmessConn) Write(p []byte) (int, error) {
// Bound each chunk well under the uint16 length field.
const maxChunk = 16 * 1024
total := 0
for len(p) > 0 {
n := len(p)
if n > maxChunk {
n = maxChunk
}
if err := c.writer.writeChunk(p[:n]); err != nil {
return total, err
}
total += n
p = p[n:]
}
return total, nil
}
func (c *vmessConn) Close() error {
c.closeOnce.Do(func() {
if c.terminateOnClose {
_ = c.writer.writeChunk(nil) // terminating empty chunk
}
})
return c.Conn.Close()
}
// vmessRawConn is used for VMess security=none when the client did not request
// ChunkStream. Xray's own server returns a raw reader/writer in that exact case;
// treating the following TLS ClientHello/HTTP bytes as a VMess chunk length makes
// real clients authenticate but then pass no data.
type vmessRawConn struct {
net.Conn
}
func (c *vmessRawConn) ReadPacket() ([]byte, error) {
buf := make([]byte, 64*1024)
n, err := c.Conn.Read(buf)
if n > 0 {
return buf[:n], nil
}
return nil, err
}
func (c *vmessRawConn) WritePacket(p []byte) error {
_, err := c.Conn.Write(p)
return err
}
func newVMessConn(stream net.Conn, req vmessRequest, respBodyKey, respBodyIV [16]byte) (nativeVMessStream, error) {
chunkMask := req.option&vmessOptChunkMasking != 0
globalPad := req.option&vmessOptGlobalPadding != 0
authLen := req.option&vmessOptAuthenticatedLength != 0
chacha := req.security == vmessSecChaCha20Poly1305
if req.security == vmessSecNone && req.option&vmessOptChunkStream == 0 {
return &vmessRawConn{Conn: stream}, nil
}
var readAEAD, writeAEAD cipher.AEAD
overhead := 16
switch req.security {
case vmessSecAES128GCM:
readAEAD = newAESGCM(req.bodyKey[:])
writeAEAD = newAESGCM(respBodyKey[:])
case vmessSecChaCha20Poly1305:
ra, _ := chacha20poly1305.New(vmessChaChaKey(req.bodyKey[:]))
wa, _ := chacha20poly1305.New(vmessChaChaKey(respBodyKey[:]))
readAEAD, writeAEAD = ra, wa
case vmessSecNone:
overhead = 0
default:
return nil, fmt.Errorf("vmess: unsupported security %d", req.security)
}
cr := &vmessChunkReader{r: stream, aead: readAEAD, overhead: overhead, globalPad: globalPad}
copy(cr.ivTail[:], req.bodyIV[2:12])
cw := &vmessChunkWriter{w: stream, aead: writeAEAD, overhead: overhead, globalPad: globalPad}
copy(cw.ivTail[:], respBodyIV[2:12])
if chunkMask {
rs := sha3.NewShake128()
rs.Write(req.bodyIV[:])
cr.shake = rs
ws := sha3.NewShake128()
ws.Write(respBodyIV[:])
cw.shake = ws
}
if authLen {
cr.authLen = newVMessAuthLen(req.bodyKey, req.bodyIV, chacha)
cw.authLen = newVMessAuthLen(req.bodyKey, req.bodyIV, chacha)
}
return &vmessConn{Conn: stream, reader: cr, writer: cw, terminateOnClose: req.option&vmessOptChunkStream != 0 || req.security != vmessSecNone}, nil
}
// ---------- handler ----------
func (ib *nativeInbound) handleVMess(stream net.Conn, remote net.Addr) {
_ = stream.SetReadDeadline(time.Now().Add(30 * time.Second))
var authid [16]byte
if _, err := io.ReadFull(stream, authid[:]); err != nil {
return
}
client := ib.matchVMess(authid, time.Now().Unix())
if client == nil {
logNativePreAuthRejection("native xray: inbound %q rejected unknown/expired VMess auth id from %s", ib.tag, remote)
return
}
if reason := xrayMgr.nativeClientAccessDenied(client.uuid); reason != "" {
log.Printf("native xray: inbound %q rejected VMess user %s: %s", ib.tag, client.email, reason)
return
}
header, err := openVMessHeader(client.cmdKey, authid, stream)
if err != nil {
log.Printf("native xray: inbound %q VMess header open failed from %s: %v", ib.tag, remote, err)
return
}
req, err := parseVMessHeader(header)
if err != nil {
log.Printf("native xray: inbound %q VMess header parse failed from %s: %v", ib.tag, remote, err)
return
}
_ = stream.SetReadDeadline(time.Time{})
if req.command != vmessCmdTCP && req.command != vmessCmdUDP {
log.Printf("native xray: inbound %q VMess command %d not supported yet", ib.tag, req.command)
return
}
releaseConnection, quotaState, ok := xrayMgr.acquireNativeClientConnection(client.uuid, client.email, stream)
if !ok {
return
}
defer releaseConnection()
respBodyKey := sha256.Sum256(req.bodyKey[:])
respBodyIV := sha256.Sum256(req.bodyIV[:])
var rk, riv [16]byte
copy(rk[:], respBodyKey[:16])
copy(riv[:], respBodyIV[:16])
if err := writeVMessResponseHeader(stream, rk, riv, req.respV); err != nil {
return
}
vc, err := newVMessConn(stream, req, rk, riv)
if err != nil {
log.Printf("native xray: inbound %q VMess codec: %v", ib.tag, err)
return
}
switch req.command {
case vmessCmdTCP:
backend, target, err := ib.nativeDialTCP(req.host, req.port)
if err != nil {
log.Printf("native xray: inbound %q VMess TCP dial %s failed: %v", ib.tag, target, err)
return
}
log.Printf("native xray: vmess/tcp user=%s src=%s -> %s (inbound %q)", client.email, backend.LocalAddr(), target, ib.tag)
nativeTunnel(vc, backend, client.uuid, client.email, quotaState, ib.upLimiter(), ib.downLimiter())
case vmessCmdUDP:
backend, target, err := ib.nativeDialUDP(req.host, req.port)
if err != nil {
log.Printf("native xray: inbound %q VMess UDP dial %s failed: %v", ib.tag, target, err)
return
}
log.Printf("native xray: vmess/udp user=%s src=%s -> %s (inbound %q)", client.email, backend.LocalAddr(), target, ib.tag)
nativeVMessUDPTunnel(vc, backend, client.uuid, client.email, quotaState, ib.upLimiter(), ib.downLimiter())
}
}
+1652
View File
File diff suppressed because it is too large Load Diff