iptables_test.go 20 KB

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