iptables_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. "testing"
  23. )
  24. func TestProto(t *testing.T) {
  25. ipt, err := New()
  26. if err != nil {
  27. t.Fatalf("New failed: %v", err)
  28. }
  29. if ipt.Proto() != ProtocolIPv4 {
  30. t.Fatalf("Expected default protocol IPv4, got %v", ipt.Proto())
  31. }
  32. ip4t, err := NewWithProtocol(ProtocolIPv4)
  33. if err != nil {
  34. t.Fatalf("NewWithProtocol(ProtocolIPv4) failed: %v", err)
  35. }
  36. if ip4t.Proto() != ProtocolIPv4 {
  37. t.Fatalf("Expected protocol IPv4, got %v", ip4t.Proto())
  38. }
  39. ip6t, err := NewWithProtocol(ProtocolIPv6)
  40. if err != nil {
  41. t.Fatalf("NewWithProtocol(ProtocolIPv6) failed: %v", err)
  42. }
  43. if ip6t.Proto() != ProtocolIPv6 {
  44. t.Fatalf("Expected protocol IPv6, got %v", ip6t.Proto())
  45. }
  46. }
  47. func randChain(t *testing.T) string {
  48. n, err := rand.Int(rand.Reader, big.NewInt(1000000))
  49. if err != nil {
  50. t.Fatalf("Failed to generate random chain name: %v", err)
  51. }
  52. return "TEST-" + n.String()
  53. }
  54. func contains(list []string, value string) bool {
  55. for _, val := range list {
  56. if val == value {
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. // mustTestableIptables returns a list of ip(6)tables handles with various
  63. // features enabled & disabled, to test compatibility.
  64. // We used to test noWait as well, but that was removed as of iptables v1.6.0
  65. func mustTestableIptables() []*IPTables {
  66. ipt, err := New()
  67. if err != nil {
  68. panic(fmt.Sprintf("New failed: %v", err))
  69. }
  70. ip6t, err := NewWithProtocol(ProtocolIPv6)
  71. if err != nil {
  72. panic(fmt.Sprintf("NewWithProtocol(ProtocolIPv6) failed: %v", err))
  73. }
  74. ipts := []*IPTables{ipt, ip6t}
  75. // ensure we check one variant without built-in checking
  76. if ipt.hasCheck {
  77. i := *ipt
  78. i.hasCheck = false
  79. ipts = append(ipts, &i)
  80. i6 := *ip6t
  81. i6.hasCheck = false
  82. ipts = append(ipts, &i6)
  83. } else {
  84. panic("iptables on this machine is too old -- missing -C")
  85. }
  86. return ipts
  87. }
  88. func TestChain(t *testing.T) {
  89. for i, ipt := range mustTestableIptables() {
  90. t.Run(fmt.Sprint(i), func(t *testing.T) {
  91. runChainTests(t, ipt)
  92. })
  93. }
  94. }
  95. func runChainTests(t *testing.T, ipt *IPTables) {
  96. t.Logf("testing %s (hasWait=%t, hasCheck=%t)", ipt.path, ipt.hasWait, ipt.hasCheck)
  97. chain := randChain(t)
  98. // Saving the list of chains before executing tests
  99. originaListChain, err := ipt.ListChains("filter")
  100. if err != nil {
  101. t.Fatalf("ListChains of Initial failed: %v", err)
  102. }
  103. // chain shouldn't exist, this will create new
  104. err = ipt.ClearChain("filter", chain)
  105. if err != nil {
  106. t.Fatalf("ClearChain (of missing) failed: %v", err)
  107. }
  108. // chain should be in listChain
  109. listChain, err := ipt.ListChains("filter")
  110. if err != nil {
  111. t.Fatalf("ListChains failed: %v", err)
  112. }
  113. if !contains(listChain, chain) {
  114. t.Fatalf("ListChains doesn't contain the new chain %v", chain)
  115. }
  116. // ChainExists should find it, too
  117. exists, err := ipt.ChainExists("filter", chain)
  118. if err != nil {
  119. t.Fatalf("ChainExists for existing chain failed: %v", err)
  120. } else if !exists {
  121. t.Fatalf("ChainExists doesn't find existing chain")
  122. }
  123. // chain now exists
  124. err = ipt.ClearChain("filter", chain)
  125. if err != nil {
  126. t.Fatalf("ClearChain (of empty) failed: %v", err)
  127. }
  128. // put a simple rule in
  129. err = ipt.Append("filter", chain, "-s", "0/0", "-j", "ACCEPT")
  130. if err != nil {
  131. t.Fatalf("Append failed: %v", err)
  132. }
  133. // can't delete non-empty chain
  134. err = ipt.DeleteChain("filter", chain)
  135. if err == nil {
  136. t.Fatalf("DeleteChain of non-empty chain did not fail")
  137. }
  138. e, ok := err.(*Error)
  139. if ok && e.IsNotExist() {
  140. t.Fatal("DeleteChain of non-empty chain returned IsNotExist")
  141. }
  142. err = ipt.ClearChain("filter", chain)
  143. if err != nil {
  144. t.Fatalf("ClearChain (of non-empty) failed: %v", err)
  145. }
  146. // rename the chain
  147. newChain := randChain(t)
  148. err = ipt.RenameChain("filter", chain, newChain)
  149. if err != nil {
  150. t.Fatalf("RenameChain failed: %v", err)
  151. }
  152. // chain empty, should be ok
  153. err = ipt.DeleteChain("filter", newChain)
  154. if err != nil {
  155. t.Fatalf("DeleteChain of empty chain failed: %v", err)
  156. }
  157. // check that chain is fully gone and that state similar to initial one
  158. listChain, err = ipt.ListChains("filter")
  159. if err != nil {
  160. t.Fatalf("ListChains failed: %v", err)
  161. }
  162. if !reflect.DeepEqual(originaListChain, listChain) {
  163. t.Fatalf("ListChains mismatch: \ngot %#v \nneed %#v", originaListChain, listChain)
  164. }
  165. // ChainExists must not find it anymore
  166. exists, err = ipt.ChainExists("filter", chain)
  167. if err != nil {
  168. t.Fatalf("ChainExists for non-existing chain failed: %v", err)
  169. } else if exists {
  170. t.Fatalf("ChainExists finds non-existing chain")
  171. }
  172. }
  173. func TestRules(t *testing.T) {
  174. for i, ipt := range mustTestableIptables() {
  175. t.Run(fmt.Sprint(i), func(t *testing.T) {
  176. runRulesTests(t, ipt)
  177. })
  178. }
  179. }
  180. func runRulesTests(t *testing.T, ipt *IPTables) {
  181. t.Logf("testing %s (hasWait=%t, hasCheck=%t)", getIptablesCommand(ipt.Proto()), ipt.hasWait, ipt.hasCheck)
  182. var address1, address2, subnet1, subnet2 string
  183. if ipt.Proto() == ProtocolIPv6 {
  184. address1 = "2001:db8::1/128"
  185. address2 = "2001:db8::2/128"
  186. subnet1 = "2001:db8:a::/48"
  187. subnet2 = "2001:db8:b::/48"
  188. } else {
  189. address1 = "203.0.113.1/32"
  190. address2 = "203.0.113.2/32"
  191. subnet1 = "192.0.2.0/24"
  192. subnet2 = "198.51.100.0/24"
  193. }
  194. chain := randChain(t)
  195. // chain shouldn't exist, this will create new
  196. err := ipt.ClearChain("filter", chain)
  197. if err != nil {
  198. t.Fatalf("ClearChain (of missing) failed: %v", err)
  199. }
  200. err = ipt.Append("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  201. if err != nil {
  202. t.Fatalf("Append failed: %v", err)
  203. }
  204. err = ipt.AppendUnique("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  205. if err != nil {
  206. t.Fatalf("AppendUnique failed: %v", err)
  207. }
  208. err = ipt.Append("filter", chain, "-s", subnet2, "-d", address1, "-j", "ACCEPT")
  209. if err != nil {
  210. t.Fatalf("Append failed: %v", err)
  211. }
  212. err = ipt.Insert("filter", chain, 2, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  213. if err != nil {
  214. t.Fatalf("Insert failed: %v", err)
  215. }
  216. err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  217. if err != nil {
  218. t.Fatalf("Insert failed: %v", err)
  219. }
  220. err = ipt.Delete("filter", chain, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  221. if err != nil {
  222. t.Fatalf("Delete failed: %v", err)
  223. }
  224. err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  225. if err != nil {
  226. t.Fatalf("Append failed: %v", err)
  227. }
  228. rules, err := ipt.List("filter", chain)
  229. if err != nil {
  230. t.Fatalf("List failed: %v", err)
  231. }
  232. expected := []string{
  233. "-N " + chain,
  234. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " -j ACCEPT",
  235. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " -j ACCEPT",
  236. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " -j ACCEPT",
  237. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " -j ACCEPT",
  238. }
  239. if !reflect.DeepEqual(rules, expected) {
  240. t.Fatalf("List mismatch: \ngot %#v \nneed %#v", rules, expected)
  241. }
  242. rules, err = ipt.ListWithCounters("filter", chain)
  243. if err != nil {
  244. t.Fatalf("ListWithCounters failed: %v", err)
  245. }
  246. suffix := " -c 0 0 -j ACCEPT"
  247. if ipt.mode == "nf_tables" {
  248. suffix = " -j ACCEPT -c 0 0"
  249. }
  250. expected = []string{
  251. "-N " + chain,
  252. "-A " + chain + " -s " + subnet1 + " -d " + address1 + suffix,
  253. "-A " + chain + " -s " + subnet2 + " -d " + address2 + suffix,
  254. "-A " + chain + " -s " + subnet2 + " -d " + address1 + suffix,
  255. "-A " + chain + " -s " + address1 + " -d " + subnet2 + suffix,
  256. }
  257. if !reflect.DeepEqual(rules, expected) {
  258. t.Fatalf("ListWithCounters mismatch: \ngot %#v \nneed %#v", rules, expected)
  259. }
  260. stats, err := ipt.Stats("filter", chain)
  261. if err != nil {
  262. t.Fatalf("Stats failed: %v", err)
  263. }
  264. opt := "--"
  265. if ipt.proto == ProtocolIPv6 {
  266. opt = " "
  267. }
  268. expectedStats := [][]string{
  269. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet1, address1, ""},
  270. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address2, ""},
  271. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address1, ""},
  272. {"0", "0", "ACCEPT", "all", opt, "*", "*", address1, subnet2, ""},
  273. }
  274. if !reflect.DeepEqual(stats, expectedStats) {
  275. t.Fatalf("Stats mismatch: \ngot %#v \nneed %#v", stats, expectedStats)
  276. }
  277. structStats, err := ipt.StructuredStats("filter", chain)
  278. if err != nil {
  279. t.Fatalf("StructuredStats failed: %v", err)
  280. }
  281. // It's okay to not check the following errors as they will be evaluated
  282. // in the subsequent usage
  283. _, address1CIDR, _ := net.ParseCIDR(address1)
  284. _, address2CIDR, _ := net.ParseCIDR(address2)
  285. _, subnet1CIDR, _ := net.ParseCIDR(subnet1)
  286. _, subnet2CIDR, _ := net.ParseCIDR(subnet2)
  287. expectedStructStats := []Stat{
  288. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet1CIDR, address1CIDR, ""},
  289. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet2CIDR, address2CIDR, ""},
  290. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet2CIDR, address1CIDR, ""},
  291. {0, 0, "ACCEPT", "all", opt, "*", "*", address1CIDR, subnet2CIDR, ""},
  292. }
  293. if !reflect.DeepEqual(structStats, expectedStructStats) {
  294. t.Fatalf("StructuredStats mismatch: \ngot %#v \nneed %#v",
  295. structStats, expectedStructStats)
  296. }
  297. for i, stat := range expectedStats {
  298. stat, err := ipt.ParseStat(stat)
  299. if err != nil {
  300. t.Fatalf("ParseStat failed: %v", err)
  301. }
  302. if !reflect.DeepEqual(stat, expectedStructStats[i]) {
  303. t.Fatalf("ParseStat mismatch: \ngot %#v \nneed %#v",
  304. stat, expectedStructStats[i])
  305. }
  306. }
  307. err = ipt.DeleteIfExists("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  308. if err != nil {
  309. t.Fatalf("DeleteIfExists failed for existing rule: %v", err)
  310. }
  311. err = ipt.DeleteIfExists("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  312. if err != nil {
  313. t.Fatalf("DeleteIfExists failed for non-existing rule: %v", err)
  314. }
  315. // Clear the chain that was created.
  316. err = ipt.ClearChain("filter", chain)
  317. if err != nil {
  318. t.Fatalf("Failed to clear test chain: %v", err)
  319. }
  320. // Delete the chain that was created
  321. err = ipt.DeleteChain("filter", chain)
  322. if err != nil {
  323. t.Fatalf("Failed to delete test chain: %v", err)
  324. }
  325. }
  326. // TestError checks that we're OK when iptables fails to execute
  327. func TestError(t *testing.T) {
  328. ipt, err := New()
  329. if err != nil {
  330. t.Fatalf("failed to init: %v", err)
  331. }
  332. chain := randChain(t)
  333. _, err = ipt.List("filter", chain)
  334. if err == nil {
  335. t.Fatalf("no error with invalid params")
  336. }
  337. switch e := err.(type) {
  338. case *Error:
  339. // OK
  340. default:
  341. t.Fatalf("expected type iptables.Error, got %t", e)
  342. }
  343. // Now set an invalid binary path
  344. ipt.path = "/does-not-exist"
  345. _, err = ipt.ListChains("filter")
  346. if err == nil {
  347. t.Fatalf("no error with invalid ipt binary")
  348. }
  349. switch e := err.(type) {
  350. case *os.PathError:
  351. // OK
  352. default:
  353. t.Fatalf("expected type os.PathError, got %t", e)
  354. }
  355. }
  356. func TestIsNotExist(t *testing.T) {
  357. ipt, err := New()
  358. if err != nil {
  359. t.Fatalf("failed to init: %v", err)
  360. }
  361. // Create a chain, add a rule
  362. chainName := randChain(t)
  363. err = ipt.NewChain("filter", chainName)
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. defer func() {
  368. ipt.ClearChain("filter", chainName)
  369. ipt.DeleteChain("filter", chainName)
  370. }()
  371. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  372. if err != nil {
  373. t.Fatal(err)
  374. }
  375. // Delete rule twice
  376. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  377. if err != nil {
  378. t.Fatal(err)
  379. }
  380. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  381. if err == nil {
  382. t.Fatal("delete twice got no error...")
  383. }
  384. e, ok := err.(*Error)
  385. if !ok {
  386. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  387. }
  388. if !e.IsNotExist() {
  389. t.Fatal("IsNotExist returned false, expected true")
  390. }
  391. // Delete chain
  392. err = ipt.DeleteChain("filter", chainName)
  393. if err != nil {
  394. t.Fatal(err)
  395. }
  396. err = ipt.DeleteChain("filter", chainName)
  397. if err == nil {
  398. t.Fatal("deletechain twice got no error...")
  399. }
  400. e, ok = err.(*Error)
  401. if !ok {
  402. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  403. }
  404. if !e.IsNotExist() {
  405. t.Fatal("IsNotExist returned false, expected true")
  406. }
  407. // iptables may add more logs to the errors msgs
  408. e.msg = "Another app is currently holding the xtables lock; waiting (1s) for it to exit..." + e.msg
  409. if !e.IsNotExist() {
  410. t.Fatal("IsNotExist returned false, expected true")
  411. }
  412. }
  413. func TestIsNotExistForIPv6(t *testing.T) {
  414. ipt, err := NewWithProtocol(ProtocolIPv6)
  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. ipt.ClearChain("filter", chainName)
  426. ipt.DeleteChain("filter", chainName)
  427. }()
  428. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  429. if err != nil {
  430. t.Fatal(err)
  431. }
  432. // Delete rule twice
  433. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  434. if err != nil {
  435. t.Fatal(err)
  436. }
  437. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  438. if err == nil {
  439. t.Fatal("delete twice got no error...")
  440. }
  441. e, ok := err.(*Error)
  442. if !ok {
  443. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  444. }
  445. if !e.IsNotExist() {
  446. t.Fatal("IsNotExist returned false, expected true")
  447. }
  448. // Delete chain
  449. err = ipt.DeleteChain("filter", chainName)
  450. if err != nil {
  451. t.Fatal(err)
  452. }
  453. err = ipt.DeleteChain("filter", chainName)
  454. if err == nil {
  455. t.Fatal("deletechain twice got no error...")
  456. }
  457. e, ok = err.(*Error)
  458. if !ok {
  459. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  460. }
  461. if !e.IsNotExist() {
  462. t.Fatal("IsNotExist returned false, expected true")
  463. }
  464. // iptables may add more logs to the errors msgs
  465. e.msg = "Another app is currently holding the xtables lock; waiting (1s) for it to exit..." + e.msg
  466. if !e.IsNotExist() {
  467. t.Fatal("IsNotExist returned false, expected true")
  468. }
  469. }
  470. func TestFilterRuleOutput(t *testing.T) {
  471. testCases := []struct {
  472. name string
  473. in string
  474. out string
  475. }{
  476. {
  477. "legacy output",
  478. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  479. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  480. },
  481. {
  482. "nft output",
  483. "[99:42] -A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  484. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT -c 99 42",
  485. },
  486. }
  487. for _, tt := range testCases {
  488. t.Run(tt.name, func(t *testing.T) {
  489. actual := filterRuleOutput(tt.in)
  490. if actual != tt.out {
  491. t.Fatalf("expect %s actual %s", tt.out, actual)
  492. }
  493. })
  494. }
  495. }
  496. func TestExtractIptablesVersion(t *testing.T) {
  497. testCases := []struct {
  498. in string
  499. v1, v2, v3 int
  500. mode string
  501. err bool
  502. }{
  503. {
  504. "iptables v1.8.0 (nf_tables)",
  505. 1, 8, 0,
  506. "nf_tables",
  507. false,
  508. },
  509. {
  510. "iptables v1.8.0 (legacy)",
  511. 1, 8, 0,
  512. "legacy",
  513. false,
  514. },
  515. {
  516. "iptables v1.6.2",
  517. 1, 6, 2,
  518. "legacy",
  519. false,
  520. },
  521. }
  522. for i, tt := range testCases {
  523. t.Run(fmt.Sprint(i), func(t *testing.T) {
  524. v1, v2, v3, mode, err := extractIptablesVersion(tt.in)
  525. if err == nil && tt.err {
  526. t.Fatal("expected err, got none")
  527. } else if err != nil && !tt.err {
  528. t.Fatalf("unexpected err %s", err)
  529. }
  530. if v1 != tt.v1 || v2 != tt.v2 || v3 != tt.v3 || mode != tt.mode {
  531. t.Fatalf("expected %d %d %d %s, got %d %d %d %s",
  532. tt.v1, tt.v2, tt.v3, tt.mode,
  533. v1, v2, v3, mode)
  534. }
  535. })
  536. }
  537. }