messages.go 14 KB

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