console_init.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package control
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "regexp"
  10. "strings"
  11. "syscall"
  12. "github.com/codegangsta/cli"
  13. "github.com/rancher/os/cmd/cloudinitexecute"
  14. "github.com/rancher/os/config"
  15. "github.com/rancher/os/log"
  16. "github.com/rancher/os/util"
  17. )
  18. const (
  19. consoleDone = "/run/console-done"
  20. dockerHome = "/home/docker"
  21. gettyCmd = "/sbin/agetty"
  22. rancherHome = "/home/rancher"
  23. startScript = "/opt/rancher/bin/start.sh"
  24. )
  25. type symlink struct {
  26. oldname, newname string
  27. }
  28. func ConsoleInitMain() {
  29. if err := consoleInitFunc(); err != nil {
  30. log.Fatal(err)
  31. }
  32. }
  33. func consoleInitAction(c *cli.Context) error {
  34. return consoleInitFunc()
  35. }
  36. func createHomeDir(homedir string, uid, gid int) {
  37. if _, err := os.Stat(homedir); os.IsNotExist(err) {
  38. if err := os.MkdirAll(homedir, 0755); err != nil {
  39. log.Error(err)
  40. }
  41. if err := os.Chown(homedir, uid, gid); err != nil {
  42. log.Error(err)
  43. }
  44. }
  45. }
  46. func consoleInitFunc() error {
  47. cfg := config.LoadConfig()
  48. // Now that we're booted, stop writing debug messages to the console
  49. cmd := exec.Command("sudo", "dmesg", "--console-off")
  50. if err := cmd.Run(); err != nil {
  51. log.Error(err)
  52. }
  53. createHomeDir(rancherHome, 1100, 1100)
  54. createHomeDir(dockerHome, 1101, 1101)
  55. password := config.GetCmdline("rancher.password")
  56. if password != "" {
  57. cmd := exec.Command("chpasswd")
  58. cmd.Stdin = strings.NewReader(fmt.Sprint("rancher:", password))
  59. if err := cmd.Run(); err != nil {
  60. log.Error(err)
  61. }
  62. cmd = exec.Command("bash", "-c", `sed -E -i 's/(rancher:.*:).*(:.*:.*:.*:.*:.*:.*)$/\1\2/' /etc/shadow`)
  63. if err := cmd.Run(); err != nil {
  64. log.Error(err)
  65. }
  66. }
  67. if err := setupSSH(cfg); err != nil {
  68. log.Error(err)
  69. }
  70. if err := writeRespawn("rancher", cfg.Rancher.SSH.Daemon, false); err != nil {
  71. log.Error(err)
  72. }
  73. if err := modifySshdConfig(); err != nil {
  74. log.Error(err)
  75. }
  76. for _, link := range []symlink{
  77. {"/var/lib/rancher/engine/docker", "/usr/bin/docker"},
  78. {"/var/lib/rancher/engine/docker-init", "/usr/bin/docker-init"},
  79. {"/var/lib/rancher/engine/docker-containerd", "/usr/bin/docker-containerd"},
  80. {"/var/lib/rancher/engine/docker-containerd-ctr", "/usr/bin/docker-containerd-ctr"},
  81. {"/var/lib/rancher/engine/docker-containerd-shim", "/usr/bin/docker-containerd-shim"},
  82. {"/var/lib/rancher/engine/dockerd", "/usr/bin/dockerd"},
  83. {"/var/lib/rancher/engine/docker-proxy", "/usr/bin/docker-proxy"},
  84. {"/var/lib/rancher/engine/docker-runc", "/usr/bin/docker-runc"},
  85. {"/usr/share/ros/os-release", "/usr/lib/os-release"},
  86. {"/usr/share/ros/os-release", "/etc/os-release"},
  87. } {
  88. syscall.Unlink(link.newname)
  89. if err := os.Symlink(link.oldname, link.newname); err != nil {
  90. log.Error(err)
  91. }
  92. }
  93. // font backslashes need to be escaped for when issue is output! (but not the others..)
  94. if err := ioutil.WriteFile("/etc/issue", []byte(config.Banner), 0644); err != nil {
  95. log.Error(err)
  96. }
  97. cmd = exec.Command("bash", "-c", `echo $(/sbin/ifconfig | grep -B1 "inet addr" |awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' |awk -F: '{ print $1 ": " $3}') >> /etc/issue`)
  98. if err := cmd.Run(); err != nil {
  99. log.Error(err)
  100. }
  101. cloudinitexecute.ApplyConsole(cfg)
  102. if err := util.RunScript(config.CloudConfigScriptFile); err != nil {
  103. log.Error(err)
  104. }
  105. if err := util.RunScript(startScript); err != nil {
  106. log.Error(err)
  107. }
  108. if err := ioutil.WriteFile(consoleDone, []byte(CurrentConsole()), 0644); err != nil {
  109. log.Error(err)
  110. }
  111. if err := util.RunScript("/etc/rc.local"); err != nil {
  112. log.Error(err)
  113. }
  114. os.Setenv("TERM", "linux")
  115. respawnBinPath, err := exec.LookPath("respawn")
  116. if err != nil {
  117. return err
  118. }
  119. return syscall.Exec(respawnBinPath, []string{"respawn", "-f", "/etc/respawn.conf"}, os.Environ())
  120. }
  121. func generateRespawnConf(cmdline, user string, sshd, recovery bool) string {
  122. var respawnConf bytes.Buffer
  123. autologinBin := "/usr/bin/autologin"
  124. if recovery {
  125. autologinBin = "/usr/bin/recovery"
  126. }
  127. for i := 1; i < 7; i++ {
  128. tty := fmt.Sprintf("tty%d", i)
  129. respawnConf.WriteString(gettyCmd)
  130. if strings.Contains(cmdline, fmt.Sprintf("rancher.autologin=%s", tty)) {
  131. respawnConf.WriteString(fmt.Sprintf(" -n -l %s -o %s:tty%d", autologinBin, user, i))
  132. }
  133. respawnConf.WriteString(fmt.Sprintf(" --noclear %s linux\n", tty))
  134. }
  135. for _, tty := range []string{"ttyS0", "ttyS1", "ttyS2", "ttyS3", "ttyAMA0"} {
  136. if !strings.Contains(cmdline, fmt.Sprintf("console=%s", tty)) {
  137. continue
  138. }
  139. respawnConf.WriteString(gettyCmd)
  140. if strings.Contains(cmdline, fmt.Sprintf("rancher.autologin=%s", tty)) {
  141. respawnConf.WriteString(fmt.Sprintf(" -n -l %s -o %s:%s", autologinBin, user, tty))
  142. }
  143. respawnConf.WriteString(fmt.Sprintf(" %s\n", tty))
  144. }
  145. if sshd {
  146. respawnConf.WriteString("/usr/sbin/sshd -D")
  147. }
  148. return respawnConf.String()
  149. }
  150. func writeRespawn(user string, sshd, recovery bool) error {
  151. cmdline, err := ioutil.ReadFile("/proc/cmdline")
  152. if err != nil {
  153. return err
  154. }
  155. respawn := generateRespawnConf(string(cmdline), user, sshd, recovery)
  156. files, err := ioutil.ReadDir("/etc/respawn.conf.d")
  157. if err == nil {
  158. for _, f := range files {
  159. p := path.Join("/etc/respawn.conf.d", f.Name())
  160. content, err := ioutil.ReadFile(p)
  161. if err != nil {
  162. log.Errorf("Failed to read %s: %v", p, err)
  163. continue
  164. }
  165. respawn += fmt.Sprintf("\n%s", string(content))
  166. }
  167. } else if !os.IsNotExist(err) {
  168. log.Error(err)
  169. }
  170. return ioutil.WriteFile("/etc/respawn.conf", []byte(respawn), 0644)
  171. }
  172. func modifySshdConfig() error {
  173. sshdConfig, err := ioutil.ReadFile("/etc/ssh/sshd_config")
  174. if err != nil {
  175. return err
  176. }
  177. sshdConfigString := string(sshdConfig)
  178. for _, item := range []string{
  179. "UseDNS no",
  180. "PermitRootLogin no",
  181. "ServerKeyBits 2048",
  182. "AllowGroups docker",
  183. } {
  184. match, err := regexp.Match("^"+item, sshdConfig)
  185. if err != nil {
  186. return err
  187. }
  188. if !match {
  189. sshdConfigString += fmt.Sprintf("%s\n", item)
  190. }
  191. }
  192. return ioutil.WriteFile("/etc/ssh/sshd_config", []byte(sshdConfigString), 0644)
  193. }
  194. func setupSSH(cfg *config.CloudConfig) error {
  195. for _, keyType := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
  196. outputFile := fmt.Sprintf("/etc/ssh/ssh_host_%s_key", keyType)
  197. outputFilePub := fmt.Sprintf("/etc/ssh/ssh_host_%s_key.pub", keyType)
  198. if _, err := os.Stat(outputFile); err == nil {
  199. continue
  200. }
  201. saved, savedExists := cfg.Rancher.SSH.Keys[keyType]
  202. pub, pubExists := cfg.Rancher.SSH.Keys[keyType+"-pub"]
  203. if savedExists && pubExists {
  204. // TODO check permissions
  205. if err := util.WriteFileAtomic(outputFile, []byte(saved), 0600); err != nil {
  206. return err
  207. }
  208. if err := util.WriteFileAtomic(outputFilePub, []byte(pub), 0600); err != nil {
  209. return err
  210. }
  211. continue
  212. }
  213. cmd := exec.Command("bash", "-c", fmt.Sprintf("ssh-keygen -f %s -N '' -t %s", outputFile, keyType))
  214. if err := cmd.Run(); err != nil {
  215. return err
  216. }
  217. savedBytes, err := ioutil.ReadFile(outputFile)
  218. if err != nil {
  219. return err
  220. }
  221. pubBytes, err := ioutil.ReadFile(outputFilePub)
  222. if err != nil {
  223. return err
  224. }
  225. config.Set(fmt.Sprintf("rancher.ssh.keys.%s", keyType), string(savedBytes))
  226. config.Set(fmt.Sprintf("rancher.ssh.keys.%s-pub", keyType), string(pubBytes))
  227. }
  228. return os.MkdirAll("/var/run/sshd", 0644)
  229. }