iptables_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 _, ipt := range mustTestableIptables() {
  89. runChainTests(t, ipt)
  90. }
  91. }
  92. func runChainTests(t *testing.T, ipt *IPTables) {
  93. t.Logf("testing %s (hasWait=%t, hasCheck=%t)", ipt.path, ipt.hasWait, ipt.hasCheck)
  94. chain := randChain(t)
  95. // Saving the list of chains before executing tests
  96. originaListChain, err := ipt.ListChains("filter")
  97. if err != nil {
  98. t.Fatalf("ListChains of Initial failed: %v", err)
  99. }
  100. // chain shouldn't exist, this will create new
  101. err = ipt.ClearChain("filter", chain)
  102. if err != nil {
  103. t.Fatalf("ClearChain (of missing) failed: %v", err)
  104. }
  105. // chain should be in listChain
  106. listChain, err := ipt.ListChains("filter")
  107. if err != nil {
  108. t.Fatalf("ListChains failed: %v", err)
  109. }
  110. if !contains(listChain, chain) {
  111. t.Fatalf("ListChains doesn't contain the new chain %v", chain)
  112. }
  113. // chain now exists
  114. err = ipt.ClearChain("filter", chain)
  115. if err != nil {
  116. t.Fatalf("ClearChain (of empty) failed: %v", err)
  117. }
  118. // put a simple rule in
  119. err = ipt.Append("filter", chain, "-s", "0/0", "-j", "ACCEPT")
  120. if err != nil {
  121. t.Fatalf("Append failed: %v", err)
  122. }
  123. // can't delete non-empty chain
  124. err = ipt.DeleteChain("filter", chain)
  125. if err == nil {
  126. t.Fatalf("DeleteChain of non-empty chain did not fail")
  127. }
  128. e, ok := err.(*Error)
  129. if ok && e.IsNotExist() {
  130. t.Fatal("DeleteChain of non-empty chain returned IsNotExist")
  131. }
  132. err = ipt.ClearChain("filter", chain)
  133. if err != nil {
  134. t.Fatalf("ClearChain (of non-empty) failed: %v", err)
  135. }
  136. // rename the chain
  137. newChain := randChain(t)
  138. err = ipt.RenameChain("filter", chain, newChain)
  139. if err != nil {
  140. t.Fatalf("RenameChain failed: %v", err)
  141. }
  142. // chain empty, should be ok
  143. err = ipt.DeleteChain("filter", newChain)
  144. if err != nil {
  145. t.Fatalf("DeleteChain of empty chain failed: %v", err)
  146. }
  147. // check that chain is fully gone and that state similar to initial one
  148. listChain, err = ipt.ListChains("filter")
  149. if err != nil {
  150. t.Fatalf("ListChains failed: %v", err)
  151. }
  152. if !reflect.DeepEqual(originaListChain, listChain) {
  153. t.Fatalf("ListChains mismatch: \ngot %#v \nneed %#v", originaListChain, listChain)
  154. }
  155. }
  156. func TestRules(t *testing.T) {
  157. for _, ipt := range mustTestableIptables() {
  158. runRulesTests(t, ipt)
  159. }
  160. }
  161. func runRulesTests(t *testing.T, ipt *IPTables) {
  162. t.Logf("testing %s (hasWait=%t, hasCheck=%t)", getIptablesCommand(ipt.Proto()), ipt.hasWait, ipt.hasCheck)
  163. var address1, address2, subnet1, subnet2 string
  164. if ipt.Proto() == ProtocolIPv6 {
  165. address1 = "2001:db8::1/128"
  166. address2 = "2001:db8::2/128"
  167. subnet1 = "2001:db8:a::/48"
  168. subnet2 = "2001:db8:b::/48"
  169. } else {
  170. address1 = "203.0.113.1/32"
  171. address2 = "203.0.113.2/32"
  172. subnet1 = "192.0.2.0/24"
  173. subnet2 = "198.51.100.0/24"
  174. }
  175. chain := randChain(t)
  176. // chain shouldn't exist, this will create new
  177. err := ipt.ClearChain("filter", chain)
  178. if err != nil {
  179. t.Fatalf("ClearChain (of missing) failed: %v", err)
  180. }
  181. err = ipt.Append("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  182. if err != nil {
  183. t.Fatalf("Append failed: %v", err)
  184. }
  185. err = ipt.AppendUnique("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  186. if err != nil {
  187. t.Fatalf("AppendUnique failed: %v", err)
  188. }
  189. err = ipt.Append("filter", chain, "-s", subnet2, "-d", address1, "-j", "ACCEPT")
  190. if err != nil {
  191. t.Fatalf("Append failed: %v", err)
  192. }
  193. err = ipt.Insert("filter", chain, 2, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  194. if err != nil {
  195. t.Fatalf("Insert failed: %v", err)
  196. }
  197. err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  198. if err != nil {
  199. t.Fatalf("Insert failed: %v", err)
  200. }
  201. err = ipt.Delete("filter", chain, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  202. if err != nil {
  203. t.Fatalf("Delete failed: %v", err)
  204. }
  205. err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  206. if err != nil {
  207. t.Fatalf("Append failed: %v", err)
  208. }
  209. rules, err := ipt.List("filter", chain)
  210. if err != nil {
  211. t.Fatalf("List failed: %v", err)
  212. }
  213. expected := []string{
  214. "-N " + chain,
  215. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " -j ACCEPT",
  216. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " -j ACCEPT",
  217. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " -j ACCEPT",
  218. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " -j ACCEPT",
  219. }
  220. if !reflect.DeepEqual(rules, expected) {
  221. t.Fatalf("List mismatch: \ngot %#v \nneed %#v", rules, expected)
  222. }
  223. rules, err = ipt.ListWithCounters("filter", chain)
  224. if err != nil {
  225. t.Fatalf("ListWithCounters failed: %v", err)
  226. }
  227. expected = []string{
  228. "-N " + chain,
  229. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " -c 0 0 -j ACCEPT",
  230. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " -c 0 0 -j ACCEPT",
  231. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " -c 0 0 -j ACCEPT",
  232. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " -c 0 0 -j ACCEPT",
  233. }
  234. if !reflect.DeepEqual(rules, expected) {
  235. t.Fatalf("ListWithCounters mismatch: \ngot %#v \nneed %#v", rules, expected)
  236. }
  237. stats, err := ipt.Stats("filter", chain)
  238. if err != nil {
  239. t.Fatalf("Stats failed: %v", err)
  240. }
  241. opt := "--"
  242. if ipt.proto == ProtocolIPv6 {
  243. opt = " "
  244. }
  245. expectedStats := [][]string{
  246. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet1, address1, ""},
  247. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address2, ""},
  248. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address1, ""},
  249. {"0", "0", "ACCEPT", "all", opt, "*", "*", address1, subnet2, ""},
  250. }
  251. if !reflect.DeepEqual(stats, expectedStats) {
  252. t.Fatalf("Stats mismatch: \ngot %#v \nneed %#v", stats, expectedStats)
  253. }
  254. // Clear the chain that was created.
  255. err = ipt.ClearChain("filter", chain)
  256. if err != nil {
  257. t.Fatalf("Failed to clear test chain: %v", err)
  258. }
  259. // Delete the chain that was created
  260. err = ipt.DeleteChain("filter", chain)
  261. if err != nil {
  262. t.Fatalf("Failed to delete test chain: %v", err)
  263. }
  264. }
  265. // TestError checks that we're OK when iptables fails to execute
  266. func TestError(t *testing.T) {
  267. ipt, err := New()
  268. if err != nil {
  269. t.Fatalf("failed to init: %v", err)
  270. }
  271. chain := randChain(t)
  272. _, err = ipt.List("filter", chain)
  273. if err == nil {
  274. t.Fatalf("no error with invalid params")
  275. }
  276. switch e := err.(type) {
  277. case *Error:
  278. // OK
  279. default:
  280. t.Fatalf("expected type iptables.Error, got %t", e)
  281. }
  282. // Now set an invalid binary path
  283. ipt.path = "/does-not-exist"
  284. _, err = ipt.ListChains("filter")
  285. if err == nil {
  286. t.Fatalf("no error with invalid ipt binary")
  287. }
  288. switch e := err.(type) {
  289. case *os.PathError:
  290. // OK
  291. default:
  292. t.Fatalf("expected type os.PathError, got %t", e)
  293. }
  294. }
  295. func TestIsNotExist(t *testing.T) {
  296. ipt, err := New()
  297. if err != nil {
  298. t.Fatalf("failed to init: %v", err)
  299. }
  300. // Create a chain, add a rule
  301. chainName := randChain(t)
  302. err = ipt.NewChain("filter", chainName)
  303. if err != nil {
  304. t.Fatal(err)
  305. }
  306. defer func() {
  307. ipt.ClearChain("filter", chainName)
  308. ipt.DeleteChain("filter", chainName)
  309. }()
  310. err = ipt.Append("filter", chainName, "-p", "tcp", "-j", "DROP")
  311. if err != nil {
  312. t.Fatal(err)
  313. }
  314. // Delete rule twice
  315. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  316. if err != nil {
  317. t.Fatal(err)
  318. }
  319. err = ipt.Delete("filter", chainName, "-p", "tcp", "-j", "DROP")
  320. if err == nil {
  321. t.Fatal("delete twice got no error...")
  322. }
  323. e, ok := err.(*Error)
  324. if !ok {
  325. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  326. }
  327. if !e.IsNotExist() {
  328. t.Fatal("IsNotExist returned false, expected true")
  329. }
  330. // Delete chain
  331. err = ipt.DeleteChain("filter", chainName)
  332. if err != nil {
  333. t.Fatal(err)
  334. }
  335. err = ipt.DeleteChain("filter", chainName)
  336. if err == nil {
  337. t.Fatal("deletechain twice got no error...")
  338. }
  339. e, ok = err.(*Error)
  340. if !ok {
  341. t.Fatalf("Got wrong error type, expected iptables.Error, got %T", err)
  342. }
  343. if !e.IsNotExist() {
  344. t.Fatal("IsNotExist returned false, expected true")
  345. }
  346. }