messages.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. "io"
  8. "math/big"
  9. "reflect"
  10. )
  11. // These are SSH message type numbers. They are scattered around several
  12. // documents but many were taken from
  13. // http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1
  14. const (
  15. msgDisconnect = 1
  16. msgIgnore = 2
  17. msgUnimplemented = 3
  18. msgDebug = 4
  19. msgServiceRequest = 5
  20. msgServiceAccept = 6
  21. msgKexInit = 20
  22. msgNewKeys = 21
  23. msgKexDHInit = 30
  24. msgKexDHReply = 31
  25. msgUserAuthRequest = 50
  26. msgUserAuthFailure = 51
  27. msgUserAuthSuccess = 52
  28. msgUserAuthBanner = 53
  29. msgUserAuthPubKeyOk = 60
  30. msgGlobalRequest = 80
  31. msgRequestSuccess = 81
  32. msgRequestFailure = 82
  33. msgChannelOpen = 90
  34. msgChannelOpenConfirm = 91
  35. msgChannelOpenFailure = 92
  36. msgChannelWindowAdjust = 93
  37. msgChannelData = 94
  38. msgChannelExtendedData = 95
  39. msgChannelEOF = 96
  40. msgChannelClose = 97
  41. msgChannelRequest = 98
  42. msgChannelSuccess = 99
  43. msgChannelFailure = 100
  44. )
  45. // SSH messages:
  46. //
  47. // These structures mirror the wire format of the corresponding SSH messages.
  48. // They are marshaled using reflection with the marshal and unmarshal functions
  49. // in this file. The only wrinkle is that a final member of type []byte with a
  50. // ssh tag of "rest" receives the remainder of a packet when unmarshaling.
  51. // See RFC 4253, section 11.1.
  52. type disconnectMsg struct {
  53. Reason uint32
  54. Message string
  55. Language string
  56. }
  57. // See RFC 4253, section 7.1.
  58. type kexInitMsg struct {
  59. Cookie [16]byte
  60. KexAlgos []string
  61. ServerHostKeyAlgos []string
  62. CiphersClientServer []string
  63. CiphersServerClient []string
  64. MACsClientServer []string
  65. MACsServerClient []string
  66. CompressionClientServer []string
  67. CompressionServerClient []string
  68. LanguagesClientServer []string
  69. LanguagesServerClient []string
  70. FirstKexFollows bool
  71. Reserved uint32
  72. }
  73. // See RFC 4253, section 8.
  74. type kexDHInitMsg struct {
  75. X *big.Int
  76. }
  77. type kexDHReplyMsg struct {
  78. HostKey []byte
  79. Y *big.Int
  80. Signature []byte
  81. }
  82. // See RFC 4253, section 10.
  83. type serviceRequestMsg struct {
  84. Service string
  85. }
  86. // See RFC 4253, section 10.
  87. type serviceAcceptMsg struct {
  88. Service string
  89. }
  90. // See RFC 4252, section 5.
  91. type userAuthRequestMsg struct {
  92. User string
  93. Service string
  94. Method string
  95. Payload []byte `ssh:"rest"`
  96. }
  97. // See RFC 4252, section 5.1
  98. type userAuthFailureMsg struct {
  99. Methods []string
  100. PartialSuccess bool
  101. }
  102. // See RFC 4254, section 5.1.
  103. type channelOpenMsg struct {
  104. ChanType string
  105. PeersId uint32
  106. PeersWindow uint32
  107. MaxPacketSize uint32
  108. TypeSpecificData []byte `ssh:"rest"`
  109. }
  110. // See RFC 4254, section 5.1.
  111. type channelOpenConfirmMsg struct {
  112. PeersId uint32
  113. MyId uint32
  114. MyWindow uint32
  115. MaxPacketSize uint32
  116. TypeSpecificData []byte `ssh:"rest"`
  117. }
  118. // See RFC 4254, section 5.1.
  119. type channelOpenFailureMsg struct {
  120. PeersId uint32
  121. Reason uint32
  122. Message string
  123. Language string
  124. }
  125. type channelRequestMsg struct {
  126. PeersId uint32
  127. Request string
  128. WantReply bool
  129. RequestSpecificData []byte `ssh:"rest"`
  130. }
  131. // See RFC 4254, section 5.4.
  132. type channelRequestSuccessMsg struct {
  133. PeersId uint32
  134. }
  135. // See RFC 4254, section 5.4.
  136. type channelRequestFailureMsg struct {
  137. PeersId uint32
  138. }
  139. // See RFC 4254, section 5.3
  140. type channelCloseMsg struct {
  141. PeersId uint32
  142. }
  143. // See RFC 4254, section 5.3
  144. type channelEOFMsg struct {
  145. PeersId uint32
  146. }
  147. // See RFC 4254, section 4
  148. type globalRequestMsg struct {
  149. Type string
  150. WantReply bool
  151. }
  152. // See RFC 4254, section 5.2
  153. type windowAdjustMsg struct {
  154. PeersId uint32
  155. AdditionalBytes uint32
  156. }
  157. // See RFC 4252, section 7
  158. type userAuthPubKeyOkMsg struct {
  159. Algo string
  160. PubKey string
  161. }
  162. // unmarshal parses the SSH wire data in packet into out using reflection.
  163. // expectedType is the expected SSH message type. It either returns nil on
  164. // success, or a ParseError or UnexpectedMessageError on error.
  165. func unmarshal(out interface{}, packet []byte, expectedType uint8) error {
  166. if len(packet) == 0 {
  167. return ParseError{expectedType}
  168. }
  169. if packet[0] != expectedType {
  170. return UnexpectedMessageError{expectedType, packet[0]}
  171. }
  172. packet = packet[1:]
  173. v := reflect.ValueOf(out).Elem()
  174. structType := v.Type()
  175. var ok bool
  176. for i := 0; i < v.NumField(); i++ {
  177. field := v.Field(i)
  178. t := field.Type()
  179. switch t.Kind() {
  180. case reflect.Bool:
  181. if len(packet) < 1 {
  182. return ParseError{expectedType}
  183. }
  184. field.SetBool(packet[0] != 0)
  185. packet = packet[1:]
  186. case reflect.Array:
  187. if t.Elem().Kind() != reflect.Uint8 {
  188. panic("array of non-uint8")
  189. }
  190. if len(packet) < t.Len() {
  191. return ParseError{expectedType}
  192. }
  193. for j := 0; j < t.Len(); j++ {
  194. field.Index(j).Set(reflect.ValueOf(packet[j]))
  195. }
  196. packet = packet[t.Len():]
  197. case reflect.Uint32:
  198. var u32 uint32
  199. if u32, packet, ok = parseUint32(packet); !ok {
  200. return ParseError{expectedType}
  201. }
  202. field.SetUint(uint64(u32))
  203. case reflect.String:
  204. var s []byte
  205. if s, packet, ok = parseString(packet); !ok {
  206. return ParseError{expectedType}
  207. }
  208. field.SetString(string(s))
  209. case reflect.Slice:
  210. switch t.Elem().Kind() {
  211. case reflect.Uint8:
  212. if structType.Field(i).Tag.Get("ssh") == "rest" {
  213. field.Set(reflect.ValueOf(packet))
  214. packet = nil
  215. } else {
  216. var s []byte
  217. if s, packet, ok = parseString(packet); !ok {
  218. return ParseError{expectedType}
  219. }
  220. field.Set(reflect.ValueOf(s))
  221. }
  222. case reflect.String:
  223. var nl []string
  224. if nl, packet, ok = parseNameList(packet); !ok {
  225. return ParseError{expectedType}
  226. }
  227. field.Set(reflect.ValueOf(nl))
  228. default:
  229. panic("slice of unknown type")
  230. }
  231. case reflect.Ptr:
  232. if t == bigIntType {
  233. var n *big.Int
  234. if n, packet, ok = parseInt(packet); !ok {
  235. return ParseError{expectedType}
  236. }
  237. field.Set(reflect.ValueOf(n))
  238. } else {
  239. panic("pointer to unknown type")
  240. }
  241. default:
  242. panic("unknown type")
  243. }
  244. }
  245. if len(packet) != 0 {
  246. return ParseError{expectedType}
  247. }
  248. return nil
  249. }
  250. // marshal serializes the message in msg, using the given message type.
  251. func marshal(msgType uint8, msg interface{}) []byte {
  252. var out []byte
  253. out = append(out, msgType)
  254. v := reflect.ValueOf(msg)
  255. structType := v.Type()
  256. for i := 0; i < v.NumField(); i++ {
  257. field := v.Field(i)
  258. t := field.Type()
  259. switch t.Kind() {
  260. case reflect.Bool:
  261. var v uint8
  262. if field.Bool() {
  263. v = 1
  264. }
  265. out = append(out, v)
  266. case reflect.Array:
  267. if t.Elem().Kind() != reflect.Uint8 {
  268. panic("array of non-uint8")
  269. }
  270. for j := 0; j < t.Len(); j++ {
  271. out = append(out, byte(field.Index(j).Uint()))
  272. }
  273. case reflect.Uint32:
  274. u32 := uint32(field.Uint())
  275. out = append(out, byte(u32>>24))
  276. out = append(out, byte(u32>>16))
  277. out = append(out, byte(u32>>8))
  278. out = append(out, byte(u32))
  279. case reflect.String:
  280. s := field.String()
  281. out = append(out, byte(len(s)>>24))
  282. out = append(out, byte(len(s)>>16))
  283. out = append(out, byte(len(s)>>8))
  284. out = append(out, byte(len(s)))
  285. out = append(out, s...)
  286. case reflect.Slice:
  287. switch t.Elem().Kind() {
  288. case reflect.Uint8:
  289. length := field.Len()
  290. if structType.Field(i).Tag.Get("ssh") != "rest" {
  291. out = append(out, byte(length>>24))
  292. out = append(out, byte(length>>16))
  293. out = append(out, byte(length>>8))
  294. out = append(out, byte(length))
  295. }
  296. for j := 0; j < length; j++ {
  297. out = append(out, byte(field.Index(j).Uint()))
  298. }
  299. case reflect.String:
  300. var length int
  301. for j := 0; j < field.Len(); j++ {
  302. if j != 0 {
  303. length++ /* comma */
  304. }
  305. length += len(field.Index(j).String())
  306. }
  307. out = append(out, byte(length>>24))
  308. out = append(out, byte(length>>16))
  309. out = append(out, byte(length>>8))
  310. out = append(out, byte(length))
  311. for j := 0; j < field.Len(); j++ {
  312. if j != 0 {
  313. out = append(out, ',')
  314. }
  315. out = append(out, field.Index(j).String()...)
  316. }
  317. default:
  318. panic("slice of unknown type")
  319. }
  320. case reflect.Ptr:
  321. if t == bigIntType {
  322. var n *big.Int
  323. nValue := reflect.ValueOf(&n)
  324. nValue.Elem().Set(field)
  325. needed := intLength(n)
  326. oldLength := len(out)
  327. if cap(out)-len(out) < needed {
  328. newOut := make([]byte, len(out), 2*(len(out)+needed))
  329. copy(newOut, out)
  330. out = newOut
  331. }
  332. out = out[:oldLength+needed]
  333. marshalInt(out[oldLength:], n)
  334. } else {
  335. panic("pointer to unknown type")
  336. }
  337. }
  338. }
  339. return out
  340. }
  341. var bigOne = big.NewInt(1)
  342. func parseString(in []byte) (out, rest []byte, ok bool) {
  343. if len(in) < 4 {
  344. return
  345. }
  346. length := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
  347. if uint32(len(in)) < 4+length {
  348. return
  349. }
  350. out = in[4 : 4+length]
  351. rest = in[4+length:]
  352. ok = true
  353. return
  354. }
  355. var (
  356. comma = []byte{','}
  357. emptyNameList = []string{}
  358. )
  359. func parseNameList(in []byte) (out []string, rest []byte, ok bool) {
  360. contents, rest, ok := parseString(in)
  361. if !ok {
  362. return
  363. }
  364. if len(contents) == 0 {
  365. out = emptyNameList
  366. return
  367. }
  368. parts := bytes.Split(contents, comma)
  369. out = make([]string, len(parts))
  370. for i, part := range parts {
  371. out[i] = string(part)
  372. }
  373. return
  374. }
  375. func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) {
  376. contents, rest, ok := parseString(in)
  377. if !ok {
  378. return
  379. }
  380. out = new(big.Int)
  381. if len(contents) > 0 && contents[0]&0x80 == 0x80 {
  382. // This is a negative number
  383. notBytes := make([]byte, len(contents))
  384. for i := range notBytes {
  385. notBytes[i] = ^contents[i]
  386. }
  387. out.SetBytes(notBytes)
  388. out.Add(out, bigOne)
  389. out.Neg(out)
  390. } else {
  391. // Positive number
  392. out.SetBytes(contents)
  393. }
  394. ok = true
  395. return
  396. }
  397. func parseUint32(in []byte) (out uint32, rest []byte, ok bool) {
  398. if len(in) < 4 {
  399. return
  400. }
  401. out = uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
  402. rest = in[4:]
  403. ok = true
  404. return
  405. }
  406. func nameListLength(namelist []string) int {
  407. length := 4 /* uint32 length prefix */
  408. for i, name := range namelist {
  409. if i != 0 {
  410. length++ /* comma */
  411. }
  412. length += len(name)
  413. }
  414. return length
  415. }
  416. func intLength(n *big.Int) int {
  417. length := 4 /* length bytes */
  418. if n.Sign() < 0 {
  419. nMinus1 := new(big.Int).Neg(n)
  420. nMinus1.Sub(nMinus1, bigOne)
  421. bitLen := nMinus1.BitLen()
  422. if bitLen%8 == 0 {
  423. // The number will need 0xff padding
  424. length++
  425. }
  426. length += (bitLen + 7) / 8
  427. } else if n.Sign() == 0 {
  428. // A zero is the zero length string
  429. } else {
  430. bitLen := n.BitLen()
  431. if bitLen%8 == 0 {
  432. // The number will need 0x00 padding
  433. length++
  434. }
  435. length += (bitLen + 7) / 8
  436. }
  437. return length
  438. }
  439. func marshalUint32(to []byte, n uint32) []byte {
  440. to[0] = byte(n >> 24)
  441. to[1] = byte(n >> 16)
  442. to[2] = byte(n >> 8)
  443. to[3] = byte(n)
  444. return to[4:]
  445. }
  446. func marshalUint64(to []byte, n uint64) []byte {
  447. to[0] = byte(n >> 56)
  448. to[1] = byte(n >> 48)
  449. to[2] = byte(n >> 40)
  450. to[3] = byte(n >> 32)
  451. to[4] = byte(n >> 24)
  452. to[5] = byte(n >> 16)
  453. to[6] = byte(n >> 8)
  454. to[7] = byte(n)
  455. return to[8:]
  456. }
  457. func marshalInt(to []byte, n *big.Int) []byte {
  458. lengthBytes := to
  459. to = to[4:]
  460. length := 0
  461. if n.Sign() < 0 {
  462. // A negative number has to be converted to two's-complement
  463. // form. So we'll subtract 1 and invert. If the
  464. // most-significant-bit isn't set then we'll need to pad the
  465. // beginning with 0xff in order to keep the number negative.
  466. nMinus1 := new(big.Int).Neg(n)
  467. nMinus1.Sub(nMinus1, bigOne)
  468. bytes := nMinus1.Bytes()
  469. for i := range bytes {
  470. bytes[i] ^= 0xff
  471. }
  472. if len(bytes) == 0 || bytes[0]&0x80 == 0 {
  473. to[0] = 0xff
  474. to = to[1:]
  475. length++
  476. }
  477. nBytes := copy(to, bytes)
  478. to = to[nBytes:]
  479. length += nBytes
  480. } else if n.Sign() == 0 {
  481. // A zero is the zero length string
  482. } else {
  483. bytes := n.Bytes()
  484. if len(bytes) > 0 && bytes[0]&0x80 != 0 {
  485. // We'll have to pad this with a 0x00 in order to
  486. // stop it looking like a negative number.
  487. to[0] = 0
  488. to = to[1:]
  489. length++
  490. }
  491. nBytes := copy(to, bytes)
  492. to = to[nBytes:]
  493. length += nBytes
  494. }
  495. lengthBytes[0] = byte(length >> 24)
  496. lengthBytes[1] = byte(length >> 16)
  497. lengthBytes[2] = byte(length >> 8)
  498. lengthBytes[3] = byte(length)
  499. return to
  500. }
  501. func writeInt(w io.Writer, n *big.Int) {
  502. length := intLength(n)
  503. buf := make([]byte, length)
  504. marshalInt(buf, n)
  505. w.Write(buf)
  506. }
  507. func writeString(w io.Writer, s []byte) {
  508. var lengthBytes [4]byte
  509. lengthBytes[0] = byte(len(s) >> 24)
  510. lengthBytes[1] = byte(len(s) >> 16)
  511. lengthBytes[2] = byte(len(s) >> 8)
  512. lengthBytes[3] = byte(len(s))
  513. w.Write(lengthBytes[:])
  514. w.Write(s)
  515. }
  516. func stringLength(s []byte) int {
  517. return 4 + len(s)
  518. }
  519. func marshalString(to []byte, s []byte) []byte {
  520. to[0] = byte(len(s) >> 24)
  521. to[1] = byte(len(s) >> 16)
  522. to[2] = byte(len(s) >> 8)
  523. to[3] = byte(len(s))
  524. to = to[4:]
  525. copy(to, s)
  526. return to[len(s):]
  527. }
  528. var bigIntType = reflect.TypeOf((*big.Int)(nil))
  529. // Decode a packet into it's corresponding message.
  530. func decode(packet []byte) interface{} {
  531. var msg interface{}
  532. switch packet[0] {
  533. case msgDisconnect:
  534. msg = new(disconnectMsg)
  535. case msgServiceRequest:
  536. msg = new(serviceRequestMsg)
  537. case msgServiceAccept:
  538. msg = new(serviceAcceptMsg)
  539. case msgKexInit:
  540. msg = new(kexInitMsg)
  541. case msgKexDHInit:
  542. msg = new(kexDHInitMsg)
  543. case msgKexDHReply:
  544. msg = new(kexDHReplyMsg)
  545. case msgUserAuthRequest:
  546. msg = new(userAuthRequestMsg)
  547. case msgUserAuthFailure:
  548. msg = new(userAuthFailureMsg)
  549. case msgUserAuthPubKeyOk:
  550. msg = new(userAuthPubKeyOkMsg)
  551. case msgGlobalRequest:
  552. msg = new(globalRequestMsg)
  553. case msgRequestSuccess:
  554. msg = new(channelRequestSuccessMsg)
  555. case msgRequestFailure:
  556. msg = new(channelRequestFailureMsg)
  557. case msgChannelOpen:
  558. msg = new(channelOpenMsg)
  559. case msgChannelOpenConfirm:
  560. msg = new(channelOpenConfirmMsg)
  561. case msgChannelOpenFailure:
  562. msg = new(channelOpenFailureMsg)
  563. case msgChannelWindowAdjust:
  564. msg = new(windowAdjustMsg)
  565. case msgChannelEOF:
  566. msg = new(channelEOFMsg)
  567. case msgChannelClose:
  568. msg = new(channelCloseMsg)
  569. case msgChannelRequest:
  570. msg = new(channelRequestMsg)
  571. case msgChannelSuccess:
  572. msg = new(channelRequestSuccessMsg)
  573. case msgChannelFailure:
  574. msg = new(channelRequestFailureMsg)
  575. default:
  576. return UnexpectedMessageError{0, packet[0]}
  577. }
  578. if err := unmarshal(msg, packet, packet[0]); err != nil {
  579. return err
  580. }
  581. return msg
  582. }