0x00 前言

之前我写过一篇自建Zerotier Controller的文章,但是昨天发现它NAT打洞又失败了!我很愤怒,于是卸载了所有节点上的Zerotier,准备换用Tailscale。

我们当然不能向大企业施舍给穷人的免费套餐低头(虽然Tailscale Inc.好像也不算大企业),因此在本篇教程中,我们将会使用第三方开源控制器Headscale 建立自己的Tailscale虚拟局域网(即tailnet)。

如果你想了解NAT打洞/穿越是如何做到的,请阅读此文章

0x01 安装headscale控制器

由于Tailscale并不像Zerotier那样,控制器与客户端共用一套代码,也就代表Headscale不能像Zerotier Controller那样兼职作为客户端,不过因此我们也可以放心地将Headscale部署至容器内,实现灵活部署。

同时,由于headscale默认是没有Web UI的,我们会使用第三方Web UI让我们的操作更方便。

0x01.199…9A 假设你有一台Linux服务器:

  1. 安装docker-compose
  2. 使用如下配置:
version: '3.5'
services:
  headscale:
    image: headscale/headscale:latest-alpine
    container_name: headscale
    volumes:
      - ./container-config:/etc/headscale
      - ./container-data/data:/var/lib/headscale
    ports:
      - 3000:8080 #不用3000也行,随便你
    command: headscale serve
    restart: unless-stopped
  headscale-ui:
    image: ghcr.io/gurucomputing/headscale-ui:latest
    restart: unless-stopped
    container_name: headscale-ui
    ports:
      - 3100:80 #虽然随便但是都要转发出来,别直接删了

container-config文件夹内建立config.yaml,写入如下配置:

---
# 没有中文标注的就是暂时还用不上的
# headscale will look for a configuration file named `config.yaml` (or `config.json`) in the following order:
#
# - `/etc/headscale`
# - `~/.headscale`
# - current working directory

# The url clients will connect to.
# Typically this will be a domain like:
#
# https://myheadscale.example.com:443
#

# 这里是你的Headscale控制器URL,是经过反代的之后的那个
# Tailscale客户端要通过这个URL和控制器建立连接
# https证书我们后面会通过Caddy套上,别急
server_url: https://hs.xxx.xx:xxx

# Address to listen to / bind to on the server
#
# 这里是需要被反代的端口,就是上文中从3000端口映射出来的
# 如果你要改这里,记得连docker-compose.yaml一起改了
listen_addr: 0.0.0.0:8080

# Address to listen to /metrics, you may want
# to keep this endpoint private to your internal
# network
#
metrics_listen_addr: 127.0.0.1:3090

# Address to listen for gRPC.
# gRPC is used for controlling a headscale server
# remotely with the CLI
# Note: Remote access _only_ works if you have
# valid certificates.
# 你使用Headscale CLI的时候要通过gRPC控制
grpc_listen_addr: 0.0.0.0:50443

# Allow the gRPC admin interface to run in INSECURE
# mode. This is not recommended as the traffic will
# be unencrypted. Only enable if you know what you
# are doing.
# 打开!一定要打开!因为https加密是在反代服务器完成的,不开的话
# gRPC服务器就不会启用,你就用不了CLI
grpc_allow_insecure: true

# Private key used encrypt the traffic between headscale
# and Tailscale clients.
# The private key file which will be
# autogenerated if it's missing
# 知道你很急,不知道私钥该怎么生成,但是别急,它运行后会自己生成的
private_key_path: /var/lib/headscale/private.key

# The Noise section includes specific configuration for the
# TS2021 Noise procotol
noise:
  # The Noise private key is used to encrypt the
  # traffic between headscale and Tailscale clients when
  # using the new Noise-based protocol. It must be different
  # from the legacy private key.
  private_key_path: /var/lib/headscale/noise_private.key

# List of IP prefixes to allocate tailaddresses from.
# Each prefix consists of either an IPv4 or IPv6 address,
# and the associated prefix length, delimited by a slash.
# 你希望给Tailscale网络上的设备分配什么IP段
# 考虑到tailscale客户端无论如何都会占走100.100.64.0/10
# 建议你也用这个网段
# 如果你不巧是阿里云用户,那么这个网段会和内部DNS冲突,后面会贴一篇解决问题的文章
ip_prefixes:
  # - fd7a:115c:a1e0::/48
  - 100.64.0.0/10

