Merge branch 'feature-90'

This commit is contained in:
GnomeZworc 2026-10-31 20:10:58 +01:00
commit c34915e3e2
Signed by: nicolas.boufideline
GPG key ID: 4406BBBF8845D632
29 changed files with 355 additions and 217 deletions

View file

@ -16,7 +16,7 @@ bash ./deploy.sh -t 0.2.0 -i
`deploy.sh` se met à jour lui-même depuis la branche, télécharge binaires, units systemd et
scripts depuis la release, et les vérifie contre le manifeste `SHA256SUMS`. Le drapeau `-i`
prépare l'host : paquets, module `br_netfilter`, `sysctl`, et bridges.
prépare l'host : paquets, `sysctl`, et bridges.
Options utiles :

View file

@ -50,12 +50,12 @@ Paquets
- network namespaces : create/delete/call
* - ``internal/netif``
- netlink : bridge, veth, vxlan, tap, routes, adresses
* - ``internal/nft``, ``internal/iptables``
- wrappers dédiés ; ne pas appeler ces binaires ailleurs
* - ``internal/nft``
- wrapper dédié ; ne pas appeler ``nft`` ailleurs
* - ``internal/qemu``, ``internal/qmp``
- lancement de QEMU et client QMP sur socket Unix
* - ``internal/vm``
- cycle de vie d'une VM : tap, iptables, metadata, qemu
- cycle de vie d'une VM : tap, nftables, metadata, qemu
* - ``internal/dhcp``
- plan d'adressage ip → mac, et configurations dnsmasq du backend historique
* - ``internal/dhcpbackend``

View file

@ -13,18 +13,18 @@ Chemin d'une requête
.. mermaid::
graph LR
V["VM<br/>vers interface_ip:53 ou :123"] --> N["netns du VPC<br/>chaîne TWO-HOSTSVC<br/>DNAT vers 169.254.169.253"]
V["VM<br/>vers interface_ip:53 ou :123"] --> N["netns du VPC<br/>chaîne nftables hostsvc<br/>DNAT vers 169.254.169.253"]
N --> H["two-hostsvc<br/>socket dans le netns<br/>169.254.169.253 sur la dummy hostsvc"]
H -->|"depuis l'hôte"| U["serveurs amont<br/>puis résolveur ou horloge de l'hôte"]
À la création d'un VPC sur l'hyperviseur, l'agent pose dans son netns :
* une interface ``dummy`` ``hostsvc`` portant ``169.254.169.253/32`` ;
* une chaîne iptables ``TWO-HOSTSVC`` (table ``nat``), appelée depuis ``PREROUTING`` pour le seul
trafic à destination d'une adresse locale du netns (``addrtype LOCAL`` : les gateways des
subnets, anycast compris). Elle renvoie d'abord ce qui arrive par ``br-public`` (le segment
public de l'hôte) et par ``l3-+`` (le lien vers la VRF), puis redirige 53 en UDP et TCP et 123
en UDP vers ``169.254.169.253`` ;
* une chaîne nftables ``hostsvc`` dans la table ``ip two``, accrochée à ``prerouting`` en
priorité ``dstnat``. Elle renvoie d'abord ce qui arrive par ``br-public`` (le segment public de
l'hôte) et par ``l3-*`` (le lien vers la VRF), puis redirige 53 en UDP et TCP et 123 en UDP vers
``169.254.169.253``, pour le seul trafic à destination d'une adresse locale du netns
(``fib daddr type local`` : les gateways des subnets, anycast compris) ;
puis demande à ``two-hostsvc`` d'ouvrir ses sockets dans ce netns. La réponse repart par
conntrack, avec l'adresse de la gateway pour source. Une VM qui interroge un résolveur extérieur

View file

@ -34,7 +34,7 @@ reçoivent du trafic. Il désactive aussi ``br_netfilter`` dans le netns
conntrack voit chaque trame pontée et le SNAT de la passerelle NAT ne s'applique plus.
Dans le netns, l'agent pose aussi la ``dummy`` ``hostsvc`` (``169.254.169.253/32``) et la chaîne
iptables ``TWO-HOSTSVC``, puis demande à ``two-hostsvc`` de servir le VPC : c'est le chemin du
nftables ``hostsvc`` (table ``ip two``), puis demande à ``two-hostsvc`` de servir le VPC : c'est le chemin du
DNS et du NTP des VM (voir :doc:`dns-ntp`). Si ``two-hostsvc`` ne répond pas, la création du VPC
échoue.

View file

@ -8,7 +8,7 @@ Prérequis
---------
Un host Linux avec KVM, sur lequel vous avez ``root``. Les opérations réseau (network
namespaces, netlink, VXLAN, nftables, iptables) et QEMU ne fonctionnent que sous Linux.
namespaces, netlink, VXLAN, nftables) et QEMU ne fonctionnent que sous Linux.
Déploiement
-----------
@ -75,7 +75,7 @@ Ce que fait ``-i``
------------------
**Paquets** — ``qemu-system-x86``, ``qemu-utils``, ``ovmf``, ``dnsmasq``, ``nftables``,
``iptables``, ``nfs-common``, ``jq``, ``curl``, **sans les paquets recommandés** : ceux de
``nfs-common``, ``jq``, ``curl``, **sans les paquets recommandés** : ceux de
``qemu-system-x86`` (interface graphique, gtk, gstreamer, pilotes de stockage réseau) ne servent
pas à un hyperviseur sans écran, et l'installation passe d'environ 270 à 65 Mo — rejouée à chaque
démarrage, la racine étant en tmpfs. ``qemu-utils`` est demandé explicitement : ``qemu-img`` sert
@ -87,10 +87,11 @@ dans les netns.
aux hyperviseurs qui déclarent ``dhcp.backend: dnsmasq``, et tant qu'un hyperviseur peut revenir
en arrière. Voir :doc:`/exploitation/configuration`.
**Noyau** — chargement de ``br_netfilter``, puis ``net.ipv4.ip_forward = 1`` et
``net.bridge.bridge-nf-call-iptables = 1``. Cette dernière clé est **requise** par la DNAT vers
le serveur de metadata : sans elle, iptables ne voit pas le trafic bridgé des VM et cloud-init
ne se provisionne pas. Contrepartie assumée : tout le trafic inter-VM traverse les tables NAT.
**Noyau** — ``net.ipv4.ip_forward = 1``. ``br_netfilter`` n'est pas chargé : le filtrage des
ponts est en nftables (famille ``bridge``) et les redirections vers le serveur de metadata et
vers ``two-hostsvc`` sont posées dans le netns de chaque VPC, où l'agent coupe déjà
``bridge-nf-call-*``. Chargé, le module ferait passer tout le trafic bridgé des VM par netfilter
(``bridge-nf-call-iptables`` vaut 1 par défaut).
**Réseau** — création du bridge public, puis rattachement de l'uplink au bridge principal,
l'adresse et la route par défaut étant déplacées de l'interface physique vers le bridge.

