Linux ip xfrm: What is the purpose of the tmpl?

Solution 1:

It tells the kernel how to process packets (for out policies), or where packets must come from (for in policies) when traffic matches this policy (fwd policies are a bit special as they might apply in both directions depending on the selector, see this answer). In your example the policy will send traffic through the ESP tunnel mode SA with endpoint IP addresses $SRC and $DST, and reqid $ID.

Why do we need to repeat them in the tmpl?

To actually find the SA/state. These are stored in a hashtable and the addresses (in particular the destination address) are part of the hash value. For tunnel mode SAs the addresses of the packet that matched the outbound policy don't necessarily match the addresses of the SA (for transport mode you might not have to add the addresses to the template).

And what is the meaning of calling it a "template"?

Not sure, but could be related to acquires, that is, if no matching SA has yet been established the information serves as template for the keying daemon when creating a new SA.