iptables_test.go 20 KB

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