iptables_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. // Copyright 2015 CoreOS, Inc.
  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 iptables
  15. import (
  16. "crypto/rand"
  17. "fmt"
  18. "math/big"
  19. "net"
  20. "os"
  21. "reflect"
  22. "strings"
  23. "testing"
  24. )
  25. func TestProto(t *testing.T) {
  26. ipt, err := New()
  27. if err != nil {
  28. t.Fatalf("New failed: %v", err)
  29. }
  30. if ipt.Proto() != ProtocolIPv4 {
  31. t.Fatalf("Expected default protocol IPv4, got %v", ipt.Proto())
  32. }
  33. ip4t, err := NewWithProtocol(ProtocolIPv4)
  34. if err != nil {
  35. t.Fatalf("NewWithProtocol(ProtocolIPv4) failed: %v", err)
  36. }
  37. if ip4t.Proto() != ProtocolIPv4 {
  38. t.Fatalf("Expected protocol IPv4, got %v", ip4t.Proto())
  39. }
  40. ip6t, err := NewWithProtocol(ProtocolIPv6)
  41. if err != nil {
  42. t.Fatalf("NewWithProtocol(ProtocolIPv6) failed: %v", err)
  43. }
  44. if ip6t.Proto() != ProtocolIPv6 {
  45. t.Fatalf("Expected protocol IPv6, got %v", ip6t.Proto())
  46. }
  47. }
  48. func TestTimeout(t *testing.T) {
  49. ipt, err := New()
  50. if err != nil {
  51. t.Fatalf("New failed: %v", err)
  52. }
  53. if ipt.timeout != 0 {
  54. t.Fatalf("Expected timeout 0 (wait forever), got %v", ipt.timeout)
  55. }
  56. ipt2, err := New(Timeout(5))
  57. if err != nil {
  58. t.Fatalf("New failed: %v", err)
  59. }
  60. if ipt2.timeout != 5 {
  61. t.Fatalf("Expected timeout 5, got %v", ipt.timeout)
  62. }
  63. }
  64. // force usage of -legacy or -nft commands and check that they're detected correctly
  65. func TestLegacyDetection(t *testing.T) {
  66. testCases := []struct {
  67. in string
  68. mode string
  69. err bool
  70. }{
  71. {
  72. "iptables-legacy",
  73. "legacy",
  74. false,
  75. },
  76. {
  77. "ip6tables-legacy",
  78. "legacy",
  79. false,
  80. },
  81. {
  82. "iptables-nft",
  83. "nf_tables",
  84. false,
  85. },
  86. {
  87. "ip6tables-nft",
  88. "nf_tables",
  89. false,
  90. },
  91. }
  92. for i, tt := range testCases {
  93. t.Run(fmt.Sprint(i), func(t *testing.T) {
  94. ipt, err := New(Path(tt.in))
  95. if err == nil && tt.err {
  96. t.Fatal("expected err, got none")
  97. } else if err != nil && !tt.err {
  98. t.Fatalf("unexpected err %s", err)
  99. }
  100. if !strings.Contains(ipt.path, tt.in) {
  101. t.Fatalf("Expected path %s in %s", tt.in, ipt.path)
  102. }
  103. if ipt.mode != tt.mode {
  104. t.Fatalf("Expected %s iptables, but got %s", tt.mode, ipt.mode)
  105. }
  106. })
  107. }
  108. }
  109. func randChain(t *testing.T) string {
  110. n, err := rand.Int(rand.Reader, big.NewInt(1000000))
  111. if err != nil {
  112. t.Fatalf("Failed to generate random chain name: %v", err)
  113. }
  114. return "TEST-" + n.String()
  115. }
  116. func contains(list []string, value string) bool {
  117. for _, val := range list {
  118. if val == value {
  119. return true
  120. }
  121. }
  122. return false
  123. }
  124. // mustTestableIptables returns a list of ip(6)tables handles with various
  125. // features enabled & disabled, to test compatibility.
  126. // We used to test noWait as well, but that was removed as of iptables v1.6.0
  127. func mustTestableIptables() []*IPTables {
  128. ipt, err := New()
  129. if err != nil {
  130. panic(fmt.Sprintf("New failed: %v", err))
  131. }
  132. ip6t, err := NewWithProtocol(ProtocolIPv6)
  133. if err != nil {
  134. panic(fmt.Sprintf("NewWithProtocol(ProtocolIPv6) failed: %v", err))
  135. }
  136. ipts := []*IPTables{ipt, ip6t}
  137. // ensure we check one variant without built-in checking
  138. if ipt.hasCheck {
  139. i := *ipt
  140. i.hasCheck = false
  141. ipts = append(ipts, &i)
  142. i6 := *ip6t
  143. i6.hasCheck = false
  144. ipts = append(ipts, &i6)
  145. } else {
  146. panic("iptables on this machine is too old -- missing -C")
  147. }
  148. return ipts
  149. }
  150. func TestChain(t *testing.T) {
  151. for i, ipt := range mustTestableIptables() {
  152. t.Run(fmt.Sprint(i), func(t *testing.T) {
  153. runChainTests(t, ipt)
  154. })
  155. }
  156. }
  157. func runChainTests(t *testing.T, ipt *IPTables) {
  158. t.Logf("testing %s (hasWait=%t, hasCheck=%t)", ipt.path, ipt.hasWait, ipt.hasCheck)
  159. chain := randChain(t)
  160. // Saving the list of chains before executing tests
  161. originalListChain, err := ipt.ListChains("filter")
  162. if err != nil {
  163. t.Fatalf("ListChains of Initial failed: %v", err)
  164. }
  165. // chain shouldn't exist, this will create new
  166. err = ipt.ClearChain("filter", chain)
  167. if err != nil {
  168. t.Fatalf("ClearChain (of missing) failed: %v", err)
  169. }
  170. // chain should be in listChain
  171. listChain, err := ipt.ListChains("filter")
  172. if err != nil {
  173. t.Fatalf("ListChains failed: %v", err)
  174. }
  175. if !contains(listChain, chain) {
  176. t.Fatalf("ListChains doesn't contain the new chain %v", chain)
  177. }
  178. // ChainExists should find it, too
  179. exists, err := ipt.ChainExists("filter", chain)
  180. if err != nil {
  181. t.Fatalf("ChainExists for existing chain failed: %v", err)
  182. } else if !exists {
  183. t.Fatalf("ChainExists doesn't find existing chain")
  184. }
  185. // chain now exists
  186. err = ipt.ClearChain("filter", chain)
  187. if err != nil {
  188. t.Fatalf("ClearChain (of empty) failed: %v", err)
  189. }
  190. // put a simple rule in
  191. err = ipt.Append("filter", chain, "-s", "0/0", "-j", "ACCEPT")
  192. if err != nil {
  193. t.Fatalf("Append failed: %v", err)
  194. }
  195. // can't delete non-empty chain
  196. err = ipt.DeleteChain("filter", chain)
  197. if err == nil {
  198. t.Fatalf("DeleteChain of non-empty chain did not fail")
  199. }
  200. e, ok := err.(*Error)
  201. if ok && e.IsNotExist() {
  202. t.Fatal("DeleteChain of non-empty chain returned IsNotExist")
  203. }
  204. err = ipt.ClearChain("filter", chain)
  205. if err != nil {
  206. t.Fatalf("ClearChain (of non-empty) failed: %v", err)
  207. }
  208. // rename the chain
  209. newChain := randChain(t)
  210. err = ipt.RenameChain("filter", chain, newChain)
  211. if err != nil {
  212. t.Fatalf("RenameChain failed: %v", err)
  213. }
  214. // chain empty, should be ok
  215. err = ipt.DeleteChain("filter", newChain)
  216. if err != nil {
  217. t.Fatalf("DeleteChain of empty chain failed: %v", err)
  218. }
  219. // check that chain is fully gone and that state similar to initial one
  220. listChain, err = ipt.ListChains("filter")
  221. if err != nil {
  222. t.Fatalf("ListChains failed: %v", err)
  223. }
  224. if !reflect.DeepEqual(originalListChain, listChain) {
  225. t.Fatalf("ListChains mismatch: \ngot %#v \nneed %#v", originalListChain, listChain)
  226. }
  227. // ChainExists must not find it anymore
  228. exists, err = ipt.ChainExists("filter", chain)
  229. if err != nil {
  230. t.Fatalf("ChainExists for non-existing chain failed: %v", err)
  231. } else if exists {
  232. t.Fatalf("ChainExists finds non-existing chain")
  233. }
  234. // test ClearAndDelete
  235. err = ipt.NewChain("filter", chain)
  236. if err != nil {
  237. t.Fatalf("NewChain failed: %v", err)
  238. }
  239. err = ipt.Append("filter", chain, "-j", "ACCEPT")
  240. if err != nil {
  241. t.Fatalf("Append failed: %v", err)
  242. }
  243. err = ipt.ClearAndDeleteChain("filter", chain)
  244. if err != nil {
  245. t.Fatalf("ClearAndDelete failed: %v", err)
  246. }
  247. exists, err = ipt.ChainExists("filter", chain)
  248. if err != nil {
  249. t.Fatalf("ChainExists failed: %v", err)
  250. }
  251. if exists {
  252. t.Fatalf("ClearAndDelete didn't delete the chain")
  253. }
  254. err = ipt.ClearAndDeleteChain("filter", chain)
  255. if err != nil {
  256. t.Fatalf("ClearAndDelete failed for non-existing chain: %v", err)
  257. }
  258. }
  259. func TestRules(t *testing.T) {
  260. for i, ipt := range mustTestableIptables() {
  261. t.Run(fmt.Sprint(i), func(t *testing.T) {
  262. runRulesTests(t, ipt)
  263. })
  264. }
  265. }
  266. func runRulesTests(t *testing.T, ipt *IPTables) {
  267. t.Logf("testing %s (hasWait=%t, hasCheck=%t)", getIptablesCommand(ipt.Proto()), ipt.hasWait, ipt.hasCheck)
  268. var address1, address2, address3, address4, subnet1, subnet2, subnet3, subnet4 string
  269. if ipt.Proto() == ProtocolIPv6 {
  270. address1 = "2001:db8::1/128"
  271. address2 = "2001:db8::2/128"
  272. address3 = "2001:db8::3/128"
  273. address4 = "2001:db8::4/128"
  274. subnet1 = "2001:db8:a::/48"
  275. subnet2 = "2001:db8:b::/48"
  276. subnet3 = "2001:db8:c::/48"
  277. subnet4 = "2001:db8:d::/48"
  278. } else {
  279. address1 = "203.0.113.1/32"
  280. address2 = "203.0.113.2/32"
  281. address3 = "203.0.113.3/32"
  282. address4 = "203.0.113.4/32"
  283. subnet1 = "192.0.2.0/24"
  284. subnet2 = "198.51.100.0/24"
  285. subnet3 = "198.51.101.0/24"
  286. subnet4 = "198.51.102.0/24"
  287. }
  288. chain := randChain(t)
  289. // chain shouldn't exist, this will create new
  290. err := ipt.ClearChain("filter", chain)
  291. if err != nil {
  292. t.Fatalf("ClearChain (of missing) failed: %v", err)
  293. }
  294. err = ipt.Append("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  295. if err != nil {
  296. t.Fatalf("Append failed: %v", err)
  297. }
  298. err = ipt.AppendUnique("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  299. if err != nil {
  300. t.Fatalf("AppendUnique failed: %v", err)
  301. }
  302. err = ipt.Append("filter", chain, "-s", subnet2, "-d", address1, "-j", "ACCEPT")
  303. if err != nil {
  304. t.Fatalf("Append failed: %v", err)
  305. }
  306. err = ipt.Insert("filter", chain, 2, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  307. if err != nil {
  308. t.Fatalf("Insert failed: %v", err)
  309. }
  310. err = ipt.InsertUnique("filter", chain, 2, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  311. if err != nil {
  312. t.Fatalf("Insert failed: %v", err)
  313. }
  314. err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  315. if err != nil {
  316. t.Fatalf("Insert failed: %v", err)
  317. }
  318. err = ipt.Delete("filter", chain, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  319. if err != nil {
  320. t.Fatalf("Delete failed: %v", err)
  321. }
  322. err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  323. if err != nil {
  324. t.Fatalf("Insert failed: %v", err)
  325. }
  326. err = ipt.Replace("filter", chain, 1, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  327. if err != nil {
  328. t.Fatalf("Replace failed: %v", err)
  329. }
  330. err = ipt.Delete("filter", chain, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  331. if err != nil {
  332. t.Fatalf("Delete failed: %v", err)
  333. }
  334. err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  335. if err != nil {
  336. t.Fatalf("Append failed: %v", err)
  337. }
  338. rules, err := ipt.List("filter", chain)
  339. if err != nil {
  340. t.Fatalf("List failed: %v", err)
  341. }
  342. // Verify DeleteById functionality by adding two new rules and removing second last
  343. ruleCount1 := len(rules)
  344. err = ipt.Append("filter", chain, "-s", address3, "-d", subnet3, "-j", "ACCEPT")
  345. if err != nil {
  346. t.Fatalf("Append failed: %v", err)
  347. }
  348. err = ipt.Append("filter", chain, "-s", address4, "-d", subnet4, "-j", "ACCEPT")
  349. if err != nil {
  350. t.Fatalf("Append failed: %v", err)
  351. }
  352. err = ipt.DeleteById("filter", chain, ruleCount1)
  353. if err != nil {
  354. t.Fatalf("DeleteById failed: %v", err)
  355. }
  356. rules, err = ipt.List("filter", chain)
  357. if err != nil {
  358. t.Fatalf("List failed: %v", err)
  359. }
  360. expected := []string{
  361. "-N " + chain,
  362. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " -j ACCEPT",
  363. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " -j ACCEPT",
  364. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " -j ACCEPT",
  365. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " -j ACCEPT",
  366. "-A " + chain + " -s " + address4 + " -d " + subnet4 + " -j ACCEPT",
  367. }
  368. if !reflect.DeepEqual(rules, expected) {
  369. t.Fatalf("List mismatch: \ngot %#v \nneed %#v", rules, expected)
  370. }
  371. rules, err = ipt.ListWithCounters("filter", chain)
  372. if err != nil {
  373. t.Fatalf("ListWithCounters failed: %v", err)
  374. }
  375. makeExpected := func(suffix string) []string {
  376. return []string{
  377. "-N " + chain,
  378. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " " + suffix,
  379. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " " + suffix,
  380. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " " + suffix,
  381. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " " + suffix,
  382. "-A " + chain + " -s " + address4 + " -d " + subnet4 + " " + suffix,
  383. }
  384. }
  385. // older nf_tables returned the second order
  386. if !reflect.DeepEqual(rules, makeExpected("-c 0 0 -j ACCEPT")) &&
  387. !reflect.DeepEqual(rules, makeExpected("-j ACCEPT -c 0 0")) {
  388. t.Fatalf("ListWithCounters mismatch: \ngot %#v \nneed %#v", rules, makeExpected("<-c 0 0 and -j ACCEPT in either order>"))
  389. }
  390. stats, err := ipt.Stats("filter", chain)
  391. if err != nil {
  392. t.Fatalf("Stats failed: %v", err)
  393. }
  394. opt := "--"
  395. prot := "0"
  396. if ipt.proto == ProtocolIPv6 &&
  397. ipt.v1 == 1 && (ipt.v2 < 8 || (ipt.v2 == 8 && ipt.v3 < 9)) {
  398. // this is fixed in iptables 1.8.9 via iptables/6e41c2d874
  399. opt = " "
  400. // this is fixed in iptables 1.8.9 via iptables/da8ecc62dd
  401. prot = "all"
  402. }
  403. if ipt.proto == ProtocolIPv4 &&
  404. ipt.v1 == 1 && (ipt.v2 < 8 || (ipt.v2 == 8 && ipt.v3 < 9)) {
  405. // this is fixed in iptables 1.8.9 via iptables/da8ecc62dd
  406. prot = "all"
  407. }
  408. expectedStats := [][]string{
  409. {"0", "0", "ACCEPT", prot, opt, "*", "*", subnet1, address1, ""},
  410. {"0", "0", "ACCEPT", prot, opt, "*", "*", subnet2, address2, ""},
  411. {"0", "0", "ACCEPT", prot, opt, "*", "*", subnet2, address1, ""},
  412. {"0", "0", "ACCEPT", prot, opt, "*", "*", address1, subnet2, ""},
  413. {"0", "0", "ACCEPT", prot, opt, "*", "*", address4, subnet4, ""},
  414. }
  415. if !reflect.DeepEqual(stats, expectedStats) {
  416. t.Fatalf("Stats mismatch: \ngot %#v \nneed %#v", stats, expectedStats)
  417. }
  418. structStats, err := ipt.StructuredStats("filter", chain)
  419. if err != nil {
  420. t.Fatalf("StructuredStats failed: %v", err)
  421. }
  422. // It's okay to not check the following errors as they will be evaluated
  423. // in the subsequent usage
  424. _, address1CIDR, _ := net.ParseCIDR(address1)
  425. _, address2CIDR, _ := net.ParseCIDR(address2)
  426. _, address4CIDR, _ := net.ParseCIDR(address4)
  427. _, subnet1CIDR, _ := net.ParseCIDR(subnet1)
  428. _, subnet2CIDR, _ := net.ParseCIDR(subnet2)
  429. _, subnet4CIDR, _ := net.ParseCIDR(subnet4)
  430. expectedStructStats := []Stat{
  431. {0, 0, "ACCEPT", prot, opt, "*", "*", subnet1CIDR, address1CIDR, ""},
  432. {0, 0, "ACCEPT", prot, opt, "*", "*", subnet2CIDR, address2CIDR, ""},
  433. {0, 0, "ACCEPT", prot, opt, "*", "*", subnet2CIDR, address1CIDR, ""},
  434. {0, 0, "ACCEPT", prot, opt, "*", "*", address1CIDR, subnet2CIDR, ""},
  435. {0, 0, "ACCEPT", prot, opt, "*", "*", address4CIDR, subnet4CIDR, ""},
  436. }
  437. if !reflect.DeepEqual(structStats, expectedStructStats) {
  438. t.Fatalf("StructuredStats mismatch: \ngot %#v \nneed %#v",
  439. structStats, expectedStructStats)
  440. }
  441. for i, stat := range expectedStats {
  442. stat, err := ipt.ParseStat(stat)
  443. if err != nil {
  444. t.Fatalf("ParseStat failed: %v", err)
  445. }
  446. if !reflect.DeepEqual(stat, expectedStructStats[i]) {
  447. t.Fatalf("ParseStat mismatch: \ngot %#v \nneed %#v",
  448. stat, expectedStructStats[i])
  449. }
  450. }
  451. err = ipt.DeleteIfExists("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  452. if err != nil {
  453. t.Fatalf("DeleteIfExists failed for existing rule: %v", err)
  454. }
  455. err = ipt.DeleteIfExists("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  456. if err != nil {
  457. t.Fatalf("DeleteIfExists failed for non-existing rule: %v", err)
  458. }
  459. // Clear the chain that was created.
  460. err = ipt.ClearChain("filter", chain)
  461. if err != nil {
  462. t.Fatalf("Failed to clear test chain: %v", err)
  463. }
  464. // Delete the chain that was created
  465. err = ipt.DeleteChain("filter", chain)
  466. if err != nil {
  467. t.Fatalf("Failed to delete test chain: %v", err)
  468. }
  469. }
  470. // TestError checks that we're OK when iptables fails to execute
  471. func TestError(t *testing.T) {
  472. ipt, err := New()
  473. if err != nil {
  474. t.Fatalf("failed to init: %v", err)
  475. }
  476. chain := randChain(t)
  477. _, err = ipt.List("filter", chain)
  478. if err == nil {
  479. t.Fatalf("no error with invalid params")
  480. }
  481. switch e := err.(type) {
  482. case *Error:
  483. // OK
  484. default:
  485. t.Fatalf("expected type iptables.Error, got %t", e)
  486. }
  487. // Now set an invalid binary path
  488. ipt.path = "/does-not-exist"
  489. _, err = ipt.ListChains("filter")
  490. if err == nil {
  491. t.Fatalf("no error with invalid ipt binary")
  492. }
  493. switch e := err.(type) {
  494. case *os.PathError:
  495. // OK
  496. default:
  497. t.Fatalf("expected type os.PathError, got %t", e)
  498. }
  499. }
  500. func TestIsNotExist(t *testing.T) {
  501. ipt, err := New()
  502. if err != nil {
  503. t.Fatalf("failed to init: %v", err)
  504. }
  505. // Create a chain, add a rule
  506. chainName := randChain(t)
  507. err = ipt.NewChain("filter", chainName)
  508. if err != nil {
  509. t.Fatal(err)
  510. }
  511. defer func() {
  512. if err := ipt.ClearChain("filter", chainName); err != nil {
  513. t.Fatal(err)
  514. }
  515. if err := ipt.DeleteChain("filter", chainName); err != nil {
  516. t.Fatal(err)
  517. }
  518. }()
  519. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  520. if err != nil {
  521. t.Fatal(err)
  522. }
  523. // Delete rule twice
  524. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  525. if err != nil {
  526. t.Fatal(err)
  527. }
  528. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  529. if err == nil {
  530. t.Fatal("delete twice got no error...")
  531. }
  532. e, ok := err.(*Error)
  533. if !ok {
  534. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  535. }
  536. if !e.IsNotExist() {
  537. t.Fatal("IsNotExist returned false, expected true")
  538. }
  539. // Delete chain
  540. err = ipt.DeleteChain("filter", chainName)
  541. if err != nil {
  542. t.Fatal(err)
  543. }
  544. err = ipt.DeleteChain("filter", chainName)
  545. if err == nil {
  546. t.Fatal("deletechain twice got no error...")
  547. }
  548. e, ok = err.(*Error)
  549. if !ok {
  550. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  551. }
  552. if !e.IsNotExist() {
  553. t.Fatal("IsNotExist returned false, expected true")
  554. }
  555. // iptables may add more logs to the errors msgs
  556. e.msg = "Another app is currently holding the xtables lock; waiting (1s) for it to exit..." + e.msg
  557. if !e.IsNotExist() {
  558. t.Fatal("IsNotExist returned false, expected true")
  559. }
  560. }
  561. func TestIsNotExistForIPv6(t *testing.T) {
  562. ipt, err := NewWithProtocol(ProtocolIPv6)
  563. if err != nil {
  564. t.Fatalf("failed to init: %v", err)
  565. }
  566. // Create a chain, add a rule
  567. chainName := randChain(t)
  568. err = ipt.NewChain("filter", chainName)
  569. if err != nil {
  570. t.Fatal(err)
  571. }
  572. defer func() {
  573. if err := ipt.ClearChain("filter", chainName); err != nil {
  574. t.Fatal(err)
  575. }
  576. if err := ipt.DeleteChain("filter", chainName); err != nil {
  577. t.Fatal(err)
  578. }
  579. }()
  580. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  581. if err != nil {
  582. t.Fatal(err)
  583. }
  584. // Delete rule twice
  585. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  586. if err != nil {
  587. t.Fatal(err)
  588. }
  589. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  590. if err == nil {
  591. t.Fatal("delete twice got no error...")
  592. }
  593. e, ok := err.(*Error)
  594. if !ok {
  595. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  596. }
  597. if !e.IsNotExist() {
  598. t.Fatal("IsNotExist returned false, expected true")
  599. }
  600. // Delete chain
  601. err = ipt.DeleteChain("filter", chainName)
  602. if err != nil {
  603. t.Fatal(err)
  604. }
  605. err = ipt.DeleteChain("filter", chainName)
  606. if err == nil {
  607. t.Fatal("deletechain twice got no error...")
  608. }
  609. e, ok = err.(*Error)
  610. if !ok {
  611. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  612. }
  613. if !e.IsNotExist() {
  614. t.Fatal("IsNotExist returned false, expected true")
  615. }
  616. // iptables may add more logs to the errors msgs
  617. e.msg = "Another app is currently holding the xtables lock; waiting (1s) for it to exit..." + e.msg
  618. if !e.IsNotExist() {
  619. t.Fatal("IsNotExist returned false, expected true")
  620. }
  621. }
  622. func TestFilterRuleOutput(t *testing.T) {
  623. testCases := []struct {
  624. name string
  625. in string
  626. out string
  627. }{
  628. {
  629. "legacy output",
  630. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  631. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  632. },
  633. {
  634. "nft output",
  635. "[99:42] -A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  636. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT -c 99 42",
  637. },
  638. }
  639. for _, tt := range testCases {
  640. t.Run(tt.name, func(t *testing.T) {
  641. actual := filterRuleOutput(tt.in)
  642. if actual != tt.out {
  643. t.Fatalf("expect %s actual %s", tt.out, actual)
  644. }
  645. })
  646. }
  647. }
  648. func TestExtractIptablesVersion(t *testing.T) {
  649. testCases := []struct {
  650. in string
  651. v1, v2, v3 int
  652. mode string
  653. err bool
  654. }{
  655. {
  656. "iptables v1.8.0 (nf_tables)",
  657. 1, 8, 0,
  658. "nf_tables",
  659. false,
  660. },
  661. {
  662. "iptables v1.8.0 (legacy)",
  663. 1, 8, 0,
  664. "legacy",
  665. false,
  666. },
  667. {
  668. "iptables v1.6.2",
  669. 1, 6, 2,
  670. "legacy",
  671. false,
  672. },
  673. }
  674. for i, tt := range testCases {
  675. t.Run(fmt.Sprint(i), func(t *testing.T) {
  676. v1, v2, v3, mode, err := extractIptablesVersion(tt.in)
  677. if err == nil && tt.err {
  678. t.Fatal("expected err, got none")
  679. } else if err != nil && !tt.err {
  680. t.Fatalf("unexpected err %s", err)
  681. }
  682. if v1 != tt.v1 || v2 != tt.v2 || v3 != tt.v3 || mode != tt.mode {
  683. t.Fatalf("expected %d %d %d %s, got %d %d %d %s",
  684. tt.v1, tt.v2, tt.v3, tt.mode,
  685. v1, v2, v3, mode)
  686. }
  687. })
  688. }
  689. }
  690. func TestListById(t *testing.T) {
  691. testCases := []struct {
  692. in string
  693. id int
  694. out string
  695. expected bool
  696. }{
  697. {
  698. "-i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3000",
  699. 1,
  700. "-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3000",
  701. true,
  702. },
  703. {
  704. "-i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3001",
  705. 2,
  706. "-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3001",
  707. true,
  708. },
  709. {
  710. "-i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3002",
  711. 3,
  712. "-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3003",
  713. false,
  714. },
  715. }
  716. ipt, err := New()
  717. if err != nil {
  718. t.Fatalf("failed to init: %v", err)
  719. }
  720. // ensure to test in a clear environment
  721. err = ipt.ClearChain("nat", "PREROUTING")
  722. if err != nil {
  723. t.Fatal(err)
  724. }
  725. defer func() {
  726. err = ipt.ClearChain("nat", "PREROUTING")
  727. if err != nil {
  728. t.Fatal(err)
  729. }
  730. }()
  731. for _, tt := range testCases {
  732. t.Run(fmt.Sprintf("Checking rule with id %d", tt.id), func(t *testing.T) {
  733. err = ipt.Append("nat", "PREROUTING", strings.Split(tt.in, " ")...)
  734. if err != nil {
  735. t.Fatal(err)
  736. }
  737. rule, err := ipt.ListById("nat", "PREROUTING", tt.id)
  738. if err != nil {
  739. t.Fatal(err)
  740. }
  741. fmt.Println(rule)
  742. test_result := false
  743. if rule == tt.out {
  744. test_result = true
  745. }
  746. if test_result != tt.expected {
  747. t.Fatal("Test failed")
  748. }
  749. })
  750. }
  751. }