siit

package module
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-siit

A Go library for stateless IP/ICMP translation (SIIT) between IPv4 and IPv6, as defined in RFC 7915. It also implements:

  • RFC 6052: IPv6 Addressing of IPv4/IPv6 Translators
  • RFC 7757: Explicit Address Mappings for Stateless IP/ICMP Translation

The library translates one packet per call. Reading and writing packets (tun devices, raw sockets, AF_XDP) is up to the caller. Callers that use raw bytes need only the standard library; callers that use gopacket can pass their decoded layers.

The API reference, with runnable examples, is on pkg.go.dev.

Requirements for the caller

  1. Pass packets that start at the IP header. Slice off a link header first, for example frame[14:] for Ethernet.
  2. Keep packets of the same flow in order. The translator never queues or reorders packets (RFC 7915 Sections 4 and 5: "The translator SHOULD make sure that the packets belonging to the same flow leave the translator in the same order in which they arrived.").
  3. Set the MTU of your IPv4 interface to 1260. The translator never splits packets (fragmentation): a packet that is too large is rejected with ErrPacketOversized. With this MTU, the kernel tells the sender to send smaller packets instead (ICMP Fragmentation Needed).
  4. Set Config.MTU only when the IPv6 side supports packets larger than 1280 bytes, and set the IPv4 interface MTU to that value minus 20. An MTU below 1280 is rejected with ErrInvalidMTU.
  5. Write a reply (see below) to the interface you read the packet from.

Why 1260: the IPv6 header is 20 bytes larger than the IPv4 header, and IPv6 guarantees 1280 bytes. An IPv4 packet that is already a fragment also needs an 8-byte IPv6 Fragment header, so it can be at most 1252 bytes.

The translator handles unicast traffic that is routed across it, not link-local protocols such as neighbor discovery.

Usage

Creating a translator
translator, err := siit.NewTranslator(siit.Config{
	NAT64Prefix:       netip.MustParsePrefix("2001:db8:64::/96"), // RFC 6052
	IPv4RouterAddress: netip.MustParseAddr("192.0.2.1"),         // source of the ICMP errors the translator generates
	EAMTable:          nil,                                      // RFC 7757, may be empty
	MTU:               0,                                        // IPv6 path MTU, 0 means 1280
})
  • NAT64 prefix: the IPv6 prefix that IPv4 addresses are put into (embedded in). With 64:ff9b::/96, the IPv4 address 1.2.3.4 becomes 64:ff9b::102:304. Most NAT64 networks use 64:ff9b::/96 (the Well-Known Prefix); others use their own prefix (a Network-Specific Prefix).
  • Router address: an IPv4 address that stands for the translator itself. It is the sender of the error messages the translator creates.
  • EAM table: fixed rules (Explicit Address Mappings) such as "IPv4 192.0.2.1 is IPv6 2001:db8::1". They take precedence over the prefix.
A private router address with 64:ff9b::/96

The RFCs do not allow private (non-global) IPv4 addresses inside the prefix 64:ff9b::/96 (RFC 6052 Section 3.1). So with that prefix, NewTranslator rejects a private router address such as 192.168.x.x or 192.0.0.x. Add an EAM entry that maps the router address to a public IPv6 address of this machine.

A CLAT, which gives one host IPv4 access on an IPv6-only network, typically needs this:

router, _ := siit.ParseEAMEntry("192.0.0.254", publicIPv6.String()) // the CLAT's own IPv6 address
host, _ := siit.ParseEAMEntry("192.0.0.1", hostIPv6.String())

translator, err := siit.NewTranslator(siit.Config{
	NAT64Prefix:       netip.MustParsePrefix("64:ff9b::/96"),
	IPv4RouterAddress: netip.MustParseAddr("192.0.0.254"),
	EAMTable:          siit.EAMTable{router, host},
})
Translating
result, err := translator.TranslateIPv4(buffer[:n])
var translationErr *siit.TranslationError
switch {
case errors.As(err, &translationErr):
	writeToIPv4(translationErr.Reply) // an ICMP error back to the sender
case err != nil:
	log.Print(err) // rejected
case len(result) > 0:
	writeToIPv6(result) // translated
}

TranslateIPv6 works the same in the other direction. A caller that already decoded the packet with gopacket passes the layer instead, so the packet is not decoded twice:

ip := packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
result, err := translator.TranslateIPv4Layer(ip)
Outcome Returned Packet Error
Translated the packet for the other side nil
Dropped on purpose (for example IGMP) empty nil
Rejected empty wraps one of the Err values; errors.Is tells why
Rejected and answered empty a *TranslationError whose Reply you write to the interface you read the packet from

