Giter VIP home page Giter VIP logo

caddy-trojan's Introduction

Caddy-Trojan

Build with xcaddy

$ xcaddy build --with github.com/imgk/caddy-trojan

Config (Caddyfile)

{
	order trojan before file_server
	servers :443 {
		listener_wrappers {
			trojan
		}
	}
	trojan {
		caddy
		no_proxy
		users pass1234 word5678
	}
}
:443, example.com {
	tls [email protected] #optional,recommended
	trojan {
		connect_method
		websocket
	}
	file_server {
		root /var/www/html
	}
}

Config (JSON)

{
  "apps": {
    "http": {
      "servers": {
        "srv0": {
          "listen": [":443"],
          "listener_wrappers": [{
            "wrapper": "trojan"
          }],
          "routes": [{
            "handle": [{
              "handler": "trojan",
              "connect_method": true,
              "websocket": true
            },
            {
              "handler": "file_server",
              "root": "/var/www/html"
            }]
          }]
        }
      }
    },
    "trojan": {
      "upstream": {
        "upstream": "caddy"
      },
      "proxy": {
        "proxy": "no_proxy"
      },
      "users": ["pass1234","word5678"]
    },
    "tls": {
      "certificates": {
        "automate": ["example.com"]
      },
      "automation": {
        "policies": [{
          "issuers": [{
            "module": "acme",
            "email": "[email protected]" //optional,recommended
          },
          {
            "module": "zerossl",
            "email": "[email protected]" //optional,recommended
          }]
        }]
      }
    }
  }
}

Manage Users

  1. Add user.
curl -X POST -H "Content-Type: application/json" -d '{"password": "test1234"}' http://localhost:2019/trojan/users/add

Docker

git clone https://github.com/imgk/caddy-trojan
cd caddy-trojan/Dockerfiles
docker build -t caddy-trojan .
docker run --env MYPASSWD=MY_PASSWORD --env MYDOMAIN=MY_DOMAIN.COM -itd --name caddy-trojan --restart always -p 80:80 -p 443:443 caddy-trojan

caddy-trojan's People

Contributors

azoway avatar bash99 avatar imgk avatar lxhao61 avatar mritd avatar weidideng avatar xh116 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

caddy-trojan's Issues

trojan与测试版caddy会出现panic

不好意识又要打扰大佬了,经过测试
由 caddy commit:caddyserver/caddy@bbe1952 加 trojan commit:8be6619 编译出来的caddy版本:

/tmp/caddy/caddy version
v2.7.0-beta.2.0.20230712203222-bbe1952a59a1 h1:KJUD4kDiKshD0zHBzVY95ELWxluG2ha1Ff2ru8peWp0=

启动后会panic
经过精简配置文件,定位到确实是与trojan相关

caddyfile配置:

{
	log {
		output file /tmp/caddy/caddy_log.txt
		level INFO
	}
	trojan {
		caddy
		no_proxy
		users pw1234
	}
	servers 127.0.0.1:88 {
		listener_wrappers {
			trojan
		}
	}
}

:88 {
	bind 127.0.0.1
	route {
		reverse_proxy 127.0.0.1:80
	}
}

log启动日志:

{"level":"warn","ts":1689223101.1303897,"msg":"unable to determine directory for user configuration; falling back to current directory","error":"neither $XDG_CONFIG_HOME nor $HOME are defined"}
{"level":"info","ts":1689223101.8108592,"msg":"using provided configuration","config_file":"/tmp/caddy/Caddyfile","config_adapter":""}
{"level":"warn","ts":1689223101.875325,"msg":"Caddyfile input is not formatted; run 'caddy fmt --overwrite' to fix inconsistencies","adapter":"caddyfile","file":"/tmp/caddy/Caddyfile","line":20}
{"level":"info","ts":1689223101.8815844,"msg":"redirected default logger","from":"stderr","to":"/tmp/caddy/caddy_log.txt"}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0xfc01ec]

goroutine 1 [running]:
github.com/caddyserver/caddy/v2.Context.AppIfConfigured(...)
	github.com/caddyserver/caddy/[email protected]/context.go:444
github.com/caddyserver/caddy/v2/modules/caddytls.(*TLS).Cleanup(0x3bb1ea0)
	github.com/caddyserver/caddy/[email protected]/modules/caddytls/tls.go:335 +0xc0
github.com/caddyserver/caddy/v2.NewContext.func1()
	github.com/caddyserver/caddy/[email protected]/context.go:67 +0x1c8
github.com/caddyserver/caddy/v2.run.func1()
	github.com/caddyserver/caddy/[email protected]/caddy.go:419 +0x54
github.com/caddyserver/caddy/v2.run(0x3930390, 0x1)
	github.com/caddyserver/caddy/[email protected]/caddy.go:484 +0x7c0
github.com/caddyserver/caddy/v2.unsyncedDecodeAndRun({0x391e5a0, 0x1c2, 0x1e0}, 0x1)
	github.com/caddyserver/caddy/[email protected]/caddy.go:337 +0x1bc
