common.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. "crypto"
  7. "fmt"
  8. "sync"
  9. _ "crypto/sha1"
  10. _ "crypto/sha256"
  11. _ "crypto/sha512"
  12. )
  13. // These are string constants in the SSH protocol.
  14. const (
  15. compressionNone = "none"
  16. serviceUserAuth = "ssh-userauth"
  17. serviceSSH = "ssh-connection"
  18. )
  19. var supportedKexAlgos = []string{
  20. kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521,
  21. kexAlgoDH14SHA1, kexAlgoDH1SHA1,
  22. }
  23. var supportedHostKeyAlgos = []string{
  24. KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521,
  25. KeyAlgoRSA, KeyAlgoDSA,
  26. }
  27. var supportedCompressions = []string{compressionNone}
  28. // hashFuncs keeps the mapping of supported algorithms to their respective
  29. // hashes needed for signature verification.
  30. var hashFuncs = map[string]crypto.Hash{
  31. KeyAlgoRSA: crypto.SHA1,
  32. KeyAlgoDSA: crypto.SHA1,
  33. KeyAlgoECDSA256: crypto.SHA256,
  34. KeyAlgoECDSA384: crypto.SHA384,
  35. KeyAlgoECDSA521: crypto.SHA512,
  36. CertAlgoRSAv01: crypto.SHA1,
  37. CertAlgoDSAv01: crypto.SHA1,
  38. CertAlgoECDSA256v01: crypto.SHA256,
  39. CertAlgoECDSA384v01: crypto.SHA384,
  40. CertAlgoECDSA521v01: crypto.SHA512,
  41. }
  42. // UnexpectedMessageError results when the SSH message that we received didn't
  43. // match what we wanted.
  44. type UnexpectedMessageError struct {
  45. expected, got uint8
  46. }
  47. func (u UnexpectedMessageError) Error() string {
  48. return fmt.Sprintf("ssh: unexpected message type %d (expected %d)", u.got, u.expected)
  49. }
  50. // ParseError results from a malformed SSH message.
  51. type ParseError struct {
  52. msgType uint8
  53. }
  54. func (p ParseError) Error() string {
  55. return fmt.Sprintf("ssh: parse error in message type %d", p.msgType)
  56. }
  57. func findCommonAlgorithm(clientAlgos []string, serverAlgos []string) (commonAlgo string, ok bool) {
  58. for _, clientAlgo := range clientAlgos {
  59. for _, serverAlgo := range serverAlgos {
  60. if clientAlgo == serverAlgo {
  61. return clientAlgo, true
  62. }
  63. }
  64. }
  65. return
  66. }
  67. func findCommonCipher(clientCiphers []string, serverCiphers []string) (commonCipher string, ok bool) {
  68. for _, clientCipher := range clientCiphers {
  69. for _, serverCipher := range serverCiphers {
  70. // reject the cipher if we have no cipherModes definition
  71. if clientCipher == serverCipher && cipherModes[clientCipher] != nil {
  72. return clientCipher, true
  73. }
  74. }
  75. }
  76. return
  77. }
  78. type algorithms struct {
  79. kex string
  80. hostKey string
  81. wCipher string
  82. rCipher string
  83. rMAC string
  84. wMAC string
  85. rCompression string
  86. wCompression string
  87. }
  88. func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms) {
  89. var ok bool
  90. result := &algorithms{}
  91. result.kex, ok = findCommonAlgorithm(clientKexInit.KexAlgos, serverKexInit.KexAlgos)
  92. if !ok {
  93. return
  94. }
  95. result.hostKey, ok = findCommonAlgorithm(clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos)
  96. if !ok {
  97. return
  98. }
  99. result.wCipher, ok = findCommonCipher(clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer)
  100. if !ok {
  101. return
  102. }
  103. result.rCipher, ok = findCommonCipher(clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient)
  104. if !ok {
  105. return
  106. }
  107. result.wMAC, ok = findCommonAlgorithm(clientKexInit.MACsClientServer, serverKexInit.MACsClientServer)
  108. if !ok {
  109. return
  110. }
  111. result.rMAC, ok = findCommonAlgorithm(clientKexInit.MACsServerClient, serverKexInit.MACsServerClient)
  112. if !ok {
  113. return
  114. }
  115. result.wCompression, ok = findCommonAlgorithm(clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer)
  116. if !ok {
  117. return
  118. }
  119. result.rCompression, ok = findCommonAlgorithm(clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient)
  120. if !ok {
  121. return
  122. }
  123. return result
  124. }
  125. // Cryptographic configuration common to both ServerConfig and ClientConfig.
  126. type CryptoConfig struct {
  127. // The allowed key exchanges algorithms. If unspecified then a
  128. // default set of algorithms is used.
  129. KeyExchanges []string
  130. // The allowed cipher algorithms. If unspecified then DefaultCipherOrder is
  131. // used.
  132. Ciphers []string
  133. // The allowed MAC algorithms. If unspecified then DefaultMACOrder is used.
  134. MACs []string
  135. }
  136. func (c *CryptoConfig) ciphers() []string {
  137. if c.Ciphers == nil {
  138. return DefaultCipherOrder
  139. }
  140. return c.Ciphers
  141. }
  142. func (c *CryptoConfig) kexes() []string {
  143. if c.KeyExchanges == nil {
  144. return defaultKeyExchangeOrder
  145. }
  146. return c.KeyExchanges
  147. }
  148. func (c *CryptoConfig) macs() []string {
  149. if c.MACs == nil {
  150. return DefaultMACOrder
  151. }
  152. return c.MACs
  153. }
  154. // serialize a signed slice according to RFC 4254 6.6. The name should
  155. // be a key type name, rather than a cert type name.
  156. func serializeSignature(name string, sig []byte) []byte {
  157. length := stringLength(len(name))
  158. length += stringLength(len(sig))
  159. ret := make([]byte, length)
  160. r := marshalString(ret, []byte(name))
  161. r = marshalString(r, sig)
  162. return ret
  163. }
  164. // MarshalPublicKey serializes a supported key or certificate for use
  165. // by the SSH wire protocol. It can be used for comparison with the
  166. // pubkey argument of ServerConfig's PublicKeyCallback as well as for
  167. // generating an authorized_keys or host_keys file.
  168. func MarshalPublicKey(key PublicKey) []byte {
  169. // See also RFC 4253 6.6.
  170. algoname := key.PublicKeyAlgo()
  171. blob := key.Marshal()
  172. length := stringLength(len(algoname))
  173. length += len(blob)
  174. ret := make([]byte, length)
  175. r := marshalString(ret, []byte(algoname))
  176. copy(r, blob)
  177. return ret
  178. }
  179. // pubAlgoToPrivAlgo returns the private key algorithm format name that
  180. // corresponds to a given public key algorithm format name. For most
  181. // public keys, the private key algorithm name is the same. For some
  182. // situations, such as openssh certificates, the private key algorithm and
  183. // public key algorithm names differ. This accounts for those situations.
  184. func pubAlgoToPrivAlgo(pubAlgo string) string {
  185. switch pubAlgo {
  186. case CertAlgoRSAv01:
  187. return KeyAlgoRSA
  188. case CertAlgoDSAv01:
  189. return KeyAlgoDSA
  190. case CertAlgoECDSA256v01:
  191. return KeyAlgoECDSA256
  192. case CertAlgoECDSA384v01:
  193. return KeyAlgoECDSA384
  194. case CertAlgoECDSA521v01:
  195. return KeyAlgoECDSA521
  196. }
  197. return pubAlgo
  198. }
  199. // buildDataSignedForAuth returns the data that is signed in order to prove
  200. // posession of a private key. See RFC 4252, section 7.
  201. func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte {
  202. user := []byte(req.User)
  203. service := []byte(req.Service)
  204. method := []byte(req.Method)
  205. length := stringLength(len(sessionId))
  206. length += 1
  207. length += stringLength(len(user))
  208. length += stringLength(len(service))
  209. length += stringLength(len(method))
  210. length += 1
  211. length += stringLength(len(algo))
  212. length += stringLength(len(pubKey))
  213. ret := make([]byte, length)
  214. r := marshalString(ret, sessionId)
  215. r[0] = msgUserAuthRequest
  216. r = r[1:]
  217. r = marshalString(r, user)
  218. r = marshalString(r, service)
  219. r = marshalString(r, method)
  220. r[0] = 1
  221. r = r[1:]
  222. r = marshalString(r, algo)
  223. r = marshalString(r, pubKey)
  224. return ret
  225. }
  226. // safeString sanitises s according to RFC 4251, section 9.2.
  227. // All control characters except tab, carriage return and newline are
  228. // replaced by 0x20.
  229. func safeString(s string) string {
  230. out := []byte(s)
  231. for i, c := range out {
  232. if c < 0x20 && c != 0xd && c != 0xa && c != 0x9 {
  233. out[i] = 0x20
  234. }
  235. }
  236. return string(out)
  237. }
  238. func appendU16(buf []byte, n uint16) []byte {
  239. return append(buf, byte(n>>8), byte(n))
  240. }
  241. func appendU32(buf []byte, n uint32) []byte {
  242. return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  243. }
  244. func appendInt(buf []byte, n int) []byte {
  245. return appendU32(buf, uint32(n))
  246. }
  247. func appendString(buf []byte, s string) []byte {
  248. buf = appendU32(buf, uint32(len(s)))
  249. buf = append(buf, s...)
  250. return buf
  251. }
  252. func appendBool(buf []byte, b bool) []byte {
  253. if b {
  254. buf = append(buf, 1)
  255. } else {
  256. buf = append(buf, 0)
  257. }
  258. return buf
  259. }
  260. // newCond is a helper to hide the fact that there is no usable zero
  261. // value for sync.Cond.
  262. func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) }
  263. // window represents the buffer available to clients
  264. // wishing to write to a channel.
  265. type window struct {
  266. *sync.Cond
  267. win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
  268. }
  269. // add adds win to the amount of window available
  270. // for consumers.
  271. func (w *window) add(win uint32) bool {
  272. // a zero sized window adjust is a noop.
  273. if win == 0 {
  274. return true
  275. }
  276. w.L.Lock()
  277. if w.win+win < win {
  278. w.L.Unlock()
  279. return false
  280. }
  281. w.win += win
  282. // It is unusual that multiple goroutines would be attempting to reserve
  283. // window space, but not guaranteed. Use broadcast to notify all waiters
  284. // that additional window is available.
  285. w.Broadcast()
  286. w.L.Unlock()
  287. return true
  288. }
  289. // reserve reserves win from the available window capacity.
  290. // If no capacity remains, reserve will block. reserve may
  291. // return less than requested.
  292. func (w *window) reserve(win uint32) uint32 {
  293. w.L.Lock()
  294. for w.win == 0 {
  295. w.Wait()
  296. }
  297. if w.win < win {
  298. win = w.win
  299. }
  300. w.win -= win
  301. w.L.Unlock()
  302. return win
  303. }