Packet is a []byte. Src(), Dst() and Version() read its header, and Decode() returns a lazily decoded gopacket view.

Buffers and concurrency
  • The input is never modified or kept, so the read buffer can be reused right away.
  • Every returned Packet and Reply is a new slice that belongs to the caller. A view from Decode() shares its bytes.
  • One Translator can be used from several goroutines.

Limitations

  • No fragmentation. A packet that does not fit the IPv6 MTU is rejected, so set the IPv4 MTU as described above.
  • No general ICMP error for dropped packets. The specific ICMP errors, such as Time Exceeded, are sent. The optional "administratively prohibited" error for any other dropped packet is not. The returned error tells you why a packet was dropped, so you can send it yourself.
  • No rate limit on the ICMP errors the translator sends.
  • No hairpinning. Two IPv6 hosts that both have EAM entries cannot reach each other through the translator by their IPv4 addresses.

docs/rfc-deviations.md lists every RFC recommendation that the library does not follow, with the RFC text.

Migrating from v0.2

v0.2 v0.3
NewTranslator(nat64Net, router, eamTable), NewTranslatorWithMTU(…, mtu) NewTranslator(siit.Config{…}) with netip types
RawEAMTable{{IPv4Prefix: "…", IPv6Prefix: "…"}} EAMTable of EAMEntry; ParseEAMEntry("…", "…") parses the text form
Translator.MTU Config.MTU
TranslateIPv4(packet gopacket.Packet, TranslationOverrides{}) TranslateIPv4(packet []byte) or TranslateIPv4Layer(*layers.IPv4)
TranslatedPacket{Packet, SrcIP, DstIP} Packet with Src(), Dst() and Version()
TranslationError.Packet TranslationError.Reply
ErrUnsupportedDestIP ErrUnsupportedDstIP

Behaviour that changed:

  • A generated ICMP error only arrives in TranslationError.Reply. Source Route Failed used to be returned as the translated packet with a nil error; it is now ErrSourceRouteFailed with a reply.
  • Time Exceeded goes back in the family of the expired packet: an ICMPv4 error for an IPv4 packet, an ICMPv6 error for an IPv6 packet.
  • Rejected packets no longer return addresses. Errors are lowercase, and new sentinels are ErrSourceRouteFailed, ErrZeroUDPChecksum and ErrInvalidConfig.
  • The router address must be a unicast address, and a non-global one needs an EAM entry with the Well-Known Prefix (see above).

A tun loop changes like this:

// v0.2
packet := gopacket.NewPacket(buffer[:n], layers.LayerTypeIPv4, gopacket.Default)
result, err := translator.TranslateIPv4(packet, siit.TranslationOverrides{})
send(result.Packet, result.DstIP)

// v0.3
result, err := translator.TranslateIPv4(buffer[:n])
send(result, result.Dst())

AI-declaration

The project is written with AI-assisted programming. Subagents are used to check all references and do code review first, then manual review is also performed before committing.

Documentation

Overview

Package siit translates packets between IPv4 and IPv6 without keeping state (SIIT, RFC 7915), with the addressing of RFC 6052 and the explicit address mappings of RFC 7757.

Creating a translator

NewTranslator takes a Config with:

  • the NAT64 prefix, the IPv6 prefix that IPv4 addresses are put into (embedded in),
  • the router address, an IPv4 address that stands for the translator itself and sends its error messages,
  • optionally an EAM table of fixed rules (Explicit Address Mappings) such as 'IPv4 192.0.2.1 is IPv6 2001:db8::1',
  • optionally the IPv6 MTU.

A Translator cannot be changed after it is created, so one translator can serve several goroutines.

The RFCs do not allow private (non-global) IPv4 addresses inside the prefix 64:ff9b::/96 (the Well-Known Prefix, RFC 6052 Section 3.1). So with that prefix, a private router address such as 192.0.0.254 (as a CLAT uses) needs an EAM entry that maps it to a public IPv6 address of this machine.

Translating

TranslateIPv4 and TranslateIPv6 take a raw packet that starts at the IP header and need only the standard library. A caller that reads link-layer frames slices the link header off first, for example frame[14:] for Ethernet; bytes after the IP length, like Ethernet padding, are ignored. A caller that already decoded the packet with gopacket passes the layer to TranslateIPv4Layer or TranslateIPv6Layer instead, so it is not decoded twice.