# DERP is a relay system that Tailscale uses when a direct
# connection cannot be established.
# https://tailscale.com/blog/how-tailscale-works/#encrypted-tcp-relays-derp
#
# headscale needs a list of DERP servers that can be presented
# to the clients.
# 这里你可以启用Headscale内置的DERP服务器,也就是帮助你中继流量与NAT打洞的服务器
# 因为我感觉东京的公共DERP服务器够用了所以还没研究这块,先不管⑧
derp:
  server:
    # If enabled, runs the embedded DERP server and merges it into the rest of the DERP config
    # The Headscale server_url defined above MUST be using https, DERP requires TLS to be in place
    enabled: false

    # Region ID to use for the embedded DERP server.
    # The local DERP prevails if the region ID collides with other region ID coming from
    # the regular DERP config.
    region_id: 999

    # Region code and name are displayed in the Tailscale UI to identify a DERP region
    region_code: "headscale"
    region_name: "Headscale Embedded DERP"

    # Listens in UDP at the configured address for STUN connections to help on NAT traversal.
    # When the embedded DERP server is enabled stun_listen_addr MUST be defined.
    #
    # For more details on how this works, check this great article: https://tailscale.com/blog/how-tailscale-works/
    stun_listen_addr: "0.0.0.0:3478"

  # List of externally available DERP maps encoded in JSON
  urls:
    - https://controlplane.tailscale.com/derpmap/default

  # Locally available DERP map files encoded in YAML
  #
  # This option is mostly interesting for people hosting
  # their own DERP servers:
  # https://tailscale.com/kb/1118/custom-derp-servers/
  #
  # paths:
  #   - /etc/headscale/derp-example.yaml
  paths: []

  # If enabled, a worker will be set up to periodically
  # refresh the given sources and update the derpmap
  # will be set up.
  auto_update_enabled: true

  # How often should we check for DERP updates?
  update_frequency: 24h

# Disables the automatic check for headscale updates on startup
disable_check_updates: false

# Time before an inactive ephemeral node is deleted?
ephemeral_node_inactivity_timeout: 30m

# Period to check for node updates in the tailnet. A value too low will severily affect
# CPU consumption of Headscale. A value too high (over 60s) will cause problems
# to the nodes, as they won't get updates or keep alive messages in time.
# In case of doubts, do not touch the default 10s.
node_update_check_interval: 10s

# SQLite config
db_type: sqlite3
db_path: /var/lib/headscale/db.sqlite

# # Postgres config
# If using a Unix socket to connect to Postgres, set the socket path in the 'host' field and leave 'port' blank.
# db_type: postgres
# db_host: localhost
# db_port: 5432
# db_name: headscale
# db_user: foo
# db_pass: bar
# db_ssl: false

### TLS configuration
#
## Let's encrypt / ACME
#
# headscale supports automatically requesting and setting up
# TLS for a domain with Let's Encrypt.
#
# URL to ACME directory
acme_url: https://acme-v02.api.letsencrypt.org/directory

# Email to register with ACME provider
acme_email: ""

# Domain name to request a TLS certificate for:
tls_letsencrypt_hostname: ""

# Client (Tailscale/Browser) authentication mode (mTLS)
# Acceptable values:
# - disabled: client authentication disabled
# - relaxed: client certificate is required but not verified
# - enforced: client certificate is required and verified
tls_client_auth_mode: relaxed

# Path to store certificates and metadata needed by
# letsencrypt
tls_letsencrypt_cache_dir: /var/lib/headscale/cache

# Type of ACME challenge to use, currently supported types:
# HTTP-01 or TLS-ALPN-01
# See [docs/tls.md](docs/tls.md) for more information
tls_letsencrypt_challenge_type: HTTP-01
# When HTTP-01 challenge is chosen, letsencrypt must set up a
# verification endpoint, and it will be listning on:
# :http = port 80
tls_letsencrypt_listen: ":http"

## Use already defined certificates:
tls_cert_path: ""
tls_key_path: ""

log_level: info

# Path to a file containg ACL policies.
# ACLs can be defined as YAML or HUJSON.
# https://tailscale.com/kb/1018/acls/
acl_policy_path: ""

