client_auth_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Copyright 2011 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 ssh
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/dsa"
  9. "crypto/rsa"
  10. _ "crypto/sha1"
  11. "crypto/x509"
  12. "encoding/pem"
  13. "errors"
  14. "io"
  15. "io/ioutil"
  16. "math/big"
  17. "testing"
  18. )
  19. // private key for mock server
  20. const testServerPrivateKey = `-----BEGIN RSA PRIVATE KEY-----
  21. MIIEpAIBAAKCAQEA19lGVsTqIT5iiNYRgnoY1CwkbETW5cq+Rzk5v/kTlf31XpSU
  22. 70HVWkbTERECjaYdXM2gGcbb+sxpq6GtXf1M3kVomycqhxwhPv4Cr6Xp4WT/jkFx
  23. 9z+FFzpeodGJWjOH6L2H5uX1Cvr9EDdQp9t9/J32/qBFntY8GwoUI/y/1MSTmMiF
  24. tupdMODN064vd3gyMKTwrlQ8tZM6aYuyOPsutLlUY7M5x5FwMDYvnPDSeyT/Iw0z
  25. s3B+NCyqeeMd2T7YzQFnRATj0M7rM5LoSs7DVqVriOEABssFyLj31PboaoLhOKgc
  26. qoM9khkNzr7FHVvi+DhYM2jD0DwvqZLN6NmnLwIDAQABAoIBAQCGVj+kuSFOV1lT
  27. +IclQYA6bM6uY5mroqcSBNegVxCNhWU03BxlW//BE9tA/+kq53vWylMeN9mpGZea
  28. riEMIh25KFGWXqXlOOioH8bkMsqA8S7sBmc7jljyv+0toQ9vCCtJ+sueNPhxQQxH
  29. D2YvUjfzBQ04I9+wn30BByDJ1QA/FoPsunxIOUCcRBE/7jxuLYcpR+JvEF68yYIh
  30. atXRld4W4in7T65YDR8jK1Uj9XAcNeDYNpT/M6oFLx1aPIlkG86aCWRO19S1jLPT
  31. b1ZAKHHxPMCVkSYW0RqvIgLXQOR62D0Zne6/2wtzJkk5UCjkSQ2z7ZzJpMkWgDgN
  32. ifCULFPBAoGBAPoMZ5q1w+zB+knXUD33n1J+niN6TZHJulpf2w5zsW+m2K6Zn62M
  33. MXndXlVAHtk6p02q9kxHdgov34Uo8VpuNjbS1+abGFTI8NZgFo+bsDxJdItemwC4
  34. KJ7L1iz39hRN/ZylMRLz5uTYRGddCkeIHhiG2h7zohH/MaYzUacXEEy3AoGBANz8
  35. e/msleB+iXC0cXKwds26N4hyMdAFE5qAqJXvV3S2W8JZnmU+sS7vPAWMYPlERPk1
  36. D8Q2eXqdPIkAWBhrx4RxD7rNc5qFNcQWEhCIxC9fccluH1y5g2M+4jpMX2CT8Uv+
  37. 3z+NoJ5uDTXZTnLCfoZzgZ4nCZVZ+6iU5U1+YXFJAoGBANLPpIV920n/nJmmquMj
  38. orI1R/QXR9Cy56cMC65agezlGOfTYxk5Cfl5Ve+/2IJCfgzwJyjWUsFx7RviEeGw
  39. 64o7JoUom1HX+5xxdHPsyZ96OoTJ5RqtKKoApnhRMamau0fWydH1yeOEJd+TRHhc
  40. XStGfhz8QNa1dVFvENczja1vAoGABGWhsd4VPVpHMc7lUvrf4kgKQtTC2PjA4xoc
  41. QJ96hf/642sVE76jl+N6tkGMzGjnVm4P2j+bOy1VvwQavKGoXqJBRd5Apppv727g
  42. /SM7hBXKFc/zH80xKBBgP/i1DR7kdjakCoeu4ngeGywvu2jTS6mQsqzkK+yWbUxJ
  43. I7mYBsECgYB/KNXlTEpXtz/kwWCHFSYA8U74l7zZbVD8ul0e56JDK+lLcJ0tJffk
  44. gqnBycHj6AhEycjda75cs+0zybZvN4x65KZHOGW/O/7OAWEcZP5TPb3zf9ned3Hl
  45. NsZoFj52ponUM6+99A2CmezFCN16c4mbA//luWF+k3VVqR6BpkrhKw==
  46. -----END RSA PRIVATE KEY-----`
  47. const testClientPrivateKey = `-----BEGIN RSA PRIVATE KEY-----
  48. MIIBOwIBAAJBALdGZxkXDAjsYk10ihwU6Id2KeILz1TAJuoq4tOgDWxEEGeTrcld
  49. r/ZwVaFzjWzxaf6zQIJbfaSEAhqD5yo72+sCAwEAAQJBAK8PEVU23Wj8mV0QjwcJ
  50. tZ4GcTUYQL7cF4+ezTCE9a1NrGnCP2RuQkHEKxuTVrxXt+6OF15/1/fuXnxKjmJC
  51. nxkCIQDaXvPPBi0c7vAxGwNY9726x01/dNbHCE0CBtcotobxpwIhANbbQbh3JHVW
  52. 2haQh4fAG5mhesZKAGcxTyv4mQ7uMSQdAiAj+4dzMpJWdSzQ+qGHlHMIBvVHLkqB
  53. y2VdEyF7DPCZewIhAI7GOI/6LDIFOvtPo6Bj2nNmyQ1HU6k/LRtNIXi4c9NJAiAr
  54. rrxx26itVhJmcvoUhOjwuzSlP2bE5VHAvkGB352YBg==
  55. -----END RSA PRIVATE KEY-----`
  56. // keychain implements the ClientKeyring interface
  57. type keychain struct {
  58. keys []interface{}
  59. }
  60. func (k *keychain) Key(i int) (interface{}, error) {
  61. if i < 0 || i >= len(k.keys) {
  62. return nil, nil
  63. }
  64. switch key := k.keys[i].(type) {
  65. case *rsa.PrivateKey:
  66. return &key.PublicKey, nil
  67. case *dsa.PrivateKey:
  68. return &key.PublicKey, nil
  69. }
  70. panic("unknown key type")
  71. }
  72. func (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) {
  73. hashFunc := crypto.SHA1
  74. h := hashFunc.New()
  75. h.Write(data)
  76. digest := h.Sum(nil)
  77. switch key := k.keys[i].(type) {
  78. case *rsa.PrivateKey:
  79. return rsa.SignPKCS1v15(rand, key, hashFunc, digest)
  80. }
  81. return nil, errors.New("ssh: unknown key type")
  82. }
  83. func (k *keychain) loadPEM(file string) error {
  84. buf, err := ioutil.ReadFile(file)
  85. if err != nil {
  86. return err
  87. }
  88. block, _ := pem.Decode(buf)
  89. if block == nil {
  90. return errors.New("ssh: no key found")
  91. }
  92. r, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  93. if err != nil {
  94. return err
  95. }
  96. k.keys = append(k.keys, r)
  97. return nil
  98. }
  99. // password implements the ClientPassword interface
  100. type password string
  101. func (p password) Password(user string) (string, error) {
  102. return string(p), nil
  103. }
  104. type keyboardInteractive map[string]string
  105. func (cr *keyboardInteractive) Challenge(user string, instruction string, questions []string, echos []bool) ([]string, error) {
  106. var answers []string
  107. for _, q := range questions {
  108. answers = append(answers, (*cr)[q])
  109. }
  110. return answers, nil
  111. }
  112. // reused internally by tests
  113. var (
  114. rsakey *rsa.PrivateKey
  115. dsakey *dsa.PrivateKey
  116. clientKeychain = new(keychain)
  117. clientPassword = password("tiger")
  118. serverConfig = &ServerConfig{
  119. PasswordCallback: func(conn *ServerConn, user, pass string) bool {
  120. return user == "testuser" && pass == string(clientPassword)
  121. },
  122. PublicKeyCallback: func(conn *ServerConn, user, algo string, pubkey []byte) bool {
  123. key := &clientKeychain.keys[0].(*rsa.PrivateKey).PublicKey
  124. expected := []byte(serializePublickey(key))
  125. algoname := algoName(key)
  126. return user == "testuser" && algo == algoname && bytes.Equal(pubkey, expected)
  127. },
  128. KeyboardInteractiveCallback: func(conn *ServerConn, user string, client ClientKeyboardInteractive) bool {
  129. ans, err := client.Challenge("user",
  130. "instruction",
  131. []string{"question1", "question2"},
  132. []bool{true, true})
  133. if err != nil {
  134. return false
  135. }
  136. ok := user == "testuser" && ans[0] == "answer1" && ans[1] == "answer2"
  137. client.Challenge("user", "motd", nil, nil)
  138. return ok
  139. },
  140. }
  141. )
  142. func init() {
  143. if err := serverConfig.SetRSAPrivateKey([]byte(testServerPrivateKey)); err != nil {
  144. panic("unable to set private key: " + err.Error())
  145. }
  146. block, _ := pem.Decode([]byte(testClientPrivateKey))
  147. rsakey, _ = x509.ParsePKCS1PrivateKey(block.Bytes)
  148. clientKeychain.keys = append(clientKeychain.keys, rsakey)
  149. dsakey = new(dsa.PrivateKey)
  150. // taken from crypto/dsa/dsa_test.go
  151. dsakey.P, _ = new(big.Int).SetString("A9B5B793FB4785793D246BAE77E8FF63CA52F442DA763C440259919FE1BC1D6065A9350637A04F75A2F039401D49F08E066C4D275A5A65DA5684BC563C14289D7AB8A67163BFBF79D85972619AD2CFF55AB0EE77A9002B0EF96293BDD0F42685EBB2C66C327079F6C98000FBCB79AACDE1BC6F9D5C7B1A97E3D9D54ED7951FEF", 16)
  152. dsakey.Q, _ = new(big.Int).SetString("E1D3391245933D68A0714ED34BBCB7A1F422B9C1", 16)
  153. dsakey.G, _ = new(big.Int).SetString("634364FC25248933D01D1993ECABD0657CC0CB2CEED7ED2E3E8AECDFCDC4A25C3B15E9E3B163ACA2984B5539181F3EFF1A5E8903D71D5B95DA4F27202B77D2C44B430BB53741A8D59A8F86887525C9F2A6A5980A195EAA7F2FF910064301DEF89D3AA213E1FAC7768D89365318E370AF54A112EFBA9246D9158386BA1B4EEFDA", 16)
  154. dsakey.Y, _ = new(big.Int).SetString("32969E5780CFE1C849A1C276D7AEB4F38A23B591739AA2FE197349AEEBD31366AEE5EB7E6C6DDB7C57D02432B30DB5AA66D9884299FAA72568944E4EEDC92EA3FBC6F39F53412FBCC563208F7C15B737AC8910DBC2D9C9B8C001E72FDC40EB694AB1F06A5A2DBD18D9E36C66F31F566742F11EC0A52E9F7B89355C02FB5D32D2", 16)
  155. dsakey.X, _ = new(big.Int).SetString("5078D4D29795CBE76D3AACFE48C9AF0BCDBEE91A", 16)
  156. }
  157. // newMockAuthServer creates a new Server bound to
  158. // the loopback interface. The server exits after
  159. // processing one handshake.
  160. func newMockAuthServer(t *testing.T) string {
  161. l, err := Listen("tcp", "127.0.0.1:0", serverConfig)
  162. if err != nil {
  163. t.Fatalf("unable to newMockAuthServer: %s", err)
  164. }
  165. go func() {
  166. defer l.Close()
  167. c, err := l.Accept()
  168. if err != nil {
  169. t.Errorf("Unable to accept incoming connection: %v", err)
  170. return
  171. }
  172. if err := c.Handshake(); err != nil {
  173. // not Errorf because this is expected to
  174. // fail for some tests.
  175. t.Logf("Handshaking error: %v", err)
  176. return
  177. }
  178. defer c.Close()
  179. }()
  180. return l.Addr().String()
  181. }
  182. func TestClientAuthPublickey(t *testing.T) {
  183. config := &ClientConfig{
  184. User: "testuser",
  185. Auth: []ClientAuth{
  186. ClientAuthKeyring(clientKeychain),
  187. },
  188. }
  189. c, err := Dial("tcp", newMockAuthServer(t), config)
  190. if err != nil {
  191. t.Fatalf("unable to dial remote side: %s", err)
  192. }
  193. c.Close()
  194. }
  195. func TestClientAuthPassword(t *testing.T) {
  196. config := &ClientConfig{
  197. User: "testuser",
  198. Auth: []ClientAuth{
  199. ClientAuthPassword(clientPassword),
  200. },
  201. }
  202. c, err := Dial("tcp", newMockAuthServer(t), config)
  203. if err != nil {
  204. t.Fatalf("unable to dial remote side: %s", err)
  205. }
  206. c.Close()
  207. }
  208. func TestClientAuthWrongPassword(t *testing.T) {
  209. wrongPw := password("wrong")
  210. config := &ClientConfig{
  211. User: "testuser",
  212. Auth: []ClientAuth{
  213. ClientAuthPassword(wrongPw),
  214. ClientAuthKeyring(clientKeychain),
  215. },
  216. }
  217. c, err := Dial("tcp", newMockAuthServer(t), config)
  218. if err != nil {
  219. t.Fatalf("unable to dial remote side: %s", err)
  220. }
  221. c.Close()
  222. }
  223. func TestClientAuthKeyboardInteractive(t *testing.T) {
  224. answers := keyboardInteractive(map[string]string{
  225. "question1": "answer1",
  226. "question2": "answer2",
  227. })
  228. config := &ClientConfig{
  229. User: "testuser",
  230. Auth: []ClientAuth{
  231. ClientAuthKeyboardInteractive(&answers),
  232. },
  233. }
  234. c, err := Dial("tcp", newMockAuthServer(t), config)
  235. if err != nil {
  236. t.Fatalf("unable to dial remote side: %s", err)
  237. }
  238. c.Close()
  239. }
  240. func TestClientAuthWrongKeyboardInteractive(t *testing.T) {
  241. answers := keyboardInteractive(map[string]string{
  242. "question1": "answer1",
  243. "question2": "WRONG",
  244. })
  245. config := &ClientConfig{
  246. User: "testuser",
  247. Auth: []ClientAuth{
  248. ClientAuthKeyboardInteractive(&answers),
  249. },
  250. }
  251. c, err := Dial("tcp", newMockAuthServer(t), config)
  252. if err == nil {
  253. c.Close()
  254. t.Fatalf("wrong answers should not have authenticated with KeyboardInteractive")
  255. }
  256. }
  257. // the mock server will only authenticate ssh-rsa keys
  258. func TestClientAuthInvalidPublickey(t *testing.T) {
  259. kc := new(keychain)
  260. kc.keys = append(kc.keys, dsakey)
  261. config := &ClientConfig{
  262. User: "testuser",
  263. Auth: []ClientAuth{
  264. ClientAuthKeyring(kc),
  265. },
  266. }
  267. c, err := Dial("tcp", newMockAuthServer(t), config)
  268. if err == nil {
  269. c.Close()
  270. t.Fatalf("dsa private key should not have authenticated with rsa public key")
  271. }
  272. }
  273. // the client should authenticate with the second key
  274. func TestClientAuthRSAandDSA(t *testing.T) {
  275. kc := new(keychain)
  276. kc.keys = append(kc.keys, dsakey, rsakey)
  277. config := &ClientConfig{
  278. User: "testuser",
  279. Auth: []ClientAuth{
  280. ClientAuthKeyring(kc),
  281. },
  282. }
  283. c, err := Dial("tcp", newMockAuthServer(t), config)
  284. if err != nil {
  285. t.Fatalf("client could not authenticate with rsa key: %v", err)
  286. }
  287. c.Close()
  288. }
  289. func TestClientHMAC(t *testing.T) {
  290. kc := new(keychain)
  291. kc.keys = append(kc.keys, rsakey)
  292. for _, mac := range DefaultMACOrder {
  293. config := &ClientConfig{
  294. User: "testuser",
  295. Auth: []ClientAuth{
  296. ClientAuthKeyring(kc),
  297. },
  298. Crypto: CryptoConfig{
  299. MACs: []string{mac},
  300. },
  301. }
  302. c, err := Dial("tcp", newMockAuthServer(t), config)
  303. if err != nil {
  304. t.Fatalf("client could not authenticate with mac algo %s: %v", mac, err)
  305. }
  306. c.Close()
  307. }
  308. }
  309. // issue 4285.
  310. func TestClientUnsupportedCipher(t *testing.T) {
  311. kc := new(keychain)
  312. kc.keys = append(kc.keys, rsakey)
  313. config := &ClientConfig{
  314. User: "testuser",
  315. Auth: []ClientAuth{
  316. ClientAuthKeyring(kc),
  317. },
  318. Crypto: CryptoConfig{
  319. Ciphers: []string{"aes128-cbc"}, // not currently supported
  320. },
  321. }
  322. c, err := Dial("tcp", newMockAuthServer(t), config)
  323. if err == nil {
  324. t.Errorf("expected no ciphers in common")
  325. c.Close()
  326. }
  327. }