View file

@ -274,7 +274,7 @@ code de sortie vaut 1 si une vérification échoue **ou si aucune n'a été fait
**Tests autonomes.** Avant chaque test, le runner supprime les ressources ``tNN`` laissées par un
passage précédent, puis relève l'état de chaque hôte de l'en-tête ``# hôtes:``. Après le test, il
supprime ses VM, ses subnets puis ses VPC, et vérifie que l'hôte est revenu à l'état relevé
(``assert_clean`` : netns, liens, adresses, routes, règles nftables de pont et iptables,
(``assert_clean`` : netns, liens, adresses, routes, règles nftables de l'hôte et de chaque netns,
configuration FRR et ``frr.conf``, fichiers de ``/run/two``, ``dnsmasq.d`` et des volumes, unités
``two-vm-*``, processus dnsmasq et QEMU). Aucun test ne dépend d'un autre : n'importe lequel se lance seul.

View file

@ -150,6 +150,7 @@ Depuis l'host, l'instance correspondante :
systemctl status 'metadata@<vm>'
ls -l /run/two/metadata/<vm>/
ip netns exec <vpc> nft list chain ip two md-<vm> # une dnat par IP de la VM
Le user-data est servi vide
---------------------------
@ -179,8 +180,7 @@ est redirigée vers ``two-hostsvc`` dans le netns du VPC (voir :doc:`../concepts
systemctl status two-hostsvc
cat /run/two/hostsvc/hostsvc.state # le VPC doit y figurer
ip -n <vpc> -4 addr show dev hostsvc # 169.254.169.253/32
ip netns exec <vpc> iptables -t nat -S TWO-HOSTSVC # 2 RETURN puis 3 DNAT
ip netns exec <vpc> iptables -t nat -L TWO-HOSTSVC -v -n # compteurs des redirections
ip netns exec <vpc> nft list chain ip two hostsvc # 2 return puis 3 dnat
ip netns exec <vpc> ss -lntu | grep 169.254.169.253 # 53/udp, 53/tcp, 123/udp
journalctl -u two-hostsvc -n 50

View file

@ -52,8 +52,8 @@ Dès qu'un VPC est ``running`` sur l'hyperviseur, il contrôle aussi le relais D
* ``two-hostsvc`` injoignable sur sa socket de contrôle : une notification, aucun VPC de
l'hyperviseur n'a plus de DNS ni de NTP ;
* pour chaque VPC ``running`` : VPC absent de la liste servie par ``two-hostsvc``,
``169.254.169.253`` absente de la ``dummy`` ``hostsvc``, ou chaîne ``TWO-HOSTSVC`` absente ou
incomplète dans son netns. Un VPC créé par une version antérieure à la 0.3.0 n'a rien de tout
``169.254.169.253`` absente de la ``dummy`` ``hostsvc``, ou chaîne ``hostsvc`` de la table
``ip two`` absente ou incomplète dans son netns. Un VPC créé par une version antérieure à la 0.3.0 n'a rien de tout
cela : il est signalé à chaque tick jusqu'à sa recréation.
Avec une section ``bgp`` dans la configuration, il contrôle aussi le plan de contrôle :

View file

@ -1,60 +0,0 @@
package iptables
import (
"errors"
"fmt"
"os/exec"
)
const HostSvcChain = "TWO-HOSTSVC"
var hostSvcExcluded = []string{"br-public", "l3-+"}
func hostSvcJump() []string {
return []string{"PREROUTING", "-m", "addrtype", "--dst-type", "LOCAL", "-j", HostSvcChain}
}
func hostSvcRules(target string) [][]string {
var rules [][]string
for _, iface := range hostSvcExcluded {
rules = append(rules, []string{HostSvcChain, "-i", iface, "-j", "RETURN"})
}
for _, p := range []struct{ proto, port string }{{"udp", "53"}, {"tcp", "53"}, {"udp", "123"}} {
rules = append(rules, []string{HostSvcChain,
"-p", p.proto, "-m", p.proto, "--dport", p.port,
"-j", "DNAT", "--to-destination", target,
})
}
return rules
}
func nat(args ...string) *exec.Cmd {
return exec.Command("iptables", append([]string{"-t", "nat"}, args...)...)
}
func AddHostSvcRedirect(target string) error {
if out, err := nat("-N", HostSvcChain).CombinedOutput(); err != nil {
return fmt.Errorf("iptables create chain %s: %w: %s", HostSvcChain, err, out)
}
for _, rule := range append(hostSvcRules(target), hostSvcJump()) {
if out, err := nat(append([]string{"-A"}, rule...)...).CombinedOutput(); err != nil {
return fmt.Errorf("iptables hostsvc redirect %v: %w: %s", rule, err, out)
}
}
return nil
}
func HasHostSvcRedirect(target string) (bool, error) {
for _, rule := range append(hostSvcRules(target), hostSvcJump()) {
err := nat(append([]string{"-C"}, rule...)...).Run()
var exit *exec.ExitError
switch {
case err == nil:
case errors.As(err, &exit) && exit.ExitCode() == 1:
return false, nil
default:
return false, fmt.Errorf("iptables check %v: %w", rule, err)
}
}
return true, nil
}

View file

@ -1,48 +0,0 @@
package iptables
import (
"reflect"
"strings"
"testing"
)
func TestHostSvcJump_OnlyLocalDestinations(t *testing.T) {
want := []string{"PREROUTING", "-m", "addrtype", "--dst-type", "LOCAL", "-j", "TWO-HOSTSVC"}
if got := hostSvcJump(); !reflect.DeepEqual(got, want) {
t.Errorf("jump = %v, want %v: traffic to an outside resolver must not be hijacked", got, want)
}
}
func TestHostSvcRules_ExclusionsComeFirst(t *testing.T) {
rules := hostSvcRules("169.254.169.253")
if len(rules) != 5 {
t.Fatalf("%d rules, want 2 exclusions and 3 redirections: %v", len(rules), rules)
}
for i, iface := range []string{"br-public", "l3-+"} {
want := []string{"TWO-HOSTSVC", "-i", iface, "-j", "RETURN"}
if !reflect.DeepEqual(rules[i], want) {
t.Errorf("rule %d = %v, want %v: the public segment and the vrf link must never reach the relay", i, rules[i], want)
}
}
}
func TestHostSvcRules_RedirectDNSAndNTPOnly(t *testing.T) {
var got []string
for _, rule := range hostSvcRules("169.254.169.253") {
if rule[len(rule)-3] != "DNAT" {
continue
}
if rule[len(rule)-1] != "169.254.169.253" {
t.Errorf("rule %v does not target 169.254.169.253", rule)
}
got = append(got, strings.Join(rule[1:7], " "))
}
want := []string{
"-p udp -m udp --dport 53",
"-p tcp -m tcp --dport 53",
"-p udp -m udp --dport 123",
}
if !reflect.DeepEqual(got, want) {
t.Errorf("redirections = %v, want %v", got, want)
}
}

View file

@ -1,44 +0,0 @@
package iptables
import (
"fmt"
"os/exec"
"git.g3e.fr/syonad/two/internal/metadata"
)
func addRule(args ...string) error {
return exec.Command("iptables", append([]string{"-t", "nat", "-A"}, args...)...).Run()
}
func deleteRule(args ...string) error {
return exec.Command("iptables", append([]string{"-t", "nat", "-D"}, args...)...).Run()
}
func AddMetadataRedirect(vmIP, gatewayIP, metadataPort string) error {
if err := addRule("PREROUTING",
"-s", vmIP+"/32",
"-d", metadata.ServiceIP+"/32",
"-p", "tcp", "-m", "tcp",
"--dport", "80",
"-j", "DNAT",
"--to-destination", gatewayIP+":"+metadataPort,
); err != nil {
return fmt.Errorf("iptables metadata redirect: %w", err)
}
return nil
}
func DeleteMetadataRedirect(vmIP, gatewayIP, metadataPort string) error {
if err := deleteRule("PREROUTING",
"-s", vmIP+"/32",
"-d", metadata.ServiceIP+"/32",
"-p", "tcp", "-m", "tcp",
"--dport", "80",
"-j", "DNAT",
"--to-destination", gatewayIP+":"+metadataPort,
); err != nil {
return fmt.Errorf("iptables delete metadata redirect: %w", err)
}
return nil
}

View file

@ -1,7 +1,7 @@
package metadata
// ServiceIP is the well-known address guests use to reach the metadata server.
// Traffic to it is DNATed to the subnet gateway by internal/iptables, and the
// Traffic to it is DNATed to the subnet gateway by internal/nft, and the
// route to it is advertised by internal/dhcp.
const ServiceIP = "169.254.169.254"

81
internal/nft/hostsvc.go Normal file
View file

@ -0,0 +1,81 @@
package nft
import (
"fmt"
"strings"
)
const HostSvcChain = "hostsvc"
var hostSvc = natChain{"", "nat", "prerouting", "dstnat"}
var hostSvcExcluded = []string{"br-public", "l3-*"}
func hostSvcRules(target string) []string {
var rules []string
for _, iface := range hostSvcExcluded {
rules = append(rules, fmt.Sprintf("iifname %q return", iface))
}
for _, p := range []struct{ proto, port string }{{"udp", "53"}, {"tcp", "53"}, {"udp", "123"}} {
rules = append(rules, fmt.Sprintf("fib daddr type local %s dport %s dnat to %s", p.proto, p.port, target))
}
return rules
}
func hostSvcScript(target string) string {
var b strings.Builder
fmt.Fprintf(&b, "add table ip %s\n", Table)
name := hostSvc.declare(&b, HostSvcChain)
for _, r := range hostSvcRules(target) {
fmt.Fprintf(&b, "add rule ip %s %s %s\n", Table, name, r)
}
return b.String()
}
func SetHostSvcRedirect(target string) error {
if err := apply(hostSvcScript(target)); err != nil {
return fmt.Errorf("set dns and ntp redirect: %w", err)
}
return nil
}
func HasHostSvcRedirect(target string) (bool, error) {
out, err := run([]string{"list", "chains", "ip"}, "")
if err != nil {
return false, err
}
if !hasChain(string(out), HostSvcChain) {
return false, nil
}
out, err = run([]string{"list", "chain", "ip", Table, HostSvcChain}, "")
if err != nil {
return false, err
}
return sameRules(chainRules(string(out)), append([]string{hostSvc.header()}, hostSvcRules(target)...)), nil
}
func hasChain(listing, chain string) bool {
table := ""
for _, line := range strings.Split(listing, "\n") {
fields := strings.Fields(line)
switch {
case len(fields) == 4 && fields[0] == "table" && fields[1] == "ip":
table = fields[2]
case len(fields) == 3 && fields[0] == "chain" && table == Table && fields[1] == chain:
return true
}
}
return false
}
func sameRules(have, want []string) bool {
if len(have) != len(want) {
return false
}
for i := range want {
if have[i] != want[i] {
return false
}
}
return true
}

View file

@ -0,0 +1,104 @@
package nft
import (
"strings"
"testing"
)
const listedHostSvcChains = `table ip two {
chain snat-ng-t46 {
type nat hook postrouting priority srcnat; policy accept;
}
chain hostsvc {
type nat hook prerouting priority dstnat; policy accept;
}
chain md-t90-m1 {
type nat hook prerouting priority dstnat; policy accept;
}
}
`
const listedHostSvcChain = `table ip two {
chain hostsvc {
type nat hook prerouting priority dstnat; policy accept;
iifname "br-public" return
iifname "l3-*" return
fib daddr type local udp dport 53 dnat to 169.254.169.253
fib daddr type local tcp dport 53 dnat to 169.254.169.253
fib daddr type local udp dport 123 dnat to 169.254.169.253
}
}
`
func TestHostSvcScript(t *testing.T) {
want := `add table ip two
add chain ip two hostsvc { type nat hook prerouting priority dstnat; policy accept; }
flush chain ip two hostsvc
add rule ip two hostsvc iifname "br-public" return
add rule ip two hostsvc iifname "l3-*" return
add rule ip two hostsvc fib daddr type local udp dport 53 dnat to 169.254.169.253
add rule ip two hostsvc fib daddr type local tcp dport 53 dnat to 169.254.169.253
add rule ip two hostsvc fib daddr type local udp dport 123 dnat to 169.254.169.253
`
if got := hostSvcScript("169.254.169.253"); got != want {
t.Errorf("script :\n%s\nattendu :\n%s", got, want)
}
}
func TestHostSvcRules_ExclusionsComeFirst(t *testing.T) {
rules := hostSvcRules("169.254.169.253")
if len(rules) != 5 {
t.Fatalf("%d règles, 2 exclusions et 3 redirections attendues : %v", len(rules), rules)
}
for i, iface := range []string{"br-public", "l3-*"} {
if want := `iifname "` + iface + `" return`; rules[i] != want {
t.Errorf("règle %d = %q, %q attendu : le segment public et le lien de la VRF n'atteignent jamais le relais", i, rules[i], want)
}
}
}
func TestHostSvcRules_OnlyLocalDestinations(t *testing.T) {
for _, r := range hostSvcRules("169.254.169.253") {
if strings.Contains(r, "dnat") && !strings.HasPrefix(r, "fib daddr type local ") {
t.Errorf("%q : un résolveur extérieur ne doit pas être détourné", r)
}
}
}
func TestHasChain(t *testing.T) {
if !hasChain(listedHostSvcChains, "hostsvc") {
t.Error("hostsvc non trouvée")
}
if hasChain(listedHostSvcChains, "md-t90") {
t.Error("md-t90 trouvée par préfixe")
}
if hasChain(strings.Replace(listedHostSvcChains, "table ip two", "table ip nat", 1), "hostsvc") {
t.Error("hostsvc trouvée dans une autre table")
}
if hasChain("", "hostsvc") {
t.Error("hostsvc trouvée sans table")
}
}
func TestHostSvcListingMatches(t *testing.T) {
want := append([]string{hostSvc.header()}, hostSvcRules("169.254.169.253")...)
if !sameRules(chainRules(listedHostSvcChain), want) {
t.Errorf("affichage nft %v, %v attendu", chainRules(listedHostSvcChain), want)
}
}
func TestHostSvcListingMismatches(t *testing.T) {
want := append([]string{hostSvc.header()}, hostSvcRules("169.254.169.253")...)
for label, listing := range map[string]string{
"règle 123 absente": strings.Replace(listedHostSvcChain, "\t\tfib daddr type local udp dport 123 dnat to 169.254.169.253\n", "", 1),
"règle 123 sans fib": strings.Replace(listedHostSvcChain, "fib daddr type local udp dport 123", "udp dport 123", 1),
"autre cible": strings.Replace(listedHostSvcChain, "53 dnat to 169.254.169.253", "53 dnat to 10.0.0.1", 1),
"exclusion après dnat": strings.Replace(strings.Replace(listedHostSvcChain, "\t\tiifname \"br-public\" return\n", "", 1), "dport 123 dnat to 169.254.169.253\n", "dport 123 dnat to 169.254.169.253\n\t\tiifname \"br-public\" return\n", 1),
"chaîne sans crochet": strings.Replace(listedHostSvcChain, "\t\ttype nat hook prerouting priority dstnat; policy accept;\n", "", 1),
"crochet d'une autre priorité": strings.Replace(listedHostSvcChain, "priority dstnat", "priority srcnat", 1),
} {
if sameRules(chainRules(listing), want) {
t.Errorf("%s : chaîne jugée conforme", label)
}
}
}

46
internal/nft/metadata.go Normal file
View file

@ -0,0 +1,46 @@
package nft
import (
"fmt"
"strings"
"git.g3e.fr/syonad/two/internal/metadata"
)
var metadataChain = natChain{"md-", "nat", "prerouting", "dstnat"}
func metadataRule(ip, target string) string {
return fmt.Sprintf("ip saddr %s ip daddr %s tcp dport 80 dnat to %s", ip, metadata.ServiceIP, target)
}
func metadataSetScript(vm string, ips []string, target string) string {
var b strings.Builder
fmt.Fprintf(&b, "add table ip %s\n", Table)
name := metadataChain.declare(&b, vm)
for _, ip := range ips {
fmt.Fprintf(&b, "add rule ip %s %s %s\n", Table, name, metadataRule(ip, target))
}
return b.String()
}
func metadataDeleteScript(vm string) string {
var b strings.Builder
fmt.Fprintf(&b, "add table ip %s\n", Table)
name := metadataChain.declare(&b, vm)
fmt.Fprintf(&b, "delete chain ip %s %s\n", Table, name)
return b.String()
}
func SetMetadataRedirect(vm string, ips []string, target string) error {
if err := apply(metadataSetScript(vm, ips, target)); err != nil {
return fmt.Errorf("set metadata redirect %s: %w", vm, err)
}
return nil
}
func DeleteMetadataRedirect(vm string) error {
if err := apply(metadataDeleteScript(vm)); err != nil {
return fmt.Errorf("delete metadata redirect %s: %w", vm, err)
}
return nil
}

View file

@ -0,0 +1,38 @@
package nft
import (
"strings"
"testing"
)
func TestMetadataSetScript(t *testing.T) {
want := `add table ip two
add chain ip two md-t90-m1 { type nat hook prerouting priority dstnat; policy accept; }
flush chain ip two md-t90-m1
add rule ip two md-t90-m1 ip saddr 10.90.1.10 ip daddr 169.254.169.254 tcp dport 80 dnat to 10.90.1.1:8001
add rule ip two md-t90-m1 ip saddr 10.90.2.10 ip daddr 169.254.169.254 tcp dport 80 dnat to 10.90.1.1:8001
`
if got := metadataSetScript("t90-m1", []string{"10.90.1.10", "10.90.2.10"}, "10.90.1.1:8001"); got != want {
t.Errorf("script :\n%s\nattendu :\n%s", got, want)
}
}
func TestMetadataDeleteScript(t *testing.T) {
want := `add table ip two
add chain ip two md-t90-m1 { type nat hook prerouting priority dstnat; policy accept; }
flush chain ip two md-t90-m1
delete chain ip two md-t90-m1
`
if got := metadataDeleteScript("t90-m1"); got != want {
t.Errorf("script :\n%s\nattendu :\n%s", got, want)
}
}
func TestMetadataScriptsStayInTheirChain(t *testing.T) {
script := metadataSetScript("t90-m1", []string{"10.90.1.10"}, "10.90.1.1:8001") + metadataDeleteScript("t90-m1")
for _, line := range strings.Split(strings.TrimSpace(script), "\n") {
if line != "add table ip two" && !strings.Contains(line, " ip two md-t90-m1") {
t.Errorf("ligne hors de la chaîne md-t90-m1 : %q", line)
}
}
}

View file

@ -23,9 +23,13 @@ var natChains = []natChain{
{"in-", "filter", "input", "filter"},
}
func (c natChain) header() string {
return fmt.Sprintf("type %s hook %s priority %s; policy accept;", c.kind, c.hook, c.priority)
}
func (c natChain) declare(b *strings.Builder, iface string) string {
name := c.prefix + iface
fmt.Fprintf(b, "add chain ip %s %s { type %s hook %s priority %s; policy accept; }\n", Table, name, c.kind, c.hook, c.priority)
fmt.Fprintf(b, "add chain ip %s %s { %s }\n", Table, name, c.header())
fmt.Fprintf(b, "flush chain ip %s %s\n", Table, name)
return name
}

View file

@ -10,7 +10,6 @@ import (
configuration "git.g3e.fr/syonad/two/internal/config/agent"
"git.g3e.fr/syonad/two/internal/dhcpbackend"
"git.g3e.fr/syonad/two/internal/iptables"
"git.g3e.fr/syonad/two/internal/l3vni"
"git.g3e.fr/syonad/two/internal/metadata"
"git.g3e.fr/syonad/two/internal/netif"
@ -63,12 +62,7 @@ func StartVM(db *badger.DB, name string, cfg *configuration.Config) error {
// métadonnées de l'interface primaire. Toutes les interfaces étant dans le
// même VPC, donc le même netns, il est joignable depuis n'importe laquelle.
if err := netns.Call(nic.vpcName, func() error {
for _, n := range d.nics {
if err := iptables.AddMetadataRedirect(n.ip, nic.interfaceIP, d.metadataPort); err != nil {
return fmt.Errorf("interface %d: %w", n.index, err)
}
}
return nil
return nft.SetMetadataRedirect(name, nicIPs(d.nics), nic.interfaceIP+":"+d.metadataPort)
}); err != nil {
return fmt.Errorf("add metadata redirect: %w", err)
}
@ -186,6 +180,14 @@ func copyFile(src, dst string) error {
return out.Sync()
}
func nicIPs(nics []nicData) []string {
ips := make([]string, len(nics))
for i, n := range nics {
ips[i] = n.ip
}
return ips
}
func nicMACs(nics []nicData) []string {
macs := make([]string, len(nics))
for i, n := range nics {

View file

@ -18,3 +18,17 @@ func TestNicMACs_KeepsTheOrderAndLowersTheCase(t *testing.T) {
t.Errorf("nicMACs = %v, attendu %v", got, want)
}
}
func TestNicIPs_EveryInterfaceGetsTheRedirect(t *testing.T) {
nics := []nicData{
{index: 0, ip: "10.49.1.10"},
{index: 1, ip: "10.49.2.10", primary: true},
}
got := nicIPs(nics)
want := []string{"10.49.1.10", "10.49.2.10"}
if !reflect.DeepEqual(got, want) {
t.Errorf("nicIPs = %v, attendu %v", got, want)
}
}

View file

@ -11,7 +11,6 @@ import (
configuration "git.g3e.fr/syonad/two/internal/config/agent"
"git.g3e.fr/syonad/two/internal/dhcpbackend"
"git.g3e.fr/syonad/two/internal/iptables"
"git.g3e.fr/syonad/two/internal/l3vni"
"git.g3e.fr/syonad/two/internal/metadata"
"git.g3e.fr/syonad/two/internal/netif"
@ -60,12 +59,7 @@ func StopVM(db *badger.DB, name string, cfg *configuration.Config) error {
}
if err := netns.Call(nic.vpcName, func() error {
for _, n := range d.nics {
if err := iptables.DeleteMetadataRedirect(n.ip, nic.interfaceIP, d.metadataPort); err != nil {
return fmt.Errorf("interface %d: %w", n.index, err)
}
}
return nil
return nft.DeleteMetadataRedirect(name)
}); err != nil {
return fmt.Errorf("delete metadata redirect: %w", err)
}

View file

@ -7,9 +7,9 @@ import (
hostsvcapi "git.g3e.fr/syonad/two/internal/api/hostsvc"
hostsvcclient "git.g3e.fr/syonad/two/internal/client/hostsvc"
"git.g3e.fr/syonad/two/internal/hostsvc"
"git.g3e.fr/syonad/two/internal/iptables"
"git.g3e.fr/syonad/two/internal/netif"
"git.g3e.fr/syonad/two/internal/netns"
"git.g3e.fr/syonad/two/internal/nft"
)
const HostSvcLink = "hostsvc"
@ -34,7 +34,7 @@ func newSystemHostSvc() systemHostSvc {
func (systemHostSvc) InNetns(vpc string, fn func() error) error { return netns.Call(vpc, fn) }
func (systemHostSvc) CreateDummy(name string) error { return netif.CreateDummy(name) }
func (systemHostSvc) AddrAdd(iface string, ip net.IP) error { return netif.AddrAdd(iface, ip) }
func (systemHostSvc) AddRedirect(target string) error { return iptables.AddHostSvcRedirect(target) }
func (systemHostSvc) AddRedirect(target string) error { return nft.SetHostSvcRedirect(target) }
func (s systemHostSvc) Open(vpc string) error { return s.client.Open(vpc) }
func (s systemHostSvc) Close(vpc string) error { return s.client.Close(vpc) }

View file

@ -7,9 +7,9 @@ import (
hostsvcapi "git.g3e.fr/syonad/two/internal/api/hostsvc"
hostsvcclient "git.g3e.fr/syonad/two/internal/client/hostsvc"
"git.g3e.fr/syonad/two/internal/hostsvc"
"git.g3e.fr/syonad/two/internal/iptables"
"git.g3e.fr/syonad/two/internal/netif"
"git.g3e.fr/syonad/two/internal/netns"
"git.g3e.fr/syonad/two/internal/nft"
"git.g3e.fr/syonad/two/internal/state"
"git.g3e.fr/syonad/two/internal/vpc"
"git.g3e.fr/syonad/two/internal/watchdog/notify"
@ -58,7 +58,7 @@ func (systemHostSvcProbe) Redirect(name string) (bool, error) {
var ok bool
err := netns.Call(name, func() error {
var err error
ok, err = iptables.HasHostSvcRedirect(hostsvc.ServiceIP)
ok, err = nft.HasHostSvcRedirect(hostsvc.ServiceIP)
return err
})
return ok, err
@ -103,7 +103,7 @@ func CheckHostSvc(db *badger.DB, p hostSvcProbe, n notify.Notifier) error {
if ok, err := p.Redirect(name); err != nil {
n.Notify(kindVPC, name, fmt.Sprintf("dns and ntp redirection unreadable: %v", err))
} else if !ok {
n.Notify(kindVPC, name, fmt.Sprintf("dns and ntp redirection to %s missing or incomplete (chain %s)", hostsvc.ServiceIP, iptables.HostSvcChain))
n.Notify(kindVPC, name, fmt.Sprintf("dns and ntp redirection to %s missing or incomplete (nft chain ip %s %s)", hostsvc.ServiceIP, nft.Table, nft.HostSvcChain))
}
}
return nil

View file

@ -97,7 +97,7 @@ func TestCheckHostSvc_ReportsEachMissingPiece(t *testing.T) {
for name, want := range map[string]string{
"vp-unserved": "not served by two-hostsvc: its vms get no dns nor ntp",
"vp-noaddr": "169.254.169.253 missing on hostsvc (in netns)",
"vp-noredirect": "dns and ntp redirection to 169.254.169.253 missing or incomplete (chain TWO-HOSTSVC)",
"vp-noredirect": "dns and ntp redirection to 169.254.169.253 missing or incomplete (nft chain ip two hostsvc)",
} {
got := r.forName(name)
if len(got) != 1 || got[0].kind != "vpc" || got[0].problem != want {

View file

@ -164,6 +164,13 @@
`nftables` à la place d'`ebtables`. Les règles ebtables des subnets existants ne sont ni
reprises ni retirées : vider l'hyperviseur (VM, subnets, VPC) avant la mise à jour, puis les
recréer
- **Les redirections passent d'iptables à nftables (#90)** : celle des métadonnées (une chaîne
`md-<vm>` par VM) et celle du DNS et du NTP (chaîne `hostsvc`) sont posées dans la table
`ip two` du netns de chaque VPC. `bootstrap_kvm.sh` n'installe plus `iptables`, ne charge plus
`br_netfilter` et n'écrit plus `net.bridge.bridge-nf-call-iptables = 1`. L'agent ne reprend
pas les règles iptables des VM créées par la 0.2.0 : le vidage de l'hyperviseur demandé
ci-dessous les retire. Sur un hyperviseur déjà déployé, le module reste chargé jusqu'au
redémarrage (ou `modprobe -r br_netfilter`)
- **Une VM ne peut plus émettre depuis une adresse qui n'est pas la sienne (#76)** : une VM qui
route pour d'autres machines, porte une adresse supplémentaire ou sert le DHCP perd ce trafic.
Pour un serveur DHCP, créer l'interface avec `dhcp_server: true`

View file

@ -16,7 +16,7 @@
# L'host est stateless (root sur tmpfs) : rien de ce qui suit ne survit à un
# reboot, deploy.sh --bootstrap est rejoué à chaque démarrage.
KVM_PACKAGES="qemu-system-x86 qemu-utils ovmf dnsmasq nftables iptables nfs-common jq curl"
KVM_PACKAGES="qemu-system-x86 qemu-utils ovmf dnsmasq nftables nfs-common jq curl"
kvm_packages () {
local DRY_RUN="${1}"
@ -39,15 +39,11 @@ kvm_kernel () {
info "kernel"
# modprobe AVANT sysctl : les clés net.bridge.* n'existent pas tant que
# br_netfilter n'est pas chargé, et sysctl --system échouerait.
run "${DRY_RUN}" "modprobe br_netfilter"
run "${DRY_RUN}" "echo br_netfilter > /etc/modules-load.d/two.conf"
# bridge-nf-call-iptables est requis par le DNAT metadata (169.254.169.254,
# cf. internal/iptables) : sans lui, iptables ne voit pas le trafic bridgé
# des VMs. Contrepartie : tout le trafic inter-VM traverse les tables nat.
run "${DRY_RUN}" "printf 'net.ipv4.ip_forward = 1\nnet.bridge.bridge-nf-call-iptables = 1\n' > /etc/sysctl.d/90-two.conf"
# Pas de br_netfilter : le filtrage des ponts est en nftables (famille
# bridge) et les DNAT vivent dans les netns, où l'agent coupe déjà
# bridge-nf-call-*. Chargé, le module ferait passer tout le trafic bridgé
# des VM par netfilter (bridge-nf-call-iptables vaut 1 par défaut).
run "${DRY_RUN}" "printf 'net.ipv4.ip_forward = 1\n' > /etc/sysctl.d/90-two.conf"
run "${DRY_RUN}" "sysctl --system >/dev/null"
}

View file

@ -56,7 +56,8 @@ host_state () {
echo "## adresses"; ip -o -4 addr show | awk '{print $2, $4}' | sort
echo "## routes"; ip -4 route show table all | grep -v '^local \|^broadcast ' | sort
echo "## nftables bridge"; nft list ruleset bridge
echo "## iptables"; iptables-save | grep -v '^#' | sed 's/ \[[0-9]*:[0-9]*\]$//'
echo "## nftables ip"; nft list ruleset ip
echo "## nftables des netns"; local ns; for ns in $(ip netns list | awk '{print $1}' | sort); do echo "# ${ns}"; ip netns exec "${ns}" nft list ruleset; done
echo "## frr"; vtysh -c 'show running-config' | grep -v '^Building\|^Current configuration\|^!'
echo "## frr.conf"; sha256sum /etc/frr/frr.conf | cut -d' ' -f1
echo "## fichiers"; find /run/two /etc/dnsmasq.d "${VOLUMES}" -mindepth 1 ! -type d 2>/dev/null | sort

View file

@ -50,9 +50,9 @@ ntp_ok () {
}
no_answer () { ! vm_py "${1}" "${2}" dns_py "${3}" udp deb.debian.org "${4}" >/dev/null 2>&1; }
served_ports () { ip netns exec "${1}" ss -Hlntu | awk '$5 ~ /^169\.254\.169\.253:/ {print $1, $5}' | sort | tr '\n' ' '; }
rules () { ip netns exec "${1}" iptables -t nat -S TWO-HOSTSVC; }
rules () { ip netns exec "${1}" nft list chain ip two hostsvc | sed -n '/^\t\t/s/^\t\t//p'; }
state_has () { grep -q "\"${1}\"" /run/two/hostsvc/hostsvc.state; }
excluded_first () { [ "$(rules "${1}" | sed -n '2p;3p' | tr '\n' ' ')" = "-A TWO-HOSTSVC -i br-public -j RETURN -A TWO-HOSTSVC -i l3-+ -j RETURN " ]; }
excluded_first () { [ "$(rules "${1}" | sed -n '2p;3p' | tr '\n' ' ')" = 'iifname "br-public" return iifname "l3-*" return ' ]; }
no_dns () { ! dns_ok "$@" >/dev/null 2>&1; }
no_ntp () { ! ntp_ok "$@" >/dev/null 2>&1; }
vpc_in_error () {
@ -71,9 +71,10 @@ check "subnet sn-t29b en mode bridge sur br-lan, interface_ip 10.33.0.29" subnet
for vpc in vp-t29 vp-t29b; do
check "${vpc} : 169.254.169.253 sur la dummy hostsvc" sh -c "ip -n ${vpc} -4 -o addr show dev hostsvc | grep -q ' 169.254.169.253/32 '"
check "${vpc} : two-hostsvc n'écoute que 53/udp, 53/tcp et 123/udp sur 169.254.169.253" test "$(served_ports "${vpc}")" = "tcp 169.254.169.253:53 udp 169.254.169.253:123 udp 169.254.169.253:53 "
check "${vpc} : chaîne TWO-HOSTSVC, br-public et l3-+ exclus avant toute redirection" excluded_first "${vpc}"
check "${vpc} : redirection de 53/udp, 53/tcp et 123/udp vers 169.254.169.253" test "$(rules "${vpc}" | grep -c 'DNAT --to-destination 169.254.169.253')" -eq 3
check "${vpc} : appel depuis PREROUTING pour les destinations locales seulement" sh -c "ip netns exec ${vpc} iptables -t nat -S PREROUTING | grep -qx -- '-A PREROUTING -m addrtype --dst-type LOCAL -j TWO-HOSTSVC'"
check "${vpc} : chaîne hostsvc de ip two accrochée à prerouting en dstnat" test "$(rules "${vpc}" | head -n 1)" = "type nat hook prerouting priority dstnat; policy accept;"
check "${vpc} : br-public et l3-* exclus avant toute redirection" excluded_first "${vpc}"
check "${vpc} : redirection de 53/udp, 53/tcp et 123/udp vers 169.254.169.253" test "$(rules "${vpc}" | grep -c 'dnat to 169.254.169.253$')" -eq 3
check "${vpc} : redirection pour les destinations locales seulement" test "$(rules "${vpc}" | grep -c '^fib daddr type local .* dnat to 169.254.169.253$')" -eq 3
check "${vpc} : inscrit dans l'état de two-hostsvc" state_has "${vpc}"
done
@ -98,10 +99,11 @@ ip -n vp-t29 addr del 169.254.169.253/32 dev hostsvc
check "watchdog : adresse 169.254.169.253 retirée signalée" wait_watchdog "169.254.169.253 missing on hostsvc (in netns)"
ip -n vp-t29 addr add 169.254.169.253/32 dev hostsvc
check "10.29.1.10 : DNS de nouveau servi une fois l'adresse remise" dns_ok vp-t29 10.29.1.10 10.29.1.254 udp
ip netns exec vp-t29 iptables -t nat -D TWO-HOSTSVC -p udp -m udp --dport 123 -j DNAT --to-destination 169.254.169.253
check "watchdog : redirection incomplète signalée" wait_watchdog "dns and ntp redirection to 169.254.169.253 missing or incomplete (chain TWO-HOSTSVC)"
HANDLE=$(ip netns exec vp-t29 nft -a list chain ip two hostsvc | awk '/udp dport 123 / {print $NF}')
check "règle 123 retirée à la main de hostsvc (handle ${HANDLE:-absent})" ip netns exec vp-t29 nft delete rule ip two hostsvc handle "${HANDLE}"
check "watchdog : redirection incomplète signalée" wait_watchdog "dns and ntp redirection to 169.254.169.253 missing or incomplete (nft chain ip two hostsvc)"
check "10.29.1.10 : sans la règle 123, plus de NTP (témoin)" no_ntp vp-t29 10.29.1.10 10.29.1.254
ip netns exec vp-t29 iptables -t nat -A TWO-HOSTSVC -p udp -m udp --dport 123 -j DNAT --to-destination 169.254.169.253
check "règle 123 reposée" ip netns exec vp-t29 nft add rule ip two hostsvc fib daddr type local udp dport 123 dnat to 169.254.169.253
check "10.29.1.10 : NTP de nouveau servi une fois la règle remise" ntp_ok vp-t29 10.29.1.10 10.29.1.254
systemctl stop two-hostsvc.service

View file

@ -48,7 +48,7 @@ sleep 20
check "après redémarrage : même processus QEMU pour t61-a (ni arrêtée ni recréée)" test "$(pgrep -f "${VOLUMES}/t61-a.qcow2" | sort | tr '\n' ' ')" = "${QEMU}"
check "après redémarrage : même processus QEMU pour t61-d" test "$(pgrep -f "${VOLUMES}/t61-d.qcow2" | sort | tr '\n' ' ')" = "${QEMU_D}"
check "après redémarrage : mêmes fichiers sous /run/two, /etc/dnsmasq.d et les volumes (sinon, fichiers en cause)" section_unchanged "${STATE_DIR}/t61.restart" fichiers
check "après redémarrage : hôte inchangé (netns, liens, taps, adresses, routes, nftables de pont, iptables, FRR, frr.conf, fichiers, unités)" same_as "${STATE_DIR}/t61.restart" host_state
check "après redémarrage : hôte inchangé (netns, liens, taps, adresses, routes, nftables de pont, ip et des netns, FRR, frr.conf, fichiers, unités)" same_as "${STATE_DIR}/t61.restart" host_state
check "après redémarrage : l'API rend les mêmes ressources dans le même état" same_as "${STATE_DIR}/t61.api" api_snapshot
for rr in 10.255.255.1 10.255.255.2; do
check "après redémarrage : session EVPN vers ${rr} établie, jamais coupée" sh -c "vtysh -c 'show bgp neighbors ${rr}' | grep -q 'BGP state = Established' && [ \"\$(vtysh -c 'show bgp neighbors ${rr}' | grep -o 'dropped [0-9]*')\" = \"\$(cat '${STATE_DIR}/t61.${rr}')\" ]"

View file

@ -18,7 +18,7 @@ check "${HOST} : aucune instance DHCP (dhcp@, dnsmasq@) ni de métadonnées (met
check "${HOST} : aucun socket de contrôle DHCP" none sh -c "ls /run/two/dhcp/*.sock 2>/dev/null"
check "${HOST} : aucun processus QEMU" none pgrep -a qemu-system
check "${HOST} : aucune règle nftables de pont qui vise une interface de subnet" none sh -c "nft list ruleset bridge | grep -E 'v-[a-z0-9]'"
check "${HOST} : aucune règle iptables qui vise une interface de subnet ou de VPC" none sh -c "iptables-save | grep -E -- '(v-|vp-|tap)[a-z0-9]'"
check "${HOST} : aucune règle nftables ip qui vise une interface de subnet ou de VPC" none sh -c "nft list ruleset ip | grep -E -- '(v-|vp-|tap)[a-z0-9]'"
check "${HOST} : aucun volume de VM de test" none sh -c "ls '${VOLUMES}'/t[0-9][0-9]-* 2>/dev/null"
check "${HOST} : FRR garde la base BGP (témoin)" sh -c "vtysh -c 'show running-config' | grep -q 'peer-group fabric'"
check "${HOST} : FRR sans aucune VRF de VPC (en mémoire)" none sh -c "vtysh -c 'show running-config' | grep -E '^(vrf |router bgp [0-9]+ vrf )'"