client.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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]: https://tools.ietf.org/html/draft-miller-ssh-agent-00
  11. package agent // import "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/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. "crypto"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  27. "golang.org/x/crypto/ed25519"
  28. )
  29. // SignatureFlags represent additional flags that can be passed to the signature
  30. // requests an defined in [PROTOCOL.agent] section 4.5.1.
  31. type SignatureFlags uint32
  32. // SignatureFlag values as defined in [PROTOCOL.agent] section 5.3.
  33. const (
  34. SignatureFlagReserved SignatureFlags = 1 << iota
  35. SignatureFlagRsaSha256
  36. SignatureFlagRsaSha512
  37. )
  38. // Agent represents the capabilities of an ssh-agent.
  39. type Agent interface {
  40. // List returns the identities known to the agent.
  41. List() ([]*Key, error)
  42. // Sign has the agent sign the data using a protocol 2 key as defined
  43. // in [PROTOCOL.agent] section 2.6.2.
  44. Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error)
  45. // Add adds a private key to the agent.
  46. Add(key AddedKey) error
  47. // Remove removes all identities with the given public key.
  48. Remove(key ssh.PublicKey) error
  49. // RemoveAll removes all identities.
  50. RemoveAll() error
  51. // Lock locks the agent. Sign and Remove will fail, and List will empty an empty list.
  52. Lock(passphrase []byte) error
  53. // Unlock undoes the effect of Lock
  54. Unlock(passphrase []byte) error
  55. // Signers returns signers for all the known keys.
  56. Signers() ([]ssh.Signer, error)
  57. }
  58. type ExtendedAgent interface {
  59. Agent
  60. // SignWithFlags signs like Sign, but allows for additional flags to be sent/received
  61. SignWithFlags(key ssh.PublicKey, data []byte, flags SignatureFlags) (*ssh.Signature, error)
  62. // Extension processes a custom extension request. Standard-compliant agents are not
  63. // required to support any extensions, but this method allows agents to implement
  64. // vendor-specific methods or add experimental features. See [PROTOCOL.agent] section 4.7.
  65. // If agent extensions are unsupported entirely this method MUST return an
  66. // ErrExtensionUnsupported error. Similarly, if just the specific extensionType in
  67. // the request is unsupported by the agent then ErrExtensionUnsupported MUST be
  68. // returned.
  69. //
  70. // In the case of success, since [PROTOCOL.agent] section 4.7 specifies that the contents
  71. // of the response are unspecified (including the type of the message), the complete
  72. // response will be returned as a []byte slice, including the "type" byte of the message.
  73. Extension(extensionType string, contents []byte) ([]byte, error)
  74. }
  75. // ConstraintExtension describes an optional constraint defined by users.
  76. type ConstraintExtension struct {
  77. // ExtensionName consist of a UTF-8 string suffixed by the
  78. // implementation domain following the naming scheme defined
  79. // in Section 4.2 of [RFC4251], e.g. "foo@example.com".
  80. ExtensionName string
  81. // ExtensionDetails contains the actual content of the extended
  82. // constraint.
  83. ExtensionDetails []byte
  84. }
  85. // AddedKey describes an SSH key to be added to an Agent.
  86. type AddedKey struct {
  87. // PrivateKey must be a *rsa.PrivateKey, *dsa.PrivateKey,
  88. // ed25519.PrivateKey or *ecdsa.PrivateKey, which will be inserted into the
  89. // agent.
  90. PrivateKey interface{}
  91. // Certificate, if not nil, is communicated to the agent and will be
  92. // stored with the key.
  93. Certificate *ssh.Certificate
  94. // Comment is an optional, free-form string.
  95. Comment string
  96. // LifetimeSecs, if not zero, is the number of seconds that the
  97. // agent will store the key for.
  98. LifetimeSecs uint32
  99. // ConfirmBeforeUse, if true, requests that the agent confirm with the
  100. // user before each use of this key.
  101. ConfirmBeforeUse bool
  102. // ConstraintExtensions are the experimental or private-use constraints
  103. // defined by users.
  104. ConstraintExtensions []ConstraintExtension
  105. }
  106. // See [PROTOCOL.agent], section 3.
  107. const (
  108. agentRequestV1Identities = 1
  109. agentRemoveAllV1Identities = 9
  110. // 3.2 Requests from client to agent for protocol 2 key operations
  111. agentAddIdentity = 17
  112. agentRemoveIdentity = 18
  113. agentRemoveAllIdentities = 19
  114. agentAddIDConstrained = 25
  115. // 3.3 Key-type independent requests from client to agent
  116. agentAddSmartcardKey = 20
  117. agentRemoveSmartcardKey = 21
  118. agentLock = 22
  119. agentUnlock = 23
  120. agentAddSmartcardKeyConstrained = 26
  121. // 3.7 Key constraint identifiers
  122. agentConstrainLifetime = 1
  123. agentConstrainConfirm = 2
  124. agentConstrainExtension = 3
  125. )
  126. // maxAgentResponseBytes is the maximum agent reply size that is accepted. This
  127. // is a sanity check, not a limit in the spec.
  128. const maxAgentResponseBytes = 16 << 20
  129. // Agent messages:
  130. // These structures mirror the wire format of the corresponding ssh agent
  131. // messages found in [PROTOCOL.agent].
  132. // 3.4 Generic replies from agent to client
  133. const agentFailure = 5
  134. type failureAgentMsg struct{}
  135. const agentSuccess = 6
  136. type successAgentMsg struct{}
  137. // See [PROTOCOL.agent], section 2.5.2.
  138. const agentRequestIdentities = 11
  139. type requestIdentitiesAgentMsg struct{}
  140. // See [PROTOCOL.agent], section 2.5.2.
  141. const agentIdentitiesAnswer = 12
  142. type identitiesAnswerAgentMsg struct {
  143. NumKeys uint32 `sshtype:"12"`
  144. Keys []byte `ssh:"rest"`
  145. }
  146. // See [PROTOCOL.agent], section 2.6.2.
  147. const agentSignRequest = 13
  148. type signRequestAgentMsg struct {
  149. KeyBlob []byte `sshtype:"13"`
  150. Data []byte
  151. Flags uint32
  152. }
  153. // See [PROTOCOL.agent], section 2.6.2.
  154. // 3.6 Replies from agent to client for protocol 2 key operations
  155. const agentSignResponse = 14
  156. type signResponseAgentMsg struct {
  157. SigBlob []byte `sshtype:"14"`
  158. }
  159. type publicKey struct {
  160. Format string
  161. Rest []byte `ssh:"rest"`
  162. }
  163. // 3.7 Key constraint identifiers
  164. type constrainLifetimeAgentMsg struct {
  165. LifetimeSecs uint32 `sshtype:"1"`
  166. }
  167. type constrainExtensionAgentMsg struct {
  168. ExtensionName string `sshtype:"3"`
  169. ExtensionDetails []byte
  170. // Rest is a field used for parsing, not part of message
  171. Rest []byte `ssh:"rest"`
  172. }
  173. // See [PROTOCOL.agent], section 4.7
  174. const agentExtension = 27
  175. const agentExtensionFailure = 28
  176. // ErrExtensionUnsupported indicates that an extension defined in
  177. // [PROTOCOL.agent] section 4.7 is unsupported by the agent. Specifically this
  178. // error indicates that the agent returned a standard SSH_AGENT_FAILURE message
  179. // as the result of a SSH_AGENTC_EXTENSION request. Note that the protocol
  180. // specification (and therefore this error) does not distinguish between a
  181. // specific extension being unsupported and extensions being unsupported entirely.
  182. var ErrExtensionUnsupported = errors.New("agent: extension unsupported")
  183. type extensionAgentMsg struct {
  184. ExtensionType string `sshtype:"27"`
  185. Contents []byte
  186. }
  187. // Key represents a protocol 2 public key as defined in
  188. // [PROTOCOL.agent], section 2.5.2.
  189. type Key struct {
  190. Format string
  191. Blob []byte
  192. Comment string
  193. }
  194. func clientErr(err error) error {
  195. return fmt.Errorf("agent: client error: %v", err)
  196. }
  197. // String returns the storage form of an agent key with the format, base64
  198. // encoded serialized key, and the comment if it is not empty.
  199. func (k *Key) String() string {
  200. s := string(k.Format) + " " + base64.StdEncoding.EncodeToString(k.Blob)
  201. if k.Comment != "" {
  202. s += " " + k.Comment
  203. }
  204. return s
  205. }
  206. // Type returns the public key type.
  207. func (k *Key) Type() string {
  208. return k.Format
  209. }
  210. // Marshal returns key blob to satisfy the ssh.PublicKey interface.
  211. func (k *Key) Marshal() []byte {
  212. return k.Blob
  213. }
  214. // Verify satisfies the ssh.PublicKey interface.
  215. func (k *Key) Verify(data []byte, sig *ssh.Signature) error {
  216. pubKey, err := ssh.ParsePublicKey(k.Blob)
  217. if err != nil {
  218. return fmt.Errorf("agent: bad public key: %v", err)
  219. }
  220. return pubKey.Verify(data, sig)
  221. }
  222. type wireKey struct {
  223. Format string
  224. Rest []byte `ssh:"rest"`
  225. }
  226. func parseKey(in []byte) (out *Key, rest []byte, err error) {
  227. var record struct {
  228. Blob []byte
  229. Comment string
  230. Rest []byte `ssh:"rest"`
  231. }
  232. if err := ssh.Unmarshal(in, &record); err != nil {
  233. return nil, nil, err
  234. }
  235. var wk wireKey
  236. if err := ssh.Unmarshal(record.Blob, &wk); err != nil {
  237. return nil, nil, err
  238. }
  239. return &Key{
  240. Format: wk.Format,
  241. Blob: record.Blob,
  242. Comment: record.Comment,
  243. }, record.Rest, nil
  244. }
  245. // client is a client for an ssh-agent process.
  246. type client struct {
  247. // conn is typically a *net.UnixConn
  248. conn io.ReadWriter
  249. // mu is used to prevent concurrent access to the agent
  250. mu sync.Mutex
  251. }
  252. // NewClient returns an Agent that talks to an ssh-agent process over
  253. // the given connection.
  254. func NewClient(rw io.ReadWriter) ExtendedAgent {
  255. return &client{conn: rw}
  256. }
  257. // call sends an RPC to the agent. On success, the reply is
  258. // unmarshaled into reply and replyType is set to the first byte of
  259. // the reply, which contains the type of the message.
  260. func (c *client) call(req []byte) (reply interface{}, err error) {
  261. buf, err := c.callRaw(req)
  262. if err != nil {
  263. return nil, err
  264. }
  265. reply, err = unmarshal(buf)
  266. if err != nil {
  267. return nil, clientErr(err)
  268. }
  269. return reply, nil
  270. }
  271. // callRaw sends an RPC to the agent. On success, the raw
  272. // bytes of the response are returned; no unmarshalling is
  273. // performed on the response.
  274. func (c *client) callRaw(req []byte) (reply []byte, err error) {
  275. c.mu.Lock()
  276. defer c.mu.Unlock()
  277. msg := make([]byte, 4+len(req))
  278. binary.BigEndian.PutUint32(msg, uint32(len(req)))
  279. copy(msg[4:], req)
  280. if _, err = c.conn.Write(msg); err != nil {
  281. return nil, clientErr(err)
  282. }
  283. var respSizeBuf [4]byte
  284. if _, err = io.ReadFull(c.conn, respSizeBuf[:]); err != nil {
  285. return nil, clientErr(err)
  286. }
  287. respSize := binary.BigEndian.Uint32(respSizeBuf[:])
  288. if respSize > maxAgentResponseBytes {
  289. return nil, clientErr(errors.New("response too large"))
  290. }
  291. buf := make([]byte, respSize)
  292. if _, err = io.ReadFull(c.conn, buf); err != nil {
  293. return nil, clientErr(err)
  294. }
  295. return buf, nil
  296. }
  297. func (c *client) simpleCall(req []byte) error {
  298. resp, err := c.call(req)
  299. if err != nil {
  300. return err
  301. }
  302. if _, ok := resp.(*successAgentMsg); ok {
  303. return nil
  304. }
  305. return errors.New("agent: failure")
  306. }
  307. func (c *client) RemoveAll() error {
  308. return c.simpleCall([]byte{agentRemoveAllIdentities})
  309. }
  310. func (c *client) Remove(key ssh.PublicKey) error {
  311. req := ssh.Marshal(&agentRemoveIdentityMsg{
  312. KeyBlob: key.Marshal(),
  313. })
  314. return c.simpleCall(req)
  315. }
  316. func (c *client) Lock(passphrase []byte) error {
  317. req := ssh.Marshal(&agentLockMsg{
  318. Passphrase: passphrase,
  319. })
  320. return c.simpleCall(req)
  321. }
  322. func (c *client) Unlock(passphrase []byte) error {
  323. req := ssh.Marshal(&agentUnlockMsg{
  324. Passphrase: passphrase,
  325. })
  326. return c.simpleCall(req)
  327. }
  328. // List returns the identities known to the agent.
  329. func (c *client) List() ([]*Key, error) {
  330. // see [PROTOCOL.agent] section 2.5.2.
  331. req := []byte{agentRequestIdentities}
  332. msg, err := c.call(req)
  333. if err != nil {
  334. return nil, err
  335. }
  336. switch msg := msg.(type) {
  337. case *identitiesAnswerAgentMsg:
  338. if msg.NumKeys > maxAgentResponseBytes/8 {
  339. return nil, errors.New("agent: too many keys in agent reply")
  340. }
  341. keys := make([]*Key, msg.NumKeys)
  342. data := msg.Keys
  343. for i := uint32(0); i < msg.NumKeys; i++ {
  344. var key *Key
  345. var err error
  346. if key, data, err = parseKey(data); err != nil {
  347. return nil, err
  348. }
  349. keys[i] = key
  350. }
  351. return keys, nil
  352. case *failureAgentMsg:
  353. return nil, errors.New("agent: failed to list keys")
  354. }
  355. panic("unreachable")
  356. }
  357. // Sign has the agent sign the data using a protocol 2 key as defined
  358. // in [PROTOCOL.agent] section 2.6.2.
  359. func (c *client) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {
  360. return c.SignWithFlags(key, data, 0)
  361. }
  362. func (c *client) SignWithFlags(key ssh.PublicKey, data []byte, flags SignatureFlags) (*ssh.Signature, error) {
  363. req := ssh.Marshal(signRequestAgentMsg{
  364. KeyBlob: key.Marshal(),
  365. Data: data,
  366. Flags: uint32(flags),
  367. })
  368. msg, err := c.call(req)
  369. if err != nil {
  370. return nil, err
  371. }
  372. switch msg := msg.(type) {
  373. case *signResponseAgentMsg:
  374. var sig ssh.Signature
  375. if err := ssh.Unmarshal(msg.SigBlob, &sig); err != nil {
  376. return nil, err
  377. }
  378. return &sig, nil
  379. case *failureAgentMsg:
  380. return nil, errors.New("agent: failed to sign challenge")
  381. }
  382. panic("unreachable")
  383. }
  384. // unmarshal parses an agent message in packet, returning the parsed
  385. // form and the message type of packet.
  386. func unmarshal(packet []byte) (interface{}, error) {
  387. if len(packet) < 1 {
  388. return nil, errors.New("agent: empty packet")
  389. }
  390. var msg interface{}
  391. switch packet[0] {
  392. case agentFailure:
  393. return new(failureAgentMsg), nil
  394. case agentSuccess:
  395. return new(successAgentMsg), nil
  396. case agentIdentitiesAnswer:
  397. msg = new(identitiesAnswerAgentMsg)
  398. case agentSignResponse:
  399. msg = new(signResponseAgentMsg)
  400. case agentV1IdentitiesAnswer:
  401. msg = new(agentV1IdentityMsg)
  402. default:
  403. return nil, fmt.Errorf("agent: unknown type tag %d", packet[0])
  404. }
  405. if err := ssh.Unmarshal(packet, msg); err != nil {
  406. return nil, err
  407. }
  408. return msg, nil
  409. }
  410. type rsaKeyMsg struct {
  411. Type string `sshtype:"17|25"`
  412. N *big.Int
  413. E *big.Int
  414. D *big.Int
  415. Iqmp *big.Int // IQMP = Inverse Q Mod P
  416. P *big.Int
  417. Q *big.Int
  418. Comments string
  419. Constraints []byte `ssh:"rest"`
  420. }
  421. type dsaKeyMsg struct {
  422. Type string `sshtype:"17|25"`
  423. P *big.Int
  424. Q *big.Int
  425. G *big.Int
  426. Y *big.Int
  427. X *big.Int
  428. Comments string
  429. Constraints []byte `ssh:"rest"`
  430. }
  431. type ecdsaKeyMsg struct {
  432. Type string `sshtype:"17|25"`
  433. Curve string
  434. KeyBytes []byte
  435. D *big.Int
  436. Comments string
  437. Constraints []byte `ssh:"rest"`
  438. }
  439. type ed25519KeyMsg struct {
  440. Type string `sshtype:"17|25"`
  441. Pub []byte
  442. Priv []byte
  443. Comments string
  444. Constraints []byte `ssh:"rest"`
  445. }
  446. // Insert adds a private key to the agent.
  447. func (c *client) insertKey(s interface{}, comment string, constraints []byte) error {
  448. var req []byte
  449. switch k := s.(type) {
  450. case *rsa.PrivateKey:
  451. if len(k.Primes) != 2 {
  452. return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes))
  453. }
  454. k.Precompute()
  455. req = ssh.Marshal(rsaKeyMsg{
  456. Type: ssh.KeyAlgoRSA,
  457. N: k.N,
  458. E: big.NewInt(int64(k.E)),
  459. D: k.D,
  460. Iqmp: k.Precomputed.Qinv,
  461. P: k.Primes[0],
  462. Q: k.Primes[1],
  463. Comments: comment,
  464. Constraints: constraints,
  465. })
  466. case *dsa.PrivateKey:
  467. req = ssh.Marshal(dsaKeyMsg{
  468. Type: ssh.KeyAlgoDSA,
  469. P: k.P,
  470. Q: k.Q,
  471. G: k.G,
  472. Y: k.Y,
  473. X: k.X,
  474. Comments: comment,
  475. Constraints: constraints,
  476. })
  477. case *ecdsa.PrivateKey:
  478. nistID := fmt.Sprintf("nistp%d", k.Params().BitSize)
  479. req = ssh.Marshal(ecdsaKeyMsg{
  480. Type: "ecdsa-sha2-" + nistID,
  481. Curve: nistID,
  482. KeyBytes: elliptic.Marshal(k.Curve, k.X, k.Y),
  483. D: k.D,
  484. Comments: comment,
  485. Constraints: constraints,
  486. })
  487. case ed25519.PrivateKey:
  488. req = ssh.Marshal(ed25519KeyMsg{
  489. Type: ssh.KeyAlgoED25519,
  490. Pub: []byte(k)[32:],
  491. Priv: []byte(k),
  492. Comments: comment,
  493. Constraints: constraints,
  494. })
  495. // This function originally supported only *ed25519.PrivateKey, however the
  496. // general idiom is to pass ed25519.PrivateKey by value, not by pointer.
  497. // We still support the pointer variant for backwards compatibility.
  498. case *ed25519.PrivateKey:
  499. req = ssh.Marshal(ed25519KeyMsg{
  500. Type: ssh.KeyAlgoED25519,
  501. Pub: []byte(*k)[32:],
  502. Priv: []byte(*k),
  503. Comments: comment,
  504. Constraints: constraints,
  505. })
  506. default:
  507. return fmt.Errorf("agent: unsupported key type %T", s)
  508. }
  509. // if constraints are present then the message type needs to be changed.
  510. if len(constraints) != 0 {
  511. req[0] = agentAddIDConstrained
  512. }
  513. resp, err := c.call(req)
  514. if err != nil {
  515. return err
  516. }
  517. if _, ok := resp.(*successAgentMsg); ok {
  518. return nil
  519. }
  520. return errors.New("agent: failure")
  521. }
  522. type rsaCertMsg struct {
  523. Type string `sshtype:"17|25"`
  524. CertBytes []byte
  525. D *big.Int
  526. Iqmp *big.Int // IQMP = Inverse Q Mod P
  527. P *big.Int
  528. Q *big.Int
  529. Comments string
  530. Constraints []byte `ssh:"rest"`
  531. }
  532. type dsaCertMsg struct {
  533. Type string `sshtype:"17|25"`
  534. CertBytes []byte
  535. X *big.Int
  536. Comments string
  537. Constraints []byte `ssh:"rest"`
  538. }
  539. type ecdsaCertMsg struct {
  540. Type string `sshtype:"17|25"`
  541. CertBytes []byte
  542. D *big.Int
  543. Comments string
  544. Constraints []byte `ssh:"rest"`
  545. }
  546. type ed25519CertMsg struct {
  547. Type string `sshtype:"17|25"`
  548. CertBytes []byte
  549. Pub []byte
  550. Priv []byte
  551. Comments string
  552. Constraints []byte `ssh:"rest"`
  553. }
  554. // Add adds a private key to the agent. If a certificate is given,
  555. // that certificate is added instead as public key.
  556. func (c *client) Add(key AddedKey) error {
  557. var constraints []byte
  558. if secs := key.LifetimeSecs; secs != 0 {
  559. constraints = append(constraints, ssh.Marshal(constrainLifetimeAgentMsg{secs})...)
  560. }
  561. if key.ConfirmBeforeUse {
  562. constraints = append(constraints, agentConstrainConfirm)
  563. }
  564. cert := key.Certificate
  565. if cert == nil {
  566. return c.insertKey(key.PrivateKey, key.Comment, constraints)
  567. }
  568. return c.insertCert(key.PrivateKey, cert, key.Comment, constraints)
  569. }
  570. func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string, constraints []byte) error {
  571. var req []byte
  572. switch k := s.(type) {
  573. case *rsa.PrivateKey:
  574. if len(k.Primes) != 2 {
  575. return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes))
  576. }
  577. k.Precompute()
  578. req = ssh.Marshal(rsaCertMsg{
  579. Type: cert.Type(),
  580. CertBytes: cert.Marshal(),
  581. D: k.D,
  582. Iqmp: k.Precomputed.Qinv,
  583. P: k.Primes[0],
  584. Q: k.Primes[1],
  585. Comments: comment,
  586. Constraints: constraints,
  587. })
  588. case *dsa.PrivateKey:
  589. req = ssh.Marshal(dsaCertMsg{
  590. Type: cert.Type(),
  591. CertBytes: cert.Marshal(),
  592. X: k.X,
  593. Comments: comment,
  594. Constraints: constraints,
  595. })
  596. case *ecdsa.PrivateKey:
  597. req = ssh.Marshal(ecdsaCertMsg{
  598. Type: cert.Type(),
  599. CertBytes: cert.Marshal(),
  600. D: k.D,
  601. Comments: comment,
  602. Constraints: constraints,
  603. })
  604. case ed25519.PrivateKey:
  605. req = ssh.Marshal(ed25519CertMsg{
  606. Type: cert.Type(),
  607. CertBytes: cert.Marshal(),
  608. Pub: []byte(k)[32:],
  609. Priv: []byte(k),
  610. Comments: comment,
  611. Constraints: constraints,
  612. })
  613. // This function originally supported only *ed25519.PrivateKey, however the
  614. // general idiom is to pass ed25519.PrivateKey by value, not by pointer.
  615. // We still support the pointer variant for backwards compatibility.
  616. case *ed25519.PrivateKey:
  617. req = ssh.Marshal(ed25519CertMsg{
  618. Type: cert.Type(),
  619. CertBytes: cert.Marshal(),
  620. Pub: []byte(*k)[32:],
  621. Priv: []byte(*k),
  622. Comments: comment,
  623. Constraints: constraints,
  624. })
  625. default:
  626. return fmt.Errorf("agent: unsupported key type %T", s)
  627. }
  628. // if constraints are present then the message type needs to be changed.
  629. if len(constraints) != 0 {
  630. req[0] = agentAddIDConstrained
  631. }
  632. signer, err := ssh.NewSignerFromKey(s)
  633. if err != nil {
  634. return err
  635. }
  636. if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 {
  637. return errors.New("agent: signer and cert have different public key")
  638. }
  639. resp, err := c.call(req)
  640. if err != nil {
  641. return err
  642. }
  643. if _, ok := resp.(*successAgentMsg); ok {
  644. return nil
  645. }
  646. return errors.New("agent: failure")
  647. }
  648. // Signers provides a callback for client authentication.
  649. func (c *client) Signers() ([]ssh.Signer, error) {
  650. keys, err := c.List()
  651. if err != nil {
  652. return nil, err
  653. }
  654. var result []ssh.Signer
  655. for _, k := range keys {
  656. result = append(result, &agentKeyringSigner{c, k})
  657. }
  658. return result, nil
  659. }
  660. type agentKeyringSigner struct {
  661. agent *client
  662. pub ssh.PublicKey
  663. }
  664. func (s *agentKeyringSigner) PublicKey() ssh.PublicKey {
  665. return s.pub
  666. }
  667. func (s *agentKeyringSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
  668. // The agent has its own entropy source, so the rand argument is ignored.
  669. return s.agent.Sign(s.pub, data)
  670. }
  671. func (s *agentKeyringSigner) SignWithOpts(rand io.Reader, data []byte, opts crypto.SignerOpts) (*ssh.Signature, error) {
  672. var flags SignatureFlags
  673. if opts != nil {
  674. switch opts.HashFunc() {
  675. case crypto.SHA256:
  676. flags = SignatureFlagRsaSha256
  677. case crypto.SHA512:
  678. flags = SignatureFlagRsaSha512
  679. }
  680. }
  681. return s.agent.SignWithFlags(s.pub, data, flags)
  682. }
  683. // Calls an extension method. It is up to the agent implementation as to whether or not
  684. // any particular extension is supported and may always return an error. Because the
  685. // type of the response is up to the implementation, this returns the bytes of the
  686. // response and does not attempt any type of unmarshalling.
  687. func (c *client) Extension(extensionType string, contents []byte) ([]byte, error) {
  688. req := ssh.Marshal(extensionAgentMsg{
  689. ExtensionType: extensionType,
  690. Contents: contents,
  691. })
  692. buf, err := c.callRaw(req)
  693. if err != nil {
  694. return nil, err
  695. }
  696. if len(buf) == 0 {
  697. return nil, errors.New("agent: failure; empty response")
  698. }
  699. // [PROTOCOL.agent] section 4.7 indicates that an SSH_AGENT_FAILURE message
  700. // represents an agent that does not support the extension
  701. if buf[0] == agentFailure {
  702. return nil, ErrExtensionUnsupported
  703. }
  704. if buf[0] == agentExtensionFailure {
  705. return nil, errors.New("agent: generic extension failure")
  706. }
  707. return buf, nil
  708. }