service_linux.go 24 KB

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