iptables_test.go 19 KB

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