Caddy2 与 Cloudflare 不完美结合方案

本贴最后更新于 1459 天前,其中的信息可能已经天翻地覆

本文的大多数信息来源于社区的 lizhongyue248 帮助以及官方文档,我这边只是将相关内容整理出来。

感谢 lizhongyue248!🙏🙏🙏

01. cloudflare 相关设置

1.环境变量设置的方式无效了,需要在配置文件里面设置 token

2.不需要设置邮箱,不能使用全局 token,要单独创建一个具有如下权限的 token

Zone / Zone / Read
Zone / DNS / Edit

进入 cloudflare 管理端,点击右下角的“获取您的 API 令牌“

image.png

进入编辑页面

image.png

修改如下配置,区域资源那边选择自己的网站。

image.png

全部处理完成之后,会出现一个 api_token,值得注意的一点是这个 token 和大多数网站一样,只显示一次,注意 ⚠️ 找个地方记录下。

02. 编译 caddy 添加 tls.dns.cloudflare 模块

可以使用 golang 的 docker 镜像来构建,你运行的环境是什么 os,你就选择什么环境的 golang

$ mkdir -p caddy && cd caddy
$ wget https://raw.githubusercontent.com/caddyserver/caddy/v2/cmd/caddy/main.go

然后编辑 main.go,在 import 代码块里面添加你需要的模块:



package main

import (
	caddycmd "github.com/caddyserver/caddy/v2/cmd"

	// plug in Caddy modules here
	_ "github.com/caddyserver/caddy/v2/modules/standard"
	_ "github.com/caddyserver/tls.dns/providers/cloudflare"
)

func main() {
	caddycmd.Main()
}

然后构建就可以了,我当时构建的是 beta.15 版本

$ go mod init caddy
$ go get github.com/caddyserver/caddy/v2@v2.0.0-beta.15
$ go build

构建完成用会在当前目录生成一个 caddy 二进制文件

./caddy list-modules

结果会包含 tls.dns.cloudflare,我之前用 caddy 的 caddy-builder 镜像一直没改成功

03. caddy 相关配置

Caddy1 可以直接从 get caddy 里面选择插件进行下载

目前 caddy2 只有手动编译,get caddy 相关页面还在开发过程中

Caddyfile 里面没有配置 dns 选项,由于 go 不是很熟悉

https://github.com/caddyserver/dnsproviders/blob/master/cloudflare/cloudflare.go

这个仓库中有一个 credentials,不知道如何配置

// Package cloudflare adapts the lego Cloudflare DNS
// provider for Caddy. Importing this package plugs it in.
package cloudflare

import (
	"errors"

	"github.com/caddyserver/caddy/caddytls"
	"github.com/go-acme/lego/v3/providers/dns/cloudflare"
)

func init() {
	caddytls.RegisterDNSProvider("cloudflare", NewDNSProvider)
}

// NewDNSProvider returns a new Cloudflare DNS challenge provider.
// The credentials are interpreted as follows:
//
// len(0): use credentials from environment
// len(2): credentials[0] = Email address
//
//	credentials[1] = API key
func NewDNSProvider(credentials ...string) (caddytls.ChallengeProvider, error) {
	switch len(credentials) {
	case 0:
		return cloudflare.NewDNSProvider()
	case 2:
		config := cloudflare.NewDefaultConfig()
		config.AuthEmail = credentials[0]
		config.AuthKey = credentials[1]
		return cloudflare.NewDNSProviderConfig(config)
	default:
		return nil, errors.New("invalid credentials length")
	}
}

代码的大概意思是可以通过环境变量获取 apikey 和 mail,也可以通过 credentials 这个来获取对应的值

熟悉 go 的小伙伴可以去深入的研究下,原先是想 caddy1 的 Caddyfile 中配完 tls,然后用 caddy2 的 adapt 来自适应,目前发现不可行

caddy2 的那部分代码发生变化,可以看出来完全使用的 json 中 key

package cloudflare

import (
	"time"

	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/caddy/v2/modules/caddytls"
	tlsdns "github.com/caddyserver/tls.dns"
	"github.com/go-acme/lego/v3/challenge"
	"github.com/go-acme/lego/v3/providers/dns/cloudflare"
)

func init() {
	caddy.RegisterModule(Cloudflare{})
}

// CaddyModule returns the Caddy module information.
func (Cloudflare) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "tls.dns.cloudflare",
		New: func() caddy.Module { return new(Cloudflare) },
	}
}

