iptables_test.go 12 KB

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