client_auth_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. "strings"
  18. "testing"
  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. +Icl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  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) (interface{}, 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 &key.PublicKey, nil
  68. case *dsa.PrivateKey:
  69. return &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. key := &clientKeychain.keys[0].(*rsa.PrivateKey).PublicKey
  125. expected := []byte(serializePublicKey(key))
  126. algoname := algoName(key)
  127. return user == "testuser" && algo == algoname && bytes.Equal(pubkey, expected)
  128. },
  129. KeyboardInteractiveCallback: func(conn *ServerConn, user string, client ClientKeyboardInteractive) bool {
  130. ans, err := client.Challenge("user",
  131. "instruction",
  132. []string{"question1", "question2"},
  133. []bool{true, true})
  134. if err != nil {
  135. return false
  136. }
  137. ok := user == "testuser" && ans[0] == "answer1" && ans[1] == "answer2"
  138. client.Challenge("user", "motd", nil, nil)
  139. return ok
  140. },
  141. }
  142. )
  143. func init() {
  144. if err := serverConfig.SetRSAPrivateKey([]byte(testServerPrivateKey)); err != nil {
  145. panic("unable to set private key: " + err.Error())
  146. }
  147. block, _ := pem.Decode([]byte(testClientPrivateKey))
  148. rsakey, _ = x509.ParsePKCS1PrivateKey(block.Bytes)
  149. clientKeychain.keys = append(clientKeychain.keys, rsakey)
  150. dsakey = new(dsa.PrivateKey)
  151. // taken from crypto/dsa/dsa_test.go
  152. dsakey.P, _ = new(big.Int).SetString("A9B5B793FB4785793D246BAE77E8FF63CA52F442DA763C440259919FE1BC1D6065A9350637A04F75A2F039401D49F08E066C4D275A5A65DA5684BC563C14289D7AB8A67163BFBF79D85972619AD2CFF55AB0EE77A9002B0EF96293BDD0F42685EBB2C66C327079F6C98000FBCB79AACDE1BC6F9D5C7B1A97E3D9D54ED7951FEF", 16)
  153. dsakey.Q, _ = new(big.Int).SetString("E1D3391245933D68A0714ED34BBCB7A1F422B9C1", 16)
  154. dsakey.G, _ = new(big.Int).SetString("634364FC25248933D01D1993ECABD0657CC0CB2CEED7ED2E3E8AECDFCDC4A25C3B15E9E3B163ACA2984B5539181F3EFF1A5E8903D71D5B95DA4F27202B77D2C44B430BB53741A8D59A8F86887525C9F2A6A5980A195EAA7F2FF910064301DEF89D3AA213E1FAC7768D89365318E370AF54A112EFBA9246D9158386BA1B4EEFDA", 16)
  155. dsakey.Y, _ = new(big.Int).SetString("32969E5780CFE1C849A1C276D7AEB4F38A23B591739AA2FE197349AEEBD31366AEE5EB7E6C6DDB7C57D02432B30DB5AA66D9884299FAA72568944E4EEDC92EA3FBC6F39F53412FBCC563208F7C15B737AC8910DBC2D9C9B8C001E72FDC40EB694AB1F06A5A2DBD18D9E36C66F31F566742F11EC0A52E9F7B89355C02FB5D32D2", 16)
  156. dsakey.X, _ = new(big.Int).SetString("5078D4D29795CBE76D3AACFE48C9AF0BCDBEE91A", 16)
  157. }
  158. // newMockAuthServer creates a new Server bound to
  159. // the loopback interface. The server exits after
  160. // processing one handshake.
  161. func newMockAuthServer(t *testing.T) string {
  162. l, err := Listen("tcp", "127.0.0.1:0", serverConfig)
  163. if err != nil {
  164. t.Fatalf("unable to newMockAuthServer: %s", err)
  165. }
  166. go func() {
  167. defer l.Close()
  168. c, err := l.Accept()
  169. if err != nil {
  170. t.Errorf("Unable to accept incoming connection: %v", err)
  171. return
  172. }
  173. if err := c.Handshake(); err != nil {
  174. // not Errorf because this is expected to
  175. // fail for some tests.
  176. t.Logf("Handshaking error: %v", err)
  177. return
  178. }
  179. defer c.Close()
  180. }()
  181. return l.Addr().String()
  182. }
  183. func TestClientAuthPublicKey(t *testing.T) {
  184. config := &ClientConfig{
  185. User: "testuser",
  186. Auth: []ClientAuth{
  187. ClientAuthKeyring(clientKeychain),
  188. },
  189. }
  190. c, err := Dial("tcp", newMockAuthServer(t), config)
  191. if err != nil {
  192. t.Fatalf("unable to dial remote side: %s", err)
  193. }
  194. c.Close()
  195. }
  196. func TestClientAuthPassword(t *testing.T) {
  197. config := &ClientConfig{
  198. User: "testuser",
  199. Auth: []ClientAuth{
  200. ClientAuthPassword(clientPassword),
  201. },
  202. }
  203. c, err := Dial("tcp", newMockAuthServer(t), config)
  204. if err != nil {
  205. t.Fatalf("unable to dial remote side: %s", err)
  206. }
  207. c.Close()
  208. }
  209. func TestClientAuthWrongPassword(t *testing.T) {
  210. wrongPw := password("wrong")
  211. config := &ClientConfig{
  212. User: "testuser",
  213. Auth: []ClientAuth{
  214. ClientAuthPassword(wrongPw),
  215. ClientAuthKeyring(clientKeychain),
  216. },
  217. }
  218. c, err := Dial("tcp", newMockAuthServer(t), config)
  219. if err != nil {
  220. t.Fatalf("unable to dial remote side: %s", err)
  221. }
  222. c.Close()
  223. }
  224. func TestClientAuthKeyboardInteractive(t *testing.T) {
  225. answers := keyboardInteractive(map[string]string{
  226. "question1": "answer1",
  227. "question2": "answer2",
  228. })
  229. config := &ClientConfig{
  230. User: "testuser",
  231. Auth: []ClientAuth{
  232. ClientAuthKeyboardInteractive(&answers),
  233. },
  234. }
  235. c, err := Dial("tcp", newMockAuthServer(t), config)
  236. if err != nil {
  237. t.Fatalf("unable to dial remote side: %s", err)
  238. }
  239. c.Close()
  240. }
  241. func TestClientAuthWrongKeyboardInteractive(t *testing.T) {
  242. answers := keyboardInteractive(map[string]string{
  243. "question1": "answer1",
  244. "question2": "WRONG",
  245. })
  246. config := &ClientConfig{
  247. User: "testuser",
  248. Auth: []ClientAuth{
  249. ClientAuthKeyboardInteractive(&answers),
  250. },
  251. }
  252. c, err := Dial("tcp", newMockAuthServer(t), config)
  253. if err == nil {
  254. c.Close()
  255. t.Fatalf("wrong answers should not have authenticated with KeyboardInteractive")
  256. }
  257. }
  258. // the mock server will only authenticate ssh-rsa keys
  259. func TestClientAuthInvalidPublicKey(t *testing.T) {
  260. kc := new(keychain)
  261. kc.keys = append(kc.keys, dsakey)
  262. config := &ClientConfig{
  263. User: "testuser",
  264. Auth: []ClientAuth{
  265. ClientAuthKeyring(kc),
  266. },
  267. }
  268. c, err := Dial("tcp", newMockAuthServer(t), config)
  269. if err == nil {
  270. c.Close()
  271. t.Fatalf("dsa private key should not have authenticated with rsa public key")
  272. }
  273. }
  274. // the client should authenticate with the second key
  275. func TestClientAuthRSAandDSA(t *testing.T) {
  276. kc := new(keychain)
  277. kc.keys = append(kc.keys, dsakey, rsakey)
  278. config := &ClientConfig{
  279. User: "testuser",
  280. Auth: []ClientAuth{
  281. ClientAuthKeyring(kc),
  282. },
  283. }
  284. c, err := Dial("tcp", newMockAuthServer(t), config)
  285. if err != nil {
  286. t.Fatalf("client could not authenticate with rsa key: %v", err)
  287. }
  288. c.Close()
  289. }
  290. func TestClientHMAC(t *testing.T) {
  291. kc := new(keychain)
  292. kc.keys = append(kc.keys, rsakey)
  293. for _, mac := range DefaultMACOrder {
  294. config := &ClientConfig{
  295. User: "testuser",
  296. Auth: []ClientAuth{
  297. ClientAuthKeyring(kc),
  298. },
  299. Crypto: CryptoConfig{
  300. MACs: []string{mac},
  301. },
  302. }
  303. c, err := Dial("tcp", newMockAuthServer(t), config)
  304. if err != nil {
  305. t.Fatalf("client could not authenticate with mac algo %s: %v", mac, err)
  306. }
  307. c.Close()
  308. }
  309. }
  310. // issue 4285.
  311. func TestClientUnsupportedCipher(t *testing.T) {
  312. kc := new(keychain)
  313. kc.keys = append(kc.keys, rsakey)
  314. config := &ClientConfig{
  315. User: "testuser",
  316. Auth: []ClientAuth{
  317. ClientAuthKeyring(kc),
  318. },
  319. Crypto: CryptoConfig{
  320. Ciphers: []string{"aes128-cbc"}, // not currently supported
  321. },
  322. }
  323. c, err := Dial("tcp", newMockAuthServer(t), config)
  324. if err == nil {
  325. t.Errorf("expected no ciphers in common")
  326. c.Close()
  327. }
  328. }
  329. func TestClientUnsupportedKex(t *testing.T) {
  330. kc := new(keychain)
  331. kc.keys = append(kc.keys, rsakey)
  332. config := &ClientConfig{
  333. User: "testuser",
  334. Auth: []ClientAuth{
  335. ClientAuthKeyring(kc),
  336. },
  337. Crypto: CryptoConfig{
  338. KeyExchanges: []string{"diffie-hellman-group-exchange-sha256"}, // not currently supported
  339. },
  340. }
  341. c, err := Dial("tcp", newMockAuthServer(t), config)
  342. if err == nil || !strings.Contains(err.Error(), "no common algorithms") {
  343. t.Errorf("got %v, expected 'no common algorithms'", err)
  344. c.Close()
  345. }
  346. }