iptables_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. // chain now exists
  117. err = ipt.ClearChain("filter", chain)
  118. if err != nil {
  119. t.Fatalf("ClearChain (of empty) failed: %v", err)
  120. }
  121. // put a simple rule in
  122. err = ipt.Append("filter", chain, "-s", "0/0", "-j", "ACCEPT")
  123. if err != nil {
  124. t.Fatalf("Append failed: %v", err)
  125. }
  126. // can't delete non-empty chain
  127. err = ipt.DeleteChain("filter", chain)
  128. if err == nil {
  129. t.Fatalf("DeleteChain of non-empty chain did not fail")
  130. }
  131. e, ok := err.(*Error)
  132. if ok && e.IsNotExist() {
  133. t.Fatal("DeleteChain of non-empty chain returned IsNotExist")
  134. }
  135. err = ipt.ClearChain("filter", chain)
  136. if err != nil {
  137. t.Fatalf("ClearChain (of non-empty) failed: %v", err)
  138. }
  139. // rename the chain
  140. newChain := randChain(t)
  141. err = ipt.RenameChain("filter", chain, newChain)
  142. if err != nil {
  143. t.Fatalf("RenameChain failed: %v", err)
  144. }
  145. // chain empty, should be ok
  146. err = ipt.DeleteChain("filter", newChain)
  147. if err != nil {
  148. t.Fatalf("DeleteChain of empty chain failed: %v", err)
  149. }
  150. // check that chain is fully gone and that state similar to initial one
  151. listChain, err = ipt.ListChains("filter")
  152. if err != nil {
  153. t.Fatalf("ListChains failed: %v", err)
  154. }
  155. if !reflect.DeepEqual(originaListChain, listChain) {
  156. t.Fatalf("ListChains mismatch: \ngot %#v \nneed %#v", originaListChain, listChain)
  157. }
  158. }
  159. func TestRules(t *testing.T) {
  160. for i, ipt := range mustTestableIptables() {
  161. t.Run(fmt.Sprint(i), func(t *testing.T) {
  162. runRulesTests(t, ipt)
  163. })
  164. }
  165. }
  166. func runRulesTests(t *testing.T, ipt *IPTables) {
  167. t.Logf("testing %s (hasWait=%t, hasCheck=%t)", getIptablesCommand(ipt.Proto()), ipt.hasWait, ipt.hasCheck)
  168. var address1, address2, subnet1, subnet2 string
  169. if ipt.Proto() == ProtocolIPv6 {
  170. address1 = "2001:db8::1/128"
  171. address2 = "2001:db8::2/128"
  172. subnet1 = "2001:db8:a::/48"
  173. subnet2 = "2001:db8:b::/48"
  174. } else {
  175. address1 = "203.0.113.1/32"
  176. address2 = "203.0.113.2/32"
  177. subnet1 = "192.0.2.0/24"
  178. subnet2 = "198.51.100.0/24"
  179. }
  180. chain := randChain(t)
  181. // chain shouldn't exist, this will create new
  182. err := ipt.ClearChain("filter", chain)
  183. if err != nil {
  184. t.Fatalf("ClearChain (of missing) failed: %v", err)
  185. }
  186. err = ipt.Append("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  187. if err != nil {
  188. t.Fatalf("Append failed: %v", err)
  189. }
  190. err = ipt.AppendUnique("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  191. if err != nil {
  192. t.Fatalf("AppendUnique failed: %v", err)
  193. }
  194. err = ipt.Append("filter", chain, "-s", subnet2, "-d", address1, "-j", "ACCEPT")
  195. if err != nil {
  196. t.Fatalf("Append failed: %v", err)
  197. }
  198. err = ipt.Insert("filter", chain, 2, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  199. if err != nil {
  200. t.Fatalf("Insert failed: %v", err)
  201. }
  202. err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  203. if err != nil {
  204. t.Fatalf("Insert failed: %v", err)
  205. }
  206. err = ipt.Delete("filter", chain, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  207. if err != nil {
  208. t.Fatalf("Delete failed: %v", err)
  209. }
  210. err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  211. if err != nil {
  212. t.Fatalf("Append failed: %v", err)
  213. }
  214. rules, err := ipt.List("filter", chain)
  215. if err != nil {
  216. t.Fatalf("List failed: %v", err)
  217. }
  218. expected := []string{
  219. "-N " + chain,
  220. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " -j ACCEPT",
  221. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " -j ACCEPT",
  222. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " -j ACCEPT",
  223. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " -j ACCEPT",
  224. }
  225. if !reflect.DeepEqual(rules, expected) {
  226. t.Fatalf("List mismatch: \ngot %#v \nneed %#v", rules, expected)
  227. }
  228. rules, err = ipt.ListWithCounters("filter", chain)
  229. if err != nil {
  230. t.Fatalf("ListWithCounters failed: %v", err)
  231. }
  232. suffix := " -c 0 0 -j ACCEPT"
  233. if ipt.mode == "nf_tables" {
  234. suffix = " -j ACCEPT -c 0 0"
  235. }
  236. expected = []string{
  237. "-N " + chain,
  238. "-A " + chain + " -s " + subnet1 + " -d " + address1 + suffix,
  239. "-A " + chain + " -s " + subnet2 + " -d " + address2 + suffix,
  240. "-A " + chain + " -s " + subnet2 + " -d " + address1 + suffix,
  241. "-A " + chain + " -s " + address1 + " -d " + subnet2 + suffix,
  242. }
  243. if !reflect.DeepEqual(rules, expected) {
  244. t.Fatalf("ListWithCounters mismatch: \ngot %#v \nneed %#v", rules, expected)
  245. }
  246. stats, err := ipt.Stats("filter", chain)
  247. if err != nil {
  248. t.Fatalf("Stats failed: %v", err)
  249. }
  250. opt := "--"
  251. if ipt.proto == ProtocolIPv6 {
  252. opt = " "
  253. }
  254. expectedStats := [][]string{
  255. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet1, address1, ""},
  256. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address2, ""},
  257. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address1, ""},
  258. {"0", "0", "ACCEPT", "all", opt, "*", "*", address1, subnet2, ""},
  259. }
  260. if !reflect.DeepEqual(stats, expectedStats) {
  261. t.Fatalf("Stats mismatch: \ngot %#v \nneed %#v", stats, expectedStats)
  262. }
  263. structStats, err := ipt.StructuredStats("filter", chain)
  264. if err != nil {
  265. t.Fatalf("StructuredStats failed: %v", err)
  266. }
  267. // It's okay to not check the following errors as they will be evaluated
  268. // in the subsequent usage
  269. _, address1CIDR, _ := net.ParseCIDR(address1)
  270. _, address2CIDR, _ := net.ParseCIDR(address2)
  271. _, subnet1CIDR, _ := net.ParseCIDR(subnet1)
  272. _, subnet2CIDR, _ := net.ParseCIDR(subnet2)
  273. expectedStructStats := []Stat{
  274. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet1CIDR, address1CIDR, ""},
  275. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet2CIDR, address2CIDR, ""},
  276. {0, 0, "ACCEPT", "all", opt, "*", "*", subnet2CIDR, address1CIDR, ""},
  277. {0, 0, "ACCEPT", "all", opt, "*", "*", address1CIDR, subnet2CIDR, ""},
  278. }
  279. if !reflect.DeepEqual(structStats, expectedStructStats) {
  280. t.Fatalf("StructuredStats mismatch: \ngot %#v \nneed %#v",
  281. structStats, expectedStructStats)
  282. }
  283. for i, stat := range expectedStats {
  284. stat, err := ipt.ParseStat(stat)
  285. if err != nil {
  286. t.Fatalf("ParseStat failed: %v", err)
  287. }
  288. if !reflect.DeepEqual(stat, expectedStructStats[i]) {
  289. t.Fatalf("ParseStat mismatch: \ngot %#v \nneed %#v",
  290. stat, expectedStructStats[i])
  291. }
  292. }
  293. // Clear the chain that was created.
  294. err = ipt.ClearChain("filter", chain)
  295. if err != nil {
  296. t.Fatalf("Failed to clear test chain: %v", err)
  297. }
  298. // Delete the chain that was created
  299. err = ipt.DeleteChain("filter", chain)
  300. if err != nil {
  301. t.Fatalf("Failed to delete test chain: %v", err)
  302. }
  303. }
  304. // TestError checks that we're OK when iptables fails to execute
  305. func TestError(t *testing.T) {
  306. ipt, err := New()
  307. if err != nil {
  308. t.Fatalf("failed to init: %v", err)
  309. }
  310. chain := randChain(t)
  311. _, err = ipt.List("filter", chain)
  312. if err == nil {
  313. t.Fatalf("no error with invalid params")
  314. }
  315. switch e := err.(type) {
  316. case *Error:
  317. // OK
  318. default:
  319. t.Fatalf("expected type iptables.Error, got %t", e)
  320. }
  321. // Now set an invalid binary path
  322. ipt.path = "/does-not-exist"
  323. _, err = ipt.ListChains("filter")
  324. if err == nil {
  325. t.Fatalf("no error with invalid ipt binary")
  326. }
  327. switch e := err.(type) {
  328. case *os.PathError:
  329. // OK
  330. default:
  331. t.Fatalf("expected type os.PathError, got %t", e)
  332. }
  333. }
  334. func TestIsNotExist(t *testing.T) {
  335. ipt, err := New()
  336. if err != nil {
  337. t.Fatalf("failed to init: %v", err)
  338. }
  339. // Create a chain, add a rule
  340. chainName := randChain(t)
  341. err = ipt.NewChain("filter", chainName)
  342. if err != nil {
  343. t.Fatal(err)
  344. }
  345. defer func() {
  346. ipt.ClearChain("filter", chainName)
  347. ipt.DeleteChain("filter", chainName)
  348. }()
  349. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. // Delete rule twice
  354. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  355. if err != nil {
  356. t.Fatal(err)
  357. }
  358. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  359. if err == nil {
  360. t.Fatal("delete twice got no error...")
  361. }
  362. e, ok := err.(*Error)
  363. if !ok {
  364. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  365. }
  366. if !e.IsNotExist() {
  367. t.Fatal("IsNotExist returned false, expected true")
  368. }
  369. // Delete chain
  370. err = ipt.DeleteChain("filter", chainName)
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. err = ipt.DeleteChain("filter", chainName)
  375. if err == nil {
  376. t.Fatal("deletechain 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. // iptables may add more logs to the errors msgs
  386. e.msg = "Another app is currently holding the xtables lock; waiting (1s) for it to exit..." + e.msg
  387. if !e.IsNotExist() {
  388. t.Fatal("IsNotExist returned false, expected true")
  389. }
  390. }
  391. func TestIsNotExistForIPv6(t *testing.T) {
  392. ipt, err := NewWithProtocol(ProtocolIPv6)
  393. if err != nil {
  394. t.Fatalf("failed to init: %v", err)
  395. }
  396. // Create a chain, add a rule
  397. chainName := randChain(t)
  398. err = ipt.NewChain("filter", chainName)
  399. if err != nil {
  400. t.Fatal(err)
  401. }
  402. defer func() {
  403. ipt.ClearChain("filter", chainName)
  404. ipt.DeleteChain("filter", chainName)
  405. }()
  406. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  407. if err != nil {
  408. t.Fatal(err)
  409. }
  410. // Delete rule twice
  411. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  412. if err != nil {
  413. t.Fatal(err)
  414. }
  415. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  416. if err == nil {
  417. t.Fatal("delete twice got no error...")
  418. }
  419. e, ok := err.(*Error)
  420. if !ok {
  421. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  422. }
  423. if !e.IsNotExist() {
  424. t.Fatal("IsNotExist returned false, expected true")
  425. }
  426. // Delete chain
  427. err = ipt.DeleteChain("filter", chainName)
  428. if err != nil {
  429. t.Fatal(err)
  430. }
  431. err = ipt.DeleteChain("filter", chainName)
  432. if err == nil {
  433. t.Fatal("deletechain 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. // iptables may add more logs to the errors msgs
  443. e.msg = "Another app is currently holding the xtables lock; waiting (1s) for it to exit..." + e.msg
  444. if !e.IsNotExist() {
  445. t.Fatal("IsNotExist returned false, expected true")
  446. }
  447. }
  448. func TestFilterRuleOutput(t *testing.T) {
  449. testCases := []struct {
  450. name string
  451. in string
  452. out string
  453. }{
  454. {
  455. "legacy output",
  456. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  457. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  458. },
  459. {
  460. "nft output",
  461. "[99:42] -A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT",
  462. "-A foo1 -p tcp -m tcp --dport 1337 -j ACCEPT -c 99 42",
  463. },
  464. }
  465. for _, tt := range testCases {
  466. t.Run(tt.name, func(t *testing.T) {
  467. actual := filterRuleOutput(tt.in)
  468. if actual != tt.out {
  469. t.Fatalf("expect %s actual %s", tt.out, actual)
  470. }
  471. })
  472. }
  473. }
  474. func TestExtractIptablesVersion(t *testing.T) {
  475. testCases := []struct {
  476. in string
  477. v1, v2, v3 int
  478. mode string
  479. err bool
  480. }{
  481. {
  482. "iptables v1.8.0 (nf_tables)",
  483. 1, 8, 0,
  484. "nf_tables",
  485. false,
  486. },
  487. {
  488. "iptables v1.8.0 (legacy)",
  489. 1, 8, 0,
  490. "legacy",
  491. false,
  492. },
  493. {
  494. "iptables v1.6.2",
  495. 1, 6, 2,
  496. "legacy",
  497. false,
  498. },
  499. }
  500. for i, tt := range testCases {
  501. t.Run(fmt.Sprint(i), func(t *testing.T) {
  502. v1, v2, v3, mode, err := extractIptablesVersion(tt.in)
  503. if err == nil && tt.err {
  504. t.Fatal("expected err, got none")
  505. } else if err != nil && !tt.err {
  506. t.Fatalf("unexpected err %s", err)
  507. }
  508. if v1 != tt.v1 || v2 != tt.v2 || v3 != tt.v3 || mode != tt.mode {
  509. t.Fatalf("expected %d %d %d %s, got %d %d %d %s",
  510. tt.v1, tt.v2, tt.v3, tt.mode,
  511. v1, v2, v3, mode)
  512. }
  513. })
  514. }
  515. }