The result is one of:

  • A translated packet and a nil error: write the packet to the interface for the other IP version.
  • An empty packet and a nil error: the packet is dropped on purpose, for example IGMP.
  • An empty packet and an error that wraps one of the Err values: the packet is rejected. errors.Is tells why.
  • An empty packet and a *TranslationError with a Reply: the packet is rejected and answered with an ICMP error. Write the reply to the interface you read the packet from.

Buffers

The input is never modified or kept, so a caller can reuse its read buffer right away. Every Packet is a new slice that belongs to the caller. Packet.Decode returns a gopacket view that shares the bytes of the packet.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// The packet is malformed: a bad header, length or checksum, or a Routing header with segments left.
	ErrInvalidPacket = errors.New("invalid packet")

	// The ICMP message is malformed, for example too short or with an invalid code. ICMP messages that have no
	// translation are dropped without an error.
	ErrInvalidICMP = errors.New("invalid ICMP packet")

	// The packet carries something the translator does not translate, such as a fragmented ICMP message.
	ErrUnsupportedProtocol = errors.New("unsupported protocol")

	// The TTL or Hop Limit ran out. Usually the error is a *TranslationError with a Time Exceeded reply to send. Some
	// packets must not be answered, such as ICMP errors; then the error is plain and there is nothing to send.
	ErrTimeExceeded = errors.New("TTL or Hop Limit expired")

	// The IPv4 packet asks to be routed along a fixed path (an unexpired source route option), which the translator
	// cannot follow. Usually the error is a
	// *TranslationError with a Source Route Failed reply to send. For an ICMP error there is nothing to send.
	ErrSourceRouteFailed = errors.New("unexpired IPv4 source route")

	// The source address is not unicast, cannot be mapped, or must not be mapped.
	ErrUnsupportedSrcIP = errors.New("unsupported source IP address")

	// The destination address is not unicast, cannot be mapped, or must not be mapped.
	ErrUnsupportedDstIP = errors.New("unsupported destination IP address")

	// The translated packet would be larger than the IPv6 MTU. The translator never splits packets (fragmentation).
	ErrPacketOversized = errors.New("packet too large for the IPv6 MTU")

	// A UDP checksum of zero that cannot be handled. The message names the addresses and ports, for the caller to
	// log.
	ErrZeroUDPChecksum = errors.New("UDP checksum is zero")
)

A rejected packet returns an error that wraps exactly one of these, so errors.Is tells why it was rejected.

View Source
var (
	ErrInvalidConfig = errors.New("invalid translator configuration")
	ErrInvalidMTU    = errors.New("MTU is below the IPv6 minimum")
)

NewTranslator returns an error wrapping ErrInvalidConfig for an invalid Config, and also ErrInvalidMTU when the MTU is the problem.

Functions

This section is empty.

Types

type Config

type Config struct {
	// The IPv6 prefix that IPv4 addresses are put into (embedded in, RFC 6052): a /32, /40, /48, /56, /64 or /96
	// prefix. With 64:ff9b::/96, the IPv4 address 1.2.3.4 becomes 64:ff9b::102:304. Most NAT64 networks use
	// 64:ff9b::/96 (the Well-Known Prefix).
	NAT64Prefix netip.Prefix

	// An IPv4 address that stands for the translator itself. It is the sender of the error messages the translator
	// creates. It also replaces the source of an error message from an IPv6 router that has no IPv4 address
	// (RFC 6791).
	//
	// With 64:ff9b::/96 and a private (non-global) address such as 192.0.0.254, add an EAM entry that maps this address to a
	// public IPv6 address of this machine.
	IPv4RouterAddress netip.Addr

	// Fixed address mappings (Explicit Address Mappings, RFC 7757), such as 'IPv4 192.0.2.1 is IPv6 2001:db8::1'. They take precedence over
	// NAT64Prefix. May be empty. The table is copied, so changing it afterwards does not affect the translator.
	EAMTable EAMTable

	// IPv6 path MTU, at least 1280. Zero means 1280.
	MTU uint32
}

Config configures a Translator. Only NAT64Prefix and IPv4RouterAddress are required. Bits after a prefix length (host bits) are ignored, so 192.0.2.5/24 is read as 192.0.2.0/24.

type EAMEntry

type EAMEntry struct {
	IPv4Prefix netip.Prefix
	IPv6Prefix netip.Prefix
}

EAMEntry is a fixed rule (an Explicit Address Mapping) that maps an IPv4 prefix to an IPv6 prefix. A single address is a prefix of 32 or 128 bits. Bits after the prefix length (host bits) are ignored, so 192.0.2.5/24 is read as 192.0.2.0/24.

func ParseEAMEntry

func ParseEAMEntry(ipv4Prefix, ipv6Prefix string) (EAMEntry, error)

