mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-05-26 07:08:01 +00:00
Security hardening: sessions, SSRF, CSP nonce, CSRF logout, trusted proxies (#4275)
* refactor(session): store user ID in session instead of full struct
Replaces storing the full User object in the session cookie with just
the user ID. GetLoginUser now re-fetches the user from the database on
every request so credential/permission changes take effect immediately
without requiring a re-login. Includes a backward-compatible migration
path for existing sessions that still carry the old struct payload.
* feat(auth): block panel with default admin/admin credentials and guide credential change
checkLogin middleware now detects default admin/admin credentials and
redirects every panel route to /panel/settings until they are changed.
The settings page auto-opens the Authentication tab, shows a
non-dismissible error banner, and lists 'Default credentials' first in
the security checklist. Login response includes mustChangeCredentials
so the login page can redirect directly. Logout is now POST-only.
Password must be at least 10 characters and cannot be admin/admin.
* feat(settings): redact secrets in AllSettingView and add TrustedProxyCIDRs
Introduces AllSettingView which strips tgBotToken, twoFactorToken,
ldapPassword, apiToken and warp/nord secrets before sending them to
the browser, replacing them with boolean hasFoo presence flags. A new
/panel/setting/secret endpoint allows updating individual secrets by
key. Secrets that arrive blank on a save are preserved from the DB
rather than overwritten. Adds TrustedProxyCIDRs as a configurable
setting (defaults to localhost CIDRs). URL fields are validated before
save.
* fix(security): SSRF prevention, trusted-proxy header gating, CSP nonce, HTTP timeouts
Adds SanitizeHTTPURL / SanitizePublicHTTPURL to reject private-range
and loopback targets before any outbound HTTP request (node probe,
xray download, outbound test, external traffic inform, tgbot API
server, panel updater). Forwarded headers (X-Real-IP, X-Forwarded-For,
X-Forwarded-Host) are now only trusted when the direct connection
arrives from a CIDR in TrustedProxyCIDRs. CSP policy is tightened with
a per-request nonce. HTTP server gains read/write/idle timeouts. Panel
updater downloads the script to a temp file instead of piping curl into
shell. Xray archive download adds a size cap and response-code check.
backuptotgbot is changed from GET to POST.
* feat(nodes): add allow-private-address toggle per node
Adds AllowPrivateAddress to the Node model (DB default false). When
enabled it bypasses the SSRF private-range check for that node's probe
URL, allowing nodes hosted on RFC-1918 or loopback addresses (e.g.
a private VPN or LAN setup).
* chore: frontend UX improvements, CI pipeline, and dev tooling
- AppSidebar: logout via POST /logout instead of navigating to GET
- InboundList: persist filter state (search, protocol, node) to
localStorage across page reloads; add protocol and node filter dropdowns
- IndexPage: add health status strip (Xray, CPU, Memory, Update) with
quick-action buttons
- dependabot: weekly go mod and npm update schedule
- ci.yml: add GitHub Actions workflow for build and vet
- .nvmrc: pin Node 22 for local development
- frontend: bump package.json and package-lock.json
- SubPage, DnsPresetsModal, api-docs: minor fixes
* fix(ci): stub web/dist before go list to satisfy go:embed at compile time
* chore(ui): remove health-strip bar from dashboard top
* Revert "feat(auth): block panel with default admin/admin credentials and guide credential change"
This reverts commit 56ce6073ce.
* fix(auth): make logout POST+CSRF and propagate session loss to other tabs
- Switch /logout from GET to POST with CSRFMiddleware so it matches the
SPA's existing HttpUtil.post('/logout') call (previously 404'd silently)
and blocks GET-based logout via image tags or link prefetchers. Handler
now returns JSON; the SPA already navigates client-side.
- Return 401 (instead of 404) from /panel/api/* when the caller is a
browser XHR (X-Requested-With: XMLHttpRequest) so the axios interceptor
redirects to the login page on logout-in-another-tab, cookie expiry,
and server restart. Anonymous callers still get 404 to keep endpoints
hidden from casual scanners.
- One-shot the 401 redirect in axios-init.js and hang the rejected
promise so queued polls don't stack reloads or surface error toasts
while the browser is navigating away.
- Add the CSP nonce to the runtime-injected <script> in dist.go so the
panel loads under the existing script-src 'nonce-...' policy.
- Update api-docs endpoints.js: GET /logout doc entry was missing.
* fix(settings): POST /logout after credential change
* fix(auth): invalidate other sessions when credentials change
When the admin changes username/password from one machine, sessions
on every other machine kept working until they manually logged out
because session storage is a signed client-side cookie — there is
no server-side session list to revoke.
Add a per-user LoginEpoch counter stamped into the session at login
and re-verified on every authenticated request. UpdateUser and
UpdateFirstUser bump the epoch (UpdateUser via gorm.Expr so a single
update statement is atomic), so any cookie issued before the change
no longer matches the user's current epoch and GetLoginUser returns
nil — the SPA's 401 interceptor then redirects to the login page.
Backward compatible: the column defaults to 0 and missing cookie
values are treated as 0, so sessions issued before this change
remain valid until the first credential update.
---------
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
committed by
GitHub
parent
406cb6dbc0
commit
428f1333ac
8
.github/dependabot.yml
vendored
8
.github/dependabot.yml
vendored
@@ -9,3 +9,11 @@ updates:
|
|||||||
directory: "/" # Location of package manifests
|
directory: "/" # Location of package manifests
|
||||||
schedule:
|
schedule:
|
||||||
interval: "weekly"
|
interval: "weekly"
|
||||||
|
- package-ecosystem: "gomod"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
- package-ecosystem: "npm"
|
||||||
|
directory: "/frontend"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
|||||||
63
.github/workflows/ci.yml
vendored
Normal file
63
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
go-test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
- uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: true
|
||||||
|
- name: Stub web/dist for go:embed
|
||||||
|
run: mkdir -p web/dist && touch web/dist/.gitkeep
|
||||||
|
- name: Test
|
||||||
|
run: |
|
||||||
|
go list ./... | grep -v '/frontend/node_modules/' > /tmp/go-packages.txt
|
||||||
|
go test $(cat /tmp/go-packages.txt)
|
||||||
|
|
||||||
|
govulncheck:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
- uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: true
|
||||||
|
- name: Stub web/dist for go:embed
|
||||||
|
run: mkdir -p web/dist && touch web/dist/.gitkeep
|
||||||
|
- name: Install govulncheck
|
||||||
|
run: go install golang.org/x/vuln/cmd/govulncheck@latest
|
||||||
|
- name: Run govulncheck
|
||||||
|
run: govulncheck ./...
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
- uses: actions/setup-node@v5
|
||||||
|
with:
|
||||||
|
node-version-file: .nvmrc
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
- name: Install
|
||||||
|
run: npm ci
|
||||||
|
working-directory: frontend
|
||||||
|
- name: Lint
|
||||||
|
run: npm run lint
|
||||||
|
working-directory: frontend
|
||||||
|
- name: Build
|
||||||
|
run: npm run build
|
||||||
|
working-directory: frontend
|
||||||
|
- name: Audit
|
||||||
|
run: npm audit --audit-level=high
|
||||||
|
working-directory: frontend
|
||||||
@@ -21,12 +21,8 @@ const (
|
|||||||
Shadowsocks Protocol = "shadowsocks"
|
Shadowsocks Protocol = "shadowsocks"
|
||||||
Mixed Protocol = "mixed"
|
Mixed Protocol = "mixed"
|
||||||
WireGuard Protocol = "wireguard"
|
WireGuard Protocol = "wireguard"
|
||||||
// UI stores Hysteria v1 and v2 both as "hysteria" and uses
|
Hysteria Protocol = "hysteria"
|
||||||
// settings.version to discriminate. Imports from outside the panel
|
Hysteria2 Protocol = "hysteria2"
|
||||||
// can carry the literal "hysteria2" string, so IsHysteria below
|
|
||||||
// accepts both.
|
|
||||||
Hysteria Protocol = "hysteria"
|
|
||||||
Hysteria2 Protocol = "hysteria2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// IsHysteria returns true for both "hysteria" and "hysteria2".
|
// IsHysteria returns true for both "hysteria" and "hysteria2".
|
||||||
@@ -38,9 +34,10 @@ func IsHysteria(p Protocol) bool {
|
|||||||
|
|
||||||
// User represents a user account in the 3x-ui panel.
|
// User represents a user account in the 3x-ui panel.
|
||||||
type User struct {
|
type User struct {
|
||||||
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
|
LoginEpoch int64 `json:"-" gorm:"default:0"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inbound represents an Xray inbound configuration with traffic statistics and settings.
|
// Inbound represents an Xray inbound configuration with traffic statistics and settings.
|
||||||
@@ -66,12 +63,7 @@ type Inbound struct {
|
|||||||
StreamSettings string `json:"streamSettings" form:"streamSettings"`
|
StreamSettings string `json:"streamSettings" form:"streamSettings"`
|
||||||
Tag string `json:"tag" form:"tag" gorm:"unique"`
|
Tag string `json:"tag" form:"tag" gorm:"unique"`
|
||||||
Sniffing string `json:"sniffing" form:"sniffing"`
|
Sniffing string `json:"sniffing" form:"sniffing"`
|
||||||
|
NodeID *int `json:"nodeId,omitempty" form:"nodeId" gorm:"index"`
|
||||||
// NodeID points at the remote panel (Node) where this inbound's xray
|
|
||||||
// actually runs. NULL means the inbound runs on the local xray (the
|
|
||||||
// pre-multi-node behaviour). Existing rows migrate to NULL with no
|
|
||||||
// backfill.
|
|
||||||
NodeID *int `json:"nodeId,omitempty" form:"nodeId" gorm:"index"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// OutboundTraffics tracks traffic statistics for Xray outbound connections.
|
// OutboundTraffics tracks traffic statistics for Xray outbound connections.
|
||||||
@@ -128,15 +120,16 @@ type Setting struct {
|
|||||||
// endpoint over HTTP using the per-node ApiToken to populate the runtime
|
// endpoint over HTTP using the per-node ApiToken to populate the runtime
|
||||||
// status fields below.
|
// status fields below.
|
||||||
type Node struct {
|
type Node struct {
|
||||||
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
|
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
|
||||||
Name string `json:"name" form:"name" gorm:"uniqueIndex"`
|
Name string `json:"name" form:"name" gorm:"uniqueIndex"`
|
||||||
Remark string `json:"remark" form:"remark"`
|
Remark string `json:"remark" form:"remark"`
|
||||||
Scheme string `json:"scheme" form:"scheme"`
|
Scheme string `json:"scheme" form:"scheme"`
|
||||||
Address string `json:"address" form:"address"`
|
Address string `json:"address" form:"address"`
|
||||||
Port int `json:"port" form:"port"`
|
Port int `json:"port" form:"port"`
|
||||||
BasePath string `json:"basePath" form:"basePath"`
|
BasePath string `json:"basePath" form:"basePath"`
|
||||||
ApiToken string `json:"apiToken" form:"apiToken"`
|
ApiToken string `json:"apiToken" form:"apiToken"`
|
||||||
Enable bool `json:"enable" form:"enable" gorm:"default:true"`
|
Enable bool `json:"enable" form:"enable" gorm:"default:true"`
|
||||||
|
AllowPrivateAddress bool `json:"allowPrivateAddress" form:"allowPrivateAddress" gorm:"default:false"`
|
||||||
|
|
||||||
// Heartbeat-updated fields. UpdatedAt advances on every probe even when
|
// Heartbeat-updated fields. UpdatedAt advances on every probe even when
|
||||||
// the row is otherwise unchanged so the UI's "last seen" tooltip is
|
// the row is otherwise unchanged so the UI's "last seen" tooltip is
|
||||||
|
|||||||
4
frontend/package-lock.json
generated
4
frontend/package-lock.json
generated
@@ -7,6 +7,10 @@
|
|||||||
"": {
|
"": {
|
||||||
"name": "3x-ui-frontend",
|
"name": "3x-ui-frontend",
|
||||||
"version": "0.0.2",
|
"version": "0.0.2",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.0.0",
|
||||||
|
"npm": ">=10.0.0"
|
||||||
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ant-design/icons-vue": "^7.0.1",
|
"@ant-design/icons-vue": "^7.0.1",
|
||||||
"ant-design-vue": "^4.2.6",
|
"ant-design-vue": "^4.2.6",
|
||||||
|
|||||||
@@ -4,6 +4,10 @@
|
|||||||
"version": "0.0.2",
|
"version": "0.0.2",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "3x-ui panel frontend (Vue 3 + Ant Design Vue 4 + Vite 8).",
|
"description": "3x-ui panel frontend (Vue 3 + Ant Design Vue 4 + Vite 8).",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.0.0",
|
||||||
|
"npm": ">=10.0.0"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
|
|||||||
@@ -2,24 +2,16 @@ import axios from 'axios';
|
|||||||
import qs from 'qs';
|
import qs from 'qs';
|
||||||
|
|
||||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
|
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
|
||||||
// Public CSRF endpoint — works pre-login (the panel-scoped
|
|
||||||
// /panel/csrf-token sits behind checkLogin and would 401 a fresh
|
|
||||||
// login page that hasn't authenticated yet).
|
|
||||||
const CSRF_TOKEN_PATH = '/csrf-token';
|
const CSRF_TOKEN_PATH = '/csrf-token';
|
||||||
|
|
||||||
// Cached session CSRF token. The legacy panel injects it via a
|
|
||||||
// <meta name="csrf-token"> tag rendered by Go; the new SPA pages
|
|
||||||
// fetch it once from /panel/csrf-token instead. Module-level so
|
|
||||||
// every axios POST sees the latest value.
|
|
||||||
let csrfToken = null;
|
let csrfToken = null;
|
||||||
let csrfFetchPromise = null;
|
let csrfFetchPromise = null;
|
||||||
|
let sessionExpired = false;
|
||||||
|
|
||||||
function readMetaToken() {
|
function readMetaToken() {
|
||||||
return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || null;
|
return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the token via a bare fetch() (not axios) so the call doesn't
|
|
||||||
// recurse through this same interceptor.
|
|
||||||
async function fetchCsrfToken() {
|
async function fetchCsrfToken() {
|
||||||
try {
|
try {
|
||||||
const basePath = window.X_UI_BASE_PATH;
|
const basePath = window.X_UI_BASE_PATH;
|
||||||
@@ -91,19 +83,16 @@ export function setupAxios() {
|
|||||||
async (error) => {
|
async (error) => {
|
||||||
const status = error.response?.status;
|
const status = error.response?.status;
|
||||||
if (status === 401) {
|
if (status === 401) {
|
||||||
// 401 → session is gone. In production, the panel routes
|
if (!sessionExpired) {
|
||||||
// are gated by Go's checkLogin which redirects to base_path
|
sessionExpired = true;
|
||||||
// serving the login page; a reload is enough. In dev, Vite
|
if (import.meta.env.DEV) {
|
||||||
// serves /index.html directly at "/", so a reload would put
|
const basePath = window.X_UI_BASE_PATH || '/';
|
||||||
// the user right back on the dashboard and the interceptor
|
window.location.href = `${basePath}login.html`;
|
||||||
// would loop. Navigate to the dev login entry instead.
|
} else {
|
||||||
if (import.meta.env.DEV) {
|
window.location.reload();
|
||||||
const basePath = window.X_UI_BASE_PATH || '/';
|
}
|
||||||
window.location.href = `${basePath}login.html`;
|
|
||||||
} else {
|
|
||||||
window.location.reload();
|
|
||||||
}
|
}
|
||||||
return Promise.reject(error);
|
return new Promise(() => { });
|
||||||
}
|
}
|
||||||
// 403 with a stale/missing CSRF token: drop the cache, re-fetch, retry once.
|
// 403 with a stale/missing CSRF token: drop the cache, re-fetch, retry once.
|
||||||
const cfg = error.config;
|
const cfg = error.config;
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
} from '@ant-design/icons-vue';
|
} from '@ant-design/icons-vue';
|
||||||
|
|
||||||
import { theme, currentTheme, toggleTheme, toggleUltra, pauseAnimationsUntilLeave } from '@/composables/useTheme.js';
|
import { theme, currentTheme, toggleTheme, toggleUltra, pauseAnimationsUntilLeave } from '@/composables/useTheme.js';
|
||||||
|
import { HttpUtil } from '@/utils';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
@@ -45,7 +46,7 @@ const tabs = computed(() => [
|
|||||||
{ key: `${prefix}panel/settings`, icon: 'setting', title: t('menu.settings') },
|
{ key: `${prefix}panel/settings`, icon: 'setting', title: t('menu.settings') },
|
||||||
{ key: `${prefix}panel/xray`, icon: 'tool', title: t('menu.xray') },
|
{ key: `${prefix}panel/xray`, icon: 'tool', title: t('menu.xray') },
|
||||||
{ key: `${prefix}panel/api-docs`, icon: 'apidocs', title: t('menu.apiDocs') },
|
{ key: `${prefix}panel/api-docs`, icon: 'apidocs', title: t('menu.apiDocs') },
|
||||||
{ key: `${prefix}logout`, icon: 'logout', title: t('logout') },
|
{ key: 'logout', icon: 'logout', title: t('logout') },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const navTabs = computed(() => tabs.value.filter((tab) => tab.icon !== 'logout'));
|
const navTabs = computed(() => tabs.value.filter((tab) => tab.icon !== 'logout'));
|
||||||
@@ -55,7 +56,12 @@ const drawerOpen = ref(false);
|
|||||||
const collapsed = ref(JSON.parse(localStorage.getItem(SIDEBAR_COLLAPSED_KEY) || 'false'));
|
const collapsed = ref(JSON.parse(localStorage.getItem(SIDEBAR_COLLAPSED_KEY) || 'false'));
|
||||||
const drawerWidth = 'min(82vw, 320px)';
|
const drawerWidth = 'min(82vw, 320px)';
|
||||||
|
|
||||||
function openLink(key) {
|
async function openLink(key) {
|
||||||
|
if (key === 'logout') {
|
||||||
|
await HttpUtil.post('/logout');
|
||||||
|
window.location.href = props.basePath || '/';
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (key.startsWith('http')) {
|
if (key.startsWith('http')) {
|
||||||
window.open(key);
|
window.open(key);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ export class AllSetting {
|
|||||||
this.webKeyFile = "";
|
this.webKeyFile = "";
|
||||||
this.webBasePath = "/";
|
this.webBasePath = "/";
|
||||||
this.sessionMaxAge = 360;
|
this.sessionMaxAge = 360;
|
||||||
|
this.trustedProxyCIDRs = "127.0.0.1/32,::1/128";
|
||||||
this.pageSize = 25;
|
this.pageSize = 25;
|
||||||
this.expireDiff = 0;
|
this.expireDiff = 0;
|
||||||
this.trafficDiff = 0;
|
this.trafficDiff = 0;
|
||||||
@@ -87,6 +88,12 @@ export class AllSetting {
|
|||||||
this.ldapDefaultTotalGB = 0;
|
this.ldapDefaultTotalGB = 0;
|
||||||
this.ldapDefaultExpiryDays = 0;
|
this.ldapDefaultExpiryDays = 0;
|
||||||
this.ldapDefaultLimitIP = 0;
|
this.ldapDefaultLimitIP = 0;
|
||||||
|
this.hasTgBotToken = false;
|
||||||
|
this.hasTwoFactorToken = false;
|
||||||
|
this.hasLdapPassword = false;
|
||||||
|
this.hasApiToken = false;
|
||||||
|
this.hasWarpSecret = false;
|
||||||
|
this.hasNordSecret = false;
|
||||||
|
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
return
|
return
|
||||||
@@ -97,4 +104,4 @@ export class AllSetting {
|
|||||||
equals(other) {
|
equals(other) {
|
||||||
return ObjectUtil.equals(this, other);
|
return ObjectUtil.equals(this, other);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,9 +46,10 @@ export const sections = [
|
|||||||
'{\n "success": false,\n "msg": "Wrong username or password"\n}',
|
'{\n "success": false,\n "msg": "Wrong username or password"\n}',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
method: 'GET',
|
method: 'POST',
|
||||||
path: '/logout',
|
path: '/logout',
|
||||||
summary: 'Clear the session cookie. Redirects back to the login page; not useful from non-browser clients.',
|
summary: 'Clear the session cookie. Requires the CSRF header for browser sessions.',
|
||||||
|
response: '{\n "success": true\n}',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -70,7 +71,7 @@ export const sections = [
|
|||||||
id: 'inbounds',
|
id: 'inbounds',
|
||||||
title: 'Inbounds API',
|
title: 'Inbounds API',
|
||||||
description:
|
description:
|
||||||
'Manage inbound configurations and their clients. All endpoints live under /panel/api/inbounds and require a logged-in session or Bearer token. Link-generating endpoints honour X-Forwarded-Host / X-Forwarded-Proto, so callers behind a reverse proxy get the correct external host in returned URLs.',
|
'Manage inbound configurations and their clients. All endpoints live under /panel/api/inbounds and require a logged-in session or Bearer token. Link-generating endpoints honour forwarded headers only when the request comes from a configured trusted proxy.',
|
||||||
endpoints: [
|
endpoints: [
|
||||||
{
|
{
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -627,7 +628,7 @@ export const sections = [
|
|||||||
description: 'Operations that interact with the configured Telegram bot.',
|
description: 'Operations that interact with the configured Telegram bot.',
|
||||||
endpoints: [
|
endpoints: [
|
||||||
{
|
{
|
||||||
method: 'GET',
|
method: 'POST',
|
||||||
path: '/panel/api/backuptotgbot',
|
path: '/panel/api/backuptotgbot',
|
||||||
summary: 'Send a fresh DB backup to every Telegram chat configured as an admin recipient. No body, no params.',
|
summary: 'Send a fresh DB backup to every Telegram chat configured as an admin recipient. No body, no params.',
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -67,9 +67,29 @@ const emit = defineEmits([
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
// ============ Toolbar / search & filter =============================
|
// ============ Toolbar / search & filter =============================
|
||||||
const enableFilter = ref(false);
|
const FILTER_STATE_KEY = 'inboundsFilterState';
|
||||||
const searchKey = ref('');
|
const savedFilterState = (() => {
|
||||||
const filterBy = ref('');
|
try {
|
||||||
|
return JSON.parse(localStorage.getItem(FILTER_STATE_KEY) || '{}');
|
||||||
|
} catch (_e) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
const enableFilter = ref(!!savedFilterState.enableFilter);
|
||||||
|
const searchKey = ref(savedFilterState.searchKey || '');
|
||||||
|
const filterBy = ref(savedFilterState.filterBy || '');
|
||||||
|
const protocolFilter = ref(savedFilterState.protocolFilter || '');
|
||||||
|
const nodeFilter = ref(savedFilterState.nodeFilter || '');
|
||||||
|
|
||||||
|
watch([enableFilter, searchKey, filterBy, protocolFilter, nodeFilter], () => {
|
||||||
|
localStorage.setItem(FILTER_STATE_KEY, JSON.stringify({
|
||||||
|
enableFilter: enableFilter.value,
|
||||||
|
searchKey: searchKey.value,
|
||||||
|
filterBy: filterBy.value,
|
||||||
|
protocolFilter: protocolFilter.value,
|
||||||
|
nodeFilter: nodeFilter.value,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
// Toggle the filter mode — flip cleans the other input.
|
// Toggle the filter mode — flip cleans the other input.
|
||||||
function onToggleFilter() {
|
function onToggleFilter() {
|
||||||
@@ -77,6 +97,35 @@ function onToggleFilter() {
|
|||||||
else filterBy.value = '';
|
else filterBy.value = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const protocolOptions = computed(() => {
|
||||||
|
const values = new Set(props.dbInbounds.map((i) => i.protocol).filter(Boolean));
|
||||||
|
return [...values].sort();
|
||||||
|
});
|
||||||
|
|
||||||
|
const nodeOptions = computed(() => {
|
||||||
|
const values = new Map();
|
||||||
|
if (props.dbInbounds.some((i) => i.nodeId == null)) {
|
||||||
|
values.set('local', t('pages.inbounds.localPanel'));
|
||||||
|
}
|
||||||
|
for (const dbInbound of props.dbInbounds) {
|
||||||
|
if (dbInbound.nodeId == null) continue;
|
||||||
|
const node = props.nodesById.get(dbInbound.nodeId);
|
||||||
|
values.set(String(dbInbound.nodeId), node?.name || `#${dbInbound.nodeId}`);
|
||||||
|
}
|
||||||
|
return [...values.entries()].map(([value, label]) => ({ value, label }));
|
||||||
|
});
|
||||||
|
|
||||||
|
function applySecondaryFilters(rows) {
|
||||||
|
return rows.filter((dbInbound) => {
|
||||||
|
if (protocolFilter.value && dbInbound.protocol !== protocolFilter.value) return false;
|
||||||
|
if (nodeFilter.value) {
|
||||||
|
const nodeValue = dbInbound.nodeId == null ? 'local' : String(dbInbound.nodeId);
|
||||||
|
if (nodeValue !== nodeFilter.value) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// ============ Search / filter projection =============================
|
// ============ Search / filter projection =============================
|
||||||
// Mirrors the legacy logic: when searching, keep inbounds that match
|
// Mirrors the legacy logic: when searching, keep inbounds that match
|
||||||
// anywhere (deep search); when filtering, keep inbounds that have at
|
// anywhere (deep search); when filtering, keep inbounds that have at
|
||||||
@@ -99,7 +148,7 @@ function projectInbound(dbInbound, predicate) {
|
|||||||
|
|
||||||
const visibleInbounds = computed(() => {
|
const visibleInbounds = computed(() => {
|
||||||
if (enableFilter.value) {
|
if (enableFilter.value) {
|
||||||
if (ObjectUtil.isEmpty(filterBy.value)) return [...props.dbInbounds];
|
if (ObjectUtil.isEmpty(filterBy.value)) return applySecondaryFilters([...props.dbInbounds]);
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const dbInbound of props.dbInbounds) {
|
for (const dbInbound of props.dbInbounds) {
|
||||||
const c = props.clientCount[dbInbound.id];
|
const c = props.clientCount[dbInbound.id];
|
||||||
@@ -107,15 +156,15 @@ const visibleInbounds = computed(() => {
|
|||||||
const list = c[filterBy.value];
|
const list = c[filterBy.value];
|
||||||
out.push(projectInbound(dbInbound, (client) => list.includes(client.email)));
|
out.push(projectInbound(dbInbound, (client) => list.includes(client.email)));
|
||||||
}
|
}
|
||||||
return out;
|
return applySecondaryFilters(out);
|
||||||
}
|
}
|
||||||
if (ObjectUtil.isEmpty(searchKey.value)) return [...props.dbInbounds];
|
if (ObjectUtil.isEmpty(searchKey.value)) return applySecondaryFilters([...props.dbInbounds]);
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const dbInbound of props.dbInbounds) {
|
for (const dbInbound of props.dbInbounds) {
|
||||||
if (!ObjectUtil.deepSearch(dbInbound, searchKey.value)) continue;
|
if (!ObjectUtil.deepSearch(dbInbound, searchKey.value)) continue;
|
||||||
out.push(projectInbound(dbInbound, (client) => ObjectUtil.deepSearch(client, searchKey.value)));
|
out.push(projectInbound(dbInbound, (client) => ObjectUtil.deepSearch(client, searchKey.value)));
|
||||||
}
|
}
|
||||||
return out;
|
return applySecondaryFilters(out);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ============ Sorting =================================================
|
// ============ Sorting =================================================
|
||||||
@@ -319,6 +368,18 @@ function showQrCodeMenu(dbInbound) {
|
|||||||
<a-radio-button value="expiring">{{ t('depletingSoon') }}</a-radio-button>
|
<a-radio-button value="expiring">{{ t('depletingSoon') }}</a-radio-button>
|
||||||
<a-radio-button value="online">{{ t('online') }}</a-radio-button>
|
<a-radio-button value="online">{{ t('online') }}</a-radio-button>
|
||||||
</a-radio-group>
|
</a-radio-group>
|
||||||
|
<a-select v-model:value="protocolFilter" allow-clear :placeholder="t('pages.inbounds.protocol')"
|
||||||
|
:size="isMobile ? 'small' : 'middle'" :style="{ width: '150px' }">
|
||||||
|
<a-select-option v-for="protocol in protocolOptions" :key="protocol" :value="protocol">
|
||||||
|
{{ protocol }}
|
||||||
|
</a-select-option>
|
||||||
|
</a-select>
|
||||||
|
<a-select v-if="nodeOptions.length > 0" v-model:value="nodeFilter" allow-clear
|
||||||
|
:placeholder="t('pages.inbounds.node')" :size="isMobile ? 'small' : 'middle'" :style="{ width: '170px' }">
|
||||||
|
<a-select-option v-for="node in nodeOptions" :key="node.value" :value="node.value">
|
||||||
|
{{ node.label }}
|
||||||
|
</a-select-option>
|
||||||
|
</a-select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ====================== Mobile: card list ======================= -->
|
<!-- ====================== Mobile: card list ======================= -->
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ function defaultForm() {
|
|||||||
basePath: '/',
|
basePath: '/',
|
||||||
apiToken: '',
|
apiToken: '',
|
||||||
enable: true,
|
enable: true,
|
||||||
|
allowPrivateAddress: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,6 +70,7 @@ function buildPayload() {
|
|||||||
basePath: form.basePath?.trim() || '/',
|
basePath: form.basePath?.trim() || '/',
|
||||||
apiToken: form.apiToken?.trim() || '',
|
apiToken: form.apiToken?.trim() || '',
|
||||||
enable: !!form.enable,
|
enable: !!form.enable,
|
||||||
|
allowPrivateAddress: !!form.allowPrivateAddress,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,6 +163,11 @@ async function onSave() {
|
|||||||
</a-col>
|
</a-col>
|
||||||
</a-row>
|
</a-row>
|
||||||
|
|
||||||
|
<a-form-item label="Allow private address">
|
||||||
|
<a-switch v-model:checked="form.allowPrivateAddress" />
|
||||||
|
<div class="hint">Enable only for nodes on a private network or VPN.</div>
|
||||||
|
</a-form-item>
|
||||||
|
|
||||||
<a-form-item :label="t('pages.nodes.apiToken')" required>
|
<a-form-item :label="t('pages.nodes.apiToken')" required>
|
||||||
<a-input-password v-model:value="form.apiToken" :placeholder="t('pages.nodes.apiTokenPlaceholder')" />
|
<a-input-password v-model:value="form.apiToken" :placeholder="t('pages.nodes.apiTokenPlaceholder')" />
|
||||||
<div class="hint">{{ t('pages.nodes.apiTokenHint') }}</div>
|
<div class="hint">{{ t('pages.nodes.apiTokenHint') }}</div>
|
||||||
|
|||||||
@@ -153,6 +153,14 @@ onMounted(loadInboundTags);
|
|||||||
</template>
|
</template>
|
||||||
</SettingListItem>
|
</SettingListItem>
|
||||||
|
|
||||||
|
<SettingListItem paddings="small">
|
||||||
|
<template #title>Trusted proxy CIDRs</template>
|
||||||
|
<template #description>Comma-separated IPs/CIDRs allowed to set forwarded host, proto, and client IP headers.</template>
|
||||||
|
<template #control>
|
||||||
|
<a-input v-model:value="allSetting.trustedProxyCIDRs" placeholder="127.0.0.1/32,::1/128" />
|
||||||
|
</template>
|
||||||
|
</SettingListItem>
|
||||||
|
|
||||||
<SettingListItem paddings="small">
|
<SettingListItem paddings="small">
|
||||||
<template #title>{{ t('pages.settings.pageSize') }}</template>
|
<template #title>{{ t('pages.settings.pageSize') }}</template>
|
||||||
<template #description>{{ t('pages.settings.pageSizeDesc') }}</template>
|
<template #description>{{ t('pages.settings.pageSizeDesc') }}</template>
|
||||||
@@ -298,8 +306,12 @@ onMounted(loadInboundTags);
|
|||||||
|
|
||||||
<SettingListItem paddings="small">
|
<SettingListItem paddings="small">
|
||||||
<template #title>{{ t('password') }}</template>
|
<template #title>{{ t('password') }}</template>
|
||||||
|
<template #description>
|
||||||
|
{{ allSetting.hasLdapPassword ? 'Configured; leave blank to keep current password.' : 'Not configured.' }}
|
||||||
|
</template>
|
||||||
<template #control>
|
<template #control>
|
||||||
<a-input-password v-model:value="allSetting.ldapPassword" />
|
<a-input-password v-model:value="allSetting.ldapPassword"
|
||||||
|
:placeholder="allSetting.hasLdapPassword ? 'Configured - enter a new value to replace' : ''" />
|
||||||
</template>
|
</template>
|
||||||
</SettingListItem>
|
</SettingListItem>
|
||||||
|
|
||||||
|
|||||||
@@ -52,10 +52,9 @@ async function sendUpdateUser() {
|
|||||||
try {
|
try {
|
||||||
const msg = await HttpUtil.post('/panel/setting/updateUser', user);
|
const msg = await HttpUtil.post('/panel/setting/updateUser', user);
|
||||||
if (msg?.success) {
|
if (msg?.success) {
|
||||||
// Force re-login at the standard logout path; basePath is handled
|
await HttpUtil.post('/logout');
|
||||||
// by the Go router so a relative redirect is correct here.
|
const basePath = window.X_UI_BASE_PATH || '/';
|
||||||
const basePath = window.X_UI_BASE_PATH || '';
|
window.location.replace(basePath);
|
||||||
window.location.replace(`${basePath}logout`);
|
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
updating.value = false;
|
updating.value = false;
|
||||||
|
|||||||
@@ -23,9 +23,12 @@ defineProps({
|
|||||||
|
|
||||||
<SettingListItem paddings="small">
|
<SettingListItem paddings="small">
|
||||||
<template #title>{{ t('pages.settings.telegramToken') }}</template>
|
<template #title>{{ t('pages.settings.telegramToken') }}</template>
|
||||||
<template #description>{{ t('pages.settings.telegramTokenDesc') }}</template>
|
<template #description>
|
||||||
|
{{ allSetting.hasTgBotToken ? 'Configured; leave blank to keep current token.' : t('pages.settings.telegramTokenDesc') }}
|
||||||
|
</template>
|
||||||
<template #control>
|
<template #control>
|
||||||
<a-input v-model:value="allSetting.tgBotToken" type="text" />
|
<a-input-password v-model:value="allSetting.tgBotToken"
|
||||||
|
:placeholder="allSetting.hasTgBotToken ? 'Configured - enter a new token to replace' : ''" />
|
||||||
</template>
|
</template>
|
||||||
</SettingListItem>
|
</SettingListItem>
|
||||||
|
|
||||||
|
|||||||
@@ -38,18 +38,24 @@ function buildTotp() {
|
|||||||
watch(() => props.open, (next) => {
|
watch(() => props.open, (next) => {
|
||||||
if (!next) return;
|
if (!next) return;
|
||||||
enteredCode.value = '';
|
enteredCode.value = '';
|
||||||
|
totp = null;
|
||||||
|
qrValue.value = '';
|
||||||
if (props.token) {
|
if (props.token) {
|
||||||
buildTotp();
|
buildTotp();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
function close(success) {
|
function close(success, code = '') {
|
||||||
emit('confirm', success);
|
emit('confirm', success, code);
|
||||||
emit('update:open', false);
|
emit('update:open', false);
|
||||||
enteredCode.value = '';
|
enteredCode.value = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function onOk() {
|
function onOk() {
|
||||||
|
if (props.type === 'confirm' && !props.token) {
|
||||||
|
close(true, enteredCode.value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!totp) return;
|
if (!totp) return;
|
||||||
if (totp.generate() === enteredCode.value) {
|
if (totp.generate() === enteredCode.value) {
|
||||||
close(true);
|
close(true);
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ const subUrl = subData.subUrl || '';
|
|||||||
const subJsonUrl = subData.subJsonUrl || '';
|
const subJsonUrl = subData.subJsonUrl || '';
|
||||||
const subClashUrl = subData.subClashUrl || '';
|
const subClashUrl = subData.subClashUrl || '';
|
||||||
const subTitle = subData.subTitle || '';
|
const subTitle = subData.subTitle || '';
|
||||||
const subSupportUrl = subData.subSupportUrl || '';
|
|
||||||
const links = Array.isArray(subData.links) ? subData.links : [];
|
const links = Array.isArray(subData.links) ? subData.links : [];
|
||||||
// Panel's "Calendar Type" setting; controls whether expiry / lastOnline
|
// Panel's "Calendar Type" setting; controls whether expiry / lastOnline
|
||||||
// render in Gregorian or Jalali on this standalone subscription page.
|
// render in Gregorian or Jalali on this standalone subscription page.
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useI18n } from 'vue-i18n';
|
|||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
const props = defineProps({
|
defineProps({
|
||||||
open: { type: Boolean, default: false },
|
open: { type: Boolean, default: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -29,25 +29,11 @@ func NewAPIController(g *gin.RouterGroup, customGeo *service.CustomGeoService) *
|
|||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
|
|
||||||
// checkAPIAuth is a middleware that returns 404 for unauthenticated API requests
|
|
||||||
// to hide the existence of API endpoints from unauthorized users.
|
|
||||||
//
|
|
||||||
// Two auth paths are accepted:
|
|
||||||
// 1. Authorization: Bearer <apiToken> — used by remote central panels
|
|
||||||
// polling this instance as a node. Matches via constant-time compare.
|
|
||||||
// Sets c.Set("api_authed", true) so CSRFMiddleware can short-circuit.
|
|
||||||
// 2. Existing session cookie — used by browsers logged into the panel UI.
|
|
||||||
//
|
|
||||||
// Anything else falls through to a 404 so the API endpoints remain hidden.
|
|
||||||
func (a *APIController) checkAPIAuth(c *gin.Context) {
|
func (a *APIController) checkAPIAuth(c *gin.Context) {
|
||||||
auth := c.GetHeader("Authorization")
|
auth := c.GetHeader("Authorization")
|
||||||
if strings.HasPrefix(auth, "Bearer ") {
|
if strings.HasPrefix(auth, "Bearer ") {
|
||||||
tok := strings.TrimPrefix(auth, "Bearer ")
|
tok := strings.TrimPrefix(auth, "Bearer ")
|
||||||
if a.settingService.MatchApiToken(tok) {
|
if a.settingService.MatchApiToken(tok) {
|
||||||
// Handlers like InboundController.addInbound assume a logged-in
|
|
||||||
// user (inbound.UserId = user.Id). Bearer callers have no
|
|
||||||
// session, so attach the first user as a fallback. Single-user
|
|
||||||
// panels are the norm here.
|
|
||||||
if u, err := a.userService.GetFirstUser(); err == nil {
|
if u, err := a.userService.GetFirstUser(); err == nil {
|
||||||
session.SetAPIAuthUser(c, u)
|
session.SetAPIAuthUser(c, u)
|
||||||
}
|
}
|
||||||
@@ -57,7 +43,11 @@ func (a *APIController) checkAPIAuth(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !session.IsLogin(c) {
|
if !session.IsLogin(c) {
|
||||||
c.AbortWithStatus(http.StatusNotFound)
|
if c.GetHeader("X-Requested-With") == "XMLHttpRequest" {
|
||||||
|
c.AbortWithStatus(http.StatusUnauthorized)
|
||||||
|
} else {
|
||||||
|
c.AbortWithStatus(http.StatusNotFound)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.Next()
|
c.Next()
|
||||||
@@ -85,7 +75,7 @@ func (a *APIController) initRouter(g *gin.RouterGroup, customGeo *service.Custom
|
|||||||
NewCustomGeoController(api.Group("/custom-geo"), customGeo)
|
NewCustomGeoController(api.Group("/custom-geo"), customGeo)
|
||||||
|
|
||||||
// Extra routes
|
// Extra routes
|
||||||
api.GET("/backuptotgbot", a.BackuptoTgbot)
|
api.POST("/backuptotgbot", a.BackuptoTgbot)
|
||||||
}
|
}
|
||||||
|
|
||||||
// BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
|
// BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
|
||||||
|
|||||||
@@ -57,7 +57,11 @@ func serveDistPage(c *gin.Context, name string) {
|
|||||||
}
|
}
|
||||||
csrfMeta := []byte(`<meta name="csrf-token" content="` + htmlpkg.EscapeString(csrfToken) + `">`)
|
csrfMeta := []byte(`<meta name="csrf-token" content="` + htmlpkg.EscapeString(csrfToken) + `">`)
|
||||||
|
|
||||||
script := `<script>window.X_UI_BASE_PATH="` + escapedBase + `"`
|
nonceAttr := ""
|
||||||
|
if nonce := c.GetString("csp_nonce"); nonce != "" {
|
||||||
|
nonceAttr = ` nonce="` + htmlpkg.EscapeString(nonce) + `"`
|
||||||
|
}
|
||||||
|
script := `<script` + nonceAttr + `>window.X_UI_BASE_PATH="` + escapedBase + `"`
|
||||||
if name != "login.html" {
|
if name != "login.html" {
|
||||||
escapedVer := jsEscape.Replace(config.GetVersion())
|
escapedVer := jsEscape.Replace(config.GetVersion())
|
||||||
script += `;window.X_UI_CUR_VER="` + escapedVer + `"`
|
script += `;window.X_UI_CUR_VER="` + escapedVer + `"`
|
||||||
|
|||||||
@@ -582,17 +582,19 @@ func (a *InboundController) delInboundClientByEmail(c *gin.Context) {
|
|||||||
// controller layer means the service interface stays HTTP-agnostic — service
|
// controller layer means the service interface stays HTTP-agnostic — service
|
||||||
// methods receive a plain host string instead of a *gin.Context.
|
// methods receive a plain host string instead of a *gin.Context.
|
||||||
func resolveHost(c *gin.Context) string {
|
func resolveHost(c *gin.Context) string {
|
||||||
if h := strings.TrimSpace(c.GetHeader("X-Forwarded-Host")); h != "" {
|
if isTrustedForwardedRequest(c) {
|
||||||
if i := strings.Index(h, ","); i >= 0 {
|
if h := strings.TrimSpace(c.GetHeader("X-Forwarded-Host")); h != "" {
|
||||||
h = strings.TrimSpace(h[:i])
|
if i := strings.Index(h, ","); i >= 0 {
|
||||||
|
h = strings.TrimSpace(h[:i])
|
||||||
|
}
|
||||||
|
if hp, _, err := net.SplitHostPort(h); err == nil {
|
||||||
|
return hp
|
||||||
|
}
|
||||||
|
return h
|
||||||
}
|
}
|
||||||
if hp, _, err := net.SplitHostPort(h); err == nil {
|
if h := c.GetHeader("X-Real-IP"); h != "" {
|
||||||
return hp
|
return h
|
||||||
}
|
}
|
||||||
return h
|
|
||||||
}
|
|
||||||
if h := c.GetHeader("X-Real-IP"); h != "" {
|
|
||||||
return h
|
|
||||||
}
|
}
|
||||||
if h, _, err := net.SplitHostPort(c.Request.Host); err == nil {
|
if h, _, err := net.SplitHostPort(c.Request.Host); err == nil {
|
||||||
return h
|
return h
|
||||||
|
|||||||
@@ -39,15 +39,10 @@ func NewIndexController(g *gin.RouterGroup) *IndexController {
|
|||||||
// initRouter sets up the routes for index, login, logout, and two-factor authentication.
|
// initRouter sets up the routes for index, login, logout, and two-factor authentication.
|
||||||
func (a *IndexController) initRouter(g *gin.RouterGroup) {
|
func (a *IndexController) initRouter(g *gin.RouterGroup) {
|
||||||
g.GET("/", a.index)
|
g.GET("/", a.index)
|
||||||
g.GET("/logout", a.logout)
|
|
||||||
// Public CSRF endpoint — the SPA login page (served by Vite in
|
|
||||||
// dev or by serveDistPage in prod) needs a token to POST /login,
|
|
||||||
// but the panel-side /panel/csrf-token sits behind checkLogin.
|
|
||||||
// EnsureCSRFToken creates a session token even for anonymous
|
|
||||||
// callers, so any pre-login flow can bootstrap from here.
|
|
||||||
g.GET("/csrf-token", a.csrfToken)
|
g.GET("/csrf-token", a.csrfToken)
|
||||||
|
|
||||||
g.POST("/login", middleware.CSRFMiddleware(), a.login)
|
g.POST("/login", middleware.CSRFMiddleware(), a.login)
|
||||||
|
g.POST("/logout", middleware.CSRFMiddleware(), a.logout)
|
||||||
g.POST("/getTwoFactorEnable", middleware.CSRFMiddleware(), a.getTwoFactorEnable)
|
g.POST("/getTwoFactorEnable", middleware.CSRFMiddleware(), a.getTwoFactorEnable)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,7 +135,7 @@ func loginFailureReason(err error) string {
|
|||||||
return "invalid credentials"
|
return "invalid credentials"
|
||||||
}
|
}
|
||||||
|
|
||||||
// logout handles user logout by clearing the session and redirecting to the login page.
|
// logout clears the session. The SPA performs the navigation client-side.
|
||||||
func (a *IndexController) logout(c *gin.Context) {
|
func (a *IndexController) logout(c *gin.Context) {
|
||||||
user := session.GetLoginUser(c)
|
user := session.GetLoginUser(c)
|
||||||
if user != nil {
|
if user != nil {
|
||||||
@@ -150,7 +145,7 @@ func (a *IndexController) logout(c *gin.Context) {
|
|||||||
logger.Warning("Unable to clear session on logout:", err)
|
logger.Warning("Unable to clear session on logout:", err)
|
||||||
}
|
}
|
||||||
c.Header("Cache-Control", "no-store")
|
c.Header("Cache-Control", "no-store")
|
||||||
c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
|
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||||
}
|
}
|
||||||
|
|
||||||
// csrfToken returns the session CSRF token. Public — the login page
|
// csrfToken returns the session CSRF token. Public — the login page
|
||||||
|
|||||||
@@ -9,29 +9,75 @@ import (
|
|||||||
|
|
||||||
"github.com/mhsanaei/3x-ui/v3/logger"
|
"github.com/mhsanaei/3x-ui/v3/logger"
|
||||||
"github.com/mhsanaei/3x-ui/v3/web/entity"
|
"github.com/mhsanaei/3x-ui/v3/web/entity"
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/web/service"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// getRemoteIp extracts the real IP address from the request headers or remote address.
|
// getRemoteIp extracts the real IP address from the request headers or remote address.
|
||||||
func getRemoteIp(c *gin.Context) string {
|
func getRemoteIp(c *gin.Context) string {
|
||||||
if ip, ok := extractTrustedIP(c.GetHeader("X-Real-IP")); ok {
|
remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
|
||||||
return ip
|
if !ok {
|
||||||
|
return "unknown"
|
||||||
}
|
}
|
||||||
|
|
||||||
if xff := c.GetHeader("X-Forwarded-For"); xff != "" {
|
if isTrustedProxy(remoteIP) {
|
||||||
for _, part := range strings.Split(xff, ",") {
|
if ip, ok := extractTrustedIP(c.GetHeader("X-Real-IP")); ok {
|
||||||
if ip, ok := extractTrustedIP(part); ok {
|
return ip
|
||||||
return ip
|
}
|
||||||
|
|
||||||
|
if xff := c.GetHeader("X-Forwarded-For"); xff != "" {
|
||||||
|
for _, part := range strings.Split(xff, ",") {
|
||||||
|
if ip, ok := extractTrustedIP(part); ok {
|
||||||
|
return ip
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip, ok := extractTrustedIP(c.Request.RemoteAddr); ok {
|
return remoteIP
|
||||||
return ip
|
}
|
||||||
|
|
||||||
|
func isTrustedForwardedRequest(c *gin.Context) bool {
|
||||||
|
remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
|
||||||
|
return ok && isTrustedProxy(remoteIP)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isTrustedProxy(ip string) bool {
|
||||||
|
addr, err := netip.ParseAddr(ip)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
return "unknown"
|
trusted := trustedProxyCIDRs()
|
||||||
|
for _, value := range strings.Split(trusted, ",") {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(value); err == nil {
|
||||||
|
if prefix.Contains(addr) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if proxyIP, err := netip.ParseAddr(value); err == nil && proxyIP.Unmap() == addr.Unmap() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func trustedProxyCIDRs() (trusted string) {
|
||||||
|
trusted = "127.0.0.1/32,::1/128"
|
||||||
|
defer func() {
|
||||||
|
_ = recover()
|
||||||
|
}()
|
||||||
|
settingService := service.SettingService{}
|
||||||
|
if value, err := settingService.GetTrustedProxyCIDRs(); err == nil && strings.TrimSpace(value) != "" {
|
||||||
|
trusted = value
|
||||||
|
}
|
||||||
|
return trusted
|
||||||
}
|
}
|
||||||
|
|
||||||
func extractTrustedIP(value string) (string, bool) {
|
func extractTrustedIP(value string) (string, bool) {
|
||||||
|
|||||||
34
web/controller/util_test.go
Normal file
34
web/controller/util_test.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetRemoteIpIgnoresForwardedHeadersFromUntrustedRemote(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
c.Request.RemoteAddr = "203.0.113.10:12345"
|
||||||
|
c.Request.Header.Set("X-Real-IP", "198.51.100.9")
|
||||||
|
c.Request.Header.Set("X-Forwarded-For", "198.51.100.8")
|
||||||
|
|
||||||
|
if got := getRemoteIp(c); got != "203.0.113.10" {
|
||||||
|
t.Fatalf("remote IP = %q, want request remote address", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetRemoteIpHonorsForwardedHeadersFromTrustedLoopbackProxy(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
c.Request.RemoteAddr = "127.0.0.1:12345"
|
||||||
|
c.Request.Header.Set("X-Forwarded-For", "198.51.100.8, 127.0.0.1")
|
||||||
|
|
||||||
|
if got := getRemoteIp(c); got != "198.51.100.8" {
|
||||||
|
t.Fatalf("remote IP = %q, want forwarded client IP", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -213,6 +213,11 @@ func (a *XraySettingController) testOutbound(c *gin.Context) {
|
|||||||
|
|
||||||
// Load the test URL from server settings to prevent SSRF via user-controlled URLs
|
// Load the test URL from server settings to prevent SSRF via user-controlled URLs
|
||||||
testURL, _ := a.SettingService.GetXrayOutboundTestUrl()
|
testURL, _ := a.SettingService.GetXrayOutboundTestUrl()
|
||||||
|
testURL, err := service.SanitizePublicHTTPURL(testURL, false)
|
||||||
|
if err != nil {
|
||||||
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
result, err := a.OutboundService.TestOutbound(outboundJSON, testURL, allOutboundsJSON, mode)
|
result, err := a.OutboundService.TestOutbound(outboundJSON, testURL, allOutboundsJSON, mode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -21,13 +21,14 @@ type Msg struct {
|
|||||||
// AllSetting contains all configuration settings for the 3x-ui panel including web server, Telegram bot, and subscription settings.
|
// AllSetting contains all configuration settings for the 3x-ui panel including web server, Telegram bot, and subscription settings.
|
||||||
type AllSetting struct {
|
type AllSetting struct {
|
||||||
// Web server settings
|
// Web server settings
|
||||||
WebListen string `json:"webListen" form:"webListen"` // Web server listen IP address
|
WebListen string `json:"webListen" form:"webListen"` // Web server listen IP address
|
||||||
WebDomain string `json:"webDomain" form:"webDomain"` // Web server domain for domain validation
|
WebDomain string `json:"webDomain" form:"webDomain"` // Web server domain for domain validation
|
||||||
WebPort int `json:"webPort" form:"webPort"` // Web server port number
|
WebPort int `json:"webPort" form:"webPort"` // Web server port number
|
||||||
WebCertFile string `json:"webCertFile" form:"webCertFile"` // Path to SSL certificate file for web server
|
WebCertFile string `json:"webCertFile" form:"webCertFile"` // Path to SSL certificate file for web server
|
||||||
WebKeyFile string `json:"webKeyFile" form:"webKeyFile"` // Path to SSL private key file for web server
|
WebKeyFile string `json:"webKeyFile" form:"webKeyFile"` // Path to SSL private key file for web server
|
||||||
WebBasePath string `json:"webBasePath" form:"webBasePath"` // Base path for web panel URLs
|
WebBasePath string `json:"webBasePath" form:"webBasePath"` // Base path for web panel URLs
|
||||||
SessionMaxAge int `json:"sessionMaxAge" form:"sessionMaxAge"` // Session maximum age in minutes
|
SessionMaxAge int `json:"sessionMaxAge" form:"sessionMaxAge"` // Session maximum age in minutes
|
||||||
|
TrustedProxyCIDRs string `json:"trustedProxyCIDRs" form:"trustedProxyCIDRs"` // Trusted reverse proxy IPs/CIDRs for forwarded headers
|
||||||
|
|
||||||
// UI settings
|
// UI settings
|
||||||
PageSize int `json:"pageSize" form:"pageSize"` // Number of items per page in lists
|
PageSize int `json:"pageSize" form:"pageSize"` // Number of items per page in lists
|
||||||
@@ -110,6 +111,20 @@ type AllSetting struct {
|
|||||||
// JSON subscription routing rules
|
// JSON subscription routing rules
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AllSettingView is the browser-safe settings read model. Secret values
|
||||||
|
// are redacted from the embedded write model and represented by presence
|
||||||
|
// flags so the UI can show configured/not configured state.
|
||||||
|
type AllSettingView struct {
|
||||||
|
AllSetting
|
||||||
|
|
||||||
|
HasTgBotToken bool `json:"hasTgBotToken"`
|
||||||
|
HasTwoFactorToken bool `json:"hasTwoFactorToken"`
|
||||||
|
HasLdapPassword bool `json:"hasLdapPassword"`
|
||||||
|
HasApiToken bool `json:"hasApiToken"`
|
||||||
|
HasWarpSecret bool `json:"hasWarpSecret"`
|
||||||
|
HasNordSecret bool `json:"hasNordSecret"`
|
||||||
|
}
|
||||||
|
|
||||||
// CheckValid validates all settings in the AllSetting struct, checking IP addresses, ports, SSL certificates, and other configuration values.
|
// CheckValid validates all settings in the AllSetting struct, checking IP addresses, ports, SSL certificates, and other configuration values.
|
||||||
func (s *AllSetting) CheckValid() error {
|
func (s *AllSetting) CheckValid() error {
|
||||||
if s.WebListen != "" {
|
if s.WebListen != "" {
|
||||||
@@ -179,6 +194,19 @@ func (s *AllSetting) CheckValid() error {
|
|||||||
s.SubClashPath += "/"
|
s.SubClashPath += "/"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, cidr := range strings.Split(s.TrustedProxyCIDRs, ",") {
|
||||||
|
cidr = strings.TrimSpace(cidr)
|
||||||
|
if cidr == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ip := net.ParseIP(cidr); ip != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, _, err := net.ParseCIDR(cidr); err != nil {
|
||||||
|
return common.NewError("trusted proxy CIDR is not valid:", cidr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
_, err := time.LoadLocation(s.TimeLocation)
|
_, err := time.LoadLocation(s.TimeLocation)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return common.NewError("time location not exist:", s.TimeLocation)
|
return common.NewError("time location not exist:", s.TimeLocation)
|
||||||
|
|||||||
@@ -152,6 +152,11 @@ func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traf
|
|||||||
logger.Warning("get ExternalTrafficInformURI failed:", err)
|
logger.Warning("get ExternalTrafficInformURI failed:", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
informURL, err = service.SanitizePublicHTTPURL(informURL, false)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warning("ExternalTrafficInformURI blocked:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
|
requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warning("parse client/inbound traffic failed:", err)
|
logger.Warning("parse client/inbound traffic failed:", err)
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/mhsanaei/3x-ui/v3/web/session"
|
"github.com/mhsanaei/3x-ui/v3/web/session"
|
||||||
@@ -11,10 +13,12 @@ import (
|
|||||||
// SecurityHeadersMiddleware adds browser hardening headers to panel responses.
|
// SecurityHeadersMiddleware adds browser hardening headers to panel responses.
|
||||||
func SecurityHeadersMiddleware(directHTTPS bool) gin.HandlerFunc {
|
func SecurityHeadersMiddleware(directHTTPS bool) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
|
nonce := newCSPNonce()
|
||||||
|
c.Set("csp_nonce", nonce)
|
||||||
c.Header("X-Content-Type-Options", "nosniff")
|
c.Header("X-Content-Type-Options", "nosniff")
|
||||||
c.Header("X-Frame-Options", "DENY")
|
c.Header("X-Frame-Options", "DENY")
|
||||||
c.Header("Referrer-Policy", "no-referrer")
|
c.Header("Referrer-Policy", "no-referrer")
|
||||||
c.Header("Content-Security-Policy", "frame-ancestors 'none'; base-uri 'self'; form-action 'self'")
|
c.Header("Content-Security-Policy", "default-src 'self'; script-src 'self' 'nonce-"+nonce+"'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws: wss:; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'")
|
||||||
if directHTTPS {
|
if directHTTPS {
|
||||||
c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
||||||
}
|
}
|
||||||
@@ -22,6 +26,14 @@ func SecurityHeadersMiddleware(directHTTPS bool) gin.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newCSPNonce() string {
|
||||||
|
var b [16]byte
|
||||||
|
if _, err := rand.Read(b[:]); err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return base64.RawStdEncoding.EncodeToString(b[:])
|
||||||
|
}
|
||||||
|
|
||||||
// CSRFMiddleware rejects unsafe requests that do not include the session CSRF token.
|
// CSRFMiddleware rejects unsafe requests that do not include the session CSRF token.
|
||||||
// Bearer-token-authenticated callers (api_authed flag set by APIController.checkAPIAuth)
|
// Bearer-token-authenticated callers (api_authed flag set by APIController.checkAPIAuth)
|
||||||
// short-circuit the CSRF check — they are not browser sessions, so the
|
// short-circuit the CSRF check — they are not browser sessions, so the
|
||||||
|
|||||||
@@ -105,14 +105,15 @@ func (s *NodeService) Update(id int, in *model.Node) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
updates := map[string]any{
|
updates := map[string]any{
|
||||||
"name": in.Name,
|
"name": in.Name,
|
||||||
"remark": in.Remark,
|
"remark": in.Remark,
|
||||||
"scheme": in.Scheme,
|
"scheme": in.Scheme,
|
||||||
"address": in.Address,
|
"address": in.Address,
|
||||||
"port": in.Port,
|
"port": in.Port,
|
||||||
"base_path": in.BasePath,
|
"base_path": in.BasePath,
|
||||||
"api_token": in.ApiToken,
|
"api_token": in.ApiToken,
|
||||||
"enable": in.Enable,
|
"enable": in.Enable,
|
||||||
|
"allow_private_address": in.AllowPrivateAddress,
|
||||||
}
|
}
|
||||||
if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
|
if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package service
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
@@ -28,6 +29,11 @@ type PanelUpdateInfo struct {
|
|||||||
UpdateAvailable bool `json:"updateAvailable"`
|
UpdateAvailable bool `json:"updateAvailable"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
panelUpdaterURL = "https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh"
|
||||||
|
maxPanelUpdaterBytes = 2 << 20
|
||||||
|
)
|
||||||
|
|
||||||
func (s *PanelService) RestartPanel(delay time.Duration) error {
|
func (s *PanelService) RestartPanel(delay time.Duration) error {
|
||||||
p, err := os.FindProcess(syscall.Getpid())
|
p, err := os.FindProcess(syscall.Getpid())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -67,13 +73,14 @@ func (s *PanelService) StartUpdate() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("bash is required to run the panel updater: %w", err)
|
return fmt.Errorf("bash is required to run the panel updater: %w", err)
|
||||||
}
|
}
|
||||||
curl, err := exec.LookPath("curl")
|
|
||||||
|
scriptPath, err := downloadPanelUpdater()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("curl is required to download the panel updater: %w", err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
mainFolder, serviceFolder := resolveUpdateFolders()
|
mainFolder, serviceFolder := resolveUpdateFolders()
|
||||||
updateScript := fmt.Sprintf("set -o pipefail; %s -fLs https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh | %s", shellQuote(curl), shellQuote(bash))
|
updateScript := fmt.Sprintf("set -e; trap 'rm -f %s' EXIT; %s %s", shellQuote(scriptPath), shellQuote(bash), shellQuote(scriptPath))
|
||||||
|
|
||||||
if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
|
if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
|
||||||
unitName := fmt.Sprintf("x-ui-web-update-%d", time.Now().Unix())
|
unitName := fmt.Sprintf("x-ui-web-update-%d", time.Now().Unix())
|
||||||
@@ -88,6 +95,7 @@ func (s *PanelService) StartUpdate() error {
|
|||||||
output := strings.TrimSpace(string(out))
|
output := strings.TrimSpace(string(out))
|
||||||
if !strings.Contains(output, "System has not been booted with systemd") &&
|
if !strings.Contains(output, "System has not been booted with systemd") &&
|
||||||
!strings.Contains(output, "Failed to connect to bus") {
|
!strings.Contains(output, "Failed to connect to bus") {
|
||||||
|
_ = os.Remove(scriptPath)
|
||||||
return fmt.Errorf("failed to start panel update job: %w: %s", err, output)
|
return fmt.Errorf("failed to start panel update job: %w: %s", err, output)
|
||||||
}
|
}
|
||||||
logger.Warning("systemd-run is unavailable, falling back to detached update process:", output)
|
logger.Warning("systemd-run is unavailable, falling back to detached update process:", output)
|
||||||
@@ -104,6 +112,7 @@ func (s *PanelService) StartUpdate() error {
|
|||||||
)
|
)
|
||||||
setDetachedProcess(cmd)
|
setDetachedProcess(cmd)
|
||||||
if err := cmd.Start(); err != nil {
|
if err := cmd.Start(); err != nil {
|
||||||
|
_ = os.Remove(scriptPath)
|
||||||
return fmt.Errorf("failed to start panel update job: %w", err)
|
return fmt.Errorf("failed to start panel update job: %w", err)
|
||||||
}
|
}
|
||||||
if err := cmd.Process.Release(); err != nil {
|
if err := cmd.Process.Release(); err != nil {
|
||||||
@@ -113,6 +122,44 @@ func (s *PanelService) StartUpdate() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func downloadPanelUpdater() (string, error) {
|
||||||
|
client := &http.Client{Timeout: 15 * time.Second}
|
||||||
|
resp, err := client.Get(panelUpdaterURL)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("download panel updater: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return "", fmt.Errorf("download panel updater: unexpected HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.CreateTemp("", "3x-ui-update-*.sh")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
path := file.Name()
|
||||||
|
ok := false
|
||||||
|
defer func() {
|
||||||
|
_ = file.Close()
|
||||||
|
if !ok {
|
||||||
|
_ = os.Remove(path)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
n, err := io.Copy(file, io.LimitReader(resp.Body, maxPanelUpdaterBytes+1))
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("write panel updater: %w", err)
|
||||||
|
}
|
||||||
|
if n > maxPanelUpdaterBytes {
|
||||||
|
return "", fmt.Errorf("panel updater exceeds %d bytes", maxPanelUpdaterBytes)
|
||||||
|
}
|
||||||
|
if err := file.Chmod(0700); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
ok = true
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
|
||||||
func fetchLatestPanelVersion() (string, error) {
|
func fetchLatestPanelVersion() (string, error) {
|
||||||
client := &http.Client{Timeout: 10 * time.Second}
|
client := &http.Client{Timeout: 10 * time.Second}
|
||||||
resp, err := client.Get("https://api.github.com/repos/MHSanaei/3x-ui/releases/latest")
|
resp, err := client.Get("https://api.github.com/repos/MHSanaei/3x-ui/releases/latest")
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -493,6 +494,11 @@ func (s *ServerService) sampleCPUUtilization() (float64, error) {
|
|||||||
|
|
||||||
var xrayVersionsClient = &http.Client{Timeout: 10 * time.Second}
|
var xrayVersionsClient = &http.Client{Timeout: 10 * time.Second}
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxXrayArchiveBytes = 200 << 20
|
||||||
|
maxXrayBinaryBytes = 200 << 20
|
||||||
|
)
|
||||||
|
|
||||||
func (s *ServerService) GetXrayVersions() ([]string, error) {
|
func (s *ServerService) GetXrayVersions() ([]string, error) {
|
||||||
const (
|
const (
|
||||||
XrayURL = "https://api.github.com/repos/XTLS/Xray-core/releases"
|
XrayURL = "https://api.github.com/repos/XTLS/Xray-core/releases"
|
||||||
@@ -601,28 +607,53 @@ func (s *ServerService) downloadXRay(version string) (string, error) {
|
|||||||
|
|
||||||
fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
|
fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
|
||||||
url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
|
url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
|
||||||
resp, err := http.Get(url)
|
client := &http.Client{Timeout: 60 * time.Second}
|
||||||
|
resp, err := client.Get(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return "", fmt.Errorf("download xray: unexpected HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if resp.ContentLength > maxXrayArchiveBytes {
|
||||||
|
return "", fmt.Errorf("download xray: archive exceeds %d bytes", maxXrayArchiveBytes)
|
||||||
|
}
|
||||||
|
|
||||||
os.Remove(fileName)
|
file, err := os.CreateTemp("", "xray-*.zip")
|
||||||
file, err := os.Create(fileName)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
defer file.Close()
|
path := file.Name()
|
||||||
|
ok := false
|
||||||
|
defer func() {
|
||||||
|
_ = file.Close()
|
||||||
|
if !ok {
|
||||||
|
_ = os.Remove(path)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
_, err = io.Copy(file, resp.Body)
|
n, err := io.Copy(file, io.LimitReader(resp.Body, maxXrayArchiveBytes+1))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
if n > maxXrayArchiveBytes {
|
||||||
|
return "", fmt.Errorf("download xray: archive exceeds %d bytes", maxXrayArchiveBytes)
|
||||||
|
}
|
||||||
|
|
||||||
return fileName, nil
|
ok = true
|
||||||
|
return path, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *ServerService) UpdateXray(version string) error {
|
func (s *ServerService) UpdateXray(version string) error {
|
||||||
|
versions, err := s.GetXrayVersions()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !slices.Contains(versions, version) {
|
||||||
|
return fmt.Errorf("xray version %q is not in the fetched release list", version)
|
||||||
|
}
|
||||||
|
|
||||||
// 1. Stop xray before doing anything
|
// 1. Stop xray before doing anything
|
||||||
if err := s.StopXrayService(); err != nil {
|
if err := s.StopXrayService(); err != nil {
|
||||||
logger.Warning("failed to stop xray before update:", err)
|
logger.Warning("failed to stop xray before update:", err)
|
||||||
@@ -657,15 +688,42 @@ func (s *ServerService) UpdateXray(version string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer zipFile.Close()
|
defer zipFile.Close()
|
||||||
os.MkdirAll(filepath.Dir(fileName), 0755)
|
if err := os.MkdirAll(filepath.Dir(fileName), 0755); err != nil {
|
||||||
os.Remove(fileName)
|
return err
|
||||||
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0755)
|
}
|
||||||
|
tmpFile, err := os.CreateTemp(filepath.Dir(fileName), ".xray-*")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer file.Close()
|
tmpPath := tmpFile.Name()
|
||||||
_, err = io.Copy(file, zipFile)
|
ok := false
|
||||||
return err
|
defer func() {
|
||||||
|
_ = tmpFile.Close()
|
||||||
|
if !ok {
|
||||||
|
_ = os.Remove(tmpPath)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
n, err := io.Copy(tmpFile, io.LimitReader(zipFile, maxXrayBinaryBytes+1))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n > maxXrayBinaryBytes {
|
||||||
|
return fmt.Errorf("xray binary exceeds %d bytes", maxXrayBinaryBytes)
|
||||||
|
}
|
||||||
|
if err := tmpFile.Chmod(0755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tmpFile.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
_ = os.Remove(fileName)
|
||||||
|
}
|
||||||
|
if err := os.Rename(tmpPath, fileName); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ok = true
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Extract correct binary
|
// 4. Extract correct binary
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ var defaultValueMap = map[string]string{
|
|||||||
"apiToken": "",
|
"apiToken": "",
|
||||||
"webBasePath": "/",
|
"webBasePath": "/",
|
||||||
"sessionMaxAge": "360",
|
"sessionMaxAge": "360",
|
||||||
|
"trustedProxyCIDRs": "127.0.0.1/32,::1/128",
|
||||||
"pageSize": "25",
|
"pageSize": "25",
|
||||||
"expireDiff": "0",
|
"expireDiff": "0",
|
||||||
"trafficDiff": "0",
|
"trafficDiff": "0",
|
||||||
@@ -199,6 +200,32 @@ func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
|
|||||||
return allSetting, nil
|
return allSetting, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *SettingService) GetAllSettingView() (*entity.AllSettingView, error) {
|
||||||
|
allSetting, err := s.GetAllSetting()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
view := &entity.AllSettingView{AllSetting: *allSetting}
|
||||||
|
view.HasTgBotToken = secretConfigured(allSetting.TgBotToken)
|
||||||
|
view.HasTwoFactorToken = secretConfigured(allSetting.TwoFactorToken)
|
||||||
|
view.HasLdapPassword = secretConfigured(allSetting.LdapPassword)
|
||||||
|
view.HasWarpSecret = secretConfigured(mustString(s.GetWarp()))
|
||||||
|
view.HasNordSecret = secretConfigured(mustString(s.GetNord()))
|
||||||
|
view.HasApiToken = secretConfigured(mustString(s.getString("apiToken")))
|
||||||
|
view.TgBotToken = ""
|
||||||
|
view.TwoFactorToken = ""
|
||||||
|
view.LdapPassword = ""
|
||||||
|
return view, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func secretConfigured(value string) bool {
|
||||||
|
return strings.TrimSpace(value) != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustString(value string, _ error) string {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
func (s *SettingService) ResetSettings() error {
|
func (s *SettingService) ResetSettings() error {
|
||||||
db := database.GetDB()
|
db := database.GetDB()
|
||||||
err := db.Where("1 = 1").Delete(model.Setting{}).Error
|
err := db.Where("1 = 1").Delete(model.Setting{}).Error
|
||||||
@@ -286,7 +313,11 @@ func (s *SettingService) GetXrayOutboundTestUrl() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *SettingService) SetXrayOutboundTestUrl(url string) error {
|
func (s *SettingService) SetXrayOutboundTestUrl(url string) error {
|
||||||
return s.setString("xrayOutboundTestUrl", url)
|
clean, err := SanitizeHTTPURL(url)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.setString("xrayOutboundTestUrl", clean)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SettingService) GetListen() (string, error) {
|
func (s *SettingService) GetListen() (string, error) {
|
||||||
@@ -417,6 +448,10 @@ func (s *SettingService) GetSessionMaxAge() (int, error) {
|
|||||||
return s.getInt("sessionMaxAge")
|
return s.getInt("sessionMaxAge")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *SettingService) GetTrustedProxyCIDRs() (string, error) {
|
||||||
|
return s.getString("trustedProxyCIDRs")
|
||||||
|
}
|
||||||
|
|
||||||
func (s *SettingService) GetRemarkModel() (string, error) {
|
func (s *SettingService) GetRemarkModel() (string, error) {
|
||||||
return s.getString("remarkModel")
|
return s.getString("remarkModel")
|
||||||
}
|
}
|
||||||
@@ -771,6 +806,12 @@ func (s *SettingService) GetLdapDefaultLimitIP() (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
|
func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
|
||||||
|
if err := s.preserveRedactedSecrets(allSetting); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := validateSettingsURLs(allSetting); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := allSetting.CheckValid(); err != nil {
|
if err := allSetting.CheckValid(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -791,6 +832,58 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
|
|||||||
return common.Combine(errs...)
|
return common.Combine(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *SettingService) preserveRedactedSecrets(allSetting *entity.AllSetting) error {
|
||||||
|
if strings.TrimSpace(allSetting.TgBotToken) == "" {
|
||||||
|
value, err := s.GetTgBotToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
allSetting.TgBotToken = value
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(allSetting.LdapPassword) == "" {
|
||||||
|
value, err := s.GetLdapPassword()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
allSetting.LdapPassword = value
|
||||||
|
}
|
||||||
|
if allSetting.TwoFactorEnable && strings.TrimSpace(allSetting.TwoFactorToken) == "" {
|
||||||
|
value, err := s.GetTwoFactorToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
allSetting.TwoFactorToken = value
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateSettingsURLs(allSetting *entity.AllSetting) error {
|
||||||
|
if allSetting.ExternalTrafficInformURI != "" {
|
||||||
|
u, err := SanitizeHTTPURL(allSetting.ExternalTrafficInformURI)
|
||||||
|
if err != nil {
|
||||||
|
return common.NewError("external traffic inform URI is invalid:", err)
|
||||||
|
}
|
||||||
|
allSetting.ExternalTrafficInformURI = u
|
||||||
|
}
|
||||||
|
if allSetting.TgBotAPIServer != "" {
|
||||||
|
u, err := SanitizeHTTPURL(allSetting.TgBotAPIServer)
|
||||||
|
if err != nil {
|
||||||
|
return common.NewError("telegram API server URL is invalid:", err)
|
||||||
|
}
|
||||||
|
allSetting.TgBotAPIServer = u
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SettingService) UpdateSecret(key string, value string) error {
|
||||||
|
switch key {
|
||||||
|
case "tgBotToken", "ldapPassword", "twoFactorToken", "apiToken":
|
||||||
|
return s.saveSetting(key, strings.TrimSpace(value))
|
||||||
|
default:
|
||||||
|
return common.NewError("secret key is not replaceable:", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (s *SettingService) GetDefaultXrayConfig() (any, error) {
|
func (s *SettingService) GetDefaultXrayConfig() (any, error) {
|
||||||
var jsonData any
|
var jsonData any
|
||||||
err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
|
err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
|
||||||
|
|||||||
92
web/service/setting_security_test.go
Normal file
92
web/service/setting_security_test.go
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
func setupSettingTestDB(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := database.CloseDB(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetAllSettingViewRedactsSecrets(t *testing.T) {
|
||||||
|
setupSettingTestDB(t)
|
||||||
|
s := &SettingService{}
|
||||||
|
if err := s.saveSetting("tgBotToken", "telegram-secret"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.saveSetting("twoFactorToken", "totp-secret"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.saveSetting("ldapPassword", "ldap-secret"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.saveSetting("apiToken", "api-secret"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
view, err := s.GetAllSettingView()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if view.TgBotToken != "" || view.TwoFactorToken != "" || view.LdapPassword != "" {
|
||||||
|
t.Fatalf("settings view leaked secrets: %#v", view)
|
||||||
|
}
|
||||||
|
if !view.HasTgBotToken || !view.HasTwoFactorToken || !view.HasLdapPassword || !view.HasApiToken {
|
||||||
|
t.Fatalf("settings view did not report configured secret flags: %#v", view)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateAllSettingPreservesRedactedSecrets(t *testing.T) {
|
||||||
|
setupSettingTestDB(t)
|
||||||
|
s := &SettingService{}
|
||||||
|
if err := s.saveSetting("tgBotToken", "telegram-secret"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.saveSetting("ldapPassword", "ldap-secret"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.saveSetting("twoFactorEnable", "true"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.saveSetting("twoFactorToken", "totp-secret"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
view, err := s.GetAllSettingView()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
settings := &view.AllSetting
|
||||||
|
if err := s.UpdateAllSetting(settings); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got, _ := s.GetTgBotToken(); got != "telegram-secret" {
|
||||||
|
t.Fatalf("tg token = %q, want preserved secret", got)
|
||||||
|
}
|
||||||
|
if got, _ := s.GetLdapPassword(); got != "ldap-secret" {
|
||||||
|
t.Fatalf("ldap password = %q, want preserved secret", got)
|
||||||
|
}
|
||||||
|
if got, _ := s.GetTwoFactorToken(); got != "totp-secret" {
|
||||||
|
t.Fatalf("2fa token = %q, want preserved secret", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSanitizePublicHTTPURLBlocksPrivateAddressUnlessAllowed(t *testing.T) {
|
||||||
|
if _, err := SanitizePublicHTTPURL("http://127.0.0.1:8080/hook", false); err == nil {
|
||||||
|
t.Fatal("expected localhost URL to be blocked")
|
||||||
|
}
|
||||||
|
if got, err := SanitizePublicHTTPURL("http://127.0.0.1:8080/hook", true); err != nil || got != "http://127.0.0.1:8080/hook" {
|
||||||
|
t.Fatalf("allowPrivate result = %q, %v", got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -341,15 +341,12 @@ func (t *Tgbot) NewBot(token string, proxyUrl string, apiServerUrl string) (*tel
|
|||||||
|
|
||||||
// Validate API server URL if provided
|
// Validate API server URL if provided
|
||||||
if apiServerUrl != "" {
|
if apiServerUrl != "" {
|
||||||
if !strings.HasPrefix(apiServerUrl, "http") {
|
safeURL, err := SanitizePublicHTTPURL(apiServerUrl, false)
|
||||||
logger.Warning("Invalid http(s) URL for API server, using default")
|
if err != nil {
|
||||||
|
logger.Warningf("Invalid or blocked API server URL, using default: %v", err)
|
||||||
apiServerUrl = ""
|
apiServerUrl = ""
|
||||||
} else {
|
} else {
|
||||||
_, err := url.Parse(apiServerUrl)
|
apiServerUrl = safeURL
|
||||||
if err != nil {
|
|
||||||
logger.Warningf("Can't parse API server URL, using default: %v", err)
|
|
||||||
apiServerUrl = ""
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
82
web/service/url_safety.go
Normal file
82
web/service/url_safety.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SanitizeHTTPURL validates and normalizes an http(s) URL without resolving
|
||||||
|
// DNS. Use SanitizePublicHTTPURL at the point of an outbound request.
|
||||||
|
func SanitizeHTTPURL(raw string) (string, error) {
|
||||||
|
raw = strings.TrimSpace(raw)
|
||||||
|
if raw == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if u.Scheme != "http" && u.Scheme != "https" {
|
||||||
|
return "", fmt.Errorf("unsupported URL scheme %q", u.Scheme)
|
||||||
|
}
|
||||||
|
if u.Host == "" || u.Hostname() == "" {
|
||||||
|
return "", fmt.Errorf("URL host is required")
|
||||||
|
}
|
||||||
|
clean := &url.URL{
|
||||||
|
Scheme: u.Scheme,
|
||||||
|
Host: u.Host,
|
||||||
|
Path: u.Path,
|
||||||
|
RawPath: u.RawPath,
|
||||||
|
RawQuery: u.RawQuery,
|
||||||
|
Fragment: u.Fragment,
|
||||||
|
}
|
||||||
|
return clean.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SanitizePublicHTTPURL validates and normalizes an http(s) URL, then blocks
|
||||||
|
// private/internal targets unless the caller explicitly allows them.
|
||||||
|
func SanitizePublicHTTPURL(raw string, allowPrivate bool) (string, error) {
|
||||||
|
clean, err := SanitizeHTTPURL(raw)
|
||||||
|
if err != nil || clean == "" {
|
||||||
|
return clean, err
|
||||||
|
}
|
||||||
|
if allowPrivate {
|
||||||
|
return clean, nil
|
||||||
|
}
|
||||||
|
u, err := url.Parse(clean)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := rejectPrivateHost(ctx, u.Hostname()); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return clean, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func rejectPrivateHost(ctx context.Context, hostname string) error {
|
||||||
|
if ip := net.ParseIP(hostname); ip != nil {
|
||||||
|
if isBlockedIP(ip) {
|
||||||
|
return fmt.Errorf("blocked private/internal address %s", ip.String())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ips, err := net.DefaultResolver.LookupIPAddr(ctx, hostname)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot resolve host %s: %w", hostname, err)
|
||||||
|
}
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return fmt.Errorf("host %s has no IP addresses", hostname)
|
||||||
|
}
|
||||||
|
for _, ipAddr := range ips {
|
||||||
|
if isBlockedIP(ipAddr.IP) {
|
||||||
|
return fmt.Errorf("host %s resolves to blocked private/internal address %s", hostname, ipAddr.IP.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -122,7 +122,11 @@ func (s *UserService) UpdateUser(id int, username string, password string) error
|
|||||||
|
|
||||||
return db.Model(model.User{}).
|
return db.Model(model.User{}).
|
||||||
Where("id = ?", id).
|
Where("id = ?", id).
|
||||||
Updates(map[string]any{"username": username, "password": hashedPassword}).
|
Updates(map[string]any{
|
||||||
|
"username": username,
|
||||||
|
"password": hashedPassword,
|
||||||
|
"login_epoch": gorm.Expr("login_epoch + 1"),
|
||||||
|
}).
|
||||||
Error
|
Error
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,5 +154,6 @@ func (s *UserService) UpdateFirstUser(username string, password string) error {
|
|||||||
}
|
}
|
||||||
user.Username = username
|
user.Username = username
|
||||||
user.Password = hashedPassword
|
user.Password = hashedPassword
|
||||||
|
user.LoginEpoch++
|
||||||
return db.Save(user).Error
|
return db.Save(user).Error
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,10 +32,10 @@ type ObsTagSnapshot struct {
|
|||||||
type XrayMetricsService struct {
|
type XrayMetricsService struct {
|
||||||
settingService SettingService
|
settingService SettingService
|
||||||
|
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
state xrayMetricsState
|
state xrayMetricsState
|
||||||
client *http.Client
|
client *http.Client
|
||||||
obsByTag map[string]ObsTagSnapshot
|
obsByTag map[string]ObsTagSnapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
var validObsTag = regexp.MustCompile(`^[a-zA-Z0-9._\-]+$`)
|
var validObsTag = regexp.MustCompile(`^[a-zA-Z0-9._\-]+$`)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/database"
|
||||||
"github.com/mhsanaei/3x-ui/v3/database/model"
|
"github.com/mhsanaei/3x-ui/v3/database/model"
|
||||||
"github.com/mhsanaei/3x-ui/v3/logger"
|
"github.com/mhsanaei/3x-ui/v3/logger"
|
||||||
|
|
||||||
@@ -14,6 +15,7 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
loginUserKey = "LOGIN_USER"
|
loginUserKey = "LOGIN_USER"
|
||||||
|
loginEpochKey = "LOGIN_EPOCH"
|
||||||
apiAuthUserKey = "api_auth_user"
|
apiAuthUserKey = "api_auth_user"
|
||||||
sessionCookieName = "3x-ui"
|
sessionCookieName = "3x-ui"
|
||||||
)
|
)
|
||||||
@@ -27,7 +29,8 @@ func SetLoginUser(c *gin.Context, user *model.User) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
s := sessions.Default(c)
|
s := sessions.Default(c)
|
||||||
s.Set(loginUserKey, *user)
|
s.Set(loginUserKey, user.Id)
|
||||||
|
s.Set(loginEpochKey, user.LoginEpoch)
|
||||||
return s.Save()
|
return s.Save()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,21 +52,113 @@ func GetLoginUser(c *gin.Context) *model.User {
|
|||||||
if obj == nil {
|
if obj == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
user, ok := obj.(model.User)
|
userID, ok := sessionUserID(obj)
|
||||||
if !ok {
|
if !ok {
|
||||||
s.Delete(loginUserKey)
|
s.Delete(loginUserKey)
|
||||||
|
s.Delete(loginEpochKey)
|
||||||
if err := s.Save(); err != nil {
|
if err := s.Save(); err != nil {
|
||||||
logger.Warning("session: failed to drop stale user payload:", err)
|
logger.Warning("session: failed to drop stale user payload:", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return &user
|
if legacyUserID, ok := legacySessionUserID(obj); ok {
|
||||||
|
s.Set(loginUserKey, legacyUserID)
|
||||||
|
if err := s.Save(); err != nil {
|
||||||
|
logger.Warning("session: failed to migrate legacy user payload:", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
user, err := getUserByID(userID)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warning("session: failed to load user:", err)
|
||||||
|
s.Delete(loginUserKey)
|
||||||
|
s.Delete(loginEpochKey)
|
||||||
|
if saveErr := s.Save(); saveErr != nil {
|
||||||
|
logger.Warning("session: failed to drop missing user:", saveErr)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !sessionEpochMatches(s.Get(loginEpochKey), user.LoginEpoch) {
|
||||||
|
s.Delete(loginUserKey)
|
||||||
|
s.Delete(loginEpochKey)
|
||||||
|
if saveErr := s.Save(); saveErr != nil {
|
||||||
|
logger.Warning("session: failed to drop stale epoch:", saveErr)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
func sessionEpochMatches(cookieVal any, userEpoch int64) bool {
|
||||||
|
var got int64
|
||||||
|
switch v := cookieVal.(type) {
|
||||||
|
case nil:
|
||||||
|
case int64:
|
||||||
|
got = v
|
||||||
|
case int:
|
||||||
|
got = int64(v)
|
||||||
|
case int32:
|
||||||
|
got = int64(v)
|
||||||
|
case float64:
|
||||||
|
got = int64(v)
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return got == userEpoch
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsLogin(c *gin.Context) bool {
|
func IsLogin(c *gin.Context) bool {
|
||||||
return GetLoginUser(c) != nil
|
return GetLoginUser(c) != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func sessionUserID(obj any) (int, bool) {
|
||||||
|
switch v := obj.(type) {
|
||||||
|
case int:
|
||||||
|
return v, v > 0
|
||||||
|
case int64:
|
||||||
|
return int(v), v > 0
|
||||||
|
case int32:
|
||||||
|
return int(v), v > 0
|
||||||
|
case float64:
|
||||||
|
id := int(v)
|
||||||
|
return id, v == float64(id) && id > 0
|
||||||
|
case model.User:
|
||||||
|
return v.Id, v.Id > 0
|
||||||
|
case *model.User:
|
||||||
|
if v == nil {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return v.Id, v.Id > 0
|
||||||
|
default:
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func legacySessionUserID(obj any) (int, bool) {
|
||||||
|
switch v := obj.(type) {
|
||||||
|
case model.User:
|
||||||
|
return v.Id, v.Id > 0
|
||||||
|
case *model.User:
|
||||||
|
if v == nil {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return v.Id, v.Id > 0
|
||||||
|
default:
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getUserByID(id int) (*model.User, error) {
|
||||||
|
db := database.GetDB()
|
||||||
|
if db == nil {
|
||||||
|
return nil, http.ErrServerClosed
|
||||||
|
}
|
||||||
|
user := &model.User{}
|
||||||
|
if err := db.Model(model.User{}).Where("id = ?", id).First(user).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
func ClearSession(c *gin.Context) error {
|
func ClearSession(c *gin.Context) error {
|
||||||
s := sessions.Default(c)
|
s := sessions.Default(c)
|
||||||
s.Clear()
|
s.Clear()
|
||||||
|
|||||||
47
web/session/session_test.go
Normal file
47
web/session/session_test.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package session
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mhsanaei/3x-ui/v3/database/model"
|
||||||
|
|
||||||
|
"github.com/gin-contrib/sessions"
|
||||||
|
"github.com/gin-contrib/sessions/cookie"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSetLoginUserStoresOnlyUserID(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
router := gin.New()
|
||||||
|
router.Use(sessions.Sessions(sessionCookieName, cookie.NewStore([]byte("01234567890123456789012345678901"))))
|
||||||
|
router.GET("/", func(c *gin.Context) {
|
||||||
|
if err := SetLoginUser(c, &model.User{Id: 7, Username: "admin", Password: "hash"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := sessions.Default(c).Get(loginUserKey)
|
||||||
|
if got != 7 {
|
||||||
|
t.Fatalf("stored session payload = %#v, want user id only", got)
|
||||||
|
}
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
})
|
||||||
|
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
router.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionUserIDSupportsLegacyUserPayload(t *testing.T) {
|
||||||
|
id, ok := sessionUserID(model.User{Id: 11, Username: "admin", Password: "hash"})
|
||||||
|
if !ok || id != 11 {
|
||||||
|
t.Fatalf("legacy session payload resolved to (%d, %v), want (11, true)", id, ok)
|
||||||
|
}
|
||||||
|
id, ok = sessionUserID(&model.User{Id: 12, Username: "admin", Password: "hash"})
|
||||||
|
if !ok || id != 12 {
|
||||||
|
t.Fatalf("legacy pointer session payload resolved to (%d, %v), want (12, true)", id, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -431,7 +431,11 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
|
|||||||
s.listener = listener
|
s.listener = listener
|
||||||
|
|
||||||
s.httpServer = &http.Server{
|
s.httpServer = &http.Server{
|
||||||
Handler: engine,
|
Handler: engine,
|
||||||
|
ReadHeaderTimeout: 5 * time.Second,
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 30 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
|
|||||||
Reference in New Issue
Block a user