iptables_test.go 19 KB

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