## DNS
#
# headscale supports Tailscale's DNS configuration and MagicDNS.
# Please have a look to their KB to better understand the concepts:
#
# - https://tailscale.com/kb/1054/dns/
# - https://tailscale.com/kb/1081/magicdns/
# - https://tailscale.com/blog/2021-09-private-dns-with-magicdns/
#
dns_config:
  # List of DNS servers to expose to clients.
  nameservers:
    - 223.5.5.5
    - 223.6.6.6

  # Split DNS (see https://tailscale.com/kb/1054/dns/),
  # list of search domains and the DNS to query for each one.
  #
  # 这是阿里云DNS问题解决方案的一部分,如果你不是阿里云用户可以不管这个
  restricted_nameservers:
    mirrors.cloud.aliyuncs.com:
      - 100.100.2.136
  #   darp.headscale.net:
  #     - 1.1.1.1
  #     - 8.8.8.8

  # Search domains to inject.
  domains: []

  # Whether to use [MagicDNS](https://tailscale.com/kb/1081/magicdns/).
  # Only works if there is at least a nameserver defined.
  # 很抱歉现在才告诉你
  # 但是Tailscale有一个很坏的缺点,就是它不能自定义节点的IP,控制器给分配什么就只能是什么
  # 所以你肯定会需要Magic DNS来帮你辨识节点的!
  magic_dns: true

  # Defines the base domain to create the hostnames for MagicDNS.
  # `base_domain` must be a FQDNs, without the trailing dot.
  # The FQDN of the hosts will be
  # `hostname.namespace.base_domain` (e.g., _myhost.mynamespace.example.com_).
  # 显示在Magic DNS里的设备域名,随便写写
  base_domain: hs.xxx.xx

# Unix socket used for the CLI to connect without authentication
# Note: for local development, you probably want to change this to:
# unix_socket: ./headscale.sock
unix_socket: /var/run/headscale.sock
unix_socket_permission: "0770"
#
# headscale supports experimental OpenID connect support,
# it is still being tested and might have some bugs, please
# help us test it.
# OpenID Connect
# oidc:
#   issuer: "https://your-oidc.issuer.com/path"
#   client_id: "your-oidc-client-id"
#   client_secret: "your-oidc-client-secret"
#
#   Customize the scopes used in the OIDC flow, defaults to "openid", "profile" and "email" and add custom query
#   parameters to the Authorize Endpoint request. Scopes default to "openid", "profile" and "email".
#
#   scope: ["openid", "profile", "email", "custom"]
#   extra_params:
#     domain_hint: example.com
#
#   List allowed principal domains and/or users. If an authenticated user's domain is not in this list, the
#   authentication request will be rejected.
#
#   allowed_domains:
#     - example.com
#   allowed_users:
#     - alice@example.com
#
#   If `strip_email_domain` is set to `true`, the domain part of the username email address will be removed.
#   This will transform `first-name.last-name@example.com` to the namespace `first-name.last-name`
#   If `strip_email_domain` is set to `false` the domain part will NOT be removed resulting to the following
#   namespace: `first-name.last-name.example.com`
#
#   strip_email_domain: true

# Logtail configuration
# Logtail is Tailscales logging and auditing infrastructure, it allows the control panel
# to instruct tailscale nodes to log their activity to a remote server.
logtail:
  # Enable logtail for this headscales clients.
  # As there is currently no support for overriding the log server in headscale, this is
  # disabled by default. Enabling this will make your clients send logs to Tailscale Inc.
  enabled: false

# Enabling this option makes devices prefer a random port for WireGuard traffic over the
# default static port 41641. This option is intended as a workaround for some buggy
# firewall devices. See https://tailscale.com/kb/1181/firewalls/ for more information.
randomize_client_port: false

好吧可能确实有点长这是我从repo里直接拉下来的配置不过我加了点中文注释方便你理解请一定要全部看完如果你发现有什么奇奇怪怪的错误可能是因为我放在这里的配置文件版本老了有字段改变了总之你可以自己去repo看一看!

现在我们可以使用docker-compose up -d 来启动服务器了.

0x01.333…3 如果你居然还没有一台Linux服务器…!

请您选购:轻量应用服务器Lighthouse - 腾讯云
之后返回阅读 0x01.199…9A 章节

0x01.4CC…CD 配置反代,暴露你的Headscale服务器!

当然,我们会选择最潮最炫酷最简洁的Caddy帮助我们完成此项工作。如果你还是顽固不化的nginx老用户,相信你已经有独立完成配置的能力了!

我们使用如下Caddyfile启动服务器:

hs.xxx.xx {
        reverse_proxy http://127.0.0.1:3000 
        handle /web* {
                reverse_proxy http://127.0.0.1:3100
        }
}

