tproxy.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2018 Google LLC. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package expr
  15. import (
  16. "encoding/binary"
  17. "github.com/google/nftables/binaryutil"
  18. "github.com/mdlayher/netlink"
  19. "golang.org/x/sys/unix"
  20. )
  21. const (
  22. // NFTA_TPROXY_FAMILY defines attribute for a table family
  23. NFTA_TPROXY_FAMILY = 0x01
  24. // NFTA_TPROXY_REG defines attribute for a register carrying redirection port value
  25. NFTA_TPROXY_REG = 0x03
  26. )
  27. // TProxy defines struct with parameters for the transparent proxy
  28. type TProxy struct {
  29. Family byte
  30. TableFamily byte
  31. RegPort uint32
  32. }
  33. func (e *TProxy) marshal(fam byte) ([]byte, error) {
  34. data, err := netlink.MarshalAttributes([]netlink.Attribute{
  35. {Type: NFTA_TPROXY_FAMILY, Data: binaryutil.BigEndian.PutUint32(uint32(e.Family))},
  36. {Type: NFTA_TPROXY_REG, Data: binaryutil.BigEndian.PutUint32(e.RegPort)},
  37. })
  38. if err != nil {
  39. return nil, err
  40. }
  41. return netlink.MarshalAttributes([]netlink.Attribute{
  42. {Type: unix.NFTA_EXPR_NAME, Data: []byte("tproxy\x00")},
  43. {Type: unix.NLA_F_NESTED | unix.NFTA_EXPR_DATA, Data: data},
  44. })
  45. }
  46. func (e *TProxy) unmarshal(fam byte, data []byte) error {
  47. ad, err := netlink.NewAttributeDecoder(data)
  48. if err != nil {
  49. return err
  50. }
  51. ad.ByteOrder = binary.BigEndian
  52. for ad.Next() {
  53. switch ad.Type() {
  54. case NFTA_TPROXY_FAMILY:
  55. e.Family = ad.Uint8()
  56. case NFTA_TPROXY_REG:
  57. e.RegPort = ad.Uint32()
  58. }
  59. }
  60. return ad.Err()
  61. }