github.com/caddyserver/caddy/v2.changeConfig({0x1a4299f, 0x4}, {0x1a4af44, 0x7}, {0x391e3c0, 0x1c2, 0x1e0}, {0x0, 0x0}, 0x1)
	github.com/caddyserver/caddy/[email protected]/caddy.go:228 +0x94c
github.com/caddyserver/caddy/v2.Load({0x391e3c0, 0x1c2, 0x1e0}, 0x1)
	github.com/caddyserver/caddy/[email protected]/caddy.go:127 +0x240
github.com/caddyserver/caddy/v2/cmd.cmdRun({0x38bc780})
	github.com/caddyserver/caddy/[email protected]/cmd/commandfuncs.go:222 +0x9d0
github.com/caddyserver/caddy/v2/cmd.WrapCommandFuncForCobra.func1(0x397e900, {0x3c69de0, 0x0, 0x2})
	github.com/caddyserver/caddy/[email protected]/cmd/cobra.go:126 +0x60
github.com/spf13/cobra.(*Command).execute(0x397e900, {0x3c69dd0, 0x2, 0x2})
	github.com/spf13/[email protected]/command.go:940 +0x8a0
github.com/spf13/cobra.(*Command).ExecuteC(0x2b51ee0)
	github.com/spf13/[email protected]/command.go:1068 +0x4c0
github.com/spf13/cobra.(*Command).Execute(...)
	github.com/spf13/[email protected]/command.go:992
github.com/caddyserver/caddy/v2/cmd.Main()
	github.com/caddyserver/caddy/[email protected]/cmd/main.go:64 +0xa8
main.main()
	caddy/main.go:18 +0x38

Caddyfile not works

Hi
It seems the latest commit has conflict with Caddyfile. (tested json config file works.)

run: loading initial config: loading new config: loading http app module: provision http: server srv0: setting up route handlers: route 0: loading handler modules: position 1: loading module 'subroute': provision http.handlers.subroute: setting up subroutes: route 0: loading handler modules: position 0: module name not specified with key 'handler' in map[]

想了解一下这个插件的trojan是使用什么加密方式连接的

如题,因为经过我近20台服务器的测试,对客户端连接加密方式的控制,可以有效预防封端口问题产生,但考虑到客户端众多,所以原来用nginx+trojan的方案,强制在服务端指定了加密算法。

这个插件的trojan该如何控制?caddy的protocols与ciphers,对这个trojan插件的连接算法指定也生效么?

trojan+http2无法连接

"allow_h2c": true,
"routes": [
{
"handle": [
{
"handler": "trojan",
"connect_method": false,
"websocket": false
}
]
}
]
当服务器上的caddy配置文件中"allow_h2c": 值为:true时,客户端上选择trojan+http2(host和path都留空)时无法连接,只有trojan+tcp才可以连接,设置这个参数的意义何在?需要填什么吗?

过期的配置参数

在 caddy 2.6.1 中 protocol 设置已经是不鼓励使用了,并且 experimental_http3 已经被移除,成为未知选项了。 README 中的示例配置中的

protocol {
        allow_h2c
        experimental_http3
}

在 caddy 2.6.1 下应该可以被替换成 protocols h1 h2 h2c h3

剛xcaddy build的版本無法使用?

caddy version:

v2.5.0 h1:eRHzZ4l3X6Ag3kUt8nj5IxATprhqKq/wToP7OHlXWA0=

caddy list-modules:

  Standard modules: 95

admin.api.trojan
caddy.listeners.trojan
http.handlers.trojan
trojan
trojan.proxies.env_proxy
trojan.proxies.no_proxy
trojan.upstreams.caddy
trojan.upstreams.memory

  Non-standard modules: 8

  Unknown modules: 0

以下兩配置trojan均無法使用:

配置1:

{
  order trojan before map
  admin off
  log {
    output discard
  }
  servers :443 {
    listener_wrappers {
      trojan
    }
    protocol {
      allow_h2c
      experimental_http3
    }
  }
  trojan {
    caddy
    no_proxy
    users password1 password2
  }
}

:443, xx.yy {
  encode {
    gzip 6
  }

  tls {
    protocols tls1.3
    curves x25519
    alpn h2
  }

  @host {
    host xx.yy
  }

  route @host {
    trojan {
      connect_method
      websocket
    }
    header {
      Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
      X-Content-Type-Options nosniff
      X-Frame-Options SAMEORIGIN
      Referrer-Policy no-referrer-when-downgrade
    }
    file_server {
      root /var/www/html
    }
  }
}

配置2:

