| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754 |
- // Copyright (c) Tailscale Inc & AUTHORS
- // SPDX-License-Identifier: BSD-3-Clause
- //go:build linux
- package linuxfw
- import (
- "encoding/binary"
- "encoding/hex"
- "errors"
- "fmt"
- "net"
- "net/netip"
- "reflect"
- "strings"
- "github.com/google/nftables"
- "github.com/google/nftables/expr"
- "golang.org/x/sys/unix"
- "tailscale.com/net/tsaddr"
- "tailscale.com/types/logger"
- "tailscale.com/types/ptr"
- )
- const (
- chainNameForward = "ts-forward"
- chainNameInput = "ts-input"
- chainNamePostrouting = "ts-postrouting"
- )
- // chainTypeRegular is an nftables chain that does not apply to a hook.
- const chainTypeRegular = ""
- type chainInfo struct {
- table *nftables.Table
- name string
- chainType nftables.ChainType
- chainHook *nftables.ChainHook
- chainPriority *nftables.ChainPriority
- chainPolicy *nftables.ChainPolicy
- }
- type nftable struct {
- Proto nftables.TableFamily
- Filter *nftables.Table
- Nat *nftables.Table
- }
- // nftablesRunner implements a netfilterRunner using the netlink based nftables
- // library. As nftables allows for arbitrary tables and chains, there is a need
- // to follow conventions in order to integrate well with a surrounding
- // ecosystem. The rules installed by nftablesRunner have the following
- // properties:
- // - Install rules that intend to take precedence over rules installed by
- // other software. Tailscale provides packet filtering for tailnet traffic
- // inside the daemon based on the tailnet ACL rules.
- // - As nftables "accept" is not final, rules from high priority tables (low
- // numbers) will fall through to lower priority tables (high numbers). In
- // order to effectively be 'final', we install "jump" rules into conventional
- // tables and chains that will reach an accept verdict inside those tables.
- // - The table and chain conventions followed here are those used by
- // `iptables-nft` and `ufw`, so that those tools co-exist and do not
- // negatively affect Tailscale function.
- type nftablesRunner struct {
- conn *nftables.Conn
- nft4 *nftable
- nft6 *nftable
- v6Available bool
- v6NATAvailable bool
- }
- func (n *nftablesRunner) ensurePreroutingChain(dst netip.Addr) (*nftables.Table, *nftables.Chain, error) {
- polAccept := nftables.ChainPolicyAccept
- table := n.getNFTByAddr(dst)
- nat, err := createTableIfNotExist(n.conn, table.Proto, "nat")
- if err != nil {
- return nil, nil, fmt.Errorf("error ensuring nat table: %w", err)
- }
- // ensure prerouting chain exists
- preroutingCh, err := getOrCreateChain(n.conn, chainInfo{
- table: nat,
- name: "PREROUTING",
- chainType: nftables.ChainTypeNAT,
- chainHook: nftables.ChainHookPrerouting,
- chainPriority: nftables.ChainPriorityNATDest,
- chainPolicy: &polAccept,
- })
- if err != nil {
- return nil, nil, fmt.Errorf("error ensuring prerouting chain: %w", err)
- }
- return nat, preroutingCh, nil
- }
- func (n *nftablesRunner) AddDNATRule(origDst netip.Addr, dst netip.Addr) error {
- nat, preroutingCh, err := n.ensurePreroutingChain(dst)
- if err != nil {
- return err
- }
- var daddrOffset, fam, dadderLen uint32
- if origDst.Is4() {
- daddrOffset = 16
- dadderLen = 4
- fam = unix.NFPROTO_IPV4
- } else {
- daddrOffset = 24
- dadderLen = 16
- fam = unix.NFPROTO_IPV6
- }
- dnatRule := &nftables.Rule{
- Table: nat,
- Chain: preroutingCh,
- Exprs: []expr.Any{
- &expr.Payload{
- DestRegister: 1,
- Base: expr.PayloadBaseNetworkHeader,
- Offset: daddrOffset,
- Len: dadderLen,
- },
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: origDst.AsSlice(),
- },
- &expr.Immediate{
- Register: 1,
- Data: dst.AsSlice(),
- },
- &expr.NAT{
- Type: expr.NATTypeDestNAT,
- Family: fam,
- RegAddrMin: 1,
- },
- },
- }
- n.conn.InsertRule(dnatRule)
- return n.conn.Flush()
- }
- func (n *nftablesRunner) DNATNonTailscaleTraffic(tunname string, dst netip.Addr) error {
- nat, preroutingCh, err := n.ensurePreroutingChain(dst)
- if err != nil {
- return err
- }
- var famConst uint32
- if dst.Is4() {
- famConst = unix.NFPROTO_IPV4
- } else {
- famConst = unix.NFPROTO_IPV6
- }
- dnatRule := &nftables.Rule{
- Table: nat,
- Chain: preroutingCh,
- Exprs: []expr.Any{
- &expr.Meta{Key: expr.MetaKeyOIFNAME, Register: 1},
- &expr.Cmp{
- Op: expr.CmpOpNeq,
- Register: 1,
- Data: []byte(tunname),
- },
- &expr.Immediate{
- Register: 1,
- Data: dst.AsSlice(),
- },
- &expr.NAT{
- Type: expr.NATTypeDestNAT,
- Family: famConst,
- RegAddrMin: 1,
- },
- },
- }
- n.conn.AddRule(dnatRule)
- return n.conn.Flush()
- }
- func (n *nftablesRunner) AddSNATRuleForDst(src, dst netip.Addr) error {
- polAccept := nftables.ChainPolicyAccept
- table := n.getNFTByAddr(dst)
- nat, err := createTableIfNotExist(n.conn, table.Proto, "nat")
- if err != nil {
- return fmt.Errorf("error ensuring nat table exists: %w", err)
- }
- // ensure postrouting chain exists
- postRoutingCh, err := getOrCreateChain(n.conn, chainInfo{
- table: nat,
- name: "POSTROUTING",
- chainType: nftables.ChainTypeNAT,
- chainHook: nftables.ChainHookPostrouting,
- chainPriority: nftables.ChainPriorityNATSource,
- chainPolicy: &polAccept,
- })
- if err != nil {
- return fmt.Errorf("error ensuring postrouting chain: %w", err)
- }
- var daddrOffset, fam, daddrLen uint32
- if dst.Is4() {
- daddrOffset = 16
- daddrLen = 4
- fam = unix.NFPROTO_IPV4
- } else {
- daddrOffset = 24
- daddrLen = 16
- fam = unix.NFPROTO_IPV6
- }
- snatRule := &nftables.Rule{
- Table: nat,
- Chain: postRoutingCh,
- Exprs: []expr.Any{
- &expr.Payload{
- DestRegister: 1,
- Base: expr.PayloadBaseNetworkHeader,
- Offset: daddrOffset,
- Len: daddrLen,
- },
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: dst.AsSlice(),
- },
- &expr.Immediate{
- Register: 1,
- Data: src.AsSlice(),
- },
- &expr.NAT{
- Type: expr.NATTypeSourceNAT,
- Family: fam,
- RegAddrMin: 1,
- },
- },
- }
- n.conn.AddRule(snatRule)
- return n.conn.Flush()
- }
- func (n *nftablesRunner) ClampMSSToPMTU(tun string, addr netip.Addr) error {
- polAccept := nftables.ChainPolicyAccept
- table := n.getNFTByAddr(addr)
- filterTable, err := createTableIfNotExist(n.conn, table.Proto, "filter")
- if err != nil {
- return fmt.Errorf("error ensuring filter table: %w", err)
- }
- // ensure forwarding chain exists
- fwChain, err := getOrCreateChain(n.conn, chainInfo{
- table: filterTable,
- name: "FORWARD",
- chainType: nftables.ChainTypeFilter,
- chainHook: nftables.ChainHookForward,
- chainPriority: nftables.ChainPriorityFilter,
- chainPolicy: &polAccept,
- })
- if err != nil {
- return fmt.Errorf("error ensuring forward chain: %w", err)
- }
- clampRule := &nftables.Rule{
- Table: filterTable,
- Chain: fwChain,
- Exprs: []expr.Any{
- &expr.Meta{Key: expr.MetaKeyOIFNAME, Register: 1},
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: []byte(tun),
- },
- &expr.Meta{Key: expr.MetaKeyL4PROTO, Register: 1},
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: []byte{unix.IPPROTO_TCP},
- },
- &expr.Payload{
- DestRegister: 1,
- Base: expr.PayloadBaseTransportHeader,
- Offset: 13,
- Len: 1,
- },
- &expr.Bitwise{
- DestRegister: 1,
- SourceRegister: 1,
- Len: 1,
- Mask: []byte{0x02},
- Xor: []byte{0x00},
- },
- &expr.Cmp{
- Op: expr.CmpOpNeq,
- Register: 1,
- Data: []byte{0x00},
- },
- &expr.Rt{
- Register: 1,
- Key: expr.RtTCPMSS,
- },
- &expr.Byteorder{
- DestRegister: 1,
- SourceRegister: 1,
- Op: expr.ByteorderHton,
- Len: 2,
- Size: 2,
- },
- &expr.Exthdr{
- SourceRegister: 1,
- Type: 2,
- Offset: 2,
- Len: 2,
- Op: expr.ExthdrOpTcpopt,
- },
- },
- }
- n.conn.AddRule(clampRule)
- return n.conn.Flush()
- }
- // deleteTableIfExists deletes a nftables table via connection c if it exists
- // within the given family.
- func deleteTableIfExists(c *nftables.Conn, family nftables.TableFamily, name string) error {
- t, err := getTableIfExists(c, family, name)
- if err != nil {
- return fmt.Errorf("get table: %w", err)
- }
- if t == nil {
- // Table does not exist, so nothing to delete.
- return nil
- }
- c.DelTable(t)
- if err := c.Flush(); err != nil {
- if t, err = getTableIfExists(c, family, name); t == nil && err == nil {
- // Check if the table still exists. If it does not, then the error
- // is due to the table not existing, so we can ignore it. Maybe a
- // concurrent process deleted the table.
- return nil
- }
- return fmt.Errorf("del table: %w", err)
- }
- return nil
- }
- // getTableIfExists returns the table with the given name from the given family
- // if it exists. If none match, it returns (nil, nil).
- func getTableIfExists(c *nftables.Conn, family nftables.TableFamily, name string) (*nftables.Table, error) {
- tables, err := c.ListTables()
- if err != nil {
- return nil, fmt.Errorf("get tables: %w", err)
- }
- for _, table := range tables {
- if table.Name == name && table.Family == family {
- return table, nil
- }
- }
- return nil, nil
- }
- // createTableIfNotExist creates a nftables table via connection c if it does
- // not exist within the given family.
- func createTableIfNotExist(c *nftables.Conn, family nftables.TableFamily, name string) (*nftables.Table, error) {
- if t, err := getTableIfExists(c, family, name); err != nil {
- return nil, fmt.Errorf("get table: %w", err)
- } else if t != nil {
- return t, nil
- }
- t := c.AddTable(&nftables.Table{
- Family: family,
- Name: name,
- })
- if err := c.Flush(); err != nil {
- return nil, fmt.Errorf("add table: %w", err)
- }
- return t, nil
- }
- type errorChainNotFound struct {
- chainName string
- tableName string
- }
- func (e errorChainNotFound) Error() string {
- return fmt.Sprintf("chain %s not found in table %s", e.chainName, e.tableName)
- }
- // getChainFromTable returns the chain with the given name from the given table.
- // Note that a chain name is unique within a table.
- func getChainFromTable(c *nftables.Conn, table *nftables.Table, name string) (*nftables.Chain, error) {
- chains, err := c.ListChainsOfTableFamily(table.Family)
- if err != nil {
- return nil, fmt.Errorf("list chains: %w", err)
- }
- for _, chain := range chains {
- // Table family is already checked so table name is unique
- if chain.Table.Name == table.Name && chain.Name == name {
- return chain, nil
- }
- }
- return nil, errorChainNotFound{table.Name, name}
- }
- // isTSChain reports whether `name` begins with "ts-" (and is thus a
- // Tailscale-managed chain).
- func isTSChain(name string) bool {
- return strings.HasPrefix(name, "ts-")
- }
- // createChainIfNotExist creates a chain with the given name in the given table
- // if it does not exist.
- func createChainIfNotExist(c *nftables.Conn, cinfo chainInfo) error {
- _, err := getOrCreateChain(c, cinfo)
- return err
- }
- func getOrCreateChain(c *nftables.Conn, cinfo chainInfo) (*nftables.Chain, error) {
- chain, err := getChainFromTable(c, cinfo.table, cinfo.name)
- if err != nil && !errors.Is(err, errorChainNotFound{cinfo.table.Name, cinfo.name}) {
- return nil, fmt.Errorf("get chain: %w", err)
- } else if err == nil {
- // The chain already exists. If it is a TS chain, check the
- // type/hook/priority, but for "conventional chains" assume they're what
- // we expect (in case iptables-nft/ufw make minor behavior changes in
- // the future).
- if isTSChain(chain.Name) && (chain.Type != cinfo.chainType || chain.Hooknum != cinfo.chainHook || chain.Priority != cinfo.chainPriority) {
- return nil, fmt.Errorf("chain %s already exists with different type/hook/priority", cinfo.name)
- }
- return chain, nil
- }
- chain = c.AddChain(&nftables.Chain{
- Name: cinfo.name,
- Table: cinfo.table,
- Type: cinfo.chainType,
- Hooknum: cinfo.chainHook,
- Priority: cinfo.chainPriority,
- Policy: cinfo.chainPolicy,
- })
- if err := c.Flush(); err != nil {
- return nil, fmt.Errorf("add chain: %w", err)
- }
- return chain, nil
- }
- // NetfilterRunner abstracts helpers to run netfilter commands. It is
- // implemented by linuxfw.IPTablesRunner and linuxfw.NfTablesRunner.
- type NetfilterRunner interface {
- // AddLoopbackRule adds a rule to permit loopback traffic to addr. This rule
- // is added only if it does not already exist.
- AddLoopbackRule(addr netip.Addr) error
- // DelLoopbackRule removes the rule added by AddLoopbackRule.
- DelLoopbackRule(addr netip.Addr) error
- // AddHooks adds rules to conventional chains like "FORWARD", "INPUT" and
- // "POSTROUTING" to jump from those chains to tailscale chains.
- AddHooks() error
- // DelHooks deletes rules added by AddHooks.
- DelHooks(logf logger.Logf) error
- // AddChains creates custom Tailscale chains.
- AddChains() error
- // DelChains removes chains added by AddChains.
- DelChains() error
- // AddBase adds rules reused by different other rules.
- AddBase(tunname string) error
- // DelBase removes rules added by AddBase.
- DelBase() error
- // AddSNATRule adds the netfilter rule to SNAT incoming traffic over
- // the Tailscale interface destined for local subnets. An error is
- // returned if the rule already exists.
- AddSNATRule() error
- // DelSNATRule removes the rule added by AddSNATRule.
- DelSNATRule() error
- // HasIPV6 reports true if the system supports IPv6.
- HasIPV6() bool
- // HasIPV6NAT reports true if the system supports IPv6 NAT.
- HasIPV6NAT() bool
- // AddDNATRule adds a rule to the nat/PREROUTING chain to DNAT traffic
- // destined for the given original destination to the given new destination.
- // This is used to forward all traffic destined for the Tailscale interface
- // to the provided destination, as used in the Kubernetes ingress proxies.
- AddDNATRule(origDst, dst netip.Addr) error
- // AddSNATRuleForDst adds a rule to the nat/POSTROUTING chain to SNAT
- // traffic destined for dst to src.
- // This is used to forward traffic destined for the local machine over
- // the Tailscale interface, as used in the Kubernetes egress proxies.
- AddSNATRuleForDst(src, dst netip.Addr) error
- // DNATNonTailscaleTraffic adds a rule to the nat/PREROUTING chain to DNAT
- // all traffic inbound from any interface except exemptInterface to dst.
- // This is used to forward traffic destined for the local machine over
- // the Tailscale interface, as used in the Kubernetes egress proxies.//
- DNATNonTailscaleTraffic(exemptInterface string, dst netip.Addr) error
- // ClampMSSToPMTU adds a rule to the mangle/FORWARD chain to clamp MSS for
- // traffic destined for the provided tun interface.
- ClampMSSToPMTU(tun string, addr netip.Addr) error
- // AddMagicsockPortRule adds a rule to the ts-input chain to accept
- // incoming traffic on the specified port, to allow magicsock to
- // communicate.
- AddMagicsockPortRule(port uint16, network string) error
- // DelMagicsockPortRule removes the rule created by AddMagicsockPortRule,
- // if it exists.
- DelMagicsockPortRule(port uint16, network string) error
- }
- // New creates a NetfilterRunner, auto-detecting whether to use
- // nftables or iptables.
- // As nftables is still experimental, iptables will be used unless
- // either the TS_DEBUG_FIREWALL_MODE environment variable, or the prefHint
- // parameter, is set to one of "nftables" or "auto".
- func New(logf logger.Logf, prefHint string) (NetfilterRunner, error) {
- mode := detectFirewallMode(logf, prefHint)
- switch mode {
- case FirewallModeIPTables:
- return newIPTablesRunner(logf)
- case FirewallModeNfTables:
- return newNfTablesRunner(logf)
- default:
- return nil, fmt.Errorf("unknown firewall mode %v", mode)
- }
- }
- // newNfTablesRunner creates a new nftablesRunner without guaranteeing
- // the existence of the tables and chains.
- func newNfTablesRunner(logf logger.Logf) (*nftablesRunner, error) {
- conn, err := nftables.New()
- if err != nil {
- return nil, fmt.Errorf("nftables connection: %w", err)
- }
- nft4 := &nftable{Proto: nftables.TableFamilyIPv4}
- v6err := checkIPv6(logf)
- if v6err != nil {
- logf("disabling tunneled IPv6 due to system IPv6 config: %v", v6err)
- }
- supportsV6 := v6err == nil
- supportsV6NAT := supportsV6 && checkSupportsV6NAT()
- var nft6 *nftable
- if supportsV6 {
- logf("v6nat availability: %v", supportsV6NAT)
- nft6 = &nftable{Proto: nftables.TableFamilyIPv6}
- }
- // TODO(KevinLiang10): convert iptables rule to nftable rules if they exist in the iptables
- return &nftablesRunner{
- conn: conn,
- nft4: nft4,
- nft6: nft6,
- v6Available: supportsV6,
- v6NATAvailable: supportsV6NAT,
- }, nil
- }
- // newLoadSaddrExpr creates a new nftables expression that loads the source
- // address of the packet into the given register.
- func newLoadSaddrExpr(proto nftables.TableFamily, destReg uint32) (expr.Any, error) {
- switch proto {
- case nftables.TableFamilyIPv4:
- return &expr.Payload{
- DestRegister: destReg,
- Base: expr.PayloadBaseNetworkHeader,
- Offset: 12,
- Len: 4,
- }, nil
- case nftables.TableFamilyIPv6:
- return &expr.Payload{
- DestRegister: destReg,
- Base: expr.PayloadBaseNetworkHeader,
- Offset: 8,
- Len: 16,
- }, nil
- default:
- return nil, fmt.Errorf("table family %v is neither IPv4 nor IPv6", proto)
- }
- }
- // newLoadDportExpr creates a new nftables express that loads the desination port
- // of a TCP/UDP packet into the given register.
- func newLoadDportExpr(destReg uint32) expr.Any {
- return &expr.Payload{
- DestRegister: destReg,
- Base: expr.PayloadBaseTransportHeader,
- Offset: 2,
- Len: 2,
- }
- }
- // HasIPV6 reports true if the system supports IPv6.
- func (n *nftablesRunner) HasIPV6() bool {
- return n.v6Available
- }
- // HasIPV6NAT returns true if the system supports IPv6 NAT.
- func (n *nftablesRunner) HasIPV6NAT() bool {
- return n.v6NATAvailable
- }
- // findRule iterates through the rules to find the rule with matching expressions.
- func findRule(conn *nftables.Conn, rule *nftables.Rule) (*nftables.Rule, error) {
- rules, err := conn.GetRules(rule.Table, rule.Chain)
- if err != nil {
- return nil, fmt.Errorf("get nftables rules: %w", err)
- }
- if len(rules) == 0 {
- return nil, nil
- }
- ruleLoop:
- for _, r := range rules {
- if len(r.Exprs) != len(rule.Exprs) {
- continue
- }
- for i, e := range r.Exprs {
- // Skip counter expressions, as they will not match.
- if _, ok := e.(*expr.Counter); ok {
- continue
- }
- if !reflect.DeepEqual(e, rule.Exprs[i]) {
- continue ruleLoop
- }
- }
- return r, nil
- }
- return nil, nil
- }
- func createLoopbackRule(
- proto nftables.TableFamily,
- table *nftables.Table,
- chain *nftables.Chain,
- addr netip.Addr,
- ) (*nftables.Rule, error) {
- saddrExpr, err := newLoadSaddrExpr(proto, 1)
- if err != nil {
- return nil, fmt.Errorf("newLoadSaddrExpr: %w", err)
- }
- loopBackRule := &nftables.Rule{
- Table: table,
- Chain: chain,
- Exprs: []expr.Any{
- &expr.Meta{
- Key: expr.MetaKeyIIFNAME,
- Register: 1,
- },
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: []byte("lo"),
- },
- saddrExpr,
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: addr.AsSlice(),
- },
- &expr.Counter{},
- &expr.Verdict{
- Kind: expr.VerdictAccept,
- },
- },
- }
- return loopBackRule, nil
- }
- // insertLoopbackRule inserts the TS loop back rule into
- // the given chain as the first rule if it does not exist.
- func insertLoopbackRule(
- conn *nftables.Conn, proto nftables.TableFamily,
- table *nftables.Table, chain *nftables.Chain, addr netip.Addr) error {
- loopBackRule, err := createLoopbackRule(proto, table, chain, addr)
- if err != nil {
- return fmt.Errorf("create loopback rule: %w", err)
- }
- // If TestDial is set, we are running in test mode and we should not
- // find rule because header will mismatch.
- if conn.TestDial == nil {
- // Check if the rule already exists.
- rule, err := findRule(conn, loopBackRule)
- if err != nil {
- return fmt.Errorf("find rule: %w", err)
- }
- if rule != nil {
- // Rule already exists, no need to insert.
- return nil
- }
- }
- // This inserts the rule to the top of the chain
- _ = conn.InsertRule(loopBackRule)
- if err = conn.Flush(); err != nil {
- return fmt.Errorf("insert rule: %w", err)
- }
- return nil
- }
- // getNFTByAddr returns the nftables with correct IP family
- // that we will be using for the given address.
- func (n *nftablesRunner) getNFTByAddr(addr netip.Addr) *nftable {
- if addr.Is6() {
- return n.nft6
- }
- return n.nft4
- }
- // AddLoopbackRule adds an nftables rule to permit loopback traffic to
- // a local Tailscale IP. This rule is added only if it does not already exist.
- func (n *nftablesRunner) AddLoopbackRule(addr netip.Addr) error {
- nf := n.getNFTByAddr(addr)
- inputChain, err := getChainFromTable(n.conn, nf.Filter, chainNameInput)
- if err != nil {
- return fmt.Errorf("get input chain: %w", err)
- }
- if err := insertLoopbackRule(n.conn, nf.Proto, nf.Filter, inputChain, addr); err != nil {
- return fmt.Errorf("add loopback rule: %w", err)
- }
- return nil
- }
- // DelLoopbackRule removes the nftables rule permitting loopback
- // traffic to a Tailscale IP.
- func (n *nftablesRunner) DelLoopbackRule(addr netip.Addr) error {
- nf := n.getNFTByAddr(addr)
- inputChain, err := getChainFromTable(n.conn, nf.Filter, chainNameInput)
- if err != nil {
- return fmt.Errorf("get input chain: %w", err)
- }
- loopBackRule, err := createLoopbackRule(nf.Proto, nf.Filter, inputChain, addr)
- if err != nil {
- return fmt.Errorf("create loopback rule: %w", err)
- }
- existingLoopBackRule, err := findRule(n.conn, loopBackRule)
- if err != nil {
- return fmt.Errorf("find loop back rule: %w", err)
- }
- if existingLoopBackRule == nil {
- // Rule does not exist, no need to delete.
- return nil
- }
- if err := n.conn.DelRule(existingLoopBackRule); err != nil {
- return fmt.Errorf("delete rule: %w", err)
- }
- return n.conn.Flush()
- }
- // getTables gets the available nftable in nftables runner.
- func (n *nftablesRunner) getTables() []*nftable {
- if n.v6Available {
- return []*nftable{n.nft4, n.nft6}
- }
- return []*nftable{n.nft4}
- }
- // getNATTables gets the available nftable in nftables runner.
- // If the system does not support IPv6 NAT, only the IPv4 nftable
- // will be returned.
- func (n *nftablesRunner) getNATTables() []*nftable {
- if n.v6NATAvailable {
- return n.getTables()
- }
- return []*nftable{n.nft4}
- }
- // AddChains creates custom Tailscale chains in netfilter via nftables
- // if the ts-chain doesn't already exist.
- func (n *nftablesRunner) AddChains() error {
- polAccept := nftables.ChainPolicyAccept
- for _, table := range n.getTables() {
- // Create the filter table if it doesn't exist, this table name is the same
- // as the name used by iptables-nft and ufw. We install rules into the
- // same conventional table so that `accept` verdicts from our jump
- // chains are conclusive.
- filter, err := createTableIfNotExist(n.conn, table.Proto, "filter")
- if err != nil {
- return fmt.Errorf("create table: %w", err)
- }
- table.Filter = filter
- // Adding the "conventional chains" that are used by iptables-nft and ufw.
- if err = createChainIfNotExist(n.conn, chainInfo{filter, "FORWARD", nftables.ChainTypeFilter, nftables.ChainHookForward, nftables.ChainPriorityFilter, &polAccept}); err != nil {
- return fmt.Errorf("create forward chain: %w", err)
- }
- if err = createChainIfNotExist(n.conn, chainInfo{filter, "INPUT", nftables.ChainTypeFilter, nftables.ChainHookInput, nftables.ChainPriorityFilter, &polAccept}); err != nil {
- return fmt.Errorf("create input chain: %w", err)
- }
- // Adding the tailscale chains that contain our rules.
- if err = createChainIfNotExist(n.conn, chainInfo{filter, chainNameForward, chainTypeRegular, nil, nil, nil}); err != nil {
- return fmt.Errorf("create forward chain: %w", err)
- }
- if err = createChainIfNotExist(n.conn, chainInfo{filter, chainNameInput, chainTypeRegular, nil, nil, nil}); err != nil {
- return fmt.Errorf("create input chain: %w", err)
- }
- }
- for _, table := range n.getNATTables() {
- // Create the nat table if it doesn't exist, this table name is the same
- // as the name used by iptables-nft and ufw. We install rules into the
- // same conventional table so that `accept` verdicts from our jump
- // chains are conclusive.
- nat, err := createTableIfNotExist(n.conn, table.Proto, "nat")
- if err != nil {
- return fmt.Errorf("create table: %w", err)
- }
- table.Nat = nat
- // Adding the "conventional chains" that are used by iptables-nft and ufw.
- if err = createChainIfNotExist(n.conn, chainInfo{nat, "POSTROUTING", nftables.ChainTypeNAT, nftables.ChainHookPostrouting, nftables.ChainPriorityNATSource, &polAccept}); err != nil {
- return fmt.Errorf("create postrouting chain: %w", err)
- }
- // Adding the tailscale chain that contains our rules.
- if err = createChainIfNotExist(n.conn, chainInfo{nat, chainNamePostrouting, chainTypeRegular, nil, nil, nil}); err != nil {
- return fmt.Errorf("create postrouting chain: %w", err)
- }
- }
- return n.conn.Flush()
- }
- // These are dummy chains and tables we create to detect if nftables is
- // available. We create them, then delete them. If we can create and delete
- // them, then we can use nftables. If we can't, then we assume that we're
- // running on a system that doesn't support nftables. See
- // createDummyPostroutingChains.
- const (
- tsDummyChainName = "ts-test-postrouting"
- tsDummyTableName = "ts-test-nat"
- )
- // createDummyPostroutingChains creates dummy postrouting chains in netfilter
- // via netfilter via nftables, as a last resort measure to detect that nftables
- // can be used. It cleans up the dummy chains after creation.
- func (n *nftablesRunner) createDummyPostroutingChains() (retErr error) {
- polAccept := ptr.To(nftables.ChainPolicyAccept)
- for _, table := range n.getNATTables() {
- nat, err := createTableIfNotExist(n.conn, table.Proto, tsDummyTableName)
- if err != nil {
- return fmt.Errorf("create nat table: %w", err)
- }
- defer func(fm nftables.TableFamily) {
- if err := deleteTableIfExists(n.conn, table.Proto, tsDummyTableName); err != nil && retErr == nil {
- retErr = fmt.Errorf("delete %q table: %w", tsDummyTableName, err)
- }
- }(table.Proto)
- table.Nat = nat
- if err = createChainIfNotExist(n.conn, chainInfo{nat, tsDummyChainName, nftables.ChainTypeNAT, nftables.ChainHookPostrouting, nftables.ChainPriorityNATSource, polAccept}); err != nil {
- return fmt.Errorf("create %q chain: %w", tsDummyChainName, err)
- }
- if err := deleteChainIfExists(n.conn, nat, tsDummyChainName); err != nil {
- return fmt.Errorf("delete %q chain: %w", tsDummyChainName, err)
- }
- }
- return nil
- }
- // deleteChainIfExists deletes a chain if it exists.
- func deleteChainIfExists(c *nftables.Conn, table *nftables.Table, name string) error {
- chain, err := getChainFromTable(c, table, name)
- if err != nil && !errors.Is(err, errorChainNotFound{table.Name, name}) {
- return fmt.Errorf("get chain: %w", err)
- } else if err != nil {
- // If the chain doesn't exist, we don't need to delete it.
- return nil
- }
- c.FlushChain(chain)
- c.DelChain(chain)
- if err := c.Flush(); err != nil {
- return fmt.Errorf("flush and delete chain: %w", err)
- }
- return nil
- }
- // DelChains removes the custom Tailscale chains from netfilter via nftables.
- func (n *nftablesRunner) DelChains() error {
- for _, table := range n.getTables() {
- if err := deleteChainIfExists(n.conn, table.Filter, chainNameForward); err != nil {
- return fmt.Errorf("delete chain: %w", err)
- }
- if err := deleteChainIfExists(n.conn, table.Filter, chainNameInput); err != nil {
- return fmt.Errorf("delete chain: %w", err)
- }
- }
- if err := deleteChainIfExists(n.conn, n.nft4.Nat, chainNamePostrouting); err != nil {
- return fmt.Errorf("delete chain: %w", err)
- }
- if n.v6NATAvailable {
- if err := deleteChainIfExists(n.conn, n.nft6.Nat, chainNamePostrouting); err != nil {
- return fmt.Errorf("delete chain: %w", err)
- }
- }
- if err := n.conn.Flush(); err != nil {
- return fmt.Errorf("flush: %w", err)
- }
- return nil
- }
- // createHookRule creates a rule to jump from a hooked chain to a regular chain.
- func createHookRule(table *nftables.Table, fromChain *nftables.Chain, toChainName string) *nftables.Rule {
- exprs := []expr.Any{
- &expr.Counter{},
- &expr.Verdict{
- Kind: expr.VerdictJump,
- Chain: toChainName,
- },
- }
- rule := &nftables.Rule{
- Table: table,
- Chain: fromChain,
- Exprs: exprs,
- }
- return rule
- }
- // addHookRule adds a rule to jump from a hooked chain to a regular chain at top of the hooked chain.
- func addHookRule(conn *nftables.Conn, table *nftables.Table, fromChain *nftables.Chain, toChainName string) error {
- rule := createHookRule(table, fromChain, toChainName)
- _ = conn.InsertRule(rule)
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush add rule: %w", err)
- }
- return nil
- }
- // AddHooks is adding rules to conventional chains like "FORWARD", "INPUT" and "POSTROUTING"
- // in tables and jump from those chains to tailscale chains.
- func (n *nftablesRunner) AddHooks() error {
- conn := n.conn
- for _, table := range n.getTables() {
- inputChain, err := getChainFromTable(conn, table.Filter, "INPUT")
- if err != nil {
- return fmt.Errorf("get INPUT chain: %w", err)
- }
- err = addHookRule(conn, table.Filter, inputChain, chainNameInput)
- if err != nil {
- return fmt.Errorf("Addhook: %w", err)
- }
- forwardChain, err := getChainFromTable(conn, table.Filter, "FORWARD")
- if err != nil {
- return fmt.Errorf("get FORWARD chain: %w", err)
- }
- err = addHookRule(conn, table.Filter, forwardChain, chainNameForward)
- if err != nil {
- return fmt.Errorf("Addhook: %w", err)
- }
- }
- for _, table := range n.getNATTables() {
- postroutingChain, err := getChainFromTable(conn, table.Nat, "POSTROUTING")
- if err != nil {
- return fmt.Errorf("get INPUT chain: %w", err)
- }
- err = addHookRule(conn, table.Nat, postroutingChain, chainNamePostrouting)
- if err != nil {
- return fmt.Errorf("Addhook: %w", err)
- }
- }
- return nil
- }
- // delHookRule deletes a rule that jumps from a hooked chain to a regular chain.
- func delHookRule(conn *nftables.Conn, table *nftables.Table, fromChain *nftables.Chain, toChainName string) error {
- rule := createHookRule(table, fromChain, toChainName)
- existingRule, err := findRule(conn, rule)
- if err != nil {
- return fmt.Errorf("Failed to find hook rule: %w", err)
- }
- if existingRule == nil {
- return nil
- }
- _ = conn.DelRule(existingRule)
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush del hook rule: %w", err)
- }
- return nil
- }
- // DelHooks is deleting the rules added to conventional chains to jump to tailscale chains.
- func (n *nftablesRunner) DelHooks(logf logger.Logf) error {
- conn := n.conn
- for _, table := range n.getTables() {
- inputChain, err := getChainFromTable(conn, table.Filter, "INPUT")
- if err != nil {
- return fmt.Errorf("get INPUT chain: %w", err)
- }
- err = delHookRule(conn, table.Filter, inputChain, chainNameInput)
- if err != nil {
- return fmt.Errorf("delhook: %w", err)
- }
- forwardChain, err := getChainFromTable(conn, table.Filter, "FORWARD")
- if err != nil {
- return fmt.Errorf("get FORWARD chain: %w", err)
- }
- err = delHookRule(conn, table.Filter, forwardChain, chainNameForward)
- if err != nil {
- return fmt.Errorf("delhook: %w", err)
- }
- }
- for _, table := range n.getNATTables() {
- postroutingChain, err := getChainFromTable(conn, table.Nat, "POSTROUTING")
- if err != nil {
- return fmt.Errorf("get INPUT chain: %w", err)
- }
- err = delHookRule(conn, table.Nat, postroutingChain, chainNamePostrouting)
- if err != nil {
- return fmt.Errorf("delhook: %w", err)
- }
- }
- return nil
- }
- // maskof returns the mask of the given prefix in big endian bytes.
- func maskof(pfx netip.Prefix) []byte {
- mask := make([]byte, 4)
- binary.BigEndian.PutUint32(mask, ^(uint32(0xffff_ffff) >> pfx.Bits()))
- return mask
- }
- // createRangeRule creates a rule that matches packets with source IP from the give
- // range (like CGNAT range or ChromeOSVM range) and the interface is not the tunname,
- // and makes the given decision. Only IPv4 is supported.
- func createRangeRule(
- table *nftables.Table, chain *nftables.Chain,
- tunname string, rng netip.Prefix, decision expr.VerdictKind,
- ) (*nftables.Rule, error) {
- if rng.Addr().Is6() {
- return nil, errors.New("IPv6 is not supported")
- }
- saddrExpr, err := newLoadSaddrExpr(nftables.TableFamilyIPv4, 1)
- if err != nil {
- return nil, fmt.Errorf("newLoadSaddrExpr: %w", err)
- }
- netip := rng.Addr().AsSlice()
- mask := maskof(rng)
- rule := &nftables.Rule{
- Table: table,
- Chain: chain,
- Exprs: []expr.Any{
- &expr.Meta{Key: expr.MetaKeyIIFNAME, Register: 1},
- &expr.Cmp{
- Op: expr.CmpOpNeq,
- Register: 1,
- Data: []byte(tunname),
- },
- saddrExpr,
- &expr.Bitwise{
- SourceRegister: 1,
- DestRegister: 1,
- Len: 4,
- Mask: mask,
- Xor: []byte{0x00, 0x00, 0x00, 0x00},
- },
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: netip,
- },
- &expr.Counter{},
- &expr.Verdict{
- Kind: decision,
- },
- },
- }
- return rule, nil
- }
- // addReturnChromeOSVMRangeRule adds a rule to return if the source IP
- // is in the ChromeOS VM range.
- func addReturnChromeOSVMRangeRule(c *nftables.Conn, table *nftables.Table, chain *nftables.Chain, tunname string) error {
- rule, err := createRangeRule(table, chain, tunname, tsaddr.ChromeOSVMRange(), expr.VerdictReturn)
- if err != nil {
- return fmt.Errorf("create rule: %w", err)
- }
- _ = c.AddRule(rule)
- if err = c.Flush(); err != nil {
- return fmt.Errorf("add rule: %w", err)
- }
- return nil
- }
- // addDropCGNATRangeRule adds a rule to drop if the source IP is in the
- // CGNAT range.
- func addDropCGNATRangeRule(c *nftables.Conn, table *nftables.Table, chain *nftables.Chain, tunname string) error {
- rule, err := createRangeRule(table, chain, tunname, tsaddr.CGNATRange(), expr.VerdictDrop)
- if err != nil {
- return fmt.Errorf("create rule: %w", err)
- }
- _ = c.AddRule(rule)
- if err = c.Flush(); err != nil {
- return fmt.Errorf("add rule: %w", err)
- }
- return nil
- }
- // createSetSubnetRouteMarkRule creates a rule to set the subnet route
- // mark if the packet is from the given interface.
- func createSetSubnetRouteMarkRule(table *nftables.Table, chain *nftables.Chain, tunname string) (*nftables.Rule, error) {
- hexTsFwmarkMaskNeg := getTailscaleFwmarkMaskNeg()
- hexTSSubnetRouteMark := getTailscaleSubnetRouteMark()
- rule := &nftables.Rule{
- Table: table,
- Chain: chain,
- Exprs: []expr.Any{
- &expr.Meta{Key: expr.MetaKeyIIFNAME, Register: 1},
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: []byte(tunname),
- },
- &expr.Counter{},
- &expr.Meta{Key: expr.MetaKeyMARK, Register: 1},
- &expr.Bitwise{
- SourceRegister: 1,
- DestRegister: 1,
- Len: 4,
- Mask: hexTsFwmarkMaskNeg,
- Xor: hexTSSubnetRouteMark,
- },
- &expr.Meta{
- Key: expr.MetaKeyMARK,
- SourceRegister: true,
- Register: 1,
- },
- },
- }
- return rule, nil
- }
- // addSetSubnetRouteMarkRule adds a rule to set the subnet route mark
- // if the packet is from the given interface.
- func addSetSubnetRouteMarkRule(c *nftables.Conn, table *nftables.Table, chain *nftables.Chain, tunname string) error {
- rule, err := createSetSubnetRouteMarkRule(table, chain, tunname)
- if err != nil {
- return fmt.Errorf("create rule: %w", err)
- }
- _ = c.AddRule(rule)
- if err := c.Flush(); err != nil {
- return fmt.Errorf("add rule: %w", err)
- }
- return nil
- }
- // createDropOutgoingPacketFromCGNATRangeRuleWithTunname creates a rule to drop
- // outgoing packets from the CGNAT range.
- func createDropOutgoingPacketFromCGNATRangeRuleWithTunname(table *nftables.Table, chain *nftables.Chain, tunname string) (*nftables.Rule, error) {
- _, ipNet, err := net.ParseCIDR(tsaddr.CGNATRange().String())
- if err != nil {
- return nil, fmt.Errorf("parse cidr: %v", err)
- }
- mask, err := hex.DecodeString(ipNet.Mask.String())
- if err != nil {
- return nil, fmt.Errorf("decode mask: %v", err)
- }
- netip := ipNet.IP.Mask(ipNet.Mask).To4()
- saddrExpr, err := newLoadSaddrExpr(nftables.TableFamilyIPv4, 1)
- if err != nil {
- return nil, fmt.Errorf("newLoadSaddrExpr: %v", err)
- }
- rule := &nftables.Rule{
- Table: table,
- Chain: chain,
- Exprs: []expr.Any{
- &expr.Meta{Key: expr.MetaKeyOIFNAME, Register: 1},
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: []byte(tunname),
- },
- saddrExpr,
- &expr.Bitwise{
- SourceRegister: 1,
- DestRegister: 1,
- Len: 4,
- Mask: mask,
- Xor: []byte{0x00, 0x00, 0x00, 0x00},
- },
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: netip,
- },
- &expr.Counter{},
- &expr.Verdict{
- Kind: expr.VerdictDrop,
- },
- },
- }
- return rule, nil
- }
- // addDropOutgoingPacketFromCGNATRangeRuleWithTunname adds a rule to drop
- // outgoing packets from the CGNAT range.
- func addDropOutgoingPacketFromCGNATRangeRuleWithTunname(conn *nftables.Conn, table *nftables.Table, chain *nftables.Chain, tunname string) error {
- rule, err := createDropOutgoingPacketFromCGNATRangeRuleWithTunname(table, chain, tunname)
- if err != nil {
- return fmt.Errorf("create rule: %w", err)
- }
- _ = conn.AddRule(rule)
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("add rule: %w", err)
- }
- return nil
- }
- // createAcceptOutgoingPacketRule creates a rule to accept outgoing packets
- // from the given interface.
- func createAcceptOutgoingPacketRule(table *nftables.Table, chain *nftables.Chain, tunname string) *nftables.Rule {
- return &nftables.Rule{
- Table: table,
- Chain: chain,
- Exprs: []expr.Any{
- &expr.Meta{Key: expr.MetaKeyOIFNAME, Register: 1},
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: []byte(tunname),
- },
- &expr.Counter{},
- &expr.Verdict{
- Kind: expr.VerdictAccept,
- },
- },
- }
- }
- // addAcceptOutgoingPacketRule adds a rule to accept outgoing packets
- // from the given interface.
- func addAcceptOutgoingPacketRule(conn *nftables.Conn, table *nftables.Table, chain *nftables.Chain, tunname string) error {
- rule := createAcceptOutgoingPacketRule(table, chain, tunname)
- _ = conn.AddRule(rule)
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush add rule: %w", err)
- }
- return nil
- }
- // createAcceptOnPortRule creates a rule to accept incoming packets to
- // a given destination UDP port.
- func createAcceptOnPortRule(table *nftables.Table, chain *nftables.Chain, port uint16) *nftables.Rule {
- portBytes := make([]byte, 2)
- binary.BigEndian.PutUint16(portBytes, port)
- return &nftables.Rule{
- Table: table,
- Chain: chain,
- Exprs: []expr.Any{
- &expr.Meta{
- Key: expr.MetaKeyL4PROTO,
- Register: 1,
- },
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: []byte{unix.IPPROTO_UDP},
- },
- newLoadDportExpr(1),
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: portBytes,
- },
- &expr.Counter{},
- &expr.Verdict{
- Kind: expr.VerdictAccept,
- },
- },
- }
- }
- // addAcceptOnPortRule adds a rule to accept incoming packets to
- // a given destination UDP port.
- func addAcceptOnPortRule(conn *nftables.Conn, table *nftables.Table, chain *nftables.Chain, port uint16) error {
- rule := createAcceptOnPortRule(table, chain, port)
- _ = conn.AddRule(rule)
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush add rule: %w", err)
- }
- return nil
- }
- // addAcceptOnPortRule removes a rule to accept incoming packets to
- // a given destination UDP port.
- func removeAcceptOnPortRule(conn *nftables.Conn, table *nftables.Table, chain *nftables.Chain, port uint16) error {
- rule := createAcceptOnPortRule(table, chain, port)
- rule, err := findRule(conn, rule)
- if err != nil {
- return fmt.Errorf("find rule: %v", err)
- }
- _ = conn.DelRule(rule)
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush del rule: %w", err)
- }
- return nil
- }
- // AddMagicsockPortRule adds a rule to nftables to allow incoming traffic on
- // the specified UDP port, so magicsock can accept incoming connections.
- // network must be either "udp4" or "udp6" - this determines whether the rule
- // is added for IPv4 or IPv6.
- func (n *nftablesRunner) AddMagicsockPortRule(port uint16, network string) error {
- var filterTable *nftables.Table
- switch network {
- case "udp4":
- filterTable = n.nft4.Filter
- case "udp6":
- filterTable = n.nft6.Filter
- default:
- return fmt.Errorf("unsupported network %s", network)
- }
- inputChain, err := getChainFromTable(n.conn, filterTable, chainNameInput)
- if err != nil {
- return fmt.Errorf("get input chain: %v", err)
- }
- err = addAcceptOnPortRule(n.conn, filterTable, inputChain, port)
- if err != nil {
- return fmt.Errorf("add accept on port rule: %v", err)
- }
- return nil
- }
- // DelMagicsockPortRule removes a rule added by AddMagicsockPortRule to accept
- // incoming traffic on a particular UDP port.
- // network must be either "udp4" or "udp6" - this determines whether the rule
- // is removed for IPv4 or IPv6.
- func (n *nftablesRunner) DelMagicsockPortRule(port uint16, network string) error {
- var filterTable *nftables.Table
- switch network {
- case "udp4":
- filterTable = n.nft4.Filter
- case "udp6":
- filterTable = n.nft6.Filter
- default:
- return fmt.Errorf("unsupported network %s", network)
- }
- inputChain, err := getChainFromTable(n.conn, filterTable, chainNameInput)
- if err != nil {
- return fmt.Errorf("get input chain: %v", err)
- }
- err = removeAcceptOnPortRule(n.conn, filterTable, inputChain, port)
- if err != nil {
- return fmt.Errorf("add accept on port rule: %v", err)
- }
- return nil
- }
- // createAcceptIncomingPacketRule creates a rule to accept incoming packets to
- // the given interface.
- func createAcceptIncomingPacketRule(table *nftables.Table, chain *nftables.Chain, tunname string) *nftables.Rule {
- return &nftables.Rule{
- Table: table,
- Chain: chain,
- Exprs: []expr.Any{
- &expr.Meta{Key: expr.MetaKeyIIFNAME, Register: 1},
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: []byte(tunname),
- },
- &expr.Counter{},
- &expr.Verdict{
- Kind: expr.VerdictAccept,
- },
- },
- }
- }
- func addAcceptIncomingPacketRule(conn *nftables.Conn, table *nftables.Table, chain *nftables.Chain, tunname string) error {
- rule := createAcceptIncomingPacketRule(table, chain, tunname)
- _ = conn.AddRule(rule)
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush add rule: %w", err)
- }
- return nil
- }
- // AddBase adds some basic processing rules.
- func (n *nftablesRunner) AddBase(tunname string) error {
- if err := n.addBase4(tunname); err != nil {
- return fmt.Errorf("add base v4: %w", err)
- }
- if n.HasIPV6() {
- if err := n.addBase6(tunname); err != nil {
- return fmt.Errorf("add base v6: %w", err)
- }
- }
- return nil
- }
- // addBase4 adds some basic IPv4 processing rules.
- func (n *nftablesRunner) addBase4(tunname string) error {
- conn := n.conn
- inputChain, err := getChainFromTable(conn, n.nft4.Filter, chainNameInput)
- if err != nil {
- return fmt.Errorf("get input chain v4: %v", err)
- }
- if err = addReturnChromeOSVMRangeRule(conn, n.nft4.Filter, inputChain, tunname); err != nil {
- return fmt.Errorf("add return chromeos vm range rule v4: %w", err)
- }
- if err = addDropCGNATRangeRule(conn, n.nft4.Filter, inputChain, tunname); err != nil {
- return fmt.Errorf("add drop cgnat range rule v4: %w", err)
- }
- if err = addAcceptIncomingPacketRule(conn, n.nft4.Filter, inputChain, tunname); err != nil {
- return fmt.Errorf("add accept incoming packet rule v4: %w", err)
- }
- forwardChain, err := getChainFromTable(conn, n.nft4.Filter, chainNameForward)
- if err != nil {
- return fmt.Errorf("get forward chain v4: %v", err)
- }
- if err = addSetSubnetRouteMarkRule(conn, n.nft4.Filter, forwardChain, tunname); err != nil {
- return fmt.Errorf("add set subnet route mark rule v4: %w", err)
- }
- if err = addMatchSubnetRouteMarkRule(conn, n.nft4.Filter, forwardChain, Accept); err != nil {
- return fmt.Errorf("add match subnet route mark rule v4: %w", err)
- }
- if err = addDropOutgoingPacketFromCGNATRangeRuleWithTunname(conn, n.nft4.Filter, forwardChain, tunname); err != nil {
- return fmt.Errorf("add drop outgoing packet from cgnat range rule v4: %w", err)
- }
- if err = addAcceptOutgoingPacketRule(conn, n.nft4.Filter, forwardChain, tunname); err != nil {
- return fmt.Errorf("add accept outgoing packet rule v4: %w", err)
- }
- if err = conn.Flush(); err != nil {
- return fmt.Errorf("flush base v4: %w", err)
- }
- return nil
- }
- // addBase6 adds some basic IPv6 processing rules.
- func (n *nftablesRunner) addBase6(tunname string) error {
- conn := n.conn
- inputChain, err := getChainFromTable(conn, n.nft6.Filter, chainNameInput)
- if err != nil {
- return fmt.Errorf("get input chain v4: %v", err)
- }
- if err = addAcceptIncomingPacketRule(conn, n.nft6.Filter, inputChain, tunname); err != nil {
- return fmt.Errorf("add accept incoming packet rule v6: %w", err)
- }
- forwardChain, err := getChainFromTable(conn, n.nft6.Filter, chainNameForward)
- if err != nil {
- return fmt.Errorf("get forward chain v6: %w", err)
- }
- if err = addSetSubnetRouteMarkRule(conn, n.nft6.Filter, forwardChain, tunname); err != nil {
- return fmt.Errorf("add set subnet route mark rule v6: %w", err)
- }
- if err = addMatchSubnetRouteMarkRule(conn, n.nft6.Filter, forwardChain, Accept); err != nil {
- return fmt.Errorf("add match subnet route mark rule v6: %w", err)
- }
- if err = addAcceptOutgoingPacketRule(conn, n.nft6.Filter, forwardChain, tunname); err != nil {
- return fmt.Errorf("add accept outgoing packet rule v6: %w", err)
- }
- if err = conn.Flush(); err != nil {
- return fmt.Errorf("flush base v6: %w", err)
- }
- return nil
- }
- // DelBase empties, but does not remove, custom Tailscale chains from
- // netfilter via iptables.
- func (n *nftablesRunner) DelBase() error {
- conn := n.conn
- for _, table := range n.getTables() {
- inputChain, err := getChainFromTable(conn, table.Filter, chainNameInput)
- if err != nil {
- return fmt.Errorf("get input chain: %v", err)
- }
- conn.FlushChain(inputChain)
- forwardChain, err := getChainFromTable(conn, table.Filter, chainNameForward)
- if err != nil {
- return fmt.Errorf("get forward chain: %v", err)
- }
- conn.FlushChain(forwardChain)
- }
- for _, table := range n.getNATTables() {
- postrouteChain, err := getChainFromTable(conn, table.Nat, chainNamePostrouting)
- if err != nil {
- return fmt.Errorf("get postrouting chain v4: %v", err)
- }
- conn.FlushChain(postrouteChain)
- }
- return conn.Flush()
- }
- // createMatchSubnetRouteMarkRule creates a rule that matches packets
- // with the subnet route mark and takes the specified action.
- func createMatchSubnetRouteMarkRule(table *nftables.Table, chain *nftables.Chain, action MatchDecision) (*nftables.Rule, error) {
- hexTSFwmarkMask := getTailscaleFwmarkMask()
- hexTSSubnetRouteMark := getTailscaleSubnetRouteMark()
- var endAction expr.Any
- endAction = &expr.Verdict{Kind: expr.VerdictAccept}
- if action == Masq {
- endAction = &expr.Masq{}
- }
- exprs := []expr.Any{
- &expr.Meta{Key: expr.MetaKeyMARK, Register: 1},
- &expr.Bitwise{
- SourceRegister: 1,
- DestRegister: 1,
- Len: 4,
- Mask: hexTSFwmarkMask,
- Xor: []byte{0x00, 0x00, 0x00, 0x00},
- },
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: hexTSSubnetRouteMark,
- },
- &expr.Counter{},
- endAction,
- }
- rule := &nftables.Rule{
- Table: table,
- Chain: chain,
- Exprs: exprs,
- }
- return rule, nil
- }
- // addMatchSubnetRouteMarkRule adds a rule that matches packets with
- // the subnet route mark and takes the specified action.
- func addMatchSubnetRouteMarkRule(conn *nftables.Conn, table *nftables.Table, chain *nftables.Chain, action MatchDecision) error {
- rule, err := createMatchSubnetRouteMarkRule(table, chain, action)
- if err != nil {
- return fmt.Errorf("create match subnet route mark rule: %w", err)
- }
- _ = conn.AddRule(rule)
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush add rule: %w", err)
- }
- return nil
- }
- // AddSNATRule adds a netfilter rule to SNAT traffic destined for
- // local subnets.
- func (n *nftablesRunner) AddSNATRule() error {
- conn := n.conn
- for _, table := range n.getNATTables() {
- chain, err := getChainFromTable(conn, table.Nat, chainNamePostrouting)
- if err != nil {
- return fmt.Errorf("get postrouting chain v4: %w", err)
- }
- if err = addMatchSubnetRouteMarkRule(conn, table.Nat, chain, Masq); err != nil {
- return fmt.Errorf("add match subnet route mark rule v4: %w", err)
- }
- }
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush add SNAT rule: %w", err)
- }
- return nil
- }
- // DelSNATRule removes the netfilter rule to SNAT traffic destined for
- // local subnets. An error is returned if the rule does not exist.
- func (n *nftablesRunner) DelSNATRule() error {
- conn := n.conn
- hexTSFwmarkMask := getTailscaleFwmarkMask()
- hexTSSubnetRouteMark := getTailscaleSubnetRouteMark()
- exprs := []expr.Any{
- &expr.Meta{Key: expr.MetaKeyMARK, Register: 1},
- &expr.Bitwise{
- SourceRegister: 1,
- DestRegister: 1,
- Len: 4,
- Mask: hexTSFwmarkMask,
- },
- &expr.Cmp{
- Op: expr.CmpOpEq,
- Register: 1,
- Data: hexTSSubnetRouteMark,
- },
- &expr.Counter{},
- &expr.Masq{},
- }
- for _, table := range n.getNATTables() {
- chain, err := getChainFromTable(conn, table.Nat, chainNamePostrouting)
- if err != nil {
- return fmt.Errorf("get postrouting chain v4: %w", err)
- }
- rule := &nftables.Rule{
- Table: table.Nat,
- Chain: chain,
- Exprs: exprs,
- }
- SNATRule, err := findRule(conn, rule)
- if err != nil {
- return fmt.Errorf("find SNAT rule v4: %w", err)
- }
- if SNATRule != nil {
- _ = conn.DelRule(SNATRule)
- }
- }
- if err := conn.Flush(); err != nil {
- return fmt.Errorf("flush del SNAT rule: %w", err)
- }
- return nil
- }
- // cleanupChain removes a jump rule from hookChainName to tsChainName, and then
- // the entire chain tsChainName. Errors are logged, but attempts to remove both
- // the jump rule and chain continue even if one errors.
- func cleanupChain(logf logger.Logf, conn *nftables.Conn, table *nftables.Table, hookChainName, tsChainName string) {
- // remove the jump first, before removing the jump destination.
- defaultChain, err := getChainFromTable(conn, table, hookChainName)
- if err != nil && !errors.Is(err, errorChainNotFound{table.Name, hookChainName}) {
- logf("cleanup: did not find default chain: %s", err)
- }
- if !errors.Is(err, errorChainNotFound{table.Name, hookChainName}) {
- // delete hook in convention chain
- _ = delHookRule(conn, table, defaultChain, tsChainName)
- }
- tsChain, err := getChainFromTable(conn, table, tsChainName)
- if err != nil && !errors.Is(err, errorChainNotFound{table.Name, tsChainName}) {
- logf("cleanup: did not find ts-chain: %s", err)
- }
- if tsChain != nil {
- // flush and delete ts-chain
- conn.FlushChain(tsChain)
- conn.DelChain(tsChain)
- err = conn.Flush()
- logf("cleanup: delete and flush chain %s: %s", tsChainName, err)
- }
- }
- // NfTablesCleanUp removes all Tailscale added nftables rules.
- // Any errors that occur are logged to the provided logf.
- func NfTablesCleanUp(logf logger.Logf) {
- conn, err := nftables.New()
- if err != nil {
- logf("cleanup: nftables connection: %s", err)
- }
- tables, err := conn.ListTables() // both v4 and v6
- if err != nil {
- logf("cleanup: list tables: %s", err)
- }
- for _, table := range tables {
- // These table names were used briefly in 1.48.0.
- if table.Name == "ts-filter" || table.Name == "ts-nat" {
- conn.DelTable(table)
- if err := conn.Flush(); err != nil {
- logf("cleanup: flush delete table %s: %s", table.Name, err)
- }
- }
- if table.Name == "filter" {
- cleanupChain(logf, conn, table, "INPUT", chainNameInput)
- cleanupChain(logf, conn, table, "FORWARD", chainNameForward)
- }
- if table.Name == "nat" {
- cleanupChain(logf, conn, table, "POSTROUTING", chainNamePostrouting)
- }
- }
- }
|