ssh.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package tunneler
  14. import (
  15. "context"
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "sync/atomic"
  23. "time"
  24. "k8s.io/apimachinery/pkg/util/clock"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. "k8s.io/klog"
  27. "k8s.io/kubernetes/pkg/ssh"
  28. utilpath "k8s.io/utils/path"
  29. )
  30. type InstallSSHKey func(ctx context.Context, user string, data []byte) error
  31. type AddressFunc func() (addresses []string, err error)
  32. type Tunneler interface {
  33. Run(AddressFunc)
  34. Stop()
  35. Dial(ctx context.Context, net, addr string) (net.Conn, error)
  36. SecondsSinceSync() int64
  37. SecondsSinceSSHKeySync() int64
  38. }
  39. // TunnelSyncHealthChecker returns a health func that indicates if a tunneler is healthy.
  40. // It's compatible with healthz.NamedCheck
  41. func TunnelSyncHealthChecker(tunneler Tunneler) func(req *http.Request) error {
  42. return func(req *http.Request) error {
  43. if tunneler == nil {
  44. return nil
  45. }
  46. lag := tunneler.SecondsSinceSync()
  47. if lag > 600 {
  48. return fmt.Errorf("Tunnel sync is taking too long: %d", lag)
  49. }
  50. sshKeyLag := tunneler.SecondsSinceSSHKeySync()
  51. // Since we are syncing ssh-keys every 5 minutes, the allowed
  52. // lag since last sync should be more than 2x higher than that
  53. // to allow for single failure, which can always happen.
  54. // For now set it to 3x, which is 15 minutes.
  55. // For more details see: http://pr.k8s.io/59347
  56. if sshKeyLag > 900 {
  57. return fmt.Errorf("SSHKey sync is taking too long: %d", sshKeyLag)
  58. }
  59. return nil
  60. }
  61. }
  62. type SSHTunneler struct {
  63. // Important: Since these two int64 fields are using sync/atomic, they have to be at the top of the struct due to a bug on 32-bit platforms
  64. // See: https://golang.org/pkg/sync/atomic/ for more information
  65. lastSync int64 // Seconds since Epoch
  66. lastSSHKeySync int64 // Seconds since Epoch
  67. SSHUser string
  68. SSHKeyfile string
  69. InstallSSHKey InstallSSHKey
  70. HealthCheckURL *url.URL
  71. tunnels *ssh.SSHTunnelList
  72. clock clock.Clock
  73. getAddresses AddressFunc
  74. stopChan chan struct{}
  75. }
  76. func New(sshUser, sshKeyfile string, healthCheckURL *url.URL, installSSHKey InstallSSHKey) Tunneler {
  77. return &SSHTunneler{
  78. SSHUser: sshUser,
  79. SSHKeyfile: sshKeyfile,
  80. InstallSSHKey: installSSHKey,
  81. HealthCheckURL: healthCheckURL,
  82. clock: clock.RealClock{},
  83. }
  84. }
  85. // Run establishes tunnel loops and returns
  86. func (c *SSHTunneler) Run(getAddresses AddressFunc) {
  87. if c.stopChan != nil {
  88. return
  89. }
  90. c.stopChan = make(chan struct{})
  91. // Save the address getter
  92. if getAddresses != nil {
  93. c.getAddresses = getAddresses
  94. }
  95. // Usernames are capped @ 32
  96. if len(c.SSHUser) > 32 {
  97. klog.Warning("SSH User is too long, truncating to 32 chars")
  98. c.SSHUser = c.SSHUser[0:32]
  99. }
  100. klog.Infof("Setting up proxy: %s %s", c.SSHUser, c.SSHKeyfile)
  101. // public keyfile is written last, so check for that.
  102. publicKeyFile := c.SSHKeyfile + ".pub"
  103. exists, err := utilpath.Exists(utilpath.CheckFollowSymlink, publicKeyFile)
  104. if err != nil {
  105. klog.Errorf("Error detecting if key exists: %v", err)
  106. } else if !exists {
  107. klog.Infof("Key doesn't exist, attempting to create")
  108. if err := generateSSHKey(c.SSHKeyfile, publicKeyFile); err != nil {
  109. klog.Errorf("Failed to create key pair: %v", err)
  110. }
  111. }
  112. c.tunnels = ssh.NewSSHTunnelList(c.SSHUser, c.SSHKeyfile, c.HealthCheckURL, c.stopChan)
  113. // Sync loop to ensure that the SSH key has been installed.
  114. c.lastSSHKeySync = c.clock.Now().Unix()
  115. c.installSSHKeySyncLoop(c.SSHUser, publicKeyFile)
  116. // Sync tunnelList w/ nodes.
  117. c.lastSync = c.clock.Now().Unix()
  118. c.nodesSyncLoop()
  119. }
  120. // Stop gracefully shuts down the tunneler
  121. func (c *SSHTunneler) Stop() {
  122. if c.stopChan != nil {
  123. close(c.stopChan)
  124. c.stopChan = nil
  125. }
  126. }
  127. func (c *SSHTunneler) Dial(ctx context.Context, net, addr string) (net.Conn, error) {
  128. return c.tunnels.Dial(ctx, net, addr)
  129. }
  130. func (c *SSHTunneler) SecondsSinceSync() int64 {
  131. now := c.clock.Now().Unix()
  132. then := atomic.LoadInt64(&c.lastSync)
  133. return now - then
  134. }
  135. func (c *SSHTunneler) SecondsSinceSSHKeySync() int64 {
  136. now := c.clock.Now().Unix()
  137. then := atomic.LoadInt64(&c.lastSSHKeySync)
  138. return now - then
  139. }
  140. func (c *SSHTunneler) installSSHKeySyncLoop(user, publicKeyfile string) {
  141. go wait.Until(func() {
  142. if c.InstallSSHKey == nil {
  143. klog.Error("Won't attempt to install ssh key: InstallSSHKey function is nil")
  144. return
  145. }
  146. key, err := ssh.ParsePublicKeyFromFile(publicKeyfile)
  147. if err != nil {
  148. klog.Errorf("Failed to load public key: %v", err)
  149. return
  150. }
  151. keyData, err := ssh.EncodeSSHKey(key)
  152. if err != nil {
  153. klog.Errorf("Failed to encode public key: %v", err)
  154. return
  155. }
  156. if err := c.InstallSSHKey(context.TODO(), user, keyData); err != nil {
  157. klog.Errorf("Failed to install ssh key: %v", err)
  158. return
  159. }
  160. atomic.StoreInt64(&c.lastSSHKeySync, c.clock.Now().Unix())
  161. }, 5*time.Minute, c.stopChan)
  162. }
  163. // nodesSyncLoop lists nodes every 15 seconds, calling Update() on the TunnelList
  164. // each time (Update() is a noop if no changes are necessary).
  165. func (c *SSHTunneler) nodesSyncLoop() {
  166. // TODO (cjcullen) make this watch.
  167. go wait.Until(func() {
  168. addrs, err := c.getAddresses()
  169. klog.V(4).Infof("Calling update w/ addrs: %v", addrs)
  170. if err != nil {
  171. klog.Errorf("Failed to getAddresses: %v", err)
  172. }
  173. c.tunnels.Update(addrs)
  174. atomic.StoreInt64(&c.lastSync, c.clock.Now().Unix())
  175. }, 15*time.Second, c.stopChan)
  176. }
  177. func generateSSHKey(privateKeyfile, publicKeyfile string) error {
  178. private, public, err := ssh.GenerateKey(2048)
  179. if err != nil {
  180. return err
  181. }
  182. // If private keyfile already exists, we must have only made it halfway
  183. // through last time, so delete it.
  184. exists, err := utilpath.Exists(utilpath.CheckFollowSymlink, privateKeyfile)
  185. if err != nil {
  186. klog.Errorf("Error detecting if private key exists: %v", err)
  187. } else if exists {
  188. klog.Infof("Private key exists, but public key does not")
  189. if err := os.Remove(privateKeyfile); err != nil {
  190. klog.Errorf("Failed to remove stale private key: %v", err)
  191. }
  192. }
  193. if err := ioutil.WriteFile(privateKeyfile, ssh.EncodePrivateKey(private), 0600); err != nil {
  194. return err
  195. }
  196. publicKeyBytes, err := ssh.EncodePublicKey(public)
  197. if err != nil {
  198. return err
  199. }
  200. if err := ioutil.WriteFile(publicKeyfile+".tmp", publicKeyBytes, 0600); err != nil {
  201. return err
  202. }
  203. return os.Rename(publicKeyfile+".tmp", publicKeyfile)
  204. }