The only way to do this in user space is to do something like diald, where a program talks SLIP (or you might choose PPP) to the kernel over a pty or two, and routes traffic back and forth through itself, making modifications.
The more reasonable way to do this is to put it in the generic network filtering. You can either do simple rewrites with the existing firewall tools or write your own firewall modules and drop them into the stack. That way you can give yourself the option of making arbitrary modifications to packets on their way in and/or out of the system.
Read Network Buffers And Memory Management first to learn about how the networking stack works, then read the ipfwadm code and the relevant kernel code. Good luck.