So anyway, back to our regularly scheduled program of fixing the padding
bug in WireGuard. Does the below diff accurately merge Björn's suggested
patch with Claudio's correction? It appears to correctly _always_ pad
the plaintext with 0s until it has length equal to the smallest multiple
of 16 greater than or equal to the length of the non-padded plaintext
while "clamping" said padding to the MTU in the event it would have
exceeded it. In the case where the plaintext already exceeds the MTU of
wg(4), padding is done normally since the payload already exceeded the
MTU.

This is what Linux does[^1]:

static unsigned int calculate_skb_padding(struct sk_buff *skb)
{
        unsigned int padded_size, last_unit = skb->len;

        if (unlikely(!PACKET_CB(skb)->mtu))
                return ALIGN(last_unit, MESSAGE_PADDING_MULTIPLE) - last_unit;

        /* We do this modulo business with the MTU, just in case the networking
         * layer gives us a packet that's bigger than the MTU. In that case, we
         * wouldn't want the final subtraction to overflow in the case of the
         * padded_size being clamped. Fortunately, that's very rarely the case,
         * so we optimize for that not happening.
         */
        if (unlikely(last_unit > PACKET_CB(skb)->mtu))
                last_unit %= PACKET_CB(skb)->mtu;

        padded_size = min(PACKET_CB(skb)->mtu,
                          ALIGN(last_unit, MESSAGE_PADDING_MULTIPLE));
        return padded_size - last_unit;
}

I'll let actual C developers understand that code, but it appears to
handle the case when the non-padded plaintext exceeds the MTU differently.
If my "guess" is correct, then I believe we should do something similar.

diff --git a/sys/net/if_wg.c b/sys/net/if_wg.c
index 0641c4b5ba9..54ca15eea18 100644
--- a/sys/net/if_wg.c
+++ b/sys/net/if_wg.c
@@ -1591,7 +1591,10 @@ wg_encap(struct wg_softc *sc, struct mbuf *m)
        t = wg_tag_get(m);
        peer = t->t_peer;

-       plaintext_len = WG_PKT_WITH_PADDING(m->m_pkthdr.len);
+       if (m->m_pkthdr.len <= t->t_mtu)
+               plaintext_len = min(WG_PKT_WITH_PADDING(m->m_pkthdr.len), 
t->t_mtu);
+       else
+               plaintext_len = WG_PKT_WITH_PADDING(m->m_pkthdr.len);
        padding_len = plaintext_len - m->m_pkthdr.len;
        out_len = sizeof(struct wg_pkt_data) + plaintext_len +
            NOISE_AUTHTAG_LEN;

[^1]: 
https://github.com/torvalds/linux/blob/master/drivers/net/wireguard/send.c#L141

P.S. Not sure what the proper etiquette is when a thread on @bugs gets
derailed. I thought about creating a new thread to remove all the noise,
but I decided I'll let a dev do that. An additional benefit of a new
thread is a more accurate Subject title that makes no mention of vio(4)
or IPv6.

Reply via email to