ParseEAMEntry parses an entry from its text form, like ParseEAMEntry("192.0.2.0/24", "2001:db8::/120"), and checks it like NewTranslator does. An invalid entry returns an error wrapping ErrInvalidConfig.

RFC 7757 Section 3.2 (MUST): "The prefix length MAY be omitted, in which case the implementation MUST assume it to be 32 for IPv4 and 128 for IPv6."

type EAMTable

type EAMTable []EAMEntry

EAMTable is a list of fixed address mappings. When several entries match an address, the longest prefix wins.

type Packet

type Packet []byte

Packet is a serialized IP packet, starting at the IP header. It is empty when nothing has to be sent.

func (Packet) Decode

func (p Packet) Decode() gopacket.Packet

Decode returns a lazily decoded gopacket view of the packet, or nil when Version is 0. The view shares the bytes of p, so p must not be modified while it is used, and it is not safe for concurrent use.

func (Packet) Dst

func (p Packet) Dst() netip.Addr

Dst returns the destination address from the IP header, or the zero Addr when the header is incomplete.

func (Packet) Src

func (p Packet) Src() netip.Addr

Src returns the source address from the IP header, or the zero Addr when the header is incomplete.

func (Packet) Version

func (p Packet) Version() int

Version returns the IP version of the packet: 4, 6, or 0 when it is empty or neither.

type TranslationError

type TranslationError struct {
	// Why the packet was rejected, one of the Err values.
	Err error

	// ICMP error for the sender of the rejected packet. Write it to the interface you read the packet from.
	Reply Packet
}

TranslationError is returned for a rejected packet that the translator answers with an ICMP error.

func (*TranslationError) Error

func (e *TranslationError) Error() string

func (*TranslationError) Unwrap

func (e *TranslationError) Unwrap() error

type Translator

type Translator struct {
	// contains filtered or unexported fields
}

Translator converts packets between IPv4 and IPv6 according to SIIT.

func NewTranslator

func NewTranslator(config Config) (*Translator, error)

NewTranslator creates a translator. It is immutable and safe for concurrent use. An invalid configuration returns an error wrapping ErrInvalidConfig, and also ErrInvalidMTU for an MTU below 1280.

Example

A CLAT with the Well-Known Prefix uses a non-global router address, so it maps that address to its own IPv6 address with an EAM entry, next to the entry for the IPv4 address of the host.

package main

import (
	"fmt"
	"net/netip"

	siit "github.com/christiaangoossens/go-siit"
)

func main() {
	router, err := siit.ParseEAMEntry("192.0.0.254", "2001:db8::254")
	if err != nil {
		panic(err)
	}

	host, err := siit.ParseEAMEntry("192.0.0.1", "2001:db8::1")
	if err != nil {
		panic(err)
	}

	_, err = siit.NewTranslator(siit.Config{
		NAT64Prefix:       netip.MustParsePrefix("64:ff9b::/96"),
		IPv4RouterAddress: netip.MustParseAddr("192.0.0.254"),
		EAMTable:          siit.EAMTable{router, host},
	})
	fmt.Println(err)
}
Output:
<nil>

func (*Translator) TranslateIPv4

func (t *Translator) TranslateIPv4(packet []byte) (Packet, error)

TranslateIPv4 translates an IPv4 packet, starting at the IP header, to IPv6. The packet is not modified or retained.

The result is empty when the packet is dropped (nil error) or rejected (non-nil error). A rejected packet that the translator answers carries the answer in a *TranslationError.

Example
package main

import (
	"errors"
	"fmt"
	"net/netip"

	siit "github.com/christiaangoossens/go-siit"
	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
)

func main() {
	translator := exampleTranslator()

	// A packet as read from a tun device, starting at the IPv4 header.
	packet := exampleIPv4Packet()

	result, err := translator.TranslateIPv4(packet)
	var translationErr *siit.TranslationError
	switch {
	case errors.As(err, &translationErr):
		// Send translationErr.Reply back out the IPv4 side.
	case err != nil:
		// Log the rejected packet.
	case len(result) > 0:
		// Send result out the IPv6 side.
		fmt.Println(result.Version(), result.Src(), "->", result.Dst())
	}
}

func exampleTranslator() *siit.Translator {
	translator, err := siit.NewTranslator(siit.Config{
		NAT64Prefix:       netip.MustParsePrefix("2001:db8:64::/96"),
		IPv4RouterAddress: netip.MustParseAddr("192.0.2.1"),
	})
	if err != nil {
		panic(err)
	}

	return translator
}

