service_linux.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. package libnetwork
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "syscall"
  15. "github.com/docker/docker/pkg/reexec"
  16. "github.com/docker/libnetwork/iptables"
  17. "github.com/docker/libnetwork/ns"
  18. "github.com/gogo/protobuf/proto"
  19. "github.com/ishidawataru/sctp"
  20. "github.com/moby/ipvs"
  21. "github.com/sirupsen/logrus"
  22. "github.com/vishvananda/netlink/nl"
  23. "github.com/vishvananda/netns"
  24. )
  25. func init() {
  26. reexec.Register("fwmarker", fwMarker)
  27. reexec.Register("redirector", redirector)
  28. }
  29. // Populate all loadbalancers on the network that the passed endpoint
  30. // belongs to, into this sandbox.
  31. func (sb *sandbox) populateLoadBalancers(ep *endpoint) {
  32. // This is an interface less endpoint. Nothing to do.
  33. if ep.Iface() == nil {
  34. return
  35. }
  36. n := ep.getNetwork()
  37. eIP := ep.Iface().Address()
  38. if n.ingress {
  39. if err := addRedirectRules(sb.Key(), eIP, ep.ingressPorts); err != nil {
  40. logrus.Errorf("Failed to add redirect rules for ep %s (%.7s): %v", ep.Name(), ep.ID(), err)
  41. }
  42. }
  43. }
  44. func (n *network) findLBEndpointSandbox() (*endpoint, *sandbox, error) {
  45. // TODO: get endpoint from store? See EndpointInfo()
  46. var ep *endpoint
  47. // Find this node's LB sandbox endpoint: there should be exactly one
  48. for _, e := range n.Endpoints() {
  49. epi := e.Info()
  50. if epi != nil && epi.LoadBalancer() {
  51. ep = e.(*endpoint)
  52. break
  53. }
  54. }
  55. if ep == nil {
  56. return nil, nil, fmt.Errorf("Unable to find load balancing endpoint for network %s", n.ID())
  57. }
  58. // Get the load balancer sandbox itself as well
  59. sb, ok := ep.getSandbox()
  60. if !ok {
  61. return nil, nil, fmt.Errorf("Unable to get sandbox for %s(%s) in for %s", ep.Name(), ep.ID(), n.ID())
  62. }
  63. var sep *endpoint
  64. sep = sb.getEndpoint(ep.ID())
  65. if sep == nil {
  66. return nil, nil, fmt.Errorf("Load balancing endpoint %s(%s) removed from %s", ep.Name(), ep.ID(), n.ID())
  67. }
  68. return sep, sb, nil
  69. }
  70. // Searches the OS sandbox for the name of the endpoint interface
  71. // within the sandbox. This is required for adding/removing IP
  72. // aliases to the interface.
  73. func findIfaceDstName(sb *sandbox, ep *endpoint) string {
  74. srcName := ep.Iface().SrcName()
  75. for _, i := range sb.osSbox.Info().Interfaces() {
  76. if i.SrcName() == srcName {
  77. return i.DstName()
  78. }
  79. }
  80. return ""
  81. }
  82. // Add loadbalancer backend to the loadbalncer sandbox for the network.
  83. // If needed add the service as well.
  84. func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) {
  85. if len(lb.vip) == 0 {
  86. return
  87. }
  88. ep, sb, err := n.findLBEndpointSandbox()
  89. if err != nil {
  90. logrus.Errorf("addLBBackend %s/%s: %v", n.ID(), n.Name(), err)
  91. return
  92. }
  93. if sb.osSbox == nil {
  94. return
  95. }
  96. eIP := ep.Iface().Address()
  97. i, err := ipvs.New(sb.Key())
  98. if err != nil {
  99. logrus.Errorf("Failed to create an ipvs handle for sbox %.7s (%.7s,%s) for lb addition: %v", sb.ID(), sb.ContainerID(), sb.Key(), err)
  100. return
  101. }
  102. defer i.Close()
  103. s := &ipvs.Service{
  104. AddressFamily: nl.FAMILY_V4,
  105. FWMark: lb.fwMark,
  106. SchedName: ipvs.RoundRobin,
  107. }
  108. if !i.IsServicePresent(s) {
  109. // Add IP alias for the VIP to the endpoint
  110. ifName := findIfaceDstName(sb, ep)
  111. if ifName == "" {
  112. logrus.Errorf("Failed find interface name for endpoint %s(%s) to create LB alias", ep.ID(), ep.Name())
  113. return
  114. }
  115. err := sb.osSbox.AddAliasIP(ifName, &net.IPNet{IP: lb.vip, Mask: net.CIDRMask(32, 32)})
  116. if err != nil {
  117. logrus.Errorf("Failed add IP alias %s to network %s LB endpoint interface %s: %v", lb.vip, n.ID(), ifName, err)
  118. return
  119. }
  120. if sb.ingress {
  121. var gwIP net.IP
  122. if ep := sb.getGatewayEndpoint(); ep != nil {
  123. gwIP = ep.Iface().Address().IP
  124. }
  125. if err := programIngress(gwIP, lb.service.ingressPorts, false); err != nil {
  126. logrus.Errorf("Failed to add ingress: %v", err)
  127. return
  128. }
  129. }
  130. logrus.Debugf("Creating service for vip %s fwMark %d ingressPorts %#v in sbox %.7s (%.7s)", lb.vip, lb.fwMark, lb.service.ingressPorts, sb.ID(), sb.ContainerID())
  131. if err := invokeFWMarker(sb.Key(), lb.vip, lb.fwMark, lb.service.ingressPorts, eIP, false, n.loadBalancerMode); err != nil {
  132. logrus.Errorf("Failed to add firewall mark rule in sbox %.7s (%.7s): %v", sb.ID(), sb.ContainerID(), err)
  133. return
  134. }
  135. if err := i.NewService(s); err != nil && err != syscall.EEXIST {
  136. logrus.Errorf("Failed to create a new service for vip %s fwmark %d in sbox %.7s (%.7s): %v", lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
  137. return
  138. }
  139. }
  140. d := &ipvs.Destination{
  141. AddressFamily: nl.FAMILY_V4,
  142. Address: ip,
  143. Weight: 1,
  144. }
  145. if n.loadBalancerMode == loadBalancerModeDSR {
  146. d.ConnectionFlags = ipvs.ConnFwdDirectRoute
  147. }
  148. // Remove the sched name before using the service to add
  149. // destination.
  150. s.SchedName = ""
  151. if err := i.NewDestination(s, d); err != nil && err != syscall.EEXIST {
  152. logrus.Errorf("Failed to create real server %s for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
  153. }
  154. }
  155. // Remove loadbalancer backend the load balancing endpoint for this
  156. // network. If 'rmService' is true, then remove the service entry as well.
  157. // If 'fullRemove' is true then completely remove the entry, otherwise
  158. // just deweight it for now.
  159. func (n *network) rmLBBackend(ip net.IP, lb *loadBalancer, rmService bool, fullRemove bool) {
  160. if len(lb.vip) == 0 {
  161. return
  162. }
  163. ep, sb, err := n.findLBEndpointSandbox()
  164. if err != nil {
  165. logrus.Debugf("rmLBBackend for %s/%s: %v -- probably transient state", n.ID(), n.Name(), err)
  166. return
  167. }
  168. if sb.osSbox == nil {
  169. return
  170. }
  171. eIP := ep.Iface().Address()
  172. i, err := ipvs.New(sb.Key())
  173. if err != nil {
  174. logrus.Errorf("Failed to create an ipvs handle for sbox %.7s (%.7s,%s) for lb removal: %v", sb.ID(), sb.ContainerID(), sb.Key(), err)
  175. return
  176. }
  177. defer i.Close()
  178. s := &ipvs.Service{
  179. AddressFamily: nl.FAMILY_V4,
  180. FWMark: lb.fwMark,
  181. }
  182. d := &ipvs.Destination{
  183. AddressFamily: nl.FAMILY_V4,
  184. Address: ip,
  185. Weight: 1,
  186. }
  187. if n.loadBalancerMode == loadBalancerModeDSR {
  188. d.ConnectionFlags = ipvs.ConnFwdDirectRoute
  189. }
  190. if fullRemove {
  191. if err := i.DelDestination(s, d); err != nil && err != syscall.ENOENT {
  192. logrus.Errorf("Failed to delete real server %s for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
  193. }
  194. } else {
  195. d.Weight = 0
  196. if err := i.UpdateDestination(s, d); err != nil && err != syscall.ENOENT {
  197. logrus.Errorf("Failed to set LB weight of real server %s to 0 for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
  198. }
  199. }
  200. if rmService {
  201. s.SchedName = ipvs.RoundRobin
  202. if err := i.DelService(s); err != nil && err != syscall.ENOENT {
  203. logrus.Errorf("Failed to delete service for vip %s fwmark %d in sbox %.7s (%.7s): %v", lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
  204. }
  205. if sb.ingress {
  206. var gwIP net.IP
  207. if ep := sb.getGatewayEndpoint(); ep != nil {
  208. gwIP = ep.Iface().Address().IP
  209. }
  210. if err := programIngress(gwIP, lb.service.ingressPorts, true); err != nil {
  211. logrus.Errorf("Failed to delete ingress: %v", err)
  212. }
  213. }
  214. if err := invokeFWMarker(sb.Key(), lb.vip, lb.fwMark, lb.service.ingressPorts, eIP, true, n.loadBalancerMode); err != nil {
  215. logrus.Errorf("Failed to delete firewall mark rule in sbox %.7s (%.7s): %v", sb.ID(), sb.ContainerID(), err)
  216. }
  217. // Remove IP alias from the VIP to the endpoint
  218. ifName := findIfaceDstName(sb, ep)
  219. if ifName == "" {
  220. logrus.Errorf("Failed find interface name for endpoint %s(%s) to create LB alias", ep.ID(), ep.Name())
  221. return
  222. }
  223. err := sb.osSbox.RemoveAliasIP(ifName, &net.IPNet{IP: lb.vip, Mask: net.CIDRMask(32, 32)})
  224. if err != nil {
  225. logrus.Errorf("Failed add IP alias %s to network %s LB endpoint interface %s: %v", lb.vip, n.ID(), ifName, err)
  226. }
  227. }
  228. }
  229. const ingressChain = "DOCKER-INGRESS"
  230. var (
  231. ingressOnce sync.Once
  232. ingressMu sync.Mutex // lock for operations on ingress
  233. ingressProxyTbl = make(map[string]io.Closer)
  234. portConfigMu sync.Mutex
  235. portConfigTbl = make(map[PortConfig]int)
  236. )
  237. func filterPortConfigs(ingressPorts []*PortConfig, isDelete bool) []*PortConfig {
  238. portConfigMu.Lock()
  239. iPorts := make([]*PortConfig, 0, len(ingressPorts))
  240. for _, pc := range ingressPorts {
  241. if isDelete {
  242. if cnt, ok := portConfigTbl[*pc]; ok {
  243. // This is the last reference to this
  244. // port config. Delete the port config
  245. // and add it to filtered list to be
  246. // plumbed.
  247. if cnt == 1 {
  248. delete(portConfigTbl, *pc)
  249. iPorts = append(iPorts, pc)
  250. continue
  251. }
  252. portConfigTbl[*pc] = cnt - 1
  253. }
  254. continue
  255. }
  256. if cnt, ok := portConfigTbl[*pc]; ok {
  257. portConfigTbl[*pc] = cnt + 1
  258. continue
  259. }
  260. // We are adding it for the first time. Add it to the
  261. // filter list to be plumbed.
  262. portConfigTbl[*pc] = 1
  263. iPorts = append(iPorts, pc)
  264. }
  265. portConfigMu.Unlock()
  266. return iPorts
  267. }
  268. func programIngress(gwIP net.IP, ingressPorts []*PortConfig, isDelete bool) error {
  269. // TODO IPv6 support
  270. iptable := iptables.GetIptable(iptables.IPv4)
  271. addDelOpt := "-I"
  272. rollbackAddDelOpt := "-D"
  273. if isDelete {
  274. addDelOpt = "-D"
  275. rollbackAddDelOpt = "-I"
  276. }
  277. ingressMu.Lock()
  278. defer ingressMu.Unlock()
  279. chainExists := iptable.ExistChain(ingressChain, iptables.Nat)
  280. filterChainExists := iptable.ExistChain(ingressChain, iptables.Filter)
  281. ingressOnce.Do(func() {
  282. // Flush nat table and filter table ingress chain rules during init if it
  283. // exists. It might contain stale rules from previous life.
  284. if chainExists {
  285. if err := iptable.RawCombinedOutput("-t", "nat", "-F", ingressChain); err != nil {
  286. logrus.Errorf("Could not flush nat table ingress chain rules during init: %v", err)
  287. }
  288. }
  289. if filterChainExists {
  290. if err := iptable.RawCombinedOutput("-F", ingressChain); err != nil {
  291. logrus.Errorf("Could not flush filter table ingress chain rules during init: %v", err)
  292. }
  293. }
  294. })
  295. if !isDelete {
  296. if !chainExists {
  297. if err := iptable.RawCombinedOutput("-t", "nat", "-N", ingressChain); err != nil {
  298. return fmt.Errorf("failed to create ingress chain: %v", err)
  299. }
  300. }
  301. if !filterChainExists {
  302. if err := iptable.RawCombinedOutput("-N", ingressChain); err != nil {
  303. return fmt.Errorf("failed to create filter table ingress chain: %v", err)
  304. }
  305. }
  306. if !iptable.Exists(iptables.Nat, ingressChain, "-j", "RETURN") {
  307. if err := iptable.RawCombinedOutput("-t", "nat", "-A", ingressChain, "-j", "RETURN"); err != nil {
  308. return fmt.Errorf("failed to add return rule in nat table ingress chain: %v", err)
  309. }
  310. }
  311. if !iptable.Exists(iptables.Filter, ingressChain, "-j", "RETURN") {
  312. if err := iptable.RawCombinedOutput("-A", ingressChain, "-j", "RETURN"); err != nil {
  313. return fmt.Errorf("failed to add return rule to filter table ingress chain: %v", err)
  314. }
  315. }
  316. for _, chain := range []string{"OUTPUT", "PREROUTING"} {
  317. if !iptable.Exists(iptables.Nat, chain, "-m", "addrtype", "--dst-type", "LOCAL", "-j", ingressChain) {
  318. if err := iptable.RawCombinedOutput("-t", "nat", "-I", chain, "-m", "addrtype", "--dst-type", "LOCAL", "-j", ingressChain); err != nil {
  319. return fmt.Errorf("failed to add jump rule in %s to ingress chain: %v", chain, err)
  320. }
  321. }
  322. }
  323. if !iptable.Exists(iptables.Filter, "FORWARD", "-j", ingressChain) {
  324. if err := iptable.RawCombinedOutput("-I", "FORWARD", "-j", ingressChain); err != nil {
  325. return fmt.Errorf("failed to add jump rule to %s in filter table forward chain: %v", ingressChain, err)
  326. }
  327. arrangeUserFilterRule()
  328. }
  329. oifName, err := findOIFName(gwIP)
  330. if err != nil {
  331. return fmt.Errorf("failed to find gateway bridge interface name for %s: %v", gwIP, err)
  332. }
  333. path := filepath.Join("/proc/sys/net/ipv4/conf", oifName, "route_localnet")
  334. if err := ioutil.WriteFile(path, []byte{'1', '\n'}, 0644); err != nil {
  335. return fmt.Errorf("could not write to %s: %v", path, err)
  336. }
  337. ruleArgs := strings.Fields(fmt.Sprintf("-m addrtype --src-type LOCAL -o %s -j MASQUERADE", oifName))
  338. if !iptable.Exists(iptables.Nat, "POSTROUTING", ruleArgs...) {
  339. if err := iptable.RawCombinedOutput(append([]string{"-t", "nat", "-I", "POSTROUTING"}, ruleArgs...)...); err != nil {
  340. return fmt.Errorf("failed to add ingress localhost POSTROUTING rule for %s: %v", oifName, err)
  341. }
  342. }
  343. }
  344. //Filter the ingress ports until port rules start to be added/deleted
  345. filteredPorts := filterPortConfigs(ingressPorts, isDelete)
  346. rollbackRules := make([][]string, 0, len(filteredPorts)*3)
  347. var portErr error
  348. defer func() {
  349. if portErr != nil && !isDelete {
  350. filterPortConfigs(filteredPorts, !isDelete)
  351. for _, rule := range rollbackRules {
  352. if err := iptable.RawCombinedOutput(rule...); err != nil {
  353. logrus.Warnf("roll back rule failed, %v: %v", rule, err)
  354. }
  355. }
  356. }
  357. }()
  358. for _, iPort := range filteredPorts {
  359. if iptable.ExistChain(ingressChain, iptables.Nat) {
  360. rule := strings.Fields(fmt.Sprintf("-t nat %s %s -p %s --dport %d -j DNAT --to-destination %s:%d",
  361. addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, gwIP, iPort.PublishedPort))
  362. if portErr = iptable.RawCombinedOutput(rule...); portErr != nil {
  363. errStr := fmt.Sprintf("set up rule failed, %v: %v", rule, portErr)
  364. if !isDelete {
  365. return fmt.Errorf("%s", errStr)
  366. }
  367. logrus.Infof("%s", errStr)
  368. }
  369. rollbackRule := strings.Fields(fmt.Sprintf("-t nat %s %s -p %s --dport %d -j DNAT --to-destination %s:%d", rollbackAddDelOpt,
  370. ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, gwIP, iPort.PublishedPort))
  371. rollbackRules = append(rollbackRules, rollbackRule)
  372. }
  373. // Filter table rules to allow a published service to be accessible in the local node from..
  374. // 1) service tasks attached to other networks
  375. // 2) unmanaged containers on bridge networks
  376. rule := strings.Fields(fmt.Sprintf("%s %s -m state -p %s --sport %d --state ESTABLISHED,RELATED -j ACCEPT",
  377. addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort))
  378. if portErr = iptable.RawCombinedOutput(rule...); portErr != nil {
  379. errStr := fmt.Sprintf("set up rule failed, %v: %v", rule, portErr)
  380. if !isDelete {
  381. return fmt.Errorf("%s", errStr)
  382. }
  383. logrus.Warnf("%s", errStr)
  384. }
  385. rollbackRule := strings.Fields(fmt.Sprintf("%s %s -m state -p %s --sport %d --state ESTABLISHED,RELATED -j ACCEPT", rollbackAddDelOpt,
  386. ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort))
  387. rollbackRules = append(rollbackRules, rollbackRule)
  388. rule = strings.Fields(fmt.Sprintf("%s %s -p %s --dport %d -j ACCEPT",
  389. addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort))
  390. if portErr = iptable.RawCombinedOutput(rule...); portErr != nil {
  391. errStr := fmt.Sprintf("set up rule failed, %v: %v", rule, portErr)
  392. if !isDelete {
  393. return fmt.Errorf("%s", errStr)
  394. }
  395. logrus.Warnf("%s", errStr)
  396. }
  397. rollbackRule = strings.Fields(fmt.Sprintf("%s %s -p %s --dport %d -j ACCEPT", rollbackAddDelOpt,
  398. ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort))
  399. rollbackRules = append(rollbackRules, rollbackRule)
  400. if err := plumbProxy(iPort, isDelete); err != nil {
  401. logrus.Warnf("failed to create proxy for port %d: %v", iPort.PublishedPort, err)
  402. }
  403. }
  404. return nil
  405. }
  406. // In the filter table FORWARD chain the first rule should be to jump to
  407. // DOCKER-USER so the user is able to filter packet first.
  408. // The second rule should be jump to INGRESS-CHAIN.
  409. // This chain has the rules to allow access to the published ports for swarm tasks
  410. // from local bridge networks and docker_gwbridge (ie:taks on other swarm networks)
  411. func arrangeIngressFilterRule() {
  412. // TODO IPv6 support
  413. iptable := iptables.GetIptable(iptables.IPv4)
  414. if iptable.ExistChain(ingressChain, iptables.Filter) {
  415. if iptable.Exists(iptables.Filter, "FORWARD", "-j", ingressChain) {
  416. if err := iptable.RawCombinedOutput("-D", "FORWARD", "-j", ingressChain); err != nil {
  417. logrus.Warnf("failed to delete jump rule to ingressChain in filter table: %v", err)
  418. }
  419. }
  420. if err := iptable.RawCombinedOutput("-I", "FORWARD", "-j", ingressChain); err != nil {
  421. logrus.Warnf("failed to add jump rule to ingressChain in filter table: %v", err)
  422. }
  423. }
  424. }
  425. func findOIFName(ip net.IP) (string, error) {
  426. nlh := ns.NlHandle()
  427. routes, err := nlh.RouteGet(ip)
  428. if err != nil {
  429. return "", err
  430. }
  431. if len(routes) == 0 {
  432. return "", fmt.Errorf("no route to %s", ip)
  433. }
  434. // Pick the first route(typically there is only one route). We
  435. // don't support multipath.
  436. link, err := nlh.LinkByIndex(routes[0].LinkIndex)
  437. if err != nil {
  438. return "", err
  439. }
  440. return link.Attrs().Name, nil
  441. }
  442. func plumbProxy(iPort *PortConfig, isDelete bool) error {
  443. var (
  444. err error
  445. l io.Closer
  446. )
  447. portSpec := fmt.Sprintf("%d/%s", iPort.PublishedPort, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]))
  448. if isDelete {
  449. if listener, ok := ingressProxyTbl[portSpec]; ok {
  450. if listener != nil {
  451. listener.Close()
  452. }
  453. }
  454. return nil
  455. }
  456. switch iPort.Protocol {
  457. case ProtocolTCP:
  458. l, err = net.ListenTCP("tcp", &net.TCPAddr{Port: int(iPort.PublishedPort)})
  459. case ProtocolUDP:
  460. l, err = net.ListenUDP("udp", &net.UDPAddr{Port: int(iPort.PublishedPort)})
  461. case ProtocolSCTP:
  462. l, err = sctp.ListenSCTP("sctp", &sctp.SCTPAddr{Port: int(iPort.PublishedPort)})
  463. default:
  464. err = fmt.Errorf("unknown protocol %v", iPort.Protocol)
  465. }
  466. if err != nil {
  467. return err
  468. }
  469. ingressProxyTbl[portSpec] = l
  470. return nil
  471. }
  472. func writePortsToFile(ports []*PortConfig) (string, error) {
  473. f, err := ioutil.TempFile("", "port_configs")
  474. if err != nil {
  475. return "", err
  476. }
  477. defer f.Close()
  478. buf, _ := proto.Marshal(&EndpointRecord{
  479. IngressPorts: ports,
  480. })
  481. n, err := f.Write(buf)
  482. if err != nil {
  483. return "", err
  484. }
  485. if n < len(buf) {
  486. return "", io.ErrShortWrite
  487. }
  488. return f.Name(), nil
  489. }
  490. func readPortsFromFile(fileName string) ([]*PortConfig, error) {
  491. buf, err := ioutil.ReadFile(fileName)
  492. if err != nil {
  493. return nil, err
  494. }
  495. var epRec EndpointRecord
  496. err = proto.Unmarshal(buf, &epRec)
  497. if err != nil {
  498. return nil, err
  499. }
  500. return epRec.IngressPorts, nil
  501. }
  502. // Invoke fwmarker reexec routine to mark vip destined packets with
  503. // the passed firewall mark.
  504. func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, isDelete bool, lbMode string) error {
  505. var ingressPortsFile string
  506. if len(ingressPorts) != 0 {
  507. var err error
  508. ingressPortsFile, err = writePortsToFile(ingressPorts)
  509. if err != nil {
  510. return err
  511. }
  512. defer os.Remove(ingressPortsFile)
  513. }
  514. addDelOpt := "-A"
  515. if isDelete {
  516. addDelOpt = "-D"
  517. }
  518. cmd := &exec.Cmd{
  519. Path: reexec.Self(),
  520. Args: append([]string{"fwmarker"}, path, vip.String(), fmt.Sprintf("%d", fwMark), addDelOpt, ingressPortsFile, eIP.String(), lbMode),
  521. Stdout: os.Stdout,
  522. Stderr: os.Stderr,
  523. }
  524. if err := cmd.Run(); err != nil {
  525. return fmt.Errorf("reexec failed: %v", err)
  526. }
  527. return nil
  528. }
  529. // Firewall marker reexec function.
  530. func fwMarker() {
  531. // TODO IPv6 support
  532. iptable := iptables.GetIptable(iptables.IPv4)
  533. runtime.LockOSThread()
  534. defer runtime.UnlockOSThread()
  535. if len(os.Args) < 8 {
  536. logrus.Error("invalid number of arguments..")
  537. os.Exit(1)
  538. }
  539. var ingressPorts []*PortConfig
  540. if os.Args[5] != "" {
  541. var err error
  542. ingressPorts, err = readPortsFromFile(os.Args[5])
  543. if err != nil {
  544. logrus.Errorf("Failed reading ingress ports file: %v", err)
  545. os.Exit(2)
  546. }
  547. }
  548. vip := os.Args[2]
  549. fwMark, err := strconv.ParseUint(os.Args[3], 10, 32)
  550. if err != nil {
  551. logrus.Errorf("bad fwmark value(%s) passed: %v", os.Args[3], err)
  552. os.Exit(3)
  553. }
  554. addDelOpt := os.Args[4]
  555. rules := [][]string{}
  556. for _, iPort := range ingressPorts {
  557. rule := strings.Fields(fmt.Sprintf("-t mangle %s PREROUTING -p %s --dport %d -j MARK --set-mark %d",
  558. addDelOpt, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, fwMark))
  559. rules = append(rules, rule)
  560. }
  561. ns, err := netns.GetFromPath(os.Args[1])
  562. if err != nil {
  563. logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
  564. os.Exit(4)
  565. }
  566. defer ns.Close()
  567. if err := netns.Set(ns); err != nil {
  568. logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
  569. os.Exit(5)
  570. }
  571. lbMode := os.Args[7]
  572. if addDelOpt == "-A" && lbMode == loadBalancerModeNAT {
  573. eIP, subnet, err := net.ParseCIDR(os.Args[6])
  574. if err != nil {
  575. logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[6], err)
  576. os.Exit(6)
  577. }
  578. ruleParams := strings.Fields(fmt.Sprintf("-m ipvs --ipvs -d %s -j SNAT --to-source %s", subnet, eIP))
  579. if !iptable.Exists("nat", "POSTROUTING", ruleParams...) {
  580. rule := append(strings.Fields("-t nat -A POSTROUTING"), ruleParams...)
  581. rules = append(rules, rule)
  582. err := ioutil.WriteFile("/proc/sys/net/ipv4/vs/conntrack", []byte{'1', '\n'}, 0644)
  583. if err != nil {
  584. logrus.Errorf("Failed to write to /proc/sys/net/ipv4/vs/conntrack: %v", err)
  585. os.Exit(7)
  586. }
  587. }
  588. }
  589. rule := strings.Fields(fmt.Sprintf("-t mangle %s INPUT -d %s/32 -j MARK --set-mark %d", addDelOpt, vip, fwMark))
  590. rules = append(rules, rule)
  591. for _, rule := range rules {
  592. if err := iptable.RawCombinedOutputNative(rule...); err != nil {
  593. logrus.Errorf("set up rule failed, %v: %v", rule, err)
  594. os.Exit(8)
  595. }
  596. }
  597. }
  598. func addRedirectRules(path string, eIP *net.IPNet, ingressPorts []*PortConfig) error {
  599. var ingressPortsFile string
  600. if len(ingressPorts) != 0 {
  601. var err error
  602. ingressPortsFile, err = writePortsToFile(ingressPorts)
  603. if err != nil {
  604. return err
  605. }
  606. defer os.Remove(ingressPortsFile)
  607. }
  608. cmd := &exec.Cmd{
  609. Path: reexec.Self(),
  610. Args: append([]string{"redirector"}, path, eIP.String(), ingressPortsFile),
  611. Stdout: os.Stdout,
  612. Stderr: os.Stderr,
  613. }
  614. if err := cmd.Run(); err != nil {
  615. return fmt.Errorf("reexec failed: %v", err)
  616. }
  617. return nil
  618. }
  619. // Redirector reexec function.
  620. func redirector() {
  621. // TODO IPv6 support
  622. iptable := iptables.GetIptable(iptables.IPv4)
  623. runtime.LockOSThread()
  624. defer runtime.UnlockOSThread()
  625. if len(os.Args) < 4 {
  626. logrus.Error("invalid number of arguments..")
  627. os.Exit(1)
  628. }
  629. var ingressPorts []*PortConfig
  630. if os.Args[3] != "" {
  631. var err error
  632. ingressPorts, err = readPortsFromFile(os.Args[3])
  633. if err != nil {
  634. logrus.Errorf("Failed reading ingress ports file: %v", err)
  635. os.Exit(2)
  636. }
  637. }
  638. eIP, _, err := net.ParseCIDR(os.Args[2])
  639. if err != nil {
  640. logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[2], err)
  641. os.Exit(3)
  642. }
  643. rules := [][]string{}
  644. for _, iPort := range ingressPorts {
  645. rule := strings.Fields(fmt.Sprintf("-t nat -A PREROUTING -d %s -p %s --dport %d -j REDIRECT --to-port %d",
  646. eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, iPort.TargetPort))
  647. rules = append(rules, rule)
  648. // Allow only incoming connections to exposed ports
  649. iRule := strings.Fields(fmt.Sprintf("-I INPUT -d %s -p %s --dport %d -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT",
  650. eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.TargetPort))
  651. rules = append(rules, iRule)
  652. // Allow only outgoing connections from exposed ports
  653. oRule := strings.Fields(fmt.Sprintf("-I OUTPUT -s %s -p %s --sport %d -m conntrack --ctstate ESTABLISHED -j ACCEPT",
  654. eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.TargetPort))
  655. rules = append(rules, oRule)
  656. }
  657. ns, err := netns.GetFromPath(os.Args[1])
  658. if err != nil {
  659. logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
  660. os.Exit(4)
  661. }
  662. defer ns.Close()
  663. if err := netns.Set(ns); err != nil {
  664. logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
  665. os.Exit(5)
  666. }
  667. for _, rule := range rules {
  668. if err := iptable.RawCombinedOutputNative(rule...); err != nil {
  669. logrus.Errorf("set up rule failed, %v: %v", rule, err)
  670. os.Exit(6)
  671. }
  672. }
  673. if len(ingressPorts) == 0 {
  674. return
  675. }
  676. // Ensure blocking rules for anything else in/to ingress network
  677. for _, rule := range [][]string{
  678. {"-d", eIP.String(), "-p", "sctp", "-j", "DROP"},
  679. {"-d", eIP.String(), "-p", "udp", "-j", "DROP"},
  680. {"-d", eIP.String(), "-p", "tcp", "-j", "DROP"},
  681. } {
  682. if !iptable.ExistsNative(iptables.Filter, "INPUT", rule...) {
  683. if err := iptable.RawCombinedOutputNative(append([]string{"-A", "INPUT"}, rule...)...); err != nil {
  684. logrus.Errorf("set up rule failed, %v: %v", rule, err)
  685. os.Exit(7)
  686. }
  687. }
  688. rule[0] = "-s"
  689. if !iptable.ExistsNative(iptables.Filter, "OUTPUT", rule...) {
  690. if err := iptable.RawCombinedOutputNative(append([]string{"-A", "OUTPUT"}, rule...)...); err != nil {
  691. logrus.Errorf("set up rule failed, %v: %v", rule, err)
  692. os.Exit(8)
  693. }
  694. }
  695. }
  696. }