console_init.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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(); 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-containerd", "/usr/bin/docker-containerd"},
  79. {"/var/lib/rancher/engine/docker-containerd-ctr", "/usr/bin/docker-containerd-ctr"},
  80. {"/var/lib/rancher/engine/docker-containerd-shim", "/usr/bin/docker-containerd-shim"},
  81. {"/var/lib/rancher/engine/dockerd", "/usr/bin/dockerd"},
  82. {"/var/lib/rancher/engine/docker-proxy", "/usr/bin/docker-proxy"},
  83. {"/var/lib/rancher/engine/docker-runc", "/usr/bin/docker-runc"},
  84. {"/usr/share/ros/os-release", "/usr/lib/os-release"},
  85. {"/usr/share/ros/os-release", "/etc/os-release"},
  86. } {
  87. syscall.Unlink(link.newname)
  88. if err := os.Symlink(link.oldname, link.newname); err != nil {
  89. log.Error(err)
  90. }
  91. }
  92. // font backslashes need to be escaped for when issue is output! (but not the others..)
  93. if err := ioutil.WriteFile("/etc/issue", []byte(`
  94. , , ______ _ _____ _____TM
  95. ,------------|'------'| | ___ \\ | | / _ / ___|
  96. / . '-' |- | |_/ /__ _ _ __ ___| |__ ___ _ __ | | | \\ '--.
  97. \\/| | | | // _' | '_ \\ / __| '_ \\ / _ \\ '__' | | | |'--. \\
  98. | .________.'----' | |\\ \\ (_| | | | | (__| | | | __/ | | \\_/ /\\__/ /
  99. | | | | \\_| \\_\\__,_|_| |_|\\___|_| |_|\\___|_| \\___/\\____/
  100. \\___/ \\___/ \s \r
  101. RancherOS `+config.Version+` \n \l
  102. `), 0644); err != nil {
  103. log.Error(err)
  104. }
  105. 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`)
  106. if err := cmd.Run(); err != nil {
  107. log.Error(err)
  108. }
  109. cloudinitexecute.ApplyConsole(cfg)
  110. if err := util.RunScript(config.CloudConfigScriptFile); err != nil {
  111. log.Error(err)
  112. }
  113. if err := util.RunScript(startScript); err != nil {
  114. log.Error(err)
  115. }
  116. if err := ioutil.WriteFile(consoleDone, []byte(cfg.Rancher.Console), 0644); err != nil {
  117. log.Error(err)
  118. }
  119. if err := util.RunScript("/etc/rc.local"); err != nil {
  120. log.Error(err)
  121. }
  122. os.Setenv("TERM", "linux")
  123. respawnBinPath, err := exec.LookPath("respawn")
  124. if err != nil {
  125. return err
  126. }
  127. return syscall.Exec(respawnBinPath, []string{"respawn", "-f", "/etc/respawn.conf"}, os.Environ())
  128. }
  129. func generateRespawnConf(cmdline string) string {
  130. var respawnConf bytes.Buffer
  131. for i := 1; i < 7; i++ {
  132. tty := fmt.Sprintf("tty%d", i)
  133. respawnConf.WriteString(gettyCmd)
  134. if strings.Contains(cmdline, fmt.Sprintf("rancher.autologin=%s", tty)) {
  135. respawnConf.WriteString(" --autologin rancher")
  136. }
  137. respawnConf.WriteString(fmt.Sprintf(" 115200 %s\n", tty))
  138. }
  139. for _, tty := range []string{"ttyS0", "ttyS1", "ttyS2", "ttyS3", "ttyAMA0"} {
  140. if !strings.Contains(cmdline, fmt.Sprintf("console=%s", tty)) {
  141. continue
  142. }
  143. respawnConf.WriteString(gettyCmd)
  144. if strings.Contains(cmdline, fmt.Sprintf("rancher.autologin=%s", tty)) {
  145. respawnConf.WriteString(" --autologin rancher")
  146. }
  147. respawnConf.WriteString(fmt.Sprintf(" 115200 %s\n", tty))
  148. }
  149. respawnConf.WriteString("/usr/sbin/sshd -D")
  150. return respawnConf.String()
  151. }
  152. func writeRespawn() error {
  153. cmdline, err := ioutil.ReadFile("/proc/cmdline")
  154. if err != nil {
  155. return err
  156. }
  157. respawn := generateRespawnConf(string(cmdline))
  158. files, err := ioutil.ReadDir("/etc/respawn.conf.d")
  159. if err == nil {
  160. for _, f := range files {
  161. p := path.Join("/etc/respawn.conf.d", f.Name())
  162. content, err := ioutil.ReadFile(p)
  163. if err != nil {
  164. log.Errorf("Failed to read %s: %v", p, err)
  165. continue
  166. }
  167. respawn += fmt.Sprintf("\n%s", string(content))
  168. }
  169. } else if !os.IsNotExist(err) {
  170. log.Error(err)
  171. }
  172. return ioutil.WriteFile("/etc/respawn.conf", []byte(respawn), 0644)
  173. }
  174. func modifySshdConfig() error {
  175. sshdConfig, err := ioutil.ReadFile("/etc/ssh/sshd_config")
  176. if err != nil {
  177. return err
  178. }
  179. sshdConfigString := string(sshdConfig)
  180. for _, item := range []string{
  181. "UseDNS no",
  182. "PermitRootLogin no",
  183. "ServerKeyBits 2048",
  184. "AllowGroups docker",
  185. } {
  186. match, err := regexp.Match("^"+item, sshdConfig)
  187. if err != nil {
  188. return err
  189. }
  190. if !match {
  191. sshdConfigString += fmt.Sprintf("%s\n", item)
  192. }
  193. }
  194. return ioutil.WriteFile("/etc/ssh/sshd_config", []byte(sshdConfigString), 0644)
  195. }
  196. func setupSSH(cfg *config.CloudConfig) error {
  197. for _, keyType := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
  198. outputFile := fmt.Sprintf("/etc/ssh/ssh_host_%s_key", keyType)
  199. outputFilePub := fmt.Sprintf("/etc/ssh/ssh_host_%s_key.pub", keyType)
  200. if _, err := os.Stat(outputFile); err == nil {
  201. continue
  202. }
  203. saved, savedExists := cfg.Rancher.SSH.Keys[keyType]
  204. pub, pubExists := cfg.Rancher.SSH.Keys[keyType+"-pub"]
  205. if savedExists && pubExists {
  206. // TODO check permissions
  207. if err := util.WriteFileAtomic(outputFile, []byte(saved), 0600); err != nil {
  208. return err
  209. }
  210. if err := util.WriteFileAtomic(outputFilePub, []byte(pub), 0600); err != nil {
  211. return err
  212. }
  213. continue
  214. }
  215. cmd := exec.Command("bash", "-c", fmt.Sprintf("ssh-keygen -f %s -N '' -t %s", outputFile, keyType))
  216. if err := cmd.Run(); err != nil {
  217. return err
  218. }
  219. savedBytes, err := ioutil.ReadFile(outputFile)
  220. if err != nil {
  221. return err
  222. }
  223. pubBytes, err := ioutil.ReadFile(outputFilePub)
  224. if err != nil {
  225. return err
  226. }
  227. config.Set(fmt.Sprintf("rancher.ssh.keys.%s", keyType), string(savedBytes))
  228. config.Set(fmt.Sprintf("rancher.ssh.keys.%s-pub", keyType), string(pubBytes))
  229. }
  230. return os.MkdirAll("/var/run/sshd", 0644)
  231. }