func exampleIPv4Packet() []byte {
	ip := &layers.IPv4{
		Version: 4, IHL: 5, TTL: 64, Protocol: layers.IPProtocolUDP,
		SrcIP: netip.MustParseAddr("192.0.2.10").AsSlice(), DstIP: netip.MustParseAddr("198.51.100.20").AsSlice(),
	}
	return exampleUDPPacket(ip, 40000, 53)
}

func exampleUDPPacket(ip gopacket.NetworkLayer, sourcePort, destinationPort layers.UDPPort) []byte {
	udp := &layers.UDP{SrcPort: sourcePort, DstPort: destinationPort}
	if err := udp.SetNetworkLayerForChecksum(ip); err != nil {
		panic(err)
	}

	buffer := gopacket.NewSerializeBuffer()
	options := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}
	if err := gopacket.SerializeLayers(buffer, options, ip.(gopacket.SerializableLayer), udp, gopacket.Payload("hello")); err != nil {
		panic(err)
	}

	return buffer.Bytes()
}
Output:
6 2001:db8:64::c000:20a -> 2001:db8:64::c633:6414

func (*Translator) TranslateIPv4Layer

func (t *Translator) TranslateIPv4Layer(ip *layers.IPv4) (Packet, error)

TranslateIPv4Layer is like TranslateIPv4, for a packet that is already decoded with gopacket. The layer must come from decoding, so that its Contents and Payload match its fields. It is not modified.

func (*Translator) TranslateIPv6

func (t *Translator) TranslateIPv6(packet []byte) (Packet, error)

TranslateIPv6 translates an IPv6 packet, starting at the IP header, to IPv4. It is like TranslateIPv4 otherwise.

func (*Translator) TranslateIPv6Layer

func (t *Translator) TranslateIPv6Layer(ip *layers.IPv6) (Packet, error)

TranslateIPv6Layer is like TranslateIPv6, for a packet that is already decoded with gopacket. The layer must come from decoding, so that its Contents and Payload match its fields. It is not modified.

Example
package main

import (
	"fmt"
	"net/netip"

	siit "github.com/christiaangoossens/go-siit"
	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
)

func main() {
	translator := exampleTranslator()

	// A packet that the caller already decoded with gopacket.
	packet := gopacket.NewPacket(exampleIPv6Packet(), layers.LayerTypeIPv6, gopacket.Default)
	ip := packet.Layer(layers.LayerTypeIPv6).(*layers.IPv6)

	result, err := translator.TranslateIPv6Layer(ip)
	if err != nil {
		panic(err)
	}

	udp := result.Decode().Layer(layers.LayerTypeUDP).(*layers.UDP)
	fmt.Println(result.Version(), result.Src(), "->", result.Dst(), "port", uint16(udp.DstPort))
}

func exampleTranslator() *siit.Translator {
	translator, err := siit.NewTranslator(siit.Config{
		NAT64Prefix:       netip.MustParsePrefix("2001:db8:64::/96"),
		IPv4RouterAddress: netip.MustParseAddr("192.0.2.1"),
	})
	if err != nil {
		panic(err)
	}

	return translator
}

func exampleIPv6Packet() []byte {
	ip := &layers.IPv6{
		Version: 6, HopLimit: 64, NextHeader: layers.IPProtocolUDP,
		SrcIP: netip.MustParseAddr("2001:db8:64::c633:6414").AsSlice(), DstIP: netip.MustParseAddr("2001:db8:64::c000:20a").AsSlice(),
	}
	return exampleUDPPacket(ip, 53, 40000)
}

func exampleUDPPacket(ip gopacket.NetworkLayer, sourcePort, destinationPort layers.UDPPort) []byte {
	udp := &layers.UDP{SrcPort: sourcePort, DstPort: destinationPort}
	if err := udp.SetNetworkLayerForChecksum(ip); err != nil {
		panic(err)
	}

	buffer := gopacket.NewSerializeBuffer()
	options := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}
	if err := gopacket.SerializeLayers(buffer, options, ip.(gopacket.SerializableLayer), udp, gopacket.Payload("hello")); err != nil {
		panic(err)
	}

	return buffer.Bytes()
}
Output:
4 198.51.100.20 -> 192.0.2.10 port 40000

Directories

Path Synopsis
tools
rfccheck command
Command rfccheck verifies the RFC citations in the Go comments and Markdown files of this repository: every cited section and figure must exist, and text quoted after a citation must appear in the cited section.
Command rfccheck verifies the RFC citations in the Go comments and Markdown files of this repository: every cited section and figure must exist, and text quoted after a citation must appear in the cited section.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址