iptables_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. originalListChain, 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(originalListChain, listChain) {
  180. t.Fatalf("ListChains mismatch: \ngot %#v \nneed %#v", originalListChain, 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.InsertUnique("filter", chain, 2, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  258. if err != nil {
  259. t.Fatalf("Insert failed: %v", err)
  260. }
  261. err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  262. if err != nil {
  263. t.Fatalf("Insert failed: %v", err)
  264. }
  265. err = ipt.Delete("filter", chain, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  266. if err != nil {
  267. t.Fatalf("Delete failed: %v", err)
  268. }
  269. err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  270. if err != nil {
  271. t.Fatalf("Append failed: %v", err)
  272. }
  273. rules, err := ipt.List("filter", chain)
  274. if err != nil {
  275. t.Fatalf("List failed: %v", err)
  276. }
  277. expected := []string{
  278. "-N " + chain,
  279. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " -j ACCEPT",
  280. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " -j ACCEPT",
  281. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " -j ACCEPT",
  282. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " -j ACCEPT",
  283. }
  284. if !reflect.DeepEqual(rules, expected) {
  285. t.Fatalf("List mismatch: \ngot %#v \nneed %#v", rules, expected)
  286. }
  287. rules, err = ipt.ListWithCounters("filter", chain)
  288. if err != nil {
  289. t.Fatalf("ListWithCounters failed: %v", err)
  290. }
  291. makeExpected := func(suffix string) []string {
  292. return []string{
  293. "-N " + chain,
  294. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " " + suffix,
  295. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " " + suffix,
  296. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " " + suffix,
  297. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " " + suffix,
  298. }
  299. }
  300. // older nf_tables returned the second order
  301. if !reflect.DeepEqual(rules, makeExpected("-c 0 0 -j ACCEPT")) &&
  302. !reflect.DeepEqual(rules, makeExpected("-j ACCEPT -c 0 0")) {
  303. t.Fatalf("ListWithCounters mismatch: \ngot %#v \nneed %#v", rules, makeExpected("<-c 0 0 and -j ACCEPT in either order>"))
  304. }
  305. stats, err := ipt.Stats("filter", chain)
  306. if err != nil {
  307. t.Fatalf("Stats failed: %v", err)
  308. }
  309. opt := "--"
  310. if ipt.proto == ProtocolIPv6 {
  311. opt = " "
  312. }
  313. expectedStats := [][]string{
  314. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet1, address1, ""},
  315. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address2, ""},
  316. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address1, ""},
  317. {"0", "0", "ACCEPT", "all", opt, "*", "*", address1, subnet2, ""},
  318. }
  319. if !reflect.DeepEqual(stats, expectedStats) {
  320. t.Fatalf("Stats mismatch: \ngot %#v \nneed %#v", stats, expectedStats)
  321. }
  322. structStats, err := ipt.StructuredStats("filter", chain)
  323. if err != nil {
  324. t.Fatalf("StructuredStats failed: %v", err)
  325. }
  326. // It's okay to not check the following errors as they will be evaluated
  327. // in the subsequent usage
  328. _, address1CIDR, _ := net.ParseCIDR(address1)
  329. _, address2CIDR, _ := net.ParseCIDR(address2)
  330. _, subnet1CIDR, _ := net.ParseCIDR(subnet1)
  331. _, subnet2CIDR, _ := net.ParseCIDR(subnet2)
  332. expectedStructStats := []Stat{
  333. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet1CIDR, address1CIDR, ""},
  334. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet2CIDR, address2CIDR, ""},
  335. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet2CIDR, address1CIDR, ""},
  336. {0, 0, "ACCEPT", "all", opt, "*", "*", address1CIDR, subnet2CIDR, ""},
  337. }
  338. if !reflect.DeepEqual(structStats, expectedStructStats) {
  339. t.Fatalf("StructuredStats mismatch: \ngot %#v \nneed %#v",
  340. structStats, expectedStructStats)
  341. }
  342. for i, stat := range expectedStats {
  343. stat, err := ipt.ParseStat(stat)
  344. if err != nil {
  345. t.Fatalf("ParseStat failed: %v", err)
  346. }
  347. if !reflect.DeepEqual(stat, expectedStructStats[i]) {
  348. t.Fatalf("ParseStat mismatch: \ngot %#v \nneed %#v",
  349. stat, expectedStructStats[i])
  350. }
  351. }
  352. err = ipt.DeleteIfExists("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  353. if err != nil {
  354. t.Fatalf("DeleteIfExists failed for existing rule: %v", err)
  355. }
  356. err = ipt.DeleteIfExists("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  357. if err != nil {
  358. t.Fatalf("DeleteIfExists failed for non-existing rule: %v", err)
  359. }
  360. // Clear the chain that was created.
  361. err = ipt.ClearChain("filter", chain)
  362. if err != nil {
  363. t.Fatalf("Failed to clear test chain: %v", err)
  364. }
  365. // Delete the chain that was created
  366. err = ipt.DeleteChain("filter", chain)
  367. if err != nil {
  368. t.Fatalf("Failed to delete test chain: %v", err)
  369. }
  370. }
  371. // TestError checks that we're OK when iptables fails to execute
  372. func TestError(t *testing.T) {
  373. ipt, err := New()
  374. if err != nil {
  375. t.Fatalf("failed to init: %v", err)
  376. }
  377. chain := randChain(t)
  378. _, err = ipt.List("filter", chain)
  379. if err == nil {
  380. t.Fatalf("no error with invalid params")
  381. }
  382. switch e := err.(type) {
  383. case *Error:
  384. // OK
  385. default:
  386. t.Fatalf("expected type iptables.Error, got %t", e)
  387. }
  388. // Now set an invalid binary path
  389. ipt.path = "/does-not-exist"
  390. _, err = ipt.ListChains("filter")
  391. if err == nil {
  392. t.Fatalf("no error with invalid ipt binary")
  393. }
  394. switch e := err.(type) {
  395. case *os.PathError:
  396. // OK
  397. default:
  398. t.Fatalf("expected type os.PathError, got %t", e)
  399. }
  400. }
  401. func TestIsNotExist(t *testing.T) {
  402. ipt, err := New()
  403. if err != nil {
  404. t.Fatalf("failed to init: %v", err)
  405. }
  406. // Create a chain, add a rule
  407. chainName := randChain(t)
  408. err = ipt.NewChain("filter", chainName)
  409. if err != nil {
  410. t.Fatal(err)
  411. }
  412. defer func() {
  413. if err := ipt.ClearChain("filter", chainName); err != nil {
  414. t.Fatal(err)
  415. }
  416. if err := ipt.DeleteChain("filter", chainName); err != nil {
  417. t.Fatal(err)
  418. }
  419. }()
  420. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  421. if err != nil {
  422. t.Fatal(err)
  423. }
  424. // Delete rule twice
  425. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  426. if err != nil {
  427. t.Fatal(err)
  428. }
  429. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  430. if err == nil {
  431. t.Fatal("delete twice got no error...")
  432. }
  433. e, ok := err.(*Error)
  434. if !ok {
  435. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  436. }
  437. if !e.IsNotExist() {
  438. t.Fatal("IsNotExist returned false, expected true")
  439. }
  440. // Delete chain
  441. err = ipt.DeleteChain("filter", chainName)
  442. if err != nil {
  443. t.Fatal(err)
  444. }
  445. err = ipt.DeleteChain("filter", chainName)
  446. if err == nil {
  447. t.Fatal("deletechain twice got no error...")
  448. }
  449. e, ok = err.(*Error)
  450. if !ok {
  451. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  452. }
  453. if !e.IsNotExist() {
  454. t.Fatal("IsNotExist returned false, expected true")
  455. }
  456. // iptables may add more logs to the errors msgs
  457. e.msg = "Another app is currently holding the xtables lock; waiting (1s) for it to exit..." + e.msg
  458. if !e.IsNotExist() {
  459. t.Fatal("IsNotExist returned false, expected true")
  460. }
  461. }
  462. func TestIsNotExistForIPv6(t *testing.T) {
  463. ipt, err := NewWithProtocol(ProtocolIPv6)
  464. if err != nil {
  465. t.Fatalf("failed to init: %v", err)
  466. }
  467. // Create a chain, add a rule
  468. chainName := randChain(t)
  469. err = ipt.NewChain("filter", chainName)
  470. if err != nil {
  471. t.Fatal(err)
  472. }
  473. defer func() {
  474. if err := ipt.ClearChain("filter", chainName); err != nil {
  475. t.Fatal(err)
  476. }
  477. if err := ipt.DeleteChain("filter", chainName); err != nil {
  478. t.Fatal(err)
  479. }
  480. }()
  481. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  482. if err != nil {
  483. t.Fatal(err)
  484. }
  485. // Delete rule twice
  486. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  487. if err != nil {
  488. t.Fatal(err)
  489. }
  490. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  491. if err == nil {
  492. t.Fatal("delete twice got no error...")
  493. }
  494. e, ok := err.(*Error)
  495. if !ok {
  496. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  497. }
  498. if !e.IsNotExist() {
  499. t.Fatal("IsNotExist returned false, expected true")
  500. }
  501. // Delete chain
  502. err = ipt.DeleteChain("filter", chainName)
  503. if err != nil {
  504. t.Fatal(err)
  505. }
  506. err = ipt.DeleteChain("filter", chainName)
  507. if err == nil {
  508. t.Fatal("deletechain twice got no error...")
  509. }
  510. e, ok = err.(*Error)
  511. if !ok {
  512. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  513. }
  514. if !e.IsNotExist() {
  515. t.Fatal("IsNotExist returned false, expected true")
  516. }
  517. // iptables may add more logs to the errors msgs
  518. e.msg = "Another app is currently holding the xtables lock; waiting (1s) for it to exit..." + e.msg
  519. if !e.IsNotExist() {
  520. t.Fatal("IsNotExist returned false, expected true")
  521. }
  522. }
  523. func TestFilterRuleOutput(t *testing.T) {
  524. testCases := []struct {
  525. name string
  526. in string
  527. out string
  528. }{
  529. {
  530. "legacy output",
  531. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  532. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  533. },
  534. {
  535. "nft output",
  536. "[99:42] -A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  537. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT -c 99 42",
  538. },
  539. }
  540. for _, tt := range testCases {
  541. t.Run(tt.name, func(t *testing.T) {
  542. actual := filterRuleOutput(tt.in)
  543. if actual != tt.out {
  544. t.Fatalf("expect %s actual %s", tt.out, actual)
  545. }
  546. })
  547. }
  548. }
  549. func TestExtractIptablesVersion(t *testing.T) {
  550. testCases := []struct {
  551. in string
  552. v1, v2, v3 int
  553. mode string
  554. err bool
  555. }{
  556. {
  557. "iptables v1.8.0 (nf_tables)",
  558. 1, 8, 0,
  559. "nf_tables",
  560. false,
  561. },
  562. {
  563. "iptables v1.8.0 (legacy)",
  564. 1, 8, 0,
  565. "legacy",
  566. false,
  567. },
  568. {
  569. "iptables v1.6.2",
  570. 1, 6, 2,
  571. "legacy",
  572. false,
  573. },
  574. }
  575. for i, tt := range testCases {
  576. t.Run(fmt.Sprint(i), func(t *testing.T) {
  577. v1, v2, v3, mode, err := extractIptablesVersion(tt.in)
  578. if err == nil && tt.err {
  579. t.Fatal("expected err, got none")
  580. } else if err != nil && !tt.err {
  581. t.Fatalf("unexpected err %s", err)
  582. }
  583. if v1 != tt.v1 || v2 != tt.v2 || v3 != tt.v3 || mode != tt.mode {
  584. t.Fatalf("expected %d %d %d %s, got %d %d %d %s",
  585. tt.v1, tt.v2, tt.v3, tt.mode,
  586. v1, v2, v3, mode)
  587. }
  588. })
  589. }
  590. }
  591. func TestListById(t *testing.T) {
  592. testCases := []struct {
  593. in string
  594. id int
  595. out string
  596. expected bool
  597. }{
  598. {
  599. "-i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3000",
  600. 1,
  601. "-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3000",
  602. true,
  603. },
  604. {
  605. "-i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3001",
  606. 2,
  607. "-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3001",
  608. true,
  609. },
  610. {
  611. "-i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3002",
  612. 3,
  613. "-A PREROUTING -i lo -p tcp -m tcp --dport 3000 -j DNAT --to-destination 127.0.0.1:3003",
  614. false,
  615. },
  616. }
  617. ipt, err := New()
  618. if err != nil {
  619. t.Fatalf("failed to init: %v", err)
  620. }
  621. // ensure to test in a clear environment
  622. err = ipt.ClearChain("nat", "PREROUTING")
  623. if err != nil {
  624. t.Fatal(err)
  625. }
  626. defer func() {
  627. err = ipt.ClearChain("nat", "PREROUTING")
  628. if err != nil {
  629. t.Fatal(err)
  630. }
  631. }()
  632. for _, tt := range testCases {
  633. t.Run(fmt.Sprintf("Checking rule with id %d", tt.id), func(t *testing.T) {
  634. err = ipt.Append("nat", "PREROUTING", strings.Split(tt.in, " ")...)
  635. if err != nil {
  636. t.Fatal(err)
  637. }
  638. rule, err := ipt.ListById("nat", "PREROUTING", tt.id)
  639. if err != nil {
  640. t.Fatal(err)
  641. }
  642. fmt.Println(rule)
  643. test_result := false
  644. if rule == tt.out {
  645. test_result = true
  646. }
  647. if test_result != tt.expected {
  648. t.Fatal("Test failed")
  649. }
  650. })
  651. }
  652. }