msys2-sshd-setup.sh 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/bin/sh
  2. #
  3. # msys2-sshd-setup.sh — configure sshd on MSYS2 and run it as a Windows service
  4. #
  5. # Replaces ssh-host-config <https://github.com/openssh/openssh-portable/blob/master/contrib/cygwin/ssh-host-config>
  6. # Adapted from <https://ghc.haskell.org/trac/ghc/wiki/Building/Windows/SSHD> by Sam Hocevar <sam@hocevar.net>
  7. # Adapted from <https://gist.github.com/samhocevar/00eec26d9e9988d080ac> by David Macek
  8. #
  9. # Prerequisites:
  10. # - pacman -S openssh cygrunsrv
  11. #
  12. #
  13. # Adapted by the MMGen Project from https://www.msys2.org/wiki/Setting-up-SSHd/
  14. #
  15. # MMGen notes:
  16. # Open PowerShell (Run as Administrator)
  17. # system32> net user administrator /active:yes
  18. # system32> C:\\msys64\usr\bin\bash.exe --login
  19. # $ path/to/msys2-sshd-setup.sh
  20. #
  21. # Now the SSH service should start automatically when Windows is rebooted.
  22. # You can manually start and stop the service by running:
  23. # net start msys2_sshd
  24. # net stop msys2_sshd
  25. set -e
  26. # Configuration
  27. UNPRIV_USER=sshd # DO NOT CHANGE; this username is hardcoded in the openssh code
  28. UNPRIV_NAME="Privilege separation user for sshd"
  29. EMPTY_DIR=/var/empty
  30. # Check installation sanity
  31. if ! cygrunsrv -v >/dev/null; then
  32. echo "ERROR: Missing 'cygrunsrv'. Try: pacman -S cygrunsrv."
  33. exit 1
  34. fi
  35. if ! ssh-keygen -A; then
  36. echo "ERROR: Missing 'ssh-keygen'. Try: pacman -S openssh."
  37. exit 1
  38. fi
  39. # The unprivileged sshd user (for privilege separation)
  40. add="$(if ! net user "${UNPRIV_USER}" >/dev/null; then echo "//add"; fi)"
  41. if ! net user "${UNPRIV_USER}" ${add} //fullname:"${UNPRIV_NAME}" \
  42. //homedir:"$(cygpath -w ${EMPTY_DIR})" //active:no; then
  43. echo "ERROR: Unable to create Windows user ${UNPRIV_USER}"
  44. exit 1
  45. fi
  46. # Add or update /etc/passwd entries
  47. if test -f /etc/passwd; then
  48. sed -i -e '/^'"${UNPRIV_USER}"':/d' /etc/passwd
  49. SED='/^'"${UNPRIV_USER}"':/s?^\(\([^:]*:\)\{5\}\).*?\1'"${EMPTY_DIR}"':/bin/false?p'
  50. mkpasswd -l -u "${UNPRIV_USER}" | sed -e 's/^[^:]*+//' | sed -ne "${SED}" >> /etc/passwd
  51. mkgroup.exe -l > /etc/group
  52. fi
  53. # Finally, register service with cygrunsrv and start it
  54. cygrunsrv -R msys2_sshd || true
  55. cygrunsrv -I msys2_sshd -d "MSYS2 sshd" -p /usr/bin/sshd.exe -a "-D -e" -y tcpip