{
  "admin": {"disabled": true},
  "logging": {
    "logs": {
      "default": {
        "writer": {"output":"discard"}
      }
    }
  },
  "apps": {
    "http": {
      "servers": {
        "srv0": {
          "listen": [":443"],
          "listener_wrappers": [{"wrapper": "trojan"}],
          "routes": [{
            "handle": [{
              "encodings": {"gzip": {"level": 6}},
              "handler": "encode",
              "prefer": ["gzip"]
            }]
          },
          {
            "handle": [{
              "handler": "trojan",
              "connect_method": false,
              "websocket": false
            }]
          },
          {
            "match": [{"host": ["xx.yy"]}],
            "handle": [{
              "handler": "subroute",
              "routes": [{
                "handle": [{
                  "handler": "headers",
                  "response": {
                    "set": {
                      "Referrer-Policy": ["no-referrer-when-downgrade"],
                      "Strict-Transport-Security": ["max-age=31536000; includeSubDomains; preload"],
                      "X-Content-Type-Options": ["nosniff"],
                      "X-Frame-Options": ["SAMEORIGIN"]
                    }
                  }
                }]
              },
              {
                "handle": [{
                  "handler": "file_server",
                  "root": "/var/www/html"
                }]
              }]
            }]
          }],
          "tls_connection_policies": [{
            "curves": ["x25519"],
            "alpn": ["h2"],
            "protocol_min": "tls1.3"
          }],
          "experimental_http3": true,
          "allow_h2c": true
        }
      }
    },
    "trojan": {
      "upstream": {
        "upstream": "caddy"
      },
      "proxy": {
        "proxy": "no_proxy"
      },
      "users": ["password1", "password2"]
    },
    "tls": {
      "certificates": {
        "automate": ["xx.yy"]
      }
    }
  }
}

能否支持trojan-go的mux模式?

对降低延迟有较好作用,而且从隐藏流量特征的角度也更好一点。(毕竟现在的h2协议下并发连接数明显变少)

是否能考虑实现upstream参数

forwardproxy 这个插件能支持:

