iptables_test.go 18 KB

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