但是不要急,Web UI需要Headscale提供的API Key才能工作,所以让我们先来生成它:

  1. 在项目目录,运行
    docker-compose exec headscale headscale apikeys create -e 720d
    

这会生成一个720天有效期的API Key,应该够你用了。

之后我们打开https://hs.xxx.xx/web,在Settings栏输入https://xxx.xx,在APIKey栏输入刚刚生成的key并保存,现在你就已经搭好了!

0x01.666…6 简单讲一下Web UI

在界面里,你可以看到三大Tab:User、Device与Settings,其中User其实对应headscale里的namespace,记得一定要先创建一个。

为了加入设备更加方便,我们还可以在这里生成一个PreAuth key,让申请加入的设备可以直接获得批准。具体操作自己试一下就知道了哈,不懂的话别勾选Ephemeral就可以。

0x02 安装Tailscale客户端

你可以在此处查阅官方安装文档。

如果你是iOS人,很高兴你可以看到这里,不过你应该关闭这篇文章了,因为Tailscale的iOS客户端目前还不支持自定义服务器>_<

0x02.199…9A 对于Linux客户端:

  1. 你可以使用一键脚本:

    curl -fsSL https://tailscale.com/install.sh | sh
    

    如果一键脚本不巧失败了,那么你可以查阅官网下载页面Manually install on部分。

  2. 运行如下命令:

    sudo tailscale up --accept-routes --login-server=https://hs.xxx.xx --auth-key=xxxxxxxxxxxxxxxxxxxxxxxxxx(你刚刚申请的PreAuth Key)
    

    你的设备就加入Tailscale网络了!

    如果你没有申请PreAuth Key,那也可以,在tailscale up之后它会给你提供一个链接,复制其中key的值,这就是这个设备的Device Key,在Web UI中的Device栏里选择添加设备,并在提示框内输入Device Key,也可以完成添加。

0x02.333…34 对于Windows客户端:

  1. 首先下载安装包,这就不用说了;
    在运行后,右键Tailscale在任务栏的图标,在Preferences菜单中勾选Run unattended
  2. 打开regedit,导航到HKEY_LOCAL_MACHINE\SOFTWARE\Tailscale IPN,新建字符串值,名称为LoginURL,数据为https://hs.xxx.xx,之后再次启动Tailscale客户端并登录。

0x02.4CC…C 对于Android客户端:

  1. 首先下载安装包,在哪下载随你便,不过至少得是1.30及之后的版本,再老的添加不了第三方服务器;
  2. 进入主界面,点击右上角菜单选项,你可能只能看到一个版本号,不要急,多点几次,就会出现一个Change Server的选项,输入你的Headscale服务器URL(https://hs.xxx.xx)并保存。
  3. 在主界面选择其它方式登录,之后你就可以从提供的链接里获得Device Key并在Web UI中添加设备。

0x03 完成!

现在你已经拥有了自己的tailscale网络,可以享受Tailscale带来的各种优势了!

0x04 更高级一点的东西……

0x04.199…98 配置Subnet Router

也许你有一些设备需要连接到Tailscale网络,但是它们的软硬件不足以运行Tailscale,这怎么办呢?

有了Tailscale,你可以将局域网内的任意设备作为Subnet Router,通过它访问整个局域网内的设备!

具体教程我摸了,你看官方文档自己参悟一下:Subnet routers and traffic relay nodes

0x04.333…34 将任意客户端配置为出口节点

出口节点模式类似于传统的C/S架构VPN,你的所有流量都会被转发到出口节点上,在某些特殊情况下会很有用。

官方文档:Exit Nodes (route all traffic)

0x04.CCC…C 尝试Tailscale客户端的其它好东西

  1. tailscale netcheck: 查看你的IP地址与到各大公共DERP服务器之间的延迟;
  2. tailscale status: 查看各客户端的连接状态,是直连还是中继一目了然;
  3. tailscale nc/ssh: 顾名思义;
  4. tailscale file: 即Taildrop功能,在要发送文件的客户端上运行tailscale file cp <path> <host-ip>:,在要接受文件的客户端上运行tailscale file get,就可以方便地传输文件!

0x05 一些可能会遇到的小问题…

0x05.199…98 在阿里云上使用

Q: 我在阿里云服务器上用了Tailscale,结果用不了100.100.2.136这个内网DNS,导致我连不上内网软件源了,怎么办?

A: 阅读文章:一次Tailscale网络问题的调试过程