xfrm_state_linux.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package netlink
  2. import (
  3. "fmt"
  4. "syscall"
  5. "unsafe"
  6. "github.com/vishvananda/netlink/nl"
  7. )
  8. func writeStateAlgo(a *XfrmStateAlgo) []byte {
  9. algo := nl.XfrmAlgo{
  10. AlgKeyLen: uint32(len(a.Key) * 8),
  11. AlgKey: a.Key,
  12. }
  13. end := len(a.Name)
  14. if end > 64 {
  15. end = 64
  16. }
  17. copy(algo.AlgName[:end], a.Name)
  18. return algo.Serialize()
  19. }
  20. func writeStateAlgoAuth(a *XfrmStateAlgo) []byte {
  21. algo := nl.XfrmAlgoAuth{
  22. AlgKeyLen: uint32(len(a.Key) * 8),
  23. AlgTruncLen: uint32(a.TruncateLen),
  24. AlgKey: a.Key,
  25. }
  26. end := len(a.Name)
  27. if end > 64 {
  28. end = 64
  29. }
  30. copy(algo.AlgName[:end], a.Name)
  31. return algo.Serialize()
  32. }
  33. func writeStateAlgoAead(a *XfrmStateAlgo) []byte {
  34. algo := nl.XfrmAlgoAEAD{
  35. AlgKeyLen: uint32(len(a.Key) * 8),
  36. AlgICVLen: uint32(a.ICVLen),
  37. AlgKey: a.Key,
  38. }
  39. end := len(a.Name)
  40. if end > 64 {
  41. end = 64
  42. }
  43. copy(algo.AlgName[:end], a.Name)
  44. return algo.Serialize()
  45. }
  46. func writeMark(m *XfrmMark) []byte {
  47. mark := &nl.XfrmMark{
  48. Value: m.Value,
  49. Mask: m.Mask,
  50. }
  51. if mark.Mask == 0 {
  52. mark.Mask = ^uint32(0)
  53. }
  54. return mark.Serialize()
  55. }
  56. func writeReplayEsn(replayWindow int) []byte {
  57. replayEsn := &nl.XfrmReplayStateEsn{
  58. OSeq: 0,
  59. Seq: 0,
  60. OSeqHi: 0,
  61. SeqHi: 0,
  62. ReplayWindow: uint32(replayWindow),
  63. }
  64. // taken from iproute2/ip/xfrm_state.c:
  65. replayEsn.BmpLen = uint32((replayWindow + (4 * 8) - 1) / (4 * 8))
  66. return replayEsn.Serialize()
  67. }
  68. // XfrmStateAdd will add an xfrm state to the system.
  69. // Equivalent to: `ip xfrm state add $state`
  70. func XfrmStateAdd(state *XfrmState) error {
  71. return pkgHandle.XfrmStateAdd(state)
  72. }
  73. // XfrmStateAdd will add an xfrm state to the system.
  74. // Equivalent to: `ip xfrm state add $state`
  75. func (h *Handle) XfrmStateAdd(state *XfrmState) error {
  76. return h.xfrmStateAddOrUpdate(state, nl.XFRM_MSG_NEWSA)
  77. }
  78. // XfrmStateAllocSpi will allocate an xfrm state in the system.
  79. // Equivalent to: `ip xfrm state allocspi`
  80. func XfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) {
  81. return pkgHandle.xfrmStateAllocSpi(state)
  82. }
  83. // XfrmStateUpdate will update an xfrm state to the system.
  84. // Equivalent to: `ip xfrm state update $state`
  85. func XfrmStateUpdate(state *XfrmState) error {
  86. return pkgHandle.XfrmStateUpdate(state)
  87. }
  88. // XfrmStateUpdate will update an xfrm state to the system.
  89. // Equivalent to: `ip xfrm state update $state`
  90. func (h *Handle) XfrmStateUpdate(state *XfrmState) error {
  91. return h.xfrmStateAddOrUpdate(state, nl.XFRM_MSG_UPDSA)
  92. }
  93. func (h *Handle) xfrmStateAddOrUpdate(state *XfrmState, nlProto int) error {
  94. // A state with spi 0 can't be deleted so don't allow it to be set
  95. if state.Spi == 0 {
  96. return fmt.Errorf("Spi must be set when adding xfrm state.")
  97. }
  98. req := h.newNetlinkRequest(nlProto, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
  99. msg := xfrmUsersaInfoFromXfrmState(state)
  100. if state.ESN {
  101. if state.ReplayWindow == 0 {
  102. return fmt.Errorf("ESN flag set without ReplayWindow")
  103. }
  104. msg.Flags |= nl.XFRM_STATE_ESN
  105. msg.ReplayWindow = 0
  106. }
  107. limitsToLft(state.Limits, &msg.Lft)
  108. req.AddData(msg)
  109. if state.Auth != nil {
  110. out := nl.NewRtAttr(nl.XFRMA_ALG_AUTH_TRUNC, writeStateAlgoAuth(state.Auth))
  111. req.AddData(out)
  112. }
  113. if state.Crypt != nil {
  114. out := nl.NewRtAttr(nl.XFRMA_ALG_CRYPT, writeStateAlgo(state.Crypt))
  115. req.AddData(out)
  116. }
  117. if state.Aead != nil {
  118. out := nl.NewRtAttr(nl.XFRMA_ALG_AEAD, writeStateAlgoAead(state.Aead))
  119. req.AddData(out)
  120. }
  121. if state.Encap != nil {
  122. encapData := make([]byte, nl.SizeofXfrmEncapTmpl)
  123. encap := nl.DeserializeXfrmEncapTmpl(encapData)
  124. encap.EncapType = uint16(state.Encap.Type)
  125. encap.EncapSport = nl.Swap16(uint16(state.Encap.SrcPort))
  126. encap.EncapDport = nl.Swap16(uint16(state.Encap.DstPort))
  127. encap.EncapOa.FromIP(state.Encap.OriginalAddress)
  128. out := nl.NewRtAttr(nl.XFRMA_ENCAP, encapData)
  129. req.AddData(out)
  130. }
  131. if state.Mark != nil {
  132. out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
  133. req.AddData(out)
  134. }
  135. if state.ESN {
  136. out := nl.NewRtAttr(nl.XFRMA_REPLAY_ESN_VAL, writeReplayEsn(state.ReplayWindow))
  137. req.AddData(out)
  138. }
  139. _, err := req.Execute(syscall.NETLINK_XFRM, 0)
  140. return err
  141. }
  142. func (h *Handle) xfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) {
  143. req := h.newNetlinkRequest(nl.XFRM_MSG_ALLOCSPI,
  144. syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
  145. msg := &nl.XfrmUserSpiInfo{}
  146. msg.XfrmUsersaInfo = *(xfrmUsersaInfoFromXfrmState(state))
  147. // 1-255 is reserved by IANA for future use
  148. msg.Min = 0x100
  149. msg.Max = 0xffffffff
  150. req.AddData(msg)
  151. if state.Mark != nil {
  152. out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
  153. req.AddData(out)
  154. }
  155. msgs, err := req.Execute(syscall.NETLINK_XFRM, 0)
  156. if err != nil {
  157. return nil, err
  158. }
  159. s, err := parseXfrmState(msgs[0], FAMILY_ALL)
  160. if err != nil {
  161. return nil, err
  162. }
  163. return s, err
  164. }
  165. // XfrmStateDel will delete an xfrm state from the system. Note that
  166. // the Algos are ignored when matching the state to delete.
  167. // Equivalent to: `ip xfrm state del $state`
  168. func XfrmStateDel(state *XfrmState) error {
  169. return pkgHandle.XfrmStateDel(state)
  170. }
  171. // XfrmStateDel will delete an xfrm state from the system. Note that
  172. // the Algos are ignored when matching the state to delete.
  173. // Equivalent to: `ip xfrm state del $state`
  174. func (h *Handle) XfrmStateDel(state *XfrmState) error {
  175. _, err := h.xfrmStateGetOrDelete(state, nl.XFRM_MSG_DELSA)
  176. return err
  177. }
  178. // XfrmStateList gets a list of xfrm states in the system.
  179. // Equivalent to: `ip [-4|-6] xfrm state show`.
  180. // The list can be filtered by ip family.
  181. func XfrmStateList(family int) ([]XfrmState, error) {
  182. return pkgHandle.XfrmStateList(family)
  183. }
  184. // XfrmStateList gets a list of xfrm states in the system.
  185. // Equivalent to: `ip xfrm state show`.
  186. // The list can be filtered by ip family.
  187. func (h *Handle) XfrmStateList(family int) ([]XfrmState, error) {
  188. req := h.newNetlinkRequest(nl.XFRM_MSG_GETSA, syscall.NLM_F_DUMP)
  189. msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWSA)
  190. if err != nil {
  191. return nil, err
  192. }
  193. var res []XfrmState
  194. for _, m := range msgs {
  195. if state, err := parseXfrmState(m, family); err == nil {
  196. res = append(res, *state)
  197. } else if err == familyError {
  198. continue
  199. } else {
  200. return nil, err
  201. }
  202. }
  203. return res, nil
  204. }
  205. // XfrmStateGet gets the xfrm state described by the ID, if found.
  206. // Equivalent to: `ip xfrm state get ID [ mark MARK [ mask MASK ] ]`.
  207. // Only the fields which constitue the SA ID must be filled in:
  208. // ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM-PROTO ] [ spi SPI ]
  209. // mark is optional
  210. func XfrmStateGet(state *XfrmState) (*XfrmState, error) {
  211. return pkgHandle.XfrmStateGet(state)
  212. }
  213. // XfrmStateGet gets the xfrm state described by the ID, if found.
  214. // Equivalent to: `ip xfrm state get ID [ mark MARK [ mask MASK ] ]`.
  215. // Only the fields which constitue the SA ID must be filled in:
  216. // ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM-PROTO ] [ spi SPI ]
  217. // mark is optional
  218. func (h *Handle) XfrmStateGet(state *XfrmState) (*XfrmState, error) {
  219. return h.xfrmStateGetOrDelete(state, nl.XFRM_MSG_GETSA)
  220. }
  221. func (h *Handle) xfrmStateGetOrDelete(state *XfrmState, nlProto int) (*XfrmState, error) {
  222. req := h.newNetlinkRequest(nlProto, syscall.NLM_F_ACK)
  223. msg := &nl.XfrmUsersaId{}
  224. msg.Family = uint16(nl.GetIPFamily(state.Dst))
  225. msg.Daddr.FromIP(state.Dst)
  226. msg.Proto = uint8(state.Proto)
  227. msg.Spi = nl.Swap32(uint32(state.Spi))
  228. req.AddData(msg)
  229. if state.Mark != nil {
  230. out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
  231. req.AddData(out)
  232. }
  233. if state.Src != nil {
  234. out := nl.NewRtAttr(nl.XFRMA_SRCADDR, state.Src.To16())
  235. req.AddData(out)
  236. }
  237. resType := nl.XFRM_MSG_NEWSA
  238. if nlProto == nl.XFRM_MSG_DELSA {
  239. resType = 0
  240. }
  241. msgs, err := req.Execute(syscall.NETLINK_XFRM, uint16(resType))
  242. if err != nil {
  243. return nil, err
  244. }
  245. if nlProto == nl.XFRM_MSG_DELSA {
  246. return nil, nil
  247. }
  248. s, err := parseXfrmState(msgs[0], FAMILY_ALL)
  249. if err != nil {
  250. return nil, err
  251. }
  252. return s, nil
  253. }
  254. var familyError = fmt.Errorf("family error")
  255. func xfrmStateFromXfrmUsersaInfo(msg *nl.XfrmUsersaInfo) *XfrmState {
  256. var state XfrmState
  257. state.Dst = msg.Id.Daddr.ToIP()
  258. state.Src = msg.Saddr.ToIP()
  259. state.Proto = Proto(msg.Id.Proto)
  260. state.Mode = Mode(msg.Mode)
  261. state.Spi = int(nl.Swap32(msg.Id.Spi))
  262. state.Reqid = int(msg.Reqid)
  263. state.ReplayWindow = int(msg.ReplayWindow)
  264. lftToLimits(&msg.Lft, &state.Limits)
  265. return &state
  266. }
  267. func parseXfrmState(m []byte, family int) (*XfrmState, error) {
  268. msg := nl.DeserializeXfrmUsersaInfo(m)
  269. // This is mainly for the state dump
  270. if family != FAMILY_ALL && family != int(msg.Family) {
  271. return nil, familyError
  272. }
  273. state := xfrmStateFromXfrmUsersaInfo(msg)
  274. attrs, err := nl.ParseRouteAttr(m[nl.SizeofXfrmUsersaInfo:])
  275. if err != nil {
  276. return nil, err
  277. }
  278. for _, attr := range attrs {
  279. switch attr.Attr.Type {
  280. case nl.XFRMA_ALG_AUTH, nl.XFRMA_ALG_CRYPT:
  281. var resAlgo *XfrmStateAlgo
  282. if attr.Attr.Type == nl.XFRMA_ALG_AUTH {
  283. if state.Auth == nil {
  284. state.Auth = new(XfrmStateAlgo)
  285. }
  286. resAlgo = state.Auth
  287. } else {
  288. state.Crypt = new(XfrmStateAlgo)
  289. resAlgo = state.Crypt
  290. }
  291. algo := nl.DeserializeXfrmAlgo(attr.Value[:])
  292. (*resAlgo).Name = nl.BytesToString(algo.AlgName[:])
  293. (*resAlgo).Key = algo.AlgKey
  294. case nl.XFRMA_ALG_AUTH_TRUNC:
  295. if state.Auth == nil {
  296. state.Auth = new(XfrmStateAlgo)
  297. }
  298. algo := nl.DeserializeXfrmAlgoAuth(attr.Value[:])
  299. state.Auth.Name = nl.BytesToString(algo.AlgName[:])
  300. state.Auth.Key = algo.AlgKey
  301. state.Auth.TruncateLen = int(algo.AlgTruncLen)
  302. case nl.XFRMA_ALG_AEAD:
  303. state.Aead = new(XfrmStateAlgo)
  304. algo := nl.DeserializeXfrmAlgoAEAD(attr.Value[:])
  305. state.Aead.Name = nl.BytesToString(algo.AlgName[:])
  306. state.Aead.Key = algo.AlgKey
  307. state.Aead.ICVLen = int(algo.AlgICVLen)
  308. case nl.XFRMA_ENCAP:
  309. encap := nl.DeserializeXfrmEncapTmpl(attr.Value[:])
  310. state.Encap = new(XfrmStateEncap)
  311. state.Encap.Type = EncapType(encap.EncapType)
  312. state.Encap.SrcPort = int(nl.Swap16(encap.EncapSport))
  313. state.Encap.DstPort = int(nl.Swap16(encap.EncapDport))
  314. state.Encap.OriginalAddress = encap.EncapOa.ToIP()
  315. case nl.XFRMA_MARK:
  316. mark := nl.DeserializeXfrmMark(attr.Value[:])
  317. state.Mark = new(XfrmMark)
  318. state.Mark.Value = mark.Value
  319. state.Mark.Mask = mark.Mask
  320. }
  321. }
  322. return state, nil
  323. }
  324. // XfrmStateFlush will flush the xfrm state on the system.
  325. // proto = 0 means any transformation protocols
  326. // Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]`
  327. func XfrmStateFlush(proto Proto) error {
  328. return pkgHandle.XfrmStateFlush(proto)
  329. }
  330. // XfrmStateFlush will flush the xfrm state on the system.
  331. // proto = 0 means any transformation protocols
  332. // Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]`
  333. func (h *Handle) XfrmStateFlush(proto Proto) error {
  334. req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHSA, syscall.NLM_F_ACK)
  335. req.AddData(&nl.XfrmUsersaFlush{Proto: uint8(proto)})
  336. _, err := req.Execute(syscall.NETLINK_XFRM, 0)
  337. if err != nil {
  338. return err
  339. }
  340. return nil
  341. }
  342. func limitsToLft(lmts XfrmStateLimits, lft *nl.XfrmLifetimeCfg) {
  343. if lmts.ByteSoft != 0 {
  344. lft.SoftByteLimit = lmts.ByteSoft
  345. } else {
  346. lft.SoftByteLimit = nl.XFRM_INF
  347. }
  348. if lmts.ByteHard != 0 {
  349. lft.HardByteLimit = lmts.ByteHard
  350. } else {
  351. lft.HardByteLimit = nl.XFRM_INF
  352. }
  353. if lmts.PacketSoft != 0 {
  354. lft.SoftPacketLimit = lmts.PacketSoft
  355. } else {
  356. lft.SoftPacketLimit = nl.XFRM_INF
  357. }
  358. if lmts.PacketHard != 0 {
  359. lft.HardPacketLimit = lmts.PacketHard
  360. } else {
  361. lft.HardPacketLimit = nl.XFRM_INF
  362. }
  363. lft.SoftAddExpiresSeconds = lmts.TimeSoft
  364. lft.HardAddExpiresSeconds = lmts.TimeHard
  365. lft.SoftUseExpiresSeconds = lmts.TimeUseSoft
  366. lft.HardUseExpiresSeconds = lmts.TimeUseHard
  367. }
  368. func lftToLimits(lft *nl.XfrmLifetimeCfg, lmts *XfrmStateLimits) {
  369. *lmts = *(*XfrmStateLimits)(unsafe.Pointer(lft))
  370. }
  371. func xfrmUsersaInfoFromXfrmState(state *XfrmState) *nl.XfrmUsersaInfo {
  372. msg := &nl.XfrmUsersaInfo{}
  373. msg.Family = uint16(nl.GetIPFamily(state.Dst))
  374. msg.Id.Daddr.FromIP(state.Dst)
  375. msg.Saddr.FromIP(state.Src)
  376. msg.Id.Proto = uint8(state.Proto)
  377. msg.Mode = uint8(state.Mode)
  378. msg.Id.Spi = nl.Swap32(uint32(state.Spi))
  379. msg.Reqid = uint32(state.Reqid)
  380. msg.ReplayWindow = uint8(state.ReplayWindow)
  381. return msg
  382. }