ssh.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package authority
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "net/http"
  6. "strings"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/authority/provisioner"
  9. "github.com/smallstep/certificates/db"
  10. "github.com/smallstep/certificates/templates"
  11. "github.com/smallstep/cli/crypto/randutil"
  12. "github.com/smallstep/cli/jose"
  13. "golang.org/x/crypto/ssh"
  14. )
  15. const (
  16. // SSHAddUserPrincipal is the principal that will run the add user command.
  17. // Defaults to "provisioner" but it can be changed in the configuration.
  18. SSHAddUserPrincipal = "provisioner"
  19. // SSHAddUserCommand is the default command to run to add a new user.
  20. // Defaults to "sudo useradd -m <principal>; nc -q0 localhost 22" but it can be changed in the
  21. // configuration. The string "<principal>" will be replace by the new
  22. // principal to add.
  23. SSHAddUserCommand = "sudo useradd -m <principal>; nc -q0 localhost 22"
  24. )
  25. // SSHConfig contains the user and host keys.
  26. type SSHConfig struct {
  27. HostKey string `json:"hostKey"`
  28. UserKey string `json:"userKey"`
  29. Keys []*SSHPublicKey `json:"keys,omitempty"`
  30. AddUserPrincipal string `json:"addUserPrincipal"`
  31. AddUserCommand string `json:"addUserCommand"`
  32. }
  33. // Validate checks the fields in SSHConfig.
  34. func (c *SSHConfig) Validate() error {
  35. if c == nil {
  36. return nil
  37. }
  38. for _, k := range c.Keys {
  39. if err := k.Validate(); err != nil {
  40. return err
  41. }
  42. }
  43. return nil
  44. }
  45. // SSHPublicKey contains a public key used by federated CAs to keep old signing
  46. // keys for this ca.
  47. type SSHPublicKey struct {
  48. Type string `json:"type"`
  49. Federated bool `json:"federated"`
  50. Key jose.JSONWebKey `json:"key"`
  51. publicKey ssh.PublicKey
  52. }
  53. // Validate checks the fields in SSHPublicKey.
  54. func (k *SSHPublicKey) Validate() error {
  55. switch {
  56. case k.Type == "":
  57. return errors.New("type cannot be empty")
  58. case k.Type != provisioner.SSHHostCert && k.Type != provisioner.SSHUserCert:
  59. return errors.Errorf("invalid type %s, it must be user or host", k.Type)
  60. case !k.Key.IsPublic():
  61. return errors.New("invalid key type, it must be a public key")
  62. }
  63. key, err := ssh.NewPublicKey(k.Key.Key)
  64. if err != nil {
  65. return errors.Wrap(err, "error creating ssh key")
  66. }
  67. k.publicKey = key
  68. return nil
  69. }
  70. // PublicKey returns the ssh public key.
  71. func (k *SSHPublicKey) PublicKey() ssh.PublicKey {
  72. return k.publicKey
  73. }
  74. // SSHKeys represents the SSH User and Host public keys.
  75. type SSHKeys struct {
  76. UserKeys []ssh.PublicKey
  77. HostKeys []ssh.PublicKey
  78. }
  79. // GetSSHRoots returns the SSH User and Host public keys.
  80. func (a *Authority) GetSSHRoots() (*SSHKeys, error) {
  81. return &SSHKeys{
  82. HostKeys: a.sshCAHostCerts,
  83. UserKeys: a.sshCAUserCerts,
  84. }, nil
  85. }
  86. // GetSSHFederation returns the public keys for federated SSH signers.
  87. func (a *Authority) GetSSHFederation() (*SSHKeys, error) {
  88. return &SSHKeys{
  89. HostKeys: a.sshCAHostFederatedCerts,
  90. UserKeys: a.sshCAUserFederatedCerts,
  91. }, nil
  92. }
  93. // GetSSHConfig returns rendered templates for clients (user) or servers (host).
  94. func (a *Authority) GetSSHConfig(typ string, data map[string]string) ([]templates.Output, error) {
  95. if a.sshCAUserCertSignKey == nil && a.sshCAHostCertSignKey == nil {
  96. return nil, &apiError{
  97. err: errors.New("getSSHConfig: ssh is not configured"),
  98. code: http.StatusNotFound,
  99. }
  100. }
  101. var ts []templates.Template
  102. switch typ {
  103. case provisioner.SSHUserCert:
  104. if a.config.Templates != nil && a.config.Templates.SSH != nil {
  105. ts = a.config.Templates.SSH.User
  106. }
  107. case provisioner.SSHHostCert:
  108. if a.config.Templates != nil && a.config.Templates.SSH != nil {
  109. ts = a.config.Templates.SSH.Host
  110. }
  111. default:
  112. return nil, &apiError{
  113. err: errors.Errorf("getSSHConfig: type %s is not valid", typ),
  114. code: http.StatusBadRequest,
  115. }
  116. }
  117. // Merge user and default data
  118. var mergedData map[string]interface{}
  119. if len(data) == 0 {
  120. mergedData = a.config.Templates.Data
  121. } else {
  122. mergedData = make(map[string]interface{}, len(a.config.Templates.Data)+1)
  123. mergedData["User"] = data
  124. for k, v := range a.config.Templates.Data {
  125. mergedData[k] = v
  126. }
  127. }
  128. // Render templates
  129. output := []templates.Output{}
  130. for _, t := range ts {
  131. o, err := t.Output(mergedData)
  132. if err != nil {
  133. return nil, err
  134. }
  135. output = append(output, o)
  136. }
  137. return output, nil
  138. }
  139. // SignSSH creates a signed SSH certificate with the given public key and options.
  140. func (a *Authority) SignSSH(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  141. var mods []provisioner.SSHCertificateModifier
  142. var validators []provisioner.SSHCertificateValidator
  143. for _, op := range signOpts {
  144. switch o := op.(type) {
  145. // modify the ssh.Certificate
  146. case provisioner.SSHCertificateModifier:
  147. mods = append(mods, o)
  148. // modify the ssh.Certificate given the SSHOptions
  149. case provisioner.SSHCertificateOptionModifier:
  150. mods = append(mods, o.Option(opts))
  151. // validate the ssh.Certificate
  152. case provisioner.SSHCertificateValidator:
  153. validators = append(validators, o)
  154. // validate the given SSHOptions
  155. case provisioner.SSHCertificateOptionsValidator:
  156. if err := o.Valid(opts); err != nil {
  157. return nil, &apiError{err: err, code: http.StatusForbidden}
  158. }
  159. default:
  160. return nil, &apiError{
  161. err: errors.Errorf("signSSH: invalid extra option type %T", o),
  162. code: http.StatusInternalServerError,
  163. }
  164. }
  165. }
  166. nonce, err := randutil.ASCII(32)
  167. if err != nil {
  168. return nil, &apiError{err: err, code: http.StatusInternalServerError}
  169. }
  170. var serial uint64
  171. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  172. return nil, &apiError{
  173. err: errors.Wrap(err, "signSSH: error reading random number"),
  174. code: http.StatusInternalServerError,
  175. }
  176. }
  177. // Build base certificate with the key and some random values
  178. cert := &ssh.Certificate{
  179. Nonce: []byte(nonce),
  180. Key: key,
  181. Serial: serial,
  182. }
  183. // Use opts to modify the certificate
  184. if err := opts.Modify(cert); err != nil {
  185. return nil, &apiError{err: err, code: http.StatusForbidden}
  186. }
  187. // Use provisioner modifiers
  188. for _, m := range mods {
  189. if err := m.Modify(cert); err != nil {
  190. return nil, &apiError{err: err, code: http.StatusForbidden}
  191. }
  192. }
  193. // Get signer from authority keys
  194. var signer ssh.Signer
  195. switch cert.CertType {
  196. case ssh.UserCert:
  197. if a.sshCAUserCertSignKey == nil {
  198. return nil, &apiError{
  199. err: errors.New("signSSH: user certificate signing is not enabled"),
  200. code: http.StatusNotImplemented,
  201. }
  202. }
  203. signer = a.sshCAUserCertSignKey
  204. case ssh.HostCert:
  205. if a.sshCAHostCertSignKey == nil {
  206. return nil, &apiError{
  207. err: errors.New("signSSH: host certificate signing is not enabled"),
  208. code: http.StatusNotImplemented,
  209. }
  210. }
  211. signer = a.sshCAHostCertSignKey
  212. default:
  213. return nil, &apiError{
  214. err: errors.Errorf("signSSH: unexpected ssh certificate type: %d", cert.CertType),
  215. code: http.StatusInternalServerError,
  216. }
  217. }
  218. cert.SignatureKey = signer.PublicKey()
  219. // Get bytes for signing trailing the signature length.
  220. data := cert.Marshal()
  221. data = data[:len(data)-4]
  222. // Sign the certificate
  223. sig, err := signer.Sign(rand.Reader, data)
  224. if err != nil {
  225. return nil, &apiError{
  226. err: errors.Wrap(err, "signSSH: error signing certificate"),
  227. code: http.StatusInternalServerError,
  228. }
  229. }
  230. cert.Signature = sig
  231. // User provisioners validators
  232. for _, v := range validators {
  233. if err := v.Valid(cert); err != nil {
  234. return nil, &apiError{err: err, code: http.StatusForbidden}
  235. }
  236. }
  237. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  238. return nil, &apiError{
  239. err: errors.Wrap(err, "signSSH: error storing certificate in db"),
  240. code: http.StatusInternalServerError,
  241. }
  242. }
  243. return cert, nil
  244. }
  245. // SignSSHAddUser signs a certificate that provisions a new user in a server.
  246. func (a *Authority) SignSSHAddUser(key ssh.PublicKey, subject *ssh.Certificate) (*ssh.Certificate, error) {
  247. if a.sshCAUserCertSignKey == nil {
  248. return nil, &apiError{
  249. err: errors.New("signSSHAddUser: user certificate signing is not enabled"),
  250. code: http.StatusNotImplemented,
  251. }
  252. }
  253. if subject.CertType != ssh.UserCert {
  254. return nil, &apiError{
  255. err: errors.New("signSSHAddUser: certificate is not a user certificate"),
  256. code: http.StatusForbidden,
  257. }
  258. }
  259. if len(subject.ValidPrincipals) != 1 {
  260. return nil, &apiError{
  261. err: errors.New("signSSHAddUser: certificate does not have only one principal"),
  262. code: http.StatusForbidden,
  263. }
  264. }
  265. nonce, err := randutil.ASCII(32)
  266. if err != nil {
  267. return nil, &apiError{err: err, code: http.StatusInternalServerError}
  268. }
  269. var serial uint64
  270. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  271. return nil, &apiError{
  272. err: errors.Wrap(err, "signSSHAddUser: error reading random number"),
  273. code: http.StatusInternalServerError,
  274. }
  275. }
  276. signer := a.sshCAUserCertSignKey
  277. principal := subject.ValidPrincipals[0]
  278. addUserPrincipal := a.getAddUserPrincipal()
  279. cert := &ssh.Certificate{
  280. Nonce: []byte(nonce),
  281. Key: key,
  282. Serial: serial,
  283. CertType: ssh.UserCert,
  284. KeyId: principal + "-" + addUserPrincipal,
  285. ValidPrincipals: []string{addUserPrincipal},
  286. ValidAfter: subject.ValidAfter,
  287. ValidBefore: subject.ValidBefore,
  288. Permissions: ssh.Permissions{
  289. CriticalOptions: map[string]string{
  290. "force-command": a.getAddUserCommand(principal),
  291. },
  292. },
  293. SignatureKey: signer.PublicKey(),
  294. }
  295. // Get bytes for signing trailing the signature length.
  296. data := cert.Marshal()
  297. data = data[:len(data)-4]
  298. // Sign the certificate
  299. sig, err := signer.Sign(rand.Reader, data)
  300. if err != nil {
  301. return nil, err
  302. }
  303. cert.Signature = sig
  304. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  305. return nil, &apiError{
  306. err: errors.Wrap(err, "signSSHAddUser: error storing certificate in db"),
  307. code: http.StatusInternalServerError,
  308. }
  309. }
  310. return cert, nil
  311. }
  312. // CheckSSHHost checks the given principal has been registered before.
  313. func (a *Authority) CheckSSHHost(principal string) (bool, error) {
  314. exists, err := a.db.IsSSHHost(principal)
  315. if err != nil {
  316. if err == db.ErrNotImplemented {
  317. return false, &apiError{
  318. err: errors.Wrap(err, "checkSSHHost: isSSHHost is not implemented"),
  319. code: http.StatusNotImplemented,
  320. }
  321. }
  322. return false, &apiError{
  323. err: errors.Wrap(err, "checkSSHHost: error checking if hosts exists"),
  324. code: http.StatusInternalServerError,
  325. }
  326. }
  327. return exists, nil
  328. }
  329. func (a *Authority) getAddUserPrincipal() (cmd string) {
  330. if a.config.SSH.AddUserPrincipal == "" {
  331. return SSHAddUserPrincipal
  332. }
  333. return a.config.SSH.AddUserPrincipal
  334. }
  335. func (a *Authority) getAddUserCommand(principal string) string {
  336. var cmd string
  337. if a.config.SSH.AddUserCommand == "" {
  338. cmd = SSHAddUserCommand
  339. } else {
  340. cmd = a.config.SSH.AddUserCommand
  341. }
  342. return strings.Replace(cmd, "<principal>", principal, -1)
  343. }