client.go 15 KB

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