// Cloudflare configures a solver for the ACME DNS challenge.
//
// Please see the following documentation about which credentials
// to supply: https://go-acme.github.io/lego/dns/cloudflare/#api-tokens.
type Cloudflare struct {
	// An API token with the scoped to all applicable domains with the
	// following permissions:
	//
	// - Zone / Zone / Read
	// - Zone / DNS / Edit
	//
	// Or, if you prefer a more strict set of privileges: give this token
	// only the `Zone / DNS / Edit` permission, scoped only to the domains
	// you want to manage certificates for, then provide a ZoneAPIToken
	// scoped to all your zones with the `Zone / Zone / Read` permission.
	APIToken string `json:"api_token,omitempty"`

	// An optional API token used in conjunction with APIToken, only
	// needed if you prefer a stricter set of privileges. If used, this
	// API token must have the `Zone / Zone / Read` for all zones.
	ZoneAPIToken string `json:"zone_api_token,omitempty"`

	tlsdns.CommonConfig
}

// NewDNSProvider returns a DNS challenge solver.
func (wrapper Cloudflare) NewDNSProvider() (challenge.Provider, error) {
	cfg := cloudflare.NewDefaultConfig()
	if wrapper.APIToken != "" {
		cfg.AuthToken = wrapper.APIToken
	}
	if wrapper.ZoneAPIToken != "" {
		cfg.ZoneToken = wrapper.ZoneAPIToken
	}
	if wrapper.CommonConfig.TTL != 0 {
		cfg.TTL = wrapper.CommonConfig.TTL
	}
	if wrapper.CommonConfig.PropagationTimeout != 0 {
		cfg.PropagationTimeout = time.Duration(wrapper.CommonConfig.PropagationTimeout)
	}
	if wrapper.CommonConfig.PollingInterval != 0 {
		cfg.PollingInterval = time.Duration(wrapper.CommonConfig.PollingInterval)
	}
	if wrapper.CommonConfig.HTTPClient != nil {
		cfg.HTTPClient = wrapper.CommonConfig.HTTPClient.HTTPClient()
	}
	return cloudflare.NewDNSProviderConfig(cfg)
}

// Interface guard
var _ caddytls.DNSProviderMaker = (*Cloudflare)(nil)

我的 caddyfile 转成 json,tls 部分如下

"tls": {
      "automation": {
        "policies": [{
          "hosts": ["solo.mufengs.com"],
          "management": {
            "challenges": {
              "dns": {
                "provider": "cloudflare",
                "api_token": "pSSnFQj",
                "base_url": "mufengs.com"
              }
            },
            "module": "acme"
          }
        }]
      }
    }

可以将上面部分直接拷到你的 josn 中 apps 那一层中

启动 caddy

caddy run --config /path/to/caddy.json

搞定收工,再次感谢 lizhongyue248

  • Caddy

    Caddy 是一款默认自动启用 HTTPS 的 HTTP/2 Web 服务器。

    10 引用 • 54 回帖 • 125 关注
  • Cloudflare
    4 引用 • 28 回帖
