xfrm_state_linux.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. package netlink
  2. import (
  3. "fmt"
  4. "unsafe"
  5. "github.com/vishvananda/netlink/nl"
  6. "golang.org/x/sys/unix"
  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. // Linux stores the bitmap to identify the already received sequence packets in blocks of uint32 elements.
  65. // Therefore bitmap length is the minimum number of uint32 elements needed. The following is a ceiling operation.
  66. bytesPerElem := int(unsafe.Sizeof(replayEsn.BmpLen)) // Any uint32 variable is good for this
  67. replayEsn.BmpLen = uint32((replayWindow + (bytesPerElem * 8) - 1) / (bytesPerElem * 8))
  68. return replayEsn.Serialize()
  69. }
  70. // XfrmStateAdd will add an xfrm state to the system.
  71. // Equivalent to: `ip xfrm state add $state`
  72. func XfrmStateAdd(state *XfrmState) error {
  73. return pkgHandle.XfrmStateAdd(state)
  74. }
  75. // XfrmStateAdd will add an xfrm state to the system.
  76. // Equivalent to: `ip xfrm state add $state`
  77. func (h *Handle) XfrmStateAdd(state *XfrmState) error {
  78. return h.xfrmStateAddOrUpdate(state, nl.XFRM_MSG_NEWSA)
  79. }
  80. // XfrmStateAllocSpi will allocate an xfrm state in the system.
  81. // Equivalent to: `ip xfrm state allocspi`
  82. func XfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) {
  83. return pkgHandle.xfrmStateAllocSpi(state)
  84. }
  85. // XfrmStateUpdate will update an xfrm state to the system.
  86. // Equivalent to: `ip xfrm state update $state`
  87. func XfrmStateUpdate(state *XfrmState) error {
  88. return pkgHandle.XfrmStateUpdate(state)
  89. }
  90. // XfrmStateUpdate will update an xfrm state to the system.
  91. // Equivalent to: `ip xfrm state update $state`
  92. func (h *Handle) XfrmStateUpdate(state *XfrmState) error {
  93. return h.xfrmStateAddOrUpdate(state, nl.XFRM_MSG_UPDSA)
  94. }
  95. func (h *Handle) xfrmStateAddOrUpdate(state *XfrmState, nlProto int) error {
  96. // A state with spi 0 can't be deleted so don't allow it to be set
  97. if state.Spi == 0 {
  98. return fmt.Errorf("Spi must be set when adding xfrm state.")
  99. }
  100. req := h.newNetlinkRequest(nlProto, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
  101. msg := xfrmUsersaInfoFromXfrmState(state)
  102. if state.ESN {
  103. if state.ReplayWindow == 0 {
  104. return fmt.Errorf("ESN flag set without ReplayWindow")
  105. }
  106. msg.Flags |= nl.XFRM_STATE_ESN
  107. msg.ReplayWindow = 0
  108. }
  109. limitsToLft(state.Limits, &msg.Lft)
  110. req.AddData(msg)
  111. if state.Auth != nil {
  112. out := nl.NewRtAttr(nl.XFRMA_ALG_AUTH_TRUNC, writeStateAlgoAuth(state.Auth))
  113. req.AddData(out)
  114. }
  115. if state.Crypt != nil {
  116. out := nl.NewRtAttr(nl.XFRMA_ALG_CRYPT, writeStateAlgo(state.Crypt))
  117. req.AddData(out)
  118. }
  119. if state.Aead != nil {
  120. out := nl.NewRtAttr(nl.XFRMA_ALG_AEAD, writeStateAlgoAead(state.Aead))
  121. req.AddData(out)
  122. }
  123. if state.Encap != nil {
  124. encapData := make([]byte, nl.SizeofXfrmEncapTmpl)
  125. encap := nl.DeserializeXfrmEncapTmpl(encapData)
  126. encap.EncapType = uint16(state.Encap.Type)
  127. encap.EncapSport = nl.Swap16(uint16(state.Encap.SrcPort))
  128. encap.EncapDport = nl.Swap16(uint16(state.Encap.DstPort))
  129. encap.EncapOa.FromIP(state.Encap.OriginalAddress)
  130. out := nl.NewRtAttr(nl.XFRMA_ENCAP, encapData)
  131. req.AddData(out)
  132. }
  133. if state.Mark != nil {
  134. out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
  135. req.AddData(out)
  136. }
  137. if state.ESN {
  138. out := nl.NewRtAttr(nl.XFRMA_REPLAY_ESN_VAL, writeReplayEsn(state.ReplayWindow))
  139. req.AddData(out)
  140. }
  141. if state.OutputMark != nil {
  142. out := nl.NewRtAttr(nl.XFRMA_SET_MARK, nl.Uint32Attr(state.OutputMark.Value))
  143. req.AddData(out)
  144. if state.OutputMark.Mask != 0 {
  145. out = nl.NewRtAttr(nl.XFRMA_SET_MARK_MASK, nl.Uint32Attr(state.OutputMark.Mask))
  146. req.AddData(out)
  147. }
  148. }
  149. ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(state.Ifid)))
  150. req.AddData(ifId)
  151. _, err := req.Execute(unix.NETLINK_XFRM, 0)
  152. return err
  153. }
  154. func (h *Handle) xfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) {
  155. req := h.newNetlinkRequest(nl.XFRM_MSG_ALLOCSPI,
  156. unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
  157. msg := &nl.XfrmUserSpiInfo{}
  158. msg.XfrmUsersaInfo = *(xfrmUsersaInfoFromXfrmState(state))
  159. // 1-255 is reserved by IANA for future use
  160. msg.Min = 0x100
  161. msg.Max = 0xffffffff
  162. req.AddData(msg)
  163. if state.Mark != nil {
  164. out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
  165. req.AddData(out)
  166. }
  167. msgs, err := req.Execute(unix.NETLINK_XFRM, 0)
  168. if err != nil {
  169. return nil, err
  170. }
  171. return parseXfrmState(msgs[0], FAMILY_ALL)
  172. }
  173. // XfrmStateDel will delete an xfrm state from the system. Note that
  174. // the Algos are ignored when matching the state to delete.
  175. // Equivalent to: `ip xfrm state del $state`
  176. func XfrmStateDel(state *XfrmState) error {
  177. return pkgHandle.XfrmStateDel(state)
  178. }
  179. // XfrmStateDel will delete an xfrm state from the system. Note that
  180. // the Algos are ignored when matching the state to delete.
  181. // Equivalent to: `ip xfrm state del $state`
  182. func (h *Handle) XfrmStateDel(state *XfrmState) error {
  183. _, err := h.xfrmStateGetOrDelete(state, nl.XFRM_MSG_DELSA)
  184. return err
  185. }
  186. // XfrmStateList gets a list of xfrm states in the system.
  187. // Equivalent to: `ip [-4|-6] xfrm state show`.
  188. // The list can be filtered by ip family.
  189. func XfrmStateList(family int) ([]XfrmState, error) {
  190. return pkgHandle.XfrmStateList(family)
  191. }
  192. // XfrmStateList gets a list of xfrm states in the system.
  193. // Equivalent to: `ip xfrm state show`.
  194. // The list can be filtered by ip family.
  195. func (h *Handle) XfrmStateList(family int) ([]XfrmState, error) {
  196. req := h.newNetlinkRequest(nl.XFRM_MSG_GETSA, unix.NLM_F_DUMP)
  197. msgs, err := req.Execute(unix.NETLINK_XFRM, nl.XFRM_MSG_NEWSA)
  198. if err != nil {
  199. return nil, err
  200. }
  201. var res []XfrmState
  202. for _, m := range msgs {
  203. if state, err := parseXfrmState(m, family); err == nil {
  204. res = append(res, *state)
  205. } else if err == familyError {
  206. continue
  207. } else {
  208. return nil, err
  209. }
  210. }
  211. return res, nil
  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 XfrmStateGet(state *XfrmState) (*XfrmState, error) {
  219. return pkgHandle.XfrmStateGet(state)
  220. }
  221. // XfrmStateGet gets the xfrm state described by the ID, if found.
  222. // Equivalent to: `ip xfrm state get ID [ mark MARK [ mask MASK ] ]`.
  223. // Only the fields which constitue the SA ID must be filled in:
  224. // ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM-PROTO ] [ spi SPI ]
  225. // mark is optional
  226. func (h *Handle) XfrmStateGet(state *XfrmState) (*XfrmState, error) {
  227. return h.xfrmStateGetOrDelete(state, nl.XFRM_MSG_GETSA)
  228. }
  229. func (h *Handle) xfrmStateGetOrDelete(state *XfrmState, nlProto int) (*XfrmState, error) {
  230. req := h.newNetlinkRequest(nlProto, unix.NLM_F_ACK)
  231. msg := &nl.XfrmUsersaId{}
  232. msg.Family = uint16(nl.GetIPFamily(state.Dst))
  233. msg.Daddr.FromIP(state.Dst)
  234. msg.Proto = uint8(state.Proto)
  235. msg.Spi = nl.Swap32(uint32(state.Spi))
  236. req.AddData(msg)
  237. if state.Mark != nil {
  238. out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
  239. req.AddData(out)
  240. }
  241. if state.Src != nil {
  242. out := nl.NewRtAttr(nl.XFRMA_SRCADDR, state.Src.To16())
  243. req.AddData(out)
  244. }
  245. ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(state.Ifid)))
  246. req.AddData(ifId)
  247. resType := nl.XFRM_MSG_NEWSA
  248. if nlProto == nl.XFRM_MSG_DELSA {
  249. resType = 0
  250. }
  251. msgs, err := req.Execute(unix.NETLINK_XFRM, uint16(resType))
  252. if err != nil {
  253. return nil, err
  254. }
  255. if nlProto == nl.XFRM_MSG_DELSA {
  256. return nil, nil
  257. }
  258. s, err := parseXfrmState(msgs[0], FAMILY_ALL)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return s, nil
  263. }
  264. var familyError = fmt.Errorf("family error")
  265. func xfrmStateFromXfrmUsersaInfo(msg *nl.XfrmUsersaInfo) *XfrmState {
  266. var state XfrmState
  267. state.Dst = msg.Id.Daddr.ToIP()
  268. state.Src = msg.Saddr.ToIP()
  269. state.Proto = Proto(msg.Id.Proto)
  270. state.Mode = Mode(msg.Mode)
  271. state.Spi = int(nl.Swap32(msg.Id.Spi))
  272. state.Reqid = int(msg.Reqid)
  273. state.ReplayWindow = int(msg.ReplayWindow)
  274. lftToLimits(&msg.Lft, &state.Limits)
  275. curToStats(&msg.Curlft, &msg.Stats, &state.Statistics)
  276. return &state
  277. }
  278. func parseXfrmState(m []byte, family int) (*XfrmState, error) {
  279. msg := nl.DeserializeXfrmUsersaInfo(m)
  280. // This is mainly for the state dump
  281. if family != FAMILY_ALL && family != int(msg.Family) {
  282. return nil, familyError
  283. }
  284. state := xfrmStateFromXfrmUsersaInfo(msg)
  285. attrs, err := nl.ParseRouteAttr(m[nl.SizeofXfrmUsersaInfo:])
  286. if err != nil {
  287. return nil, err
  288. }
  289. for _, attr := range attrs {
  290. switch attr.Attr.Type {
  291. case nl.XFRMA_ALG_AUTH, nl.XFRMA_ALG_CRYPT:
  292. var resAlgo *XfrmStateAlgo
  293. if attr.Attr.Type == nl.XFRMA_ALG_AUTH {
  294. if state.Auth == nil {
  295. state.Auth = new(XfrmStateAlgo)
  296. }
  297. resAlgo = state.Auth
  298. } else {
  299. state.Crypt = new(XfrmStateAlgo)
  300. resAlgo = state.Crypt
  301. }
  302. algo := nl.DeserializeXfrmAlgo(attr.Value[:])
  303. (*resAlgo).Name = nl.BytesToString(algo.AlgName[:])
  304. (*resAlgo).Key = algo.AlgKey
  305. case nl.XFRMA_ALG_AUTH_TRUNC:
  306. if state.Auth == nil {
  307. state.Auth = new(XfrmStateAlgo)
  308. }
  309. algo := nl.DeserializeXfrmAlgoAuth(attr.Value[:])
  310. state.Auth.Name = nl.BytesToString(algo.AlgName[:])
  311. state.Auth.Key = algo.AlgKey
  312. state.Auth.TruncateLen = int(algo.AlgTruncLen)
  313. case nl.XFRMA_ALG_AEAD:
  314. state.Aead = new(XfrmStateAlgo)
  315. algo := nl.DeserializeXfrmAlgoAEAD(attr.Value[:])
  316. state.Aead.Name = nl.BytesToString(algo.AlgName[:])
  317. state.Aead.Key = algo.AlgKey
  318. state.Aead.ICVLen = int(algo.AlgICVLen)
  319. case nl.XFRMA_ENCAP:
  320. encap := nl.DeserializeXfrmEncapTmpl(attr.Value[:])
  321. state.Encap = new(XfrmStateEncap)
  322. state.Encap.Type = EncapType(encap.EncapType)
  323. state.Encap.SrcPort = int(nl.Swap16(encap.EncapSport))
  324. state.Encap.DstPort = int(nl.Swap16(encap.EncapDport))
  325. state.Encap.OriginalAddress = encap.EncapOa.ToIP()
  326. case nl.XFRMA_MARK:
  327. mark := nl.DeserializeXfrmMark(attr.Value[:])
  328. state.Mark = new(XfrmMark)
  329. state.Mark.Value = mark.Value
  330. state.Mark.Mask = mark.Mask
  331. case nl.XFRMA_SET_MARK:
  332. if state.OutputMark == nil {
  333. state.OutputMark = new(XfrmMark)
  334. }
  335. state.OutputMark.Value = native.Uint32(attr.Value)
  336. case nl.XFRMA_SET_MARK_MASK:
  337. if state.OutputMark == nil {
  338. state.OutputMark = new(XfrmMark)
  339. }
  340. state.OutputMark.Mask = native.Uint32(attr.Value)
  341. if state.OutputMark.Mask == 0xffffffff {
  342. state.OutputMark.Mask = 0
  343. }
  344. case nl.XFRMA_IF_ID:
  345. state.Ifid = int(native.Uint32(attr.Value))
  346. }
  347. }
  348. return state, nil
  349. }
  350. // XfrmStateFlush will flush the xfrm state on the system.
  351. // proto = 0 means any transformation protocols
  352. // Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]`
  353. func XfrmStateFlush(proto Proto) error {
  354. return pkgHandle.XfrmStateFlush(proto)
  355. }
  356. // XfrmStateFlush will flush the xfrm state on the system.
  357. // proto = 0 means any transformation protocols
  358. // Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]`
  359. func (h *Handle) XfrmStateFlush(proto Proto) error {
  360. req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHSA, unix.NLM_F_ACK)
  361. req.AddData(&nl.XfrmUsersaFlush{Proto: uint8(proto)})
  362. _, err := req.Execute(unix.NETLINK_XFRM, 0)
  363. return err
  364. }
  365. func limitsToLft(lmts XfrmStateLimits, lft *nl.XfrmLifetimeCfg) {
  366. if lmts.ByteSoft != 0 {
  367. lft.SoftByteLimit = lmts.ByteSoft
  368. } else {
  369. lft.SoftByteLimit = nl.XFRM_INF
  370. }
  371. if lmts.ByteHard != 0 {
  372. lft.HardByteLimit = lmts.ByteHard
  373. } else {
  374. lft.HardByteLimit = nl.XFRM_INF
  375. }
  376. if lmts.PacketSoft != 0 {
  377. lft.SoftPacketLimit = lmts.PacketSoft
  378. } else {
  379. lft.SoftPacketLimit = nl.XFRM_INF
  380. }
  381. if lmts.PacketHard != 0 {
  382. lft.HardPacketLimit = lmts.PacketHard
  383. } else {
  384. lft.HardPacketLimit = nl.XFRM_INF
  385. }
  386. lft.SoftAddExpiresSeconds = lmts.TimeSoft
  387. lft.HardAddExpiresSeconds = lmts.TimeHard
  388. lft.SoftUseExpiresSeconds = lmts.TimeUseSoft
  389. lft.HardUseExpiresSeconds = lmts.TimeUseHard
  390. }
  391. func lftToLimits(lft *nl.XfrmLifetimeCfg, lmts *XfrmStateLimits) {
  392. *lmts = *(*XfrmStateLimits)(unsafe.Pointer(lft))
  393. }
  394. func curToStats(cur *nl.XfrmLifetimeCur, wstats *nl.XfrmStats, stats *XfrmStateStats) {
  395. stats.Bytes = cur.Bytes
  396. stats.Packets = cur.Packets
  397. stats.AddTime = cur.AddTime
  398. stats.UseTime = cur.UseTime
  399. stats.ReplayWindow = wstats.ReplayWindow
  400. stats.Replay = wstats.Replay
  401. stats.Failed = wstats.IntegrityFailed
  402. }
  403. func xfrmUsersaInfoFromXfrmState(state *XfrmState) *nl.XfrmUsersaInfo {
  404. msg := &nl.XfrmUsersaInfo{}
  405. msg.Family = uint16(nl.GetIPFamily(state.Dst))
  406. msg.Id.Daddr.FromIP(state.Dst)
  407. msg.Saddr.FromIP(state.Src)
  408. msg.Id.Proto = uint8(state.Proto)
  409. msg.Mode = uint8(state.Mode)
  410. msg.Id.Spi = nl.Swap32(uint32(state.Spi))
  411. msg.Reqid = uint32(state.Reqid)
  412. msg.ReplayWindow = uint8(state.ReplayWindow)
  413. return msg
  414. }