iptables_test.go 15 KB

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