iptables_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. err = ipt.ClearChain("filter", chain)
  129. if err != nil {
  130. t.Fatalf("ClearChain (of non-empty) failed: %v", err)
  131. }
  132. // rename the chain
  133. newChain := randChain(t)
  134. err = ipt.RenameChain("filter", chain, newChain)
  135. if err != nil {
  136. t.Fatalf("RenameChain failed: %v", err)
  137. }
  138. // chain empty, should be ok
  139. err = ipt.DeleteChain("filter", newChain)
  140. if err != nil {
  141. t.Fatalf("DeleteChain of empty chain failed: %v", err)
  142. }
  143. // check that chain is fully gone and that state similar to initial one
  144. listChain, err = ipt.ListChains("filter")
  145. if err != nil {
  146. t.Fatalf("ListChains failed: %v", err)
  147. }
  148. if !reflect.DeepEqual(originaListChain, listChain) {
  149. t.Fatalf("ListChains mismatch: \ngot %#v \nneed %#v", originaListChain, listChain)
  150. }
  151. }
  152. func TestRules(t *testing.T) {
  153. for _, ipt := range mustTestableIptables() {
  154. runRulesTests(t, ipt)
  155. }
  156. }
  157. func runRulesTests(t *testing.T, ipt *IPTables) {
  158. t.Logf("testing %s (hasWait=%t, hasCheck=%t)", getIptablesCommand(ipt.Proto()), ipt.hasWait, ipt.hasCheck)
  159. var address1, address2, subnet1, subnet2 string
  160. if ipt.Proto() == ProtocolIPv6 {
  161. address1 = "2001:db8::1/128"
  162. address2 = "2001:db8::2/128"
  163. subnet1 = "2001:db8:a::/48"
  164. subnet2 = "2001:db8:b::/48"
  165. } else {
  166. address1 = "203.0.113.1/32"
  167. address2 = "203.0.113.2/32"
  168. subnet1 = "192.0.2.0/24"
  169. subnet2 = "198.51.100.0/24"
  170. }
  171. chain := randChain(t)
  172. // chain shouldn't exist, this will create new
  173. err := ipt.ClearChain("filter", chain)
  174. if err != nil {
  175. t.Fatalf("ClearChain (of missing) failed: %v", err)
  176. }
  177. err = ipt.Append("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  178. if err != nil {
  179. t.Fatalf("Append failed: %v", err)
  180. }
  181. err = ipt.AppendUnique("filter", chain, "-s", subnet1, "-d", address1, "-j", "ACCEPT")
  182. if err != nil {
  183. t.Fatalf("AppendUnique failed: %v", err)
  184. }
  185. err = ipt.Append("filter", chain, "-s", subnet2, "-d", address1, "-j", "ACCEPT")
  186. if err != nil {
  187. t.Fatalf("Append failed: %v", err)
  188. }
  189. err = ipt.Insert("filter", chain, 2, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
  190. if err != nil {
  191. t.Fatalf("Insert failed: %v", err)
  192. }
  193. err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  194. if err != nil {
  195. t.Fatalf("Insert failed: %v", err)
  196. }
  197. err = ipt.Delete("filter", chain, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
  198. if err != nil {
  199. t.Fatalf("Delete failed: %v", err)
  200. }
  201. err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
  202. if err != nil {
  203. t.Fatalf("Append failed: %v", err)
  204. }
  205. rules, err := ipt.List("filter", chain)
  206. if err != nil {
  207. t.Fatalf("List failed: %v", err)
  208. }
  209. expected := []string{
  210. "-N " + chain,
  211. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " -j ACCEPT",
  212. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " -j ACCEPT",
  213. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " -j ACCEPT",
  214. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " -j ACCEPT",
  215. }
  216. if !reflect.DeepEqual(rules, expected) {
  217. t.Fatalf("List mismatch: \ngot %#v \nneed %#v", rules, expected)
  218. }
  219. rules, err = ipt.ListWithCounters("filter", chain)
  220. if err != nil {
  221. t.Fatalf("ListWithCounters failed: %v", err)
  222. }
  223. expected = []string{
  224. "-N " + chain,
  225. "-A " + chain + " -s " + subnet1 + " -d " + address1 + " -c 0 0 -j ACCEPT",
  226. "-A " + chain + " -s " + subnet2 + " -d " + address2 + " -c 0 0 -j ACCEPT",
  227. "-A " + chain + " -s " + subnet2 + " -d " + address1 + " -c 0 0 -j ACCEPT",
  228. "-A " + chain + " -s " + address1 + " -d " + subnet2 + " -c 0 0 -j ACCEPT",
  229. }
  230. if !reflect.DeepEqual(rules, expected) {
  231. t.Fatalf("ListWithCounters mismatch: \ngot %#v \nneed %#v", rules, expected)
  232. }
  233. stats, err := ipt.Stats("filter", chain)
  234. if err != nil {
  235. t.Fatalf("Stats failed: %v", err)
  236. }
  237. opt := "--"
  238. if ipt.proto == ProtocolIPv6 {
  239. opt = " "
  240. }
  241. expectedStats := [][]string{
  242. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet1, address1, ""},
  243. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address2, ""},
  244. {"0", "0", "ACCEPT", "all", opt, "*", "*", subnet2, address1, ""},
  245. {"0", "0", "ACCEPT", "all", opt, "*", "*", address1, subnet2, ""},
  246. }
  247. if !reflect.DeepEqual(stats, expectedStats) {
  248. t.Fatalf("Stats mismatch: \ngot %#v \nneed %#v", stats, expectedStats)
  249. }
  250. // Clear the chain that was created.
  251. err = ipt.ClearChain("filter", chain)
  252. if err != nil {
  253. t.Fatalf("Failed to clear test chain: %v", err)
  254. }
  255. // Delete the chain that was created
  256. err = ipt.DeleteChain("filter", chain)
  257. if err != nil {
  258. t.Fatalf("Failed to delete test chain: %v", err)
  259. }
  260. }
  261. // TestError checks that we're OK when iptables fails to execute
  262. func TestError(t *testing.T) {
  263. ipt, err := New()
  264. if err != nil {
  265. t.Fatalf("failed to init: %v", err)
  266. }
  267. chain := randChain(t)
  268. _, err = ipt.List("filter", chain)
  269. if err == nil {
  270. t.Fatalf("no error with invalid params")
  271. }
  272. switch e := err.(type) {
  273. case *Error:
  274. // OK
  275. default:
  276. t.Fatalf("expected type iptables.Error, got %t", e)
  277. }
  278. // Now set an invalid binary path
  279. ipt.path = "/does-not-exist"
  280. _, err = ipt.ListChains("filter")
  281. if err == nil {
  282. t.Fatalf("no error with invalid ipt binary")
  283. }
  284. switch e := err.(type) {
  285. case *os.PathError:
  286. // OK
  287. default:
  288. t.Fatalf("expected type os.PathError, got %t", e)
  289. }
  290. }