common.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. func findAgreedAlgorithms(transport *transport, clientKexInit, serverKexInit *kexInitMsg) (kexAlgo, hostKeyAlgo string, ok bool) {
  79. kexAlgo, ok = findCommonAlgorithm(clientKexInit.KexAlgos, serverKexInit.KexAlgos)
  80. if !ok {
  81. return
  82. }
  83. hostKeyAlgo, ok = findCommonAlgorithm(clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos)
  84. if !ok {
  85. return
  86. }
  87. transport.writer.cipherAlgo, ok = findCommonCipher(clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer)
  88. if !ok {
  89. return
  90. }
  91. transport.reader.cipherAlgo, ok = findCommonCipher(clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient)
  92. if !ok {
  93. return
  94. }
  95. transport.writer.macAlgo, ok = findCommonAlgorithm(clientKexInit.MACsClientServer, serverKexInit.MACsClientServer)
  96. if !ok {
  97. return
  98. }
  99. transport.reader.macAlgo, ok = findCommonAlgorithm(clientKexInit.MACsServerClient, serverKexInit.MACsServerClient)
  100. if !ok {
  101. return
  102. }
  103. transport.writer.compressionAlgo, ok = findCommonAlgorithm(clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer)
  104. if !ok {
  105. return
  106. }
  107. transport.reader.compressionAlgo, ok = findCommonAlgorithm(clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient)
  108. if !ok {
  109. return
  110. }
  111. ok = true
  112. return
  113. }
  114. // Cryptographic configuration common to both ServerConfig and ClientConfig.
  115. type CryptoConfig struct {
  116. // The allowed key exchanges algorithms. If unspecified then a
  117. // default set of algorithms is used.
  118. KeyExchanges []string
  119. // The allowed cipher algorithms. If unspecified then DefaultCipherOrder is
  120. // used.
  121. Ciphers []string
  122. // The allowed MAC algorithms. If unspecified then DefaultMACOrder is used.
  123. MACs []string
  124. }
  125. func (c *CryptoConfig) ciphers() []string {
  126. if c.Ciphers == nil {
  127. return DefaultCipherOrder
  128. }
  129. return c.Ciphers
  130. }
  131. func (c *CryptoConfig) kexes() []string {
  132. if c.KeyExchanges == nil {
  133. return defaultKeyExchangeOrder
  134. }
  135. return c.KeyExchanges
  136. }
  137. func (c *CryptoConfig) macs() []string {
  138. if c.MACs == nil {
  139. return DefaultMACOrder
  140. }
  141. return c.MACs
  142. }
  143. // serialize a signed slice according to RFC 4254 6.6. The name should
  144. // be a key type name, rather than a cert type name.
  145. func serializeSignature(name string, sig []byte) []byte {
  146. length := stringLength(len(name))
  147. length += stringLength(len(sig))
  148. ret := make([]byte, length)
  149. r := marshalString(ret, []byte(name))
  150. r = marshalString(r, sig)
  151. return ret
  152. }
  153. // MarshalPublicKey serializes a supported key or certificate for use
  154. // by the SSH wire protocol. It can be used for comparison with the
  155. // pubkey argument of ServerConfig's PublicKeyCallback as well as for
  156. // generating an authorized_keys or host_keys file.
  157. func MarshalPublicKey(key PublicKey) []byte {
  158. // See also RFC 4253 6.6.
  159. algoname := key.PrivateKeyAlgo()
  160. blob := key.Marshal()
  161. length := stringLength(len(algoname))
  162. length += len(blob)
  163. ret := make([]byte, length)
  164. r := marshalString(ret, []byte(algoname))
  165. copy(r, blob)
  166. return ret
  167. }
  168. // pubAlgoToPrivAlgo returns the private key algorithm format name that
  169. // corresponds to a given public key algorithm format name. For most
  170. // public keys, the private key algorithm name is the same. For some
  171. // situations, such as openssh certificates, the private key algorithm and
  172. // public key algorithm names differ. This accounts for those situations.
  173. func pubAlgoToPrivAlgo(pubAlgo string) string {
  174. switch pubAlgo {
  175. case CertAlgoRSAv01:
  176. return KeyAlgoRSA
  177. case CertAlgoDSAv01:
  178. return KeyAlgoDSA
  179. case CertAlgoECDSA256v01:
  180. return KeyAlgoECDSA256
  181. case CertAlgoECDSA384v01:
  182. return KeyAlgoECDSA384
  183. case CertAlgoECDSA521v01:
  184. return KeyAlgoECDSA521
  185. }
  186. return pubAlgo
  187. }
  188. // buildDataSignedForAuth returns the data that is signed in order to prove
  189. // posession of a private key. See RFC 4252, section 7.
  190. func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte {
  191. user := []byte(req.User)
  192. service := []byte(req.Service)
  193. method := []byte(req.Method)
  194. length := stringLength(len(sessionId))
  195. length += 1
  196. length += stringLength(len(user))
  197. length += stringLength(len(service))
  198. length += stringLength(len(method))
  199. length += 1
  200. length += stringLength(len(algo))
  201. length += stringLength(len(pubKey))
  202. ret := make([]byte, length)
  203. r := marshalString(ret, sessionId)
  204. r[0] = msgUserAuthRequest
  205. r = r[1:]
  206. r = marshalString(r, user)
  207. r = marshalString(r, service)
  208. r = marshalString(r, method)
  209. r[0] = 1
  210. r = r[1:]
  211. r = marshalString(r, algo)
  212. r = marshalString(r, pubKey)
  213. return ret
  214. }
  215. // safeString sanitises s according to RFC 4251, section 9.2.
  216. // All control characters except tab, carriage return and newline are
  217. // replaced by 0x20.
  218. func safeString(s string) string {
  219. out := []byte(s)
  220. for i, c := range out {
  221. if c < 0x20 && c != 0xd && c != 0xa && c != 0x9 {
  222. out[i] = 0x20
  223. }
  224. }
  225. return string(out)
  226. }
  227. func appendU16(buf []byte, n uint16) []byte {
  228. return append(buf, byte(n>>8), byte(n))
  229. }
  230. func appendU32(buf []byte, n uint32) []byte {
  231. return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  232. }
  233. func appendInt(buf []byte, n int) []byte {
  234. return appendU32(buf, uint32(n))
  235. }
  236. func appendString(buf []byte, s string) []byte {
  237. buf = appendU32(buf, uint32(len(s)))
  238. buf = append(buf, s...)
  239. return buf
  240. }
  241. func appendBool(buf []byte, b bool) []byte {
  242. if b {
  243. buf = append(buf, 1)
  244. } else {
  245. buf = append(buf, 0)
  246. }
  247. return buf
  248. }
  249. // newCond is a helper to hide the fact that there is no usable zero
  250. // value for sync.Cond.
  251. func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) }
  252. // window represents the buffer available to clients
  253. // wishing to write to a channel.
  254. type window struct {
  255. *sync.Cond
  256. win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
  257. }
  258. // add adds win to the amount of window available
  259. // for consumers.
  260. func (w *window) add(win uint32) bool {
  261. // a zero sized window adjust is a noop.
  262. if win == 0 {
  263. return true
  264. }
  265. w.L.Lock()
  266. if w.win+win < win {
  267. w.L.Unlock()
  268. return false
  269. }
  270. w.win += win
  271. // It is unusual that multiple goroutines would be attempting to reserve
  272. // window space, but not guaranteed. Use broadcast to notify all waiters
  273. // that additional window is available.
  274. w.Broadcast()
  275. w.L.Unlock()
  276. return true
  277. }
  278. // reserve reserves win from the available window capacity.
  279. // If no capacity remains, reserve will block. reserve may
  280. // return less than requested.
  281. func (w *window) reserve(win uint32) uint32 {
  282. w.L.Lock()
  283. for w.win == 0 {
  284. w.Wait()
  285. }
  286. if w.win < win {
  287. win = w.win
  288. }
  289. w.win -= win
  290. w.L.Unlock()
  291. return win
  292. }