client.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package agent implements the ssh-agent protocol, and provides both
  5. // a client and a server. The client can talk to a standard ssh-agent
  6. // that uses UNIX sockets, and one could implement an alternative
  7. // ssh-agent process using the sample server.
  8. //
  9. // References:
  10. // [PROTOCOL.agent]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent?rev=HEAD
  11. package agent // import "golang.org/x/crypto/ssh/agent"
  12. import (
  13. "bytes"
  14. "crypto/dsa"
  15. "crypto/ecdsa"
  16. "crypto/elliptic"
  17. "crypto/rsa"
  18. "encoding/base64"
  19. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "math/big"
  24. "sync"
  25. "golang.org/x/crypto/ssh"
  26. )
  27. // Agent represents the capabilities of an ssh-agent.
  28. type Agent interface {
  29. // List returns the identities known to the agent.
  30. List() ([]*Key, error)
  31. // Sign has the agent sign the data using a protocol 2 key as defined
  32. // in [PROTOCOL.agent] section 2.6.2.
  33. Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error)
  34. // Add adds a private key to the agent.
  35. Add(key AddedKey) error
  36. // Remove removes all identities with the given public key.
  37. Remove(key ssh.PublicKey) error
  38. // RemoveAll removes all identities.
  39. RemoveAll() error
  40. // Lock locks the agent. Sign and Remove will fail, and List will empty an empty list.
  41. Lock(passphrase []byte) error
  42. // Unlock undoes the effect of Lock
  43. Unlock(passphrase []byte) error
  44. // Signers returns signers for all the known keys.
  45. Signers() ([]ssh.Signer, error)
  46. }
  47. // AddedKey describes an SSH key to be added to an Agent.
  48. type AddedKey struct {
  49. // PrivateKey must be a *rsa.PrivateKey, *dsa.PrivateKey or
  50. // *ecdsa.PrivateKey, which will be inserted into the agent.
  51. PrivateKey interface{}
  52. // Certificate, if not nil, is communicated to the agent and will be
  53. // stored with the key.
  54. Certificate *ssh.Certificate
  55. // Comment is an optional, free-form string.
  56. Comment string
  57. // LifetimeSecs, if not zero, is the number of seconds that the
  58. // agent will store the key for.
  59. LifetimeSecs uint32
  60. // ConfirmBeforeUse, if true, requests that the agent confirm with the
  61. // user before each use of this key.
  62. ConfirmBeforeUse bool
  63. }
  64. // See [PROTOCOL.agent], section 3.
  65. const (
  66. agentRequestV1Identities = 1
  67. // 3.2 Requests from client to agent for protocol 2 key operations
  68. agentAddIdentity = 17
  69. agentRemoveIdentity = 18
  70. agentRemoveAllIdentities = 19
  71. agentAddIdConstrained = 25
  72. // 3.3 Key-type independent requests from client to agent
  73. agentAddSmartcardKey = 20
  74. agentRemoveSmartcardKey = 21
  75. agentLock = 22
  76. agentUnlock = 23
  77. agentAddSmartcardKeyConstrained = 26
  78. // 3.7 Key constraint identifiers
  79. agentConstrainLifetime = 1
  80. agentConstrainConfirm = 2
  81. )
  82. // maxAgentResponseBytes is the maximum agent reply size that is accepted. This
  83. // is a sanity check, not a limit in the spec.
  84. const maxAgentResponseBytes = 16 << 20
  85. // Agent messages:
  86. // These structures mirror the wire format of the corresponding ssh agent
  87. // messages found in [PROTOCOL.agent].
  88. // 3.4 Generic replies from agent to client
  89. const agentFailure = 5
  90. type failureAgentMsg struct{}
  91. const agentSuccess = 6
  92. type successAgentMsg struct{}
  93. // See [PROTOCOL.agent], section 2.5.2.
  94. const agentRequestIdentities = 11
  95. type requestIdentitiesAgentMsg struct{}
  96. // See [PROTOCOL.agent], section 2.5.2.
  97. const agentIdentitiesAnswer = 12
  98. type identitiesAnswerAgentMsg struct {
  99. NumKeys uint32 `sshtype:"12"`
  100. Keys []byte `ssh:"rest"`
  101. }
  102. // See [PROTOCOL.agent], section 2.6.2.
  103. const agentSignRequest = 13
  104. type signRequestAgentMsg struct {
  105. KeyBlob []byte `sshtype:"13"`
  106. Data []byte
  107. Flags uint32
  108. }
  109. // See [PROTOCOL.agent], section 2.6.2.
  110. // 3.6 Replies from agent to client for protocol 2 key operations
  111. const agentSignResponse = 14
  112. type signResponseAgentMsg struct {
  113. SigBlob []byte `sshtype:"14"`
  114. }
  115. type publicKey struct {
  116. Format string
  117. Rest []byte `ssh:"rest"`
  118. }
  119. // Key represents a protocol 2 public key as defined in
  120. // [PROTOCOL.agent], section 2.5.2.
  121. type Key struct {
  122. Format string
  123. Blob []byte
  124. Comment string
  125. }
  126. func clientErr(err error) error {
  127. return fmt.Errorf("agent: client error: %v", err)
  128. }
  129. // String returns the storage form of an agent key with the format, base64
  130. // encoded serialized key, and the comment if it is not empty.
  131. func (k *Key) String() string {
  132. s := string(k.Format) + " " + base64.StdEncoding.EncodeToString(k.Blob)
  133. if k.Comment != "" {
  134. s += " " + k.Comment
  135. }
  136. return s
  137. }
  138. // Type returns the public key type.
  139. func (k *Key) Type() string {
  140. return k.Format
  141. }
  142. // Marshal returns key blob to satisfy the ssh.PublicKey interface.
  143. func (k *Key) Marshal() []byte {
  144. return k.Blob
  145. }
  146. // Verify satisfies the ssh.PublicKey interface, but is not
  147. // implemented for agent keys.
  148. func (k *Key) Verify(data []byte, sig *ssh.Signature) error {
  149. return errors.New("agent: agent key does not know how to verify")
  150. }
  151. type wireKey struct {
  152. Format string
  153. Rest []byte `ssh:"rest"`
  154. }
  155. func parseKey(in []byte) (out *Key, rest []byte, err error) {
  156. var record struct {
  157. Blob []byte
  158. Comment string
  159. Rest []byte `ssh:"rest"`
  160. }
  161. if err := ssh.Unmarshal(in, &record); err != nil {
  162. return nil, nil, err
  163. }
  164. var wk wireKey
  165. if err := ssh.Unmarshal(record.Blob, &wk); err != nil {
  166. return nil, nil, err
  167. }
  168. return &Key{
  169. Format: wk.Format,
  170. Blob: record.Blob,
  171. Comment: record.Comment,
  172. }, record.Rest, nil
  173. }
  174. // client is a client for an ssh-agent process.
  175. type client struct {
  176. // conn is typically a *net.UnixConn
  177. conn io.ReadWriter
  178. // mu is used to prevent concurrent access to the agent
  179. mu sync.Mutex
  180. }
  181. // NewClient returns an Agent that talks to an ssh-agent process over
  182. // the given connection.
  183. func NewClient(rw io.ReadWriter) Agent {
  184. return &client{conn: rw}
  185. }
  186. // call sends an RPC to the agent. On success, the reply is
  187. // unmarshaled into reply and replyType is set to the first byte of
  188. // the reply, which contains the type of the message.
  189. func (c *client) call(req []byte) (reply interface{}, err error) {
  190. c.mu.Lock()
  191. defer c.mu.Unlock()
  192. msg := make([]byte, 4+len(req))
  193. binary.BigEndian.PutUint32(msg, uint32(len(req)))
  194. copy(msg[4:], req)
  195. if _, err = c.conn.Write(msg); err != nil {
  196. return nil, clientErr(err)
  197. }
  198. var respSizeBuf [4]byte
  199. if _, err = io.ReadFull(c.conn, respSizeBuf[:]); err != nil {
  200. return nil, clientErr(err)
  201. }
  202. respSize := binary.BigEndian.Uint32(respSizeBuf[:])
  203. if respSize > maxAgentResponseBytes {
  204. return nil, clientErr(err)
  205. }
  206. buf := make([]byte, respSize)
  207. if _, err = io.ReadFull(c.conn, buf); err != nil {
  208. return nil, clientErr(err)
  209. }
  210. reply, err = unmarshal(buf)
  211. if err != nil {
  212. return nil, clientErr(err)
  213. }
  214. return reply, err
  215. }
  216. func (c *client) simpleCall(req []byte) error {
  217. resp, err := c.call(req)
  218. if err != nil {
  219. return err
  220. }
  221. if _, ok := resp.(*successAgentMsg); ok {
  222. return nil
  223. }
  224. return errors.New("agent: failure")
  225. }
  226. func (c *client) RemoveAll() error {
  227. return c.simpleCall([]byte{agentRemoveAllIdentities})
  228. }
  229. func (c *client) Remove(key ssh.PublicKey) error {
  230. req := ssh.Marshal(&agentRemoveIdentityMsg{
  231. KeyBlob: key.Marshal(),
  232. })
  233. return c.simpleCall(req)
  234. }
  235. func (c *client) Lock(passphrase []byte) error {
  236. req := ssh.Marshal(&agentLockMsg{
  237. Passphrase: passphrase,
  238. })
  239. return c.simpleCall(req)
  240. }
  241. func (c *client) Unlock(passphrase []byte) error {
  242. req := ssh.Marshal(&agentUnlockMsg{
  243. Passphrase: passphrase,
  244. })
  245. return c.simpleCall(req)
  246. }
  247. // List returns the identities known to the agent.
  248. func (c *client) List() ([]*Key, error) {
  249. // see [PROTOCOL.agent] section 2.5.2.
  250. req := []byte{agentRequestIdentities}
  251. msg, err := c.call(req)
  252. if err != nil {
  253. return nil, err
  254. }
  255. switch msg := msg.(type) {
  256. case *identitiesAnswerAgentMsg:
  257. if msg.NumKeys > maxAgentResponseBytes/8 {
  258. return nil, errors.New("agent: too many keys in agent reply")
  259. }
  260. keys := make([]*Key, msg.NumKeys)
  261. data := msg.Keys
  262. for i := uint32(0); i < msg.NumKeys; i++ {
  263. var key *Key
  264. var err error
  265. if key, data, err = parseKey(data); err != nil {
  266. return nil, err
  267. }
  268. keys[i] = key
  269. }
  270. return keys, nil
  271. case *failureAgentMsg:
  272. return nil, errors.New("agent: failed to list keys")
  273. }
  274. panic("unreachable")
  275. }
  276. // Sign has the agent sign the data using a protocol 2 key as defined
  277. // in [PROTOCOL.agent] section 2.6.2.
  278. func (c *client) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {
  279. req := ssh.Marshal(signRequestAgentMsg{
  280. KeyBlob: key.Marshal(),
  281. Data: data,
  282. })
  283. msg, err := c.call(req)
  284. if err != nil {
  285. return nil, err
  286. }
  287. switch msg := msg.(type) {
  288. case *signResponseAgentMsg:
  289. var sig ssh.Signature
  290. if err := ssh.Unmarshal(msg.SigBlob, &sig); err != nil {
  291. return nil, err
  292. }
  293. return &sig, nil
  294. case *failureAgentMsg:
  295. return nil, errors.New("agent: failed to sign challenge")
  296. }
  297. panic("unreachable")
  298. }
  299. // unmarshal parses an agent message in packet, returning the parsed
  300. // form and the message type of packet.
  301. func unmarshal(packet []byte) (interface{}, error) {
  302. if len(packet) < 1 {
  303. return nil, errors.New("agent: empty packet")
  304. }
  305. var msg interface{}
  306. switch packet[0] {
  307. case agentFailure:
  308. return new(failureAgentMsg), nil
  309. case agentSuccess:
  310. return new(successAgentMsg), nil
  311. case agentIdentitiesAnswer:
  312. msg = new(identitiesAnswerAgentMsg)
  313. case agentSignResponse:
  314. msg = new(signResponseAgentMsg)
  315. default:
  316. return nil, fmt.Errorf("agent: unknown type tag %d", packet[0])
  317. }
  318. if err := ssh.Unmarshal(packet, msg); err != nil {
  319. return nil, err
  320. }
  321. return msg, nil
  322. }
  323. type rsaKeyMsg struct {
  324. Type string `sshtype:"17"`
  325. N *big.Int
  326. E *big.Int
  327. D *big.Int
  328. Iqmp *big.Int // IQMP = Inverse Q Mod P
  329. P *big.Int
  330. Q *big.Int
  331. Comments string
  332. Constraints []byte `ssh:"rest"`
  333. }
  334. type dsaKeyMsg struct {
  335. Type string `sshtype:"17"`
  336. P *big.Int
  337. Q *big.Int
  338. G *big.Int
  339. Y *big.Int
  340. X *big.Int
  341. Comments string
  342. Constraints []byte `ssh:"rest"`
  343. }
  344. type ecdsaKeyMsg struct {
  345. Type string `sshtype:"17"`
  346. Curve string
  347. KeyBytes []byte
  348. D *big.Int
  349. Comments string
  350. Constraints []byte `ssh:"rest"`
  351. }
  352. // Insert adds a private key to the agent.
  353. func (c *client) insertKey(s interface{}, comment string, constraints []byte) error {
  354. var req []byte
  355. switch k := s.(type) {
  356. case *rsa.PrivateKey:
  357. if len(k.Primes) != 2 {
  358. return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes))
  359. }
  360. k.Precompute()
  361. req = ssh.Marshal(rsaKeyMsg{
  362. Type: ssh.KeyAlgoRSA,
  363. N: k.N,
  364. E: big.NewInt(int64(k.E)),
  365. D: k.D,
  366. Iqmp: k.Precomputed.Qinv,
  367. P: k.Primes[0],
  368. Q: k.Primes[1],
  369. Comments: comment,
  370. Constraints: constraints,
  371. })
  372. case *dsa.PrivateKey:
  373. req = ssh.Marshal(dsaKeyMsg{
  374. Type: ssh.KeyAlgoDSA,
  375. P: k.P,
  376. Q: k.Q,
  377. G: k.G,
  378. Y: k.Y,
  379. X: k.X,
  380. Comments: comment,
  381. Constraints: constraints,
  382. })
  383. case *ecdsa.PrivateKey:
  384. nistID := fmt.Sprintf("nistp%d", k.Params().BitSize)
  385. req = ssh.Marshal(ecdsaKeyMsg{
  386. Type: "ecdsa-sha2-" + nistID,
  387. Curve: nistID,
  388. KeyBytes: elliptic.Marshal(k.Curve, k.X, k.Y),
  389. D: k.D,
  390. Comments: comment,
  391. Constraints: constraints,
  392. })
  393. default:
  394. return fmt.Errorf("agent: unsupported key type %T", s)
  395. }
  396. // if constraints are present then the message type needs to be changed.
  397. if len(constraints) != 0 {
  398. req[0] = agentAddIdConstrained
  399. }
  400. resp, err := c.call(req)
  401. if err != nil {
  402. return err
  403. }
  404. if _, ok := resp.(*successAgentMsg); ok {
  405. return nil
  406. }
  407. return errors.New("agent: failure")
  408. }
  409. type rsaCertMsg struct {
  410. Type string `sshtype:"17"`
  411. CertBytes []byte
  412. D *big.Int
  413. Iqmp *big.Int // IQMP = Inverse Q Mod P
  414. P *big.Int
  415. Q *big.Int
  416. Comments string
  417. Constraints []byte `ssh:"rest"`
  418. }
  419. type dsaCertMsg struct {
  420. Type string `sshtype:"17"`
  421. CertBytes []byte
  422. X *big.Int
  423. Comments string
  424. Constraints []byte `ssh:"rest"`
  425. }
  426. type ecdsaCertMsg struct {
  427. Type string `sshtype:"17"`
  428. CertBytes []byte
  429. D *big.Int
  430. Comments string
  431. Constraints []byte `ssh:"rest"`
  432. }
  433. // Insert adds a private key to the agent. If a certificate is given,
  434. // that certificate is added instead as public key.
  435. func (c *client) Add(key AddedKey) error {
  436. var constraints []byte
  437. if secs := key.LifetimeSecs; secs != 0 {
  438. constraints = append(constraints, agentConstrainLifetime)
  439. var secsBytes [4]byte
  440. binary.BigEndian.PutUint32(secsBytes[:], secs)
  441. constraints = append(constraints, secsBytes[:]...)
  442. }
  443. if key.ConfirmBeforeUse {
  444. constraints = append(constraints, agentConstrainConfirm)
  445. }
  446. if cert := key.Certificate; cert == nil {
  447. return c.insertKey(key.PrivateKey, key.Comment, constraints)
  448. } else {
  449. return c.insertCert(key.PrivateKey, cert, key.Comment, constraints)
  450. }
  451. }
  452. func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string, constraints []byte) error {
  453. var req []byte
  454. switch k := s.(type) {
  455. case *rsa.PrivateKey:
  456. if len(k.Primes) != 2 {
  457. return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes))
  458. }
  459. k.Precompute()
  460. req = ssh.Marshal(rsaCertMsg{
  461. Type: cert.Type(),
  462. CertBytes: cert.Marshal(),
  463. D: k.D,
  464. Iqmp: k.Precomputed.Qinv,
  465. P: k.Primes[0],
  466. Q: k.Primes[1],
  467. Comments: comment,
  468. Constraints: constraints,
  469. })
  470. case *dsa.PrivateKey:
  471. req = ssh.Marshal(dsaCertMsg{
  472. Type: cert.Type(),
  473. CertBytes: cert.Marshal(),
  474. X: k.X,
  475. Comments: comment,
  476. })
  477. case *ecdsa.PrivateKey:
  478. req = ssh.Marshal(ecdsaCertMsg{
  479. Type: cert.Type(),
  480. CertBytes: cert.Marshal(),
  481. D: k.D,
  482. Comments: comment,
  483. })
  484. default:
  485. return fmt.Errorf("agent: unsupported key type %T", s)
  486. }
  487. // if constraints are present then the message type needs to be changed.
  488. if len(constraints) != 0 {
  489. req[0] = agentAddIdConstrained
  490. }
  491. signer, err := ssh.NewSignerFromKey(s)
  492. if err != nil {
  493. return err
  494. }
  495. if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 {
  496. return errors.New("agent: signer and cert have different public key")
  497. }
  498. resp, err := c.call(req)
  499. if err != nil {
  500. return err
  501. }
  502. if _, ok := resp.(*successAgentMsg); ok {
  503. return nil
  504. }
  505. return errors.New("agent: failure")
  506. }
  507. // Signers provides a callback for client authentication.
  508. func (c *client) Signers() ([]ssh.Signer, error) {
  509. keys, err := c.List()
  510. if err != nil {
  511. return nil, err
  512. }
  513. var result []ssh.Signer
  514. for _, k := range keys {
  515. result = append(result, &agentKeyringSigner{c, k})
  516. }
  517. return result, nil
  518. }
  519. type agentKeyringSigner struct {
  520. agent *client
  521. pub ssh.PublicKey
  522. }
  523. func (s *agentKeyringSigner) PublicKey() ssh.PublicKey {
  524. return s.pub
  525. }
  526. func (s *agentKeyringSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
  527. // The agent has its own entropy source, so the rand argument is ignored.
  528. return s.agent.Sign(s.pub, data)
  529. }