2 操作
yuanhenglizhen 在 2020-03-30 17:43:23 更新了该帖
yuanhenglizhen 在 2020-03-30 17:11:23 置顶了该帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • yuanhenglizhen 4 评论

    @88250 顺便说下 cloudflare 在社区的标签有问题,会自动转换成云计算

    感谢反馈,已经修复。 本文的代码块好像有问题,麻烦检查一下。
    88250
    @88250 收到,复制导致的。粘贴的时候会有 html 标签
    yuanhenglizhen
    @mufengcoding 有空的话可以给 Vditor 项目提 issue,谢谢 ❤️
    88250
    @88250 好的格式已修复
    yuanhenglizhen 1
  • yuanhenglizhen 2 评论
    是你提的呀,但是我没能重现。可以具体说一下重现步骤么?
    Vanessa
    @Vanessa 就是你复制本文内容,然后粘贴到随见即所得模式下,就会有这样的
    yuanhenglizhen 1
  • winggy3

    博主你好,我之前用 caddy 1.0.4 在 VPS 上反向代理了一个网站与一个 websocket 端口,并且通过 cloudflare cdn 中转。之前跑得好好的,前几天参照你另一篇博文手动修改 main.go 编译了带 tls.dns.cloudflare 模块的 caddy v.2.1.1,手贱升级 v2 之后发现踩了大坑……想重新编译 1.0.4 版发现官方居然已经将 V1 的全部链接下线了……没办法重新编译带 cloudflare 的 v1 caddy。没办法我一个 Linux 只会基本皮毛的菜鸡,只能在官方指引和中文资料不全情况下硬靠 Google 搜索把 caddyfile 写好,好不容易可以运行起来了,还是不停报错……不知道博主是否愿意帮忙把脉诊断 😭

    Caddyfile 内容:

    {
      debug
      http_port   80
      https_port  443
      admin   off
      key_type p384
    }
    
    domain1.com
    {
    header {
      Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
      X-XSS-Protection "1; mode=block;"
      X-Content-Type-Options nosniff
      X-Frame-Options DENY
    }
    
      {
      @http {
        protocol http
        }
      redir @http https://domain1.com
      }
    
      encode gzip
      root * /var/lib/caddy/domain1.com
      tls {
      dns cloudflare <cloudflare_dns_api_key>
      protocols tls1.2 tls1.3
      }
    
      log {
        output file /var/log/access.log 
        format single_field common_log
      }
    
      reverse_proxy https://reverse.domain1.com:443
    
      @proxyport {
      header Connection *Upgrade*
      header Upgrade    websocket
      }
      reverse_proxy @proxyport 127.0.0.1:1024
    }
    
    domain2.com
    {
    header {
      Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
      X-XSS-Protection "1; mode=block;"
      X-Content-Type-Options nosniff
      X-Frame-Options DENY
    }
    
     {
      @http {
        protocol http
      }
      redir @http https://domain2.com
      }
    
      encode gzip
      root * /var/lib/caddy/domain2.com
      tls email@example.com {
      protocols tls1.2 tls1.3
      }
    
      log {
        output file /var/log/access.log
        format single_field common_log
      }
    
      reverse_proxy https://reverse.domain2.com:443
    
      @proxyport {
      header Connection *Upgrade*
      header Upgrade    websocket
      }
      reverse_proxy @proxyport 127.0.0.1:1024
    }
    

    caddy.service 内容

    # caddy.service
    #
    # For using Caddy with a config file.
    #
    # Make sure the ExecStart and ExecReload commands are correct
    # for your installation.
    #
    # See https://caddyserver.com/docs/install for instructions.
    #
    # WARNING: This service does not use the --resume flag, so if you
    # use the API to make changes, they will be overwritten by the
    # Caddyfile next time the service is restarted. If you intend to
    # use Caddy's API to configure it, add the --resume flag to the
    # `caddy run` command or use the caddy-api.service file instead.
    
    [Unit]
    Description=Caddy
    Documentation=https://caddyserver.com/docs/
    After=network.target
    
    [Service]
    User=www-data
    Group=www-data
    Environment=CADDYPATH=/etc/caddy/ssl
    ExecStart=/usr/local/bin/caddy run --environ --config /etc/caddy/Caddyfile
    ExecReload=/usr/local/bin/caddy reload --config /etc/caddy/Caddyfile
    TimeoutStopSec=5s
    LimitNOFILE=1048576
    LimitNPROC=512
    PrivateTmp=true
    ProtectSystem=full
    AmbientCapabilities=CAP_NET_BIND_SERVICE
    
    [Install]
    WantedBy=multi-user.target
    
    

    然而跑的时候一直报错

    ● caddy.service - Caddy
    Loaded: loaded (/etc/systemd/system/caddy.service; enabled)
    Active: active (running) since Wed 2020-08-12 17:15:28 HKT; 5s ago
    Docs: https://caddyserver.com/docs/
    Main PID: 30943 (caddy)
    CGroup: /system.slice/caddy.service
    └─30943 /usr/local/bin/caddy run --environ --config /etc/caddy/Caddyfile
    
    Aug 12 17:15:33 debian caddy[30943]: 2020/08/12 17:15:33 http: TLS handshake error from X.X.X.X:42468: no certificate available for 'domain1.com'
    
    

    不知道是证书路径,还是 let's encrypt 的问题。不胜感谢。

    2 回复
    3 操作
    winggy3 在 2020-08-12 21:11:45 更新了该回帖
    winggy3 在 2020-08-12 18:30:33 更新了该回帖
    winggy3 在 2020-08-12 18:15:44 更新了该回帖
  • winggy3

    差点忘了……补充一下 caddy.service 内容

    # caddy.service
    #
    # For using Caddy with a config file.
    #
    # Make sure the ExecStart and ExecReload commands are correct
    # for your installation.
    #
    # See https://caddyserver.com/docs/install for instructions.
    #
    # WARNING: This service does not use the --resume flag, so if you
    # use the API to make changes, they will be overwritten by the
    # Caddyfile next time the service is restarted. If you intend to
    # use Caddy's API to configure it, add the --resume flag to the
    # `caddy run` command or use the caddy-api.service file instead.
    
    [Unit]
    Description=Caddy
    Documentation=https://caddyserver.com/docs/
    After=network.target
    
    [Service]
    User=www-data
    Group=www-data
    Environment=CADDYPATH=/etc/caddy/ssl
    ExecStart=/usr/local/bin/caddy run --environ --config /etc/caddy/Caddyfile
    ExecReload=/usr/local/bin/caddy reload --config /etc/caddy/Caddyfile
    TimeoutStopSec=5s
    LimitNOFILE=1048576
    LimitNPROC=512
    PrivateTmp=true
    ProtectSystem=full
    AmbientCapabilities=CAP_NET_BIND_SERVICE
    
    [Install]
    WantedBy=multi-user.target
    
    
    1 操作
    winggy3 在 2020-08-12 18:30:15 更新了该回帖
  • yuanhenglizhen

    image.png你这是有效域名吗

  • yuanhenglizhen

    你这是 caddy 想证书申请中心申请证书的时候出错了

    1 回复
  • winggy3 1 赞同

    感谢博主~!果真是证书存储路径的问题,之前没有留意 caddy V2 已经改用 XDG 目录规范,以为可以继续沿用 caddy v1 的 www-data 用户和证书存储路径,后来搜索才知道 caddy V2 的证书存储路径是用户目录下面的/.local/share/caddy/,于是创建/var/www/.local/share/caddy/路径并且赋予 www-data 用户 0770 权限 caddy 就可以正常申请证书下来了。

    v2 配置和 v1 差别比较大,目前 v2 没多少中文教程,硬啃生肉英文有些地方也不是很明白。上面的配置文件域名是参考论坛的一般做法把真实域名和 IP 隐藏了,见谅。现在证书问题已经解决,v2ray websocket 也已经解决,v2ray 后端已经可以和客户端正常工作了。之后剩下的大问题就是网站反代的问题了,第一个域名是用了 cloudflare 的 cdn,打开显示 403 错误;第二个域名是直接访问的,显示 525 错误。后来搜索了一下才知道原来要加入几行 header_up 命令才行。最终总算是基本完满解决了 caddy v1 升级到 v2 的配置文件问题。最终的 Caddyfile 配置文件如下:

    {
    	debug
    	http_port 80
    	https_port 443
    	admin off
    	key_type p384
    }
    
    domain1.com {
    	header {
    		Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
    		X-XSS-Protection "1; mode=block;"
    		X-Content-Type-Options nosniff
    		X-Frame-Options DENY
    	}
    
    	encode gzip
    	root * /var/lib/caddy/domain1.com
    	file_server
    	tls {
    		dns cloudflare <cloudflare_dns_api_token>
    		protocols tls1.2 tls1.3
    	}
    
    	log {
    		output file /var/log/access.log
    		format single_field common_log
    	}
    
    	reverse_proxy * https://reverse.domain1.net:443 {
    		header_up Host reverse.domain1.net
    		header_up X-Real-IP {http.request.remote.host}
    		header_up X-Forwarded-For {http.request.remote.host}
    		header_up X-Forwarded-Port {http.request.port}
    		header_up X-Forwarded-Proto {http.request.scheme}
    		header_down Set-Cookie reverse.domain1.net domain1.com
    	}
    
    	@proxyport {
    		path /v2rayport
    		header Connection *Upgrade*
    		header Upgrade websocket
    	}
    	reverse_proxy @proxyport 127.0.0.1:1024
    }
    
    domain2.com {
    	header {
    		Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
    		X-XSS-Protection "1; mode=block;"
    		X-Content-Type-Options nosniff
    		X-Frame-Options DENY
    	}
    
    	encode gzip
    	root * /var/lib/caddy/domain2.com
    	file_server
    	tls email@example.com {
    		protocols tls1.2 tls1.3
    	}
    
    	log {
    		output file /var/log/access.log
    		format single_field common_log
    	}
    
    	reverse_proxy * http://reverse.domain2.net:80 {
    		header_up Host reverse.domain2.net
    		header_up X-Real-IP {http.request.remote.host}
    		header_up X-Forwarded-For {http.request.remote.host}
    		header_up X-Forwarded-Port {http.request.port}
    		header_up X-Forwarded-Proto {http.request.scheme}
    		header_down Set-Cookie reverse.domain2.net domain2.com
    	}
    
    	@proxyport {
    		path /v2rayport
    		header Connection *Upgrade*
    		header Upgrade websocket
    	}
    	reverse_proxy @proxyport 127.0.0.1:1024
    }
    
    1 回复
    5 操作
    winggy3 在 2020-08-17 01:30:41 更新了该回帖
    winggy3 在 2020-08-17 01:17:04 更新了该回帖
    winggy3 在 2020-08-17 01:16:21 更新了该回帖
    winggy3 在 2020-08-17 01:12:54 更新了该回帖 winggy3 在 2020-08-15 22:53:32 更新了该回帖
  • yuanhenglizhen

    真棒 👍

  • wzy911

    你好,楼主,刚刚用了你的方法,发现 main.go 里的地址下已经无法找到编译所需文件,我用的是 caddy v2.4.0,已经弄了好几天了,都没弄明白,麻烦帮我研究一些吧,非常感谢~

请输入回帖内容 ...