mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-12-02 09:16:47 +00:00
feat: add age-secret-key for proxy-provider and -age-secret-key for cmdline to support age armor format config decryption
This commit is contained in:
1 parent
90b1066e1a
commit
358fa5eb24
9 files changed
+260
-2
No files matched your search
@@ -37,6 +37,7 @@ type proxyProviderSchema struct {
|
||||
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
||||
SizeLimit int64 `provider:"size-limit,omitempty"`
|
||||
Payload []map[string]any `provider:"payload,omitempty"`
|
||||
AgeSecretKey string `provider:"age-secret-key,omitempty"`
|
||||
|
||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||
Override overrideSchema `provider:"override,omitempty"`
|
||||
@@ -69,7 +70,7 @@ func ParseProxyProvider(name string, mapping map[string]any, tunnel C.Tunnel) (P
|
||||
}
|
||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, uint(schema.HealthCheck.TestTimeout), hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
||||
|
||||
parser, err := NewProxiesParser(name, tunnel, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override)
|
||||
parser, err := NewProxiesParser(name, tunnel, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override, schema.AgeSecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/convert"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/common/yaml"
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||
"github.com/metacubex/mihomo/component/resource"
|
||||
C "github.com/metacubex/mihomo/constant"
|
||||
@@ -339,7 +340,7 @@ func (cp *CompatibleProvider) Close() error {
|
||||
return cp.compatibleProvider.Close()
|
||||
}
|
||||
|
||||
func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema) (resource.Parser[[]C.Proxy], error) {
|
||||
func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema, ageSecretKey string) (resource.Parser[[]C.Proxy], error) {
|
||||
var excludeTypeArray []string
|
||||
if excludeType != "" {
|
||||
excludeTypeArray = strings.Split(excludeType, "|")
|
||||
@@ -365,9 +366,24 @@ func NewProxiesParser(pdName string, tunnel C.Tunnel, filter string, excludeFilt
|
||||
filterRegs = append(filterRegs, filterReg)
|
||||
}
|
||||
|
||||
var identities []age.Identity
|
||||
if ageSecretKey != "" {
|
||||
var err error
|
||||
identities, err = age.ParseIdentities(ageSecretKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse age-secret-key error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return func(buf []byte) ([]C.Proxy, error) {
|
||||
schema := &ProxySchema{}
|
||||
|
||||
// decrypt config
|
||||
buf, err := age.DecryptBytes(buf, identities...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt config error: %w", err)
|
||||
}
|
||||
|
||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||
proxies, err1 := convert.ConvertsV2Ray(buf)
|
||||
if err1 != nil {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package age
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/metacubex/age"
|
||||
"github.com/metacubex/age/armor"
|
||||
)
|
||||
|
||||
const FileHeader = armor.Header
|
||||
|
||||
type Identity = age.Identity
|
||||
type Recipient = age.Recipient
|
||||
|
||||
var globalIdentities []Identity
|
||||
|
||||
func ParseIdentities(secretKey string) ([]Identity, error) {
|
||||
return age.ParseIdentities(strings.NewReader(secretKey))
|
||||
}
|
||||
|
||||
func ParseRecipients(publicKey string) ([]Recipient, error) {
|
||||
return age.ParseRecipients(strings.NewReader(publicKey))
|
||||
}
|
||||
|
||||
func SetGlobalIdentities(id []Identity) {
|
||||
globalIdentities = append(globalIdentities[:0], id...)
|
||||
}
|
||||
|
||||
// DecryptBytes decrypt age encrypted data
|
||||
// if not age encrypted, return original data
|
||||
func DecryptBytes(data []byte, identities ...Identity) ([]byte, error) {
|
||||
if !strings.HasPrefix(string(data), FileHeader) { // not age encrypted
|
||||
return data, nil
|
||||
}
|
||||
identities = append(identities[:len(identities):len(identities)], globalIdentities...)
|
||||
r, err := age.Decrypt(armor.NewReader(bytes.NewReader(data)), identities...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return io.ReadAll(r)
|
||||
}
|
||||
|
||||
// EncryptBytes encrypt data with age armor format
|
||||
func EncryptBytes(data []byte, recipients ...Recipient) ([]byte, error) {
|
||||
buf := &bytes.Buffer{}
|
||||
armorWriter := armor.NewWriter(buf)
|
||||
w, err := age.Encrypt(armorWriter, recipients...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = w.Write(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = w.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = armorWriter.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func GenX25519KeyPair() (string, string, error) {
|
||||
identity, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return identity.String(), identity.Recipient().String(), nil
|
||||
}
|
||||
|
||||
func GenHybridKeyPair() (string, string, error) {
|
||||
identity, err := age.GenerateHybridIdentity()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return identity.String(), identity.Recipient().String(), nil
|
||||
}
|
||||
|
||||
func Main(args []string) {
|
||||
if len(args) < 1 {
|
||||
panic("Using: age keygen/keygen-pq/decrypt/encrypt")
|
||||
}
|
||||
switch args[0] {
|
||||
case "keygen":
|
||||
secretKey, publicKey, err := GenX25519KeyPair()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("# created: %s\n", time.Now().Format(time.RFC3339))
|
||||
fmt.Printf("# public key: %s\n", publicKey)
|
||||
fmt.Printf("%s\n", secretKey)
|
||||
case "keygen-pq":
|
||||
secretKey, publicKey, err := GenHybridKeyPair()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("# created: %s\n", time.Now().Format(time.RFC3339))
|
||||
fmt.Printf("# public key: %s\n", publicKey)
|
||||
fmt.Printf("%s\n", secretKey)
|
||||
case "decrypt":
|
||||
if len(args) < 3 {
|
||||
panic("Using: age decrypt <secret_key> <source_file> <target_file>")
|
||||
}
|
||||
identities, err := ParseIdentities(args[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
data, err := os.ReadFile(args[2])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
result, err := DecryptBytes(data, identities...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = os.WriteFile(args[3], result, 0644)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
case "encrypt":
|
||||
if len(args) < 3 {
|
||||
panic("Using: age encrypt <public_key> <source_file> <target_file>")
|
||||
}
|
||||
recipients, err := ParseRecipients(args[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
data, err := os.ReadFile(args[2])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
result, err := EncryptBytes(data, recipients...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = os.WriteFile(args[3], result, 0644)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package age_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
)
|
||||
|
||||
func TestAge(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
gen func() (string, string, error)
|
||||
}{
|
||||
{"X25519", age.GenX25519KeyPair},
|
||||
{"MLKEM768X25519", age.GenHybridKeyPair},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
secretKey, publicKey, err := tc.gen()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(secretKey, publicKey)
|
||||
identities, err := age.ParseIdentities(secretKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recipients, err := age.ParseRecipients(publicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rawData := []byte("hello world")
|
||||
encryptData, err := age.EncryptBytes(rawData, recipients...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(string(encryptData))
|
||||
decryptData, err := age.DecryptBytes(encryptData, identities...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(decryptData) != string(rawData) {
|
||||
t.Fatal("decrypt data is not equal to raw data")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/metacubex/mihomo/common/orderedmap"
|
||||
"github.com/metacubex/mihomo/common/utils"
|
||||
"github.com/metacubex/mihomo/common/yaml"
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
"github.com/metacubex/mihomo/component/auth"
|
||||
"github.com/metacubex/mihomo/component/cidr"
|
||||
"github.com/metacubex/mihomo/component/fakeip"
|
||||
@@ -594,6 +595,12 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||
// config with default value
|
||||
rawCfg := DefaultRawConfig()
|
||||
|
||||
// decrypt config
|
||||
buf, err := age.DecryptBytes(buf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt config error: %w", err)
|
||||
}
|
||||
|
||||
if err := yaml.Unmarshal(buf, rawCfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1469,6 +1469,21 @@ proxy-providers:
|
||||
path: ./provider1.yaml # 默认只允许存储在 mihomo 的 Home Dir,如果想存储到其他位置,请通过设置 SAFE_PATHS 环境变量指定额外的安全路径。该环境变量的语法同本操作系统的PATH环境变量解析规则(即Windows下以分号分割,其他系统下以冒号分割)
|
||||
proxy: DIRECT
|
||||
# size-limit: 10240 # 限制下载文件最大为10kb,默认为0即不限制文件大小
|
||||
# #
|
||||
# # 如果设置会age-secret-key尝试通过此secret解密age armor格式加密的配置文件
|
||||
# #
|
||||
# # 注意:
|
||||
# # 对于加密内容,目前仅支持 age-encryption.org/v1 的 official ASCII "armor" format
|
||||
# # 对于key格式,目前仅支持 age-encryption.org/v1 的 x25519 recipient type 和 The mlkem768-X25519 hybrid post-quantum recipient type
|
||||
# # 实用工具:
|
||||
# # 您可以通过 "mihomo age keygen" 生成符合要求的 x25519 key
|
||||
# # 您可以通过 "mihomo age keygen-pq" 生成符合要求的 mlkem768-X25519 key
|
||||
# # 您可以通过 "mihome age decrypt <secret_key> <source_file> <target_file>" 将已加密文件解密
|
||||
# # 您可以通过 "mihome age encrypt <public_key> <source_file> <target_file>" 将未加密文件加密
|
||||
# # 参考实现:
|
||||
# # https://github.com/FiloSottile/awesome-age#implementations
|
||||
# #
|
||||
# age-secret-key: AGE-SECRET-KEY-1ZTQLLN0A4U3ZTT3DCZKYN0CGZEZQLWX2DFTXUWMT4ZHR0N2UG6LSW9NT0N
|
||||
header:
|
||||
User-Agent:
|
||||
- "Clash/v1.18.0"
|
||||
@@ -1477,6 +1492,8 @@ proxy-providers:
|
||||
# - 'application/vnd.github.v3.raw'
|
||||
# Authorization:
|
||||
# - 'token 1231231'
|
||||
# X-Age-Public-Key:
|
||||
# - 'age1xh86kh9v23vattr58yedspm3f57sxvnswu9krr6ns438amekx5gsd09uma'
|
||||
health-check:
|
||||
enable: true
|
||||
interval: 600
|
||||
|
||||
@@ -10,6 +10,7 @@ require (
|
||||
github.com/gobwas/ws v1.4.0
|
||||
github.com/gofrs/uuid/v5 v5.4.0
|
||||
github.com/golang/snappy v1.0.0
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d
|
||||
github.com/metacubex/bart v0.26.0
|
||||
github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b
|
||||
|
||||
@@ -91,6 +91,8 @@ github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/
|
||||
github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw=
|
||||
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
|
||||
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78 h1:LqWr0vb9zDNuQS+jJd4fnRYk/SEI7KJ7TDe/L4WFK48=
|
||||
github.com/metacubex/age v0.0.0-20260603010618-28d156b4ea78/go.mod h1:BTBG/iVY7rg3qq5WdVCg0GFk58CSvCDSbjy8I7kEx/c=
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d h1:vAJ0ZT4aO803F1uw2roIA9yH7Sxzox34tVVyye1bz6c=
|
||||
github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY=
|
||||
github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM=
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/metacubex/mihomo/common/cmd"
|
||||
"github.com/metacubex/mihomo/component/age"
|
||||
"github.com/metacubex/mihomo/component/generator"
|
||||
"github.com/metacubex/mihomo/component/geodata"
|
||||
"github.com/metacubex/mihomo/component/updater"
|
||||
@@ -37,6 +38,7 @@ var (
|
||||
configFile string
|
||||
configString string
|
||||
configBytes []byte
|
||||
ageSecretKey string
|
||||
externalUI string
|
||||
externalController string
|
||||
externalControllerUnix string
|
||||
@@ -50,6 +52,7 @@ func init() {
|
||||
flag.StringVar(&homeDir, "d", os.Getenv("CLASH_HOME_DIR"), "set configuration directory")
|
||||
flag.StringVar(&configFile, "f", os.Getenv("CLASH_CONFIG_FILE"), "specify configuration file")
|
||||
flag.StringVar(&configString, "config", os.Getenv("CLASH_CONFIG_STRING"), "specify base64-encoded configuration string")
|
||||
flag.StringVar(&ageSecretKey, "age-secret-key", os.Getenv("CLASH_AGE_SECRET_KEY"), "specify age secret key to decrypt configuration")
|
||||
flag.StringVar(&externalUI, "ext-ui", os.Getenv("CLASH_OVERRIDE_EXTERNAL_UI_DIR"), "override external ui directory")
|
||||
flag.StringVar(&externalController, "ext-ctl", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER"), "override external controller address")
|
||||
flag.StringVar(&externalControllerUnix, "ext-ctl-unix", os.Getenv("CLASH_OVERRIDE_EXTERNAL_CONTROLLER_UNIX"), "override external controller unix address")
|
||||
@@ -94,6 +97,11 @@ func main() {
|
||||
return
|
||||
}
|
||||
|
||||
if len(os.Args) > 1 && os.Args[1] == "age" {
|
||||
age.Main(os.Args[2:])
|
||||
return
|
||||
}
|
||||
|
||||
if version {
|
||||
fmt.Printf("Mihomo Meta %s %s %s with %s %s\n",
|
||||
C.Version, runtime.GOOS, runtime.GOARCH, runtime.Version(), C.BuildTime)
|
||||
@@ -116,6 +124,14 @@ func main() {
|
||||
geodata.SetGeodataMode(true)
|
||||
}
|
||||
|
||||
if ageSecretKey != "" {
|
||||
identities, err := age.ParseIdentities(ageSecretKey)
|
||||
if err != nil {
|
||||
log.Errorln("Parse age-secret-key error: %s", err.Error())
|
||||
}
|
||||
age.SetGlobalIdentities(identities)
|
||||
}
|
||||
|
||||
if configString != "" {
|
||||
var err error
|
||||
configBytes, err = base64.StdEncoding.DecodeString(configString)
|
||||
|
||||
Reference in new issue
Block a user