client_auth_test.go 11 KB

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