upstream [https://username:[email protected]:443]
Sets upstream proxy to route all forwardproxy requests through it. This setting does not affect non-forwardproxy requests nor requests with wrong credentials. Upstream is incompatible with acl and ports subdirectives.
Supported schemes to remote host: https.
Supported schemes to localhost: socks5, http, https (certificate check is ignored).
Default: no upstream proxy.

实际用处的话,我是用v2ray建一个代理做路由控制,比如禁止一些网站,转发NF流量

编译最新的caddy 2.7.0-beta.2.0(0e2c7e1)报错

caddy commit:
caddyserver/caddy@0e2c7e1
加master分支的trojan:
--with github.com/imgk/caddy-trojan@master

报错:

github.com/imgk/caddy-trojan/admin

/root/gopath/pkg/mod/github.com/imgk/[email protected]/admin/admin.go:34:15: assignment mismatch: 2 variables but ctx.AppIfConfigured returns 1 value

github.com/imgk/caddy-trojan/handler

/root/gopath/pkg/mod/github.com/imgk/[email protected]/handler/handler.go:58:15: assignment mismatch: 2 variables but ctx.AppIfConfigured returns 1 value

github.com/imgk/caddy-trojan/listener

/root/gopath/pkg/mod/github.com/imgk/[email protected]/listener/listener.go:50:15: assignment mismatch: 2 variables but ctx.AppIfConfigured returns 1 value

Where/How to enable the IPV6 ?

Sometimes ipv6 has better latency and even no bandwidth limitation.
Caddy itself works well with ipv6 now, but seems not able to use Ipv6 for trojan module.

By the way, does it support gRPC protocol just like websocket?

配置能跑起来但是日志里大量报错是怎么回事?

日志:

 {"level":"error","ts":1628333075.3740613,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37364 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333075.4770167,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37372 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333075.554954,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37326 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333075.8206017,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37406 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333076.0460594,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37414 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333076.13074,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37418 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333076.1324344,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37416 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333076.1643324,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37002 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333076.1855006,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37420 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333076.2123344,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37422 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333076.7358618,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37398 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333090.6926646,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37432 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333098.582598,"logger":"caddy.listeners.trojan","msg":"handle net.Conn error: handle tcp error: dial tcp 97.103.142.250:7680: connect: connection timed out"}
{"level":"error","ts":1628333131.4615848,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37480 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333142.0983384,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37560 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333143.2427561,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37562 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333144.4719136,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37588 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333144.4796648,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37590 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333146.1707826,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37610 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333146.1710782,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37608 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333147.567538,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37634 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333147.5704322,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37636 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333149.9503307,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37674 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333149.9531937,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37676 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333150.0335038,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37678 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333150.033562,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37680 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333177.1543846,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37716 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333177.1547074,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37714 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333178.3147156,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37734 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333178.3150752,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37736 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333178.8151402,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37750 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333178.8235142,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37748 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333185.31525,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37774 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333185.315627,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37772 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333230.847019,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37824 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333230.8484578,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37826 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333232.5331128,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37838 -> 222.222.222.222:443: read: EOF"}
{"level":"error","ts":1628333232.5392232,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp 111.11.11.111:37840 -> 222.222.222.222:443: read: EOF"}

caddyfile:

{
        admin off
#       acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
        log {
                output file /var/log/caddy/caddy.log {
                        roll_size 100mb
                        roll_keep 3
                }
                level ERROR
        }
        servers {
                listener_wrappers {
                        trojan
                }
                protocol {
                        allow_h2c
                        experimental_http3
                }
        }
}
(ACME) {
        dns cloudflare
}
(TLS) {
        protocols tls1.3
        ciphers TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
}
(HSTS) {
        header / Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
}
(COMBO) {
        encode zstd gzip
        tls [email protected] {
                import TLS
                import ACME
        }
        import HSTS
}
xxx.yyy, ccc.ooo {
        tls {
                import TLS
                alpn h2 http/1.1
        }
        @host {
                host xxx.yyy, ccc.ooo
        }
        route @host {
                trojan {
                        user opennetwork
                        connect_method
                        websocket
                }
                redir https://www.xxx.yyy{uri} permanent
        }
}

*.xxx.yyy {
import COMBO
.....
}

/usr/bin/caddy list-modules

admin.api.load
admin.api.metrics
admin.api.reverse_proxy
caddy.adapters.caddyfile
caddy.config_loaders.http
caddy.listeners.tls
caddy.logging.encoders.console
caddy.logging.encoders.filter
caddy.logging.encoders.filter.delete
caddy.logging.encoders.filter.ip_mask
caddy.logging.encoders.filter.replace
caddy.logging.encoders.json
caddy.logging.encoders.single_field
caddy.logging.writers.discard
caddy.logging.writers.file
caddy.logging.writers.net
caddy.logging.writers.stderr
caddy.logging.writers.stdout
caddy.storage.file_system
http
http.authentication.hashes.bcrypt
http.authentication.hashes.scrypt
http.authentication.providers.http_basic
http.encoders.gzip
http.encoders.zstd
http.handlers.acme_server
http.handlers.authentication
http.handlers.encode
http.handlers.error
http.handlers.file_server
http.handlers.headers
http.handlers.map
http.handlers.metrics
http.handlers.push
http.handlers.request_body
http.handlers.reverse_proxy
http.handlers.rewrite
http.handlers.static_response
http.handlers.subroute
http.handlers.templates
http.handlers.vars
http.matchers.expression
http.matchers.file
http.matchers.header
http.matchers.header_regexp
http.matchers.host
http.matchers.method
http.matchers.not
http.matchers.path
http.matchers.path_regexp
http.matchers.protocol
http.matchers.query
http.matchers.remote_ip
http.matchers.vars
http.matchers.vars_regexp
http.precompressed.br
http.precompressed.gzip
http.precompressed.zstd
http.reverse_proxy.selection_policies.cookie
http.reverse_proxy.selection_policies.first
http.reverse_proxy.selection_policies.header
http.reverse_proxy.selection_policies.ip_hash
http.reverse_proxy.selection_policies.least_conn
http.reverse_proxy.selection_policies.random
http.reverse_proxy.selection_policies.random_choose
http.reverse_proxy.selection_policies.round_robin
http.reverse_proxy.selection_policies.uri_hash
http.reverse_proxy.transport.fastcgi
http.reverse_proxy.transport.http
pki
tls
tls.certificates.automate
tls.certificates.load_files
tls.certificates.load_folders
tls.certificates.load_pem
tls.certificates.load_storage
tls.handshake_match.remote_ip
tls.handshake_match.sni
tls.issuance.acme
tls.issuance.internal
tls.issuance.zerossl
tls.stek.distributed
tls.stek.standard
 
   Standard modules: 83
 
 admin.api.trojan
caddy.listeners.trojan
caddy.logging.encoders.formatted
dns.providers.alidns
dns.providers.cloudflare
dns.providers.dnspod
dns.providers.route53
exec
http.authentication.providers.jwt
http.handlers.authp
http.handlers.exec
http.handlers.realip
http.handlers.teapot
http.handlers.trace
http.handlers.trojan
http.handlers.webdav
http.matchers.maxmind_geolocation
layer4
layer4.handlers.echo
layer4.handlers.proxy
layer4.handlers.tee
layer4.handlers.throttle
layer4.handlers.tls
layer4.matchers.http
layer4.matchers.ip
layer4.matchers.ssh
layer4.matchers.tls
layer4.proxy.selection_policies.first
layer4.proxy.selection_policies.ip_hash
layer4.proxy.selection_policies.least_conn
layer4.proxy.selection_policies.random
layer4.proxy.selection_policies.random_choose
layer4.proxy.selection_policies.round_robin
 
   Non-standard modules: 33
 
   Unknown modules: 0

这是什么问题?

Rewind tls.Conn

tls.Conn can be rewound by using reflect to modify its internal buffer.

func RewindTlsConn(conn *tls.Conn, read []byte) {
	var (
		tlsInput, _ = reflect.TypeOf(tls.Conn{}).FieldByName("input")
		input     = (*bytes.Reader)(unsafe.Add(unsafe.Pointer(conn), tlsInput.Offset))
		remaining = input.Len()
		size      = int(input.Size())
		buffered  = len(read)
	)
	if buffered <= size {
		_, _ = input.Seek(0, 0)
	} else {
		buf := make([]byte, buffered+remaining)
		copy(buf, read)
		_, _ = input.Read(buf[buffered:])
		input.Reset(buf)
	}
}

There is no need to turn on allow h2c if caddy is using https.

Build FATAL

go version go1.18 linux/amd64

FATAL:
2022/03/29 14:42:44 [INFO] Build environment ready
2022/03/29 14:42:44 [INFO] Building Caddy
2022/03/29 14:42:44 [INFO] exec (timeout=0s): /usr/local/bin/go mod tidy
caddy imports
github.com/caddyserver/caddy/v2/modules/standard imports
github.com/caddyserver/caddy/v2/modules/caddypki imports
github.com/smallstep/certificates/authority imports
github.com/smallstep/certificates/kms tested by
github.com/smallstep/certificates/kms.test imports
github.com/smallstep/certificates/kms/cloudkms imports
cloud.google.com/go/kms/apiv1: ambiguous import: found package cloud.google.com/go/kms/apiv1 in multiple modules:
cloud.google.com/go v0.83.0 (/home/wiselau/go/pkg/mod/cloud.google.com/[email protected]/kms/apiv1)
cloud.google.com/go/kms v1.1.0 (/home/wiselau/go/pkg/mod/cloud.google.com/go/[email protected]/apiv1)
2022/03/29 14:42:44 [INFO] Cleaning up temporary folder: /tmp/buildenv_2022-03-29-1442.3882018425
2022/03/29 14:42:44 [FATAL] exit status 1

syntax error

https://github.com/Gzxhwq/caddy-cloudflaredns/runs/5610293409?check_suite_focus=true

github.com/imgk/caddy-trojan/memory

/go/pkg/mod/github.com/imgk/[email protected]/memory/alloc.go:4:14: syntax error: unexpected any, expecting ]
/go/pkg/mod/github.com/imgk/[email protected]/memory/alloc.go:9:17: syntax error: unexpected [, expecting comma or )
/go/pkg/mod/github.com/imgk/[email protected]/memory/alloc.go:14:17: syntax error: unexpected [, expecting comma or )
/go/pkg/mod/github.com/imgk/[email protected]/memory/alloc_go.go:7:6: missing function body
/go/pkg/mod/github.com/imgk/[email protected]/memory/alloc_go.go:7:11: syntax error: unexpected [, expecting (
/go/pkg/mod/github.com/imgk/[email protected]/memory/alloc_go.go:12:6: missing function body
/go/pkg/mod/github.com/imgk/[email protected]/memory/alloc_go.go:12:10: syntax error: unexpected [, expecting (

一处协议探测弱点

if n > 1 && b[n-1] == 0x0d && b[n] == 0x0a && n < trojan.HeaderLen+1 {

这里检查协议的第一次 0D0A. HTTP 协议虽然规定以 0D0A 分割,但 nginx 和基本全部在线的 web 服务器都是按 nginx 的头部解析过程来实现的。参考代码
https://github.com/nginx/nginx/blob/master/src/http/ngx_http_parse.c#L1049

nginx 中, 0D(\r) 是可以重复或略过,其后必须有一个 0A(\n)
举例:
向正常的 http 服务器
发送 whatever\r\r\r\r\r\r\ 服务器会等待
发送 whatever\n\n\n\n\n 服务器返回错误页面

而本项目发送 whatever\n\n\n\n\n 服务器会继续等待,表现与正常 web 服务器不同
因此这里不必要求 \n 前有 \r

if n > 1 && b[n] == 0x0a && n < trojan.HeaderLen+1 

建议配置参数简约化

大佬,现在配置参数是否可以回到以前,甚至比以前更加简约化。
觉得现在配置参数太繁琐(多个配置块、多个关联参数无条理。),希望一个配置块搞定(类似naiveproxy配置)。

报错EOF

手机端v2rayNG测速会报错 失败:EOF 大概率出现

Caddy 版本依赖建议

问题描述

目前有一个自动化任务在定时编译 Caddy, 其中为了保持插件更新会定期 rebuild; 现在遇到的问题是 trojan 插件使用了未发布的 Caddy 版本, 导致在编译 release 版本时出现依赖错误

解决建议

能否新开一个分支用于对下一个版本的开发, main 分支保持与当前 Caddy release 锁定, 如果 hotfix 之类的可以直接 main 分支 commit; 这样可以保证 main 一直可以兼容最新的 Caddy release.

与其他插件(klzgrad/forwardproxy)共存有问题

首先非常感谢作者的辛劳付出

我在折腾过程中发现和 NaïveProxy 这个插件结合起来使用的时候,torjan 完全没有问题,而那个插件则失效了。
因为对 caddy 和 go 都不是非常了解,我猜测是 caddy-torjan 的处理导致 naive 没有接受到相应的数据。
不知可否添加一个相应的属性,类似 trojan-go 中的 fallback_addr 和 fallback_port,或者直接在插件内交给其他插件处理呢?

我两个插件结合使用时的 Caddyfile 如下,也许这只是个配置问题,请大家看看。

{
    order trojan before respond
    order forward_proxy before respond
    https_port 443
    servers :443 {
        listener_wrappers {
            trojan
        }
        protocols h2 h1
    }
    servers :80 {
        protocols h1
    }
    trojan {
        caddy
        no_proxy
        users *******
    }
}
trojan.*******.com:443 {
    tls "/home/******/cert/*******.me/cert.pem" "/home/*******/cert/*******.me/key.pem" {
        protocols tls1.2 tls1.2
        ciphers TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
    }
    log {
        level ERROR
    }
    trojan {
        websocket
    }
    respond "Service Unavailable" 503 {
        close
    }
}
naive.*******.com:443 {
    tls "/home/****/cert/*******.me/cert.pem" "/home/*******/cert/*******.me/key.pem" {
        protocols tls1.2 tls1.2
        ciphers TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
    }
    forward_proxy {
        basic_auth ******* *********
        hide_ip
        hide_via
        probe_resistance
    }
    respond "Service Unavailable" 503 {
        close
    }
}
:80 {
    redir https://{host}{uri} permanent
}

再次感谢作者创作出这么好用的插件。

支持上级代理和 TCP 代码优化

首先感谢作者提供了很好的思路,嵌入到 caddy 中是十分优雅的实现

看了下代码,提两个建议

  1. tcp 发起连接使用 x/net/proxy,可以自动处理环境变量中的 HTTP_PROXY,十分好用
  2. tcp 交换数据的代码是不是有些复杂,本质是两个 io.Copy,可以考虑下

我自己实现了下,代码如下,暂时自用以发现问题

wen-long@17a2feb

编译:
xcaddy build master --with github.com/wen-long/caddy-trojan@17a2feb9ec061b72d0a246d1820172fa509f24c2

The program crashes automatically

error message:
caddy[10980]: panic: runtime error: slice bounds out of range [:62378] with capacity 16384
caddy[10980]: goroutine 5505 [running]:
caddy[10980]: github.com/imgk/caddy-trojan/trojan.HandleUDP.func1(0xc000512c68, {0x7fd2109d4718, 0xc00097f500}, 0xc000074ae0?)
caddy[10980]: github.com/imgk/[email protected]/trojan/trojan_udp.go:72 +0x545
caddy[10980]: created by github.com/imgk/caddy-trojan/trojan.HandleUDP
caddy[10980]: github.com/imgk/[email protected]/trojan/trojan_udp.go:30 +0x16b
systemd[1]: caddy.service: Main process exited, code=exited, status=2/INVALIDARGUMENT
systemd[1]: caddy.service: Failed with result 'exit-code'.
systemd[1]: caddy.service: Consumed 32.130s CPU time.

failed to build with 2cd4633

  • build command:
CGO_ENABLED=0 GOARCH=amd64 GOOS=linux XCADDY_GO_BUILD_FLAGS="-ldflags '-s -w -buildid='" xcaddy build v2.7.6 --output caddy-v2.7.6-x86_64 --with github.com/imgk/caddy-trojan
  • error message:
# github.com/caddyserver/caddy/v2
../../../go/pkg/mod/github.com/caddyserver/caddy/[email protected]/listeners.go:477:4: unknown field RequireAddressValidation in struct literal of type quic.Config
../../../go/pkg/mod/github.com/caddyserver/caddy/[email protected]/listeners.go:516:4: unknown field RequireAddressValidation in struct literal of type quic.Config
2024/04/12 10:02:59 [INFO] Cleaning up temporary folder: /Users/m1/make/caddy-trojan/buildenv_2024-04-12-1002.443345072
2024/04/12 10:02:59 [FATAL] exit status 1
  • remarks:
    --with github.com/imgk/caddy-trojan@b1603cd is fine.

GetUsers的API调用问题

如题,想了解一下这个API如何调用

GetUsers 通过curl调用后,得到的key值是密文,应当如何输出明文密码?

compatibility with forwardproxy module

firstly, Thanks for this project !

I often use naiveproxy which is based on another module of Caddy called forwardyproxy (https://github.com/caddyserver/forwardproxy). however it is not compatible with most of mobile clients.
After testing your project, I found it very efficient to solve this problem.

but seems the two modules are not compatible.

 :443, xx.yy.com {
tls [email protected]
trojan_gfw
route {
 forward_proxy {
    basic_auth user password
    hide_ip
    hide_via
    probe_resistance 
  }
  trojan // for websocket
  file_server { root /var/www/html }
 }
}

do you have any suggestions

failed to build with v2.8.0-rc.1

failed to build with v2.8.0-rc.1, but v2.8.0-beta.2 is ok.

# github.com/imgk/caddy-trojan/admin
../admin/admin.go:35:5: multiple-value ctx.AppIfConfigured(app.CaddyAppID) (value of type (any, error)) in single-value context
# github.com/imgk/caddy-trojan/listener
../listener/listener.go:51:5: multiple-value ctx.AppIfConfigured(app.CaddyAppID) (value of type (any, error)) in single-value context
# github.com/imgk/caddy-trojan/handler
../handler/handler.go:61:5: multiple-value ctx.AppIfConfigured(app.CaddyAppID) (value of type (any, error)) in single-value context

Missing description and explanation

I looked at this project for quite a while and was wandering for what it is. Because usually the plugins have description what they do and about what they are for. Can you please add that? Because I'm a beginner in Go and I'm not understanding what the plugin does in the code.

请问有 caddyfile 配置吗?

此trojan是 翻墙的那个trojan协议变成caddy模块了吗?
无意搜到此项目,不知道有没有caddyfile配置, 尝试是否能让二者共存?

打印了大量的log

web_1 | {"level":"error","ts":1685293954.0146098,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp :18629 -> 172.18.0.15:443: read: EOF"}
web_1 | {"level":"error","ts":1685294244.9202943,"logger":"caddy.listeners.trojan","msg":"read prefix error, not io, rewind and let normal caddy deal with it: no certificate available for '172.18.0.15'"}
web_1 | {"level":"error","ts":1685294244.930999,"logger":"caddy.listeners.trojan","msg":"read prefix error, not io, rewind and let normal caddy deal with it: no certificate available for '172.18.0.15'"}
web_1 | {"level":"error","ts":1685294244.9397044,"logger":"caddy.listeners.trojan","msg":"read prefix error, not io, rewind and let normal caddy deal with it: no certificate available for '172.18.0.15'"}
web_1 | {"level":"error","ts":1685294244.9489136,"logger":"caddy.listeners.trojan","msg":"read prefix error, not io, rewind and let normal caddy deal with it: no certificate available for '172.18.0.15'"}
web_1 | {"level":"error","ts":1685294244.9561362,"logger":"caddy.listeners.trojan","msg":"read prefix error, not io, rewind and let normal caddy deal with it: no certificate available for '172.18.0.15'"}
web_1 | {"level":"error","ts":1685294244.9757292,"logger":"caddy.listeners.trojan","msg":"read prefix error, not io, rewind and let normal caddy deal with it: no certificate available for '172.18.0.15'"}
web_1 | {"level":"error","ts":1685294318.235925,"logger":"caddy.listeners.trojan","msg":"read prefix error, not io, rewind and let normal caddy deal with it: no certificate available for 'hkbgp.fccloud.xyz'"}
web_1 | {"level":"error","ts":1685294355.2818253,"logger":"caddy.listeners.trojan","msg":"read prefix error: read tcp :19079 -> 172.18.0.15:443: read: EOF"}

上述 log 中有两种类型的报错 log:1. 是 read: EOF",2. 是 no certificate available for

请问,这两种 log 为什么是 trojan 来打印呢?特别是第二种,不应该是 caddy 本身来负责吗?

不能和其他插件一起编译吗

这个插件是不能和其他插件一起编译吗

go version go1.18.3 linux/amd64
xcaddy v0.3.0

单独编译 caddy-trojan 没有问题

xcaddy build master --with github.com/imgk/caddy-trojan

只编译其他插件时候也没有问题

xcaddy build master \
    --with github.com/mholt/caddy-webdav \
    --with github.com/sjtug/caddy2-filter

但是一起编译的时候就会报错

xcaddy build master \
    --with github.com/mholt/caddy-webdav \
    --with github.com/sjtug/caddy2-filter \
    --with github.com/imgk/caddy-trojan

xcaddy build master \
    --with github.com/mholt/caddy-webdav \
    --with github.com/imgk/caddy-trojan

xcaddy build master \
    --with github.com/sjtug/caddy2-filter \
    --with github.com/imgk/caddy-trojan

都是同样的错误

2022/06/06 03:59:54 [INFO] exec (timeout=0s): /opt/hostedtoolcache/go/1.18.3/x64/bin/go build -o /home/runner/caddy -ldflags -w -s -trimpath 
# github.com/google/cel-go/parser/gen
Error: /home/runner/go/pkg/mod/github.com/google/[email protected]/parser/gen/cel_lexer.go:271:32: deserializer.Deserialize undefined (type *antlr.ATNDeserializer has no field or method Deserialize)
Error: /home/runner/go/pkg/mod/github.com/google/[email protected]/parser/gen/cel_parser.go:151:32: deserializer.Deserialize undefined (type *antlr.ATNDeserializer has no field or method Deserialize)
2022/06/06 04:01:12 [INFO] Cleaning up temporary folder: /tmp/buildenv_2022-06-06-0359.768204966
2022/06/06 04:01:12 [FATAL] exit status 2
Error: Process completed with exit code 1.

已经看过 #17 #20 ,不知道是哪里的问题。

发现listener_wrappers参数影响反向代理gRPC应用。

发现 listener_wrappers参数影响反向代理gRPC应用,希望大神修复。
当caddy与Xray或v2ray配合,对Xray或v2ray的WebSocket、h2c、gRPC进行反向代理,且同时naiveproxy与trojian-go代理时(caddy插件),发现仅反向代理gRPC无法正常工作。情况是:
1、配置listener_wrappers参数时,在CDN模式下反向代理gRPC正常,如cloudflare的CDN;正常模式下反向代理gRPC反而不正常。
2、去除listener_wrappers参数时,在CDN模式下与正常模式下,反向代理gRPC都正常;但trojian-go代理无法用了。

相关应用见示例:
反向代理gRPC应用 :https://github.com/lxhao61/integrated-examples/tree/main/v2ray(vless%5Cvmess%2Bgrpc)%2Bcaddy%5Cnginx
反向代理综合应用:https://github.com/lxhao61/integrated-examples/tree/main/v2ray(B%2BC%2BD%2BA)%2Bcaddy(N%2BT)

trojanXX.lock : Empty lockfile (EOF) , Lock for 'trojan/XX' is stale

caddy 2.6.4 with caddy-trojan main, lots of log like this , every 3~10 minutes:

caddy[pid]: {"level":"info","ts":hide_TIMESTAMP,"msg":"[INFO][FileStorage:/home/caddy/.local/share/caddy] /home/caddy/.local/share/caddy/locks/trojanxxxxxxxxxxx.lock: Empty lockfile (EOF) - likely previous process crashed or storage medium failure; treating as stale"}

caddy[pid]: {"level":"info","ts":hide_TIMESTAMP,"msg":"[INFO][FileStorage:/home/caddy/.local/share/caddy] Lock for 'trojan/xxxxxxxxxxx' is stale (created: 0001-01-01 00:00:00 +0000 UTC, last update: 0001-01-01 00:00:00 +0000 UTC); removing then retrying: /home/caddy/.local/share/caddy/locks/trojanxxxxxxxxxxx.lock"}

the user/group is caddy:caddy, home is /home/caddy, permissions/ownership are all fine as i've checked. , i already set global log level to PANIC. btw, trojan is working fine, it's just the logs are annoying.

what could be the causes?

Caddyfile (with sensitive info replaced)

{
    servers :443 {
        listener_wrappers {
            trojan
        }
        protocols h1 h2
    }
    trojan {
        caddy
        no_proxy
        users $pw
    }
    log {
        level PANIC
    }
    admin off
    order trojan before file_server
}

:443, $name {
    tls $mail
    header {
        Strict-Transport-Security max-age=31536000
        X-Content-Type-Options nosniff
        X-Robots-Tag "noindex, nofollow, nosnippet, noarchive"
        X-Frame-Options DENY
        Permissions-Policy interest-cohort=()
        Referrer-Policy no-referrer-when-downgrade
    }
    trojan {
        #connect_method
        #websocket
    }
    file_server browse {
        root /var/www/html
    }
}

Error when compiling caddy

Hello,

When I tried to compile caddy today this your plugin, it failed:

xcaddy build --with github.com/mastercactapus/caddy2-proxyprotocol --with github.com/imgk/caddy-trojan --with github.com/WeidiDeng/caddy-cloudflare-ip --with github.com/caddy-dns/cloudflare --output /usr/bin/caddy

Error:

github.com/imgk/caddy-trojan imports
	github.com/imgk/caddy-trojan/app imports
	github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile imports
	github.com/caddyserver/caddy/v2/modules/caddypki imports
	github.com/smallstep/certificates/authority imports
	github.com/smallstep/nosql imports
	github.com/smallstep/nosql/badger/v2 imports
	github.com/dgraph-io/badger/v2 imports
	github.com/dgraph-io/badger/v2/y imports
	github.com/klauspost/compress/zstd: github.com/klauspost/[email protected]: reading https://proxy.golang.org/github.com/klauspost/compress/@v/v1.15.15.zip: 403 Forbidden
2023/06/06 10:44:30 [FATAL] exit status 1

Thanks

一处可能的协议探测漏洞

Gaukas 提到的
enfein/mieru#8 (comment)_

未开启trojan相关配置,和普通的caddy一样,对443端口收到的普通HTTP请求返回400

root@xxx:~# curl -D - http://xxx.mysite.com:443/
HTTP/1.0 400 Bad Request

Client sent an HTTP request to an HTTPS server.

开启trojan相关配置,响应不一样了

root@xxx:~# curl -D - http://xxx.mysite.com:443/
curl: (52) Empty reply from server

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.