messages.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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 [SSH-PARAMETERS].
  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 RejectionReason
  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 4
  153. type globalRequestSuccessMsg struct {
  154. Data []byte `ssh:"rest"`
  155. }
  156. // See RFC 4254, section 4
  157. type globalRequestFailureMsg struct {
  158. Data []byte `ssh:"rest"`
  159. }
  160. // See RFC 4254, section 5.2
  161. type windowAdjustMsg struct {
  162. PeersId uint32
  163. AdditionalBytes uint32
  164. }
  165. // See RFC 4252, section 7
  166. type userAuthPubKeyOkMsg struct {
  167. Algo string
  168. PubKey string
  169. }
  170. // unmarshal parses the SSH wire data in packet into out using reflection.
  171. // expectedType is the expected SSH message type. It either returns nil on
  172. // success, or a ParseError or UnexpectedMessageError on error.
  173. func unmarshal(out interface{}, packet []byte, expectedType uint8) error {
  174. if len(packet) == 0 {
  175. return ParseError{expectedType}
  176. }
  177. if packet[0] != expectedType {
  178. return UnexpectedMessageError{expectedType, packet[0]}
  179. }
  180. packet = packet[1:]
  181. v := reflect.ValueOf(out).Elem()
  182. structType := v.Type()
  183. var ok bool
  184. for i := 0; i < v.NumField(); i++ {
  185. field := v.Field(i)
  186. t := field.Type()
  187. switch t.Kind() {
  188. case reflect.Bool:
  189. if len(packet) < 1 {
  190. return ParseError{expectedType}
  191. }
  192. field.SetBool(packet[0] != 0)
  193. packet = packet[1:]
  194. case reflect.Array:
  195. if t.Elem().Kind() != reflect.Uint8 {
  196. panic("array of non-uint8")
  197. }
  198. if len(packet) < t.Len() {
  199. return ParseError{expectedType}
  200. }
  201. for j, n := 0, t.Len(); j < n; j++ {
  202. field.Index(j).Set(reflect.ValueOf(packet[j]))
  203. }
  204. packet = packet[t.Len():]
  205. case reflect.Uint32:
  206. var u32 uint32
  207. if u32, packet, ok = parseUint32(packet); !ok {
  208. return ParseError{expectedType}
  209. }
  210. field.SetUint(uint64(u32))
  211. case reflect.String:
  212. var s []byte
  213. if s, packet, ok = parseString(packet); !ok {
  214. return ParseError{expectedType}
  215. }
  216. field.SetString(string(s))
  217. case reflect.Slice:
  218. switch t.Elem().Kind() {
  219. case reflect.Uint8:
  220. if structType.Field(i).Tag.Get("ssh") == "rest" {
  221. field.Set(reflect.ValueOf(packet))
  222. packet = nil
  223. } else {
  224. var s []byte
  225. if s, packet, ok = parseString(packet); !ok {
  226. return ParseError{expectedType}
  227. }
  228. field.Set(reflect.ValueOf(s))
  229. }
  230. case reflect.String:
  231. var nl []string
  232. if nl, packet, ok = parseNameList(packet); !ok {
  233. return ParseError{expectedType}
  234. }
  235. field.Set(reflect.ValueOf(nl))
  236. default:
  237. panic("slice of unknown type")
  238. }
  239. case reflect.Ptr:
  240. if t == bigIntType {
  241. var n *big.Int
  242. if n, packet, ok = parseInt(packet); !ok {
  243. return ParseError{expectedType}
  244. }
  245. field.Set(reflect.ValueOf(n))
  246. } else {
  247. panic("pointer to unknown type")
  248. }
  249. default:
  250. panic("unknown type")
  251. }
  252. }
  253. if len(packet) != 0 {
  254. return ParseError{expectedType}
  255. }
  256. return nil
  257. }
  258. // marshal serializes the message in msg, using the given message type.
  259. func marshal(msgType uint8, msg interface{}) []byte {
  260. out := make([]byte, 1, 64)
  261. out[0] = msgType
  262. v := reflect.ValueOf(msg)
  263. for i, n := 0, v.NumField(); i < n; i++ {
  264. field := v.Field(i)
  265. switch t := field.Type(); t.Kind() {
  266. case reflect.Bool:
  267. var v uint8
  268. if field.Bool() {
  269. v = 1
  270. }
  271. out = append(out, v)
  272. case reflect.Array:
  273. if t.Elem().Kind() != reflect.Uint8 {
  274. panic("array of non-uint8")
  275. }
  276. for j, l := 0, t.Len(); j < l; j++ {
  277. out = append(out, uint8(field.Index(j).Uint()))
  278. }
  279. case reflect.Uint32:
  280. out = appendU32(out, uint32(field.Uint()))
  281. case reflect.String:
  282. s := field.String()
  283. out = appendInt(out, len(s))
  284. out = append(out, s...)
  285. case reflect.Slice:
  286. switch t.Elem().Kind() {
  287. case reflect.Uint8:
  288. if v.Type().Field(i).Tag.Get("ssh") != "rest" {
  289. out = appendInt(out, field.Len())
  290. }
  291. out = append(out, field.Bytes()...)
  292. case reflect.String:
  293. offset := len(out)
  294. out = appendU32(out, 0)
  295. if n := field.Len(); n > 0 {
  296. for j := 0; j < n; j++ {
  297. f := field.Index(j)
  298. if j != 0 {
  299. out = append(out, ',')
  300. }
  301. out = append(out, f.String()...)
  302. }
  303. // overwrite length value
  304. binary.BigEndian.PutUint32(out[offset:], uint32(len(out)-offset-4))
  305. }
  306. default:
  307. panic("slice of unknown type")
  308. }
  309. case reflect.Ptr:
  310. if t == bigIntType {
  311. var n *big.Int
  312. nValue := reflect.ValueOf(&n)
  313. nValue.Elem().Set(field)
  314. needed := intLength(n)
  315. oldLength := len(out)
  316. if cap(out)-len(out) < needed {
  317. newOut := make([]byte, len(out), 2*(len(out)+needed))
  318. copy(newOut, out)
  319. out = newOut
  320. }
  321. out = out[:oldLength+needed]
  322. marshalInt(out[oldLength:], n)
  323. } else {
  324. panic("pointer to unknown type")
  325. }
  326. }
  327. }
  328. return out
  329. }
  330. var bigOne = big.NewInt(1)
  331. func parseString(in []byte) (out, rest []byte, ok bool) {
  332. if len(in) < 4 {
  333. return
  334. }
  335. length := binary.BigEndian.Uint32(in)
  336. if uint32(len(in)) < 4+length {
  337. return
  338. }
  339. out = in[4 : 4+length]
  340. rest = in[4+length:]
  341. ok = true
  342. return
  343. }
  344. var (
  345. comma = []byte{','}
  346. emptyNameList = []string{}
  347. )
  348. func parseNameList(in []byte) (out []string, rest []byte, ok bool) {
  349. contents, rest, ok := parseString(in)
  350. if !ok {
  351. return
  352. }
  353. if len(contents) == 0 {
  354. out = emptyNameList
  355. return
  356. }
  357. parts := bytes.Split(contents, comma)
  358. out = make([]string, len(parts))
  359. for i, part := range parts {
  360. out[i] = string(part)
  361. }
  362. return
  363. }
  364. func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) {
  365. contents, rest, ok := parseString(in)
  366. if !ok {
  367. return
  368. }
  369. out = new(big.Int)
  370. if len(contents) > 0 && contents[0]&0x80 == 0x80 {
  371. // This is a negative number
  372. notBytes := make([]byte, len(contents))
  373. for i := range notBytes {
  374. notBytes[i] = ^contents[i]
  375. }
  376. out.SetBytes(notBytes)
  377. out.Add(out, bigOne)
  378. out.Neg(out)
  379. } else {
  380. // Positive number
  381. out.SetBytes(contents)
  382. }
  383. ok = true
  384. return
  385. }
  386. func parseUint32(in []byte) (uint32, []byte, bool) {
  387. if len(in) < 4 {
  388. return 0, nil, false
  389. }
  390. return binary.BigEndian.Uint32(in), in[4:], true
  391. }
  392. func parseUint64(in []byte) (uint64, []byte, bool) {
  393. if len(in) < 8 {
  394. return 0, nil, false
  395. }
  396. return binary.BigEndian.Uint64(in), in[8:], true
  397. }
  398. func nameListLength(namelist []string) int {
  399. length := 4 /* uint32 length prefix */
  400. for i, name := range namelist {
  401. if i != 0 {
  402. length++ /* comma */
  403. }
  404. length += len(name)
  405. }
  406. return length
  407. }
  408. func intLength(n *big.Int) int {
  409. length := 4 /* length bytes */
  410. if n.Sign() < 0 {
  411. nMinus1 := new(big.Int).Neg(n)
  412. nMinus1.Sub(nMinus1, bigOne)
  413. bitLen := nMinus1.BitLen()
  414. if bitLen%8 == 0 {
  415. // The number will need 0xff padding
  416. length++
  417. }
  418. length += (bitLen + 7) / 8
  419. } else if n.Sign() == 0 {
  420. // A zero is the zero length string
  421. } else {
  422. bitLen := n.BitLen()
  423. if bitLen%8 == 0 {
  424. // The number will need 0x00 padding
  425. length++
  426. }
  427. length += (bitLen + 7) / 8
  428. }
  429. return length
  430. }
  431. func marshalUint32(to []byte, n uint32) []byte {
  432. binary.BigEndian.PutUint32(to, n)
  433. return to[4:]
  434. }
  435. func marshalUint64(to []byte, n uint64) []byte {
  436. binary.BigEndian.PutUint64(to, n)
  437. return to[8:]
  438. }
  439. func marshalInt(to []byte, n *big.Int) []byte {
  440. lengthBytes := to
  441. to = to[4:]
  442. length := 0
  443. if n.Sign() < 0 {
  444. // A negative number has to be converted to two's-complement
  445. // form. So we'll subtract 1 and invert. If the
  446. // most-significant-bit isn't set then we'll need to pad the
  447. // beginning with 0xff in order to keep the number negative.
  448. nMinus1 := new(big.Int).Neg(n)
  449. nMinus1.Sub(nMinus1, bigOne)
  450. bytes := nMinus1.Bytes()
  451. for i := range bytes {
  452. bytes[i] ^= 0xff
  453. }
  454. if len(bytes) == 0 || bytes[0]&0x80 == 0 {
  455. to[0] = 0xff
  456. to = to[1:]
  457. length++
  458. }
  459. nBytes := copy(to, bytes)
  460. to = to[nBytes:]
  461. length += nBytes
  462. } else if n.Sign() == 0 {
  463. // A zero is the zero length string
  464. } else {
  465. bytes := n.Bytes()
  466. if len(bytes) > 0 && bytes[0]&0x80 != 0 {
  467. // We'll have to pad this with a 0x00 in order to
  468. // stop it looking like a negative number.
  469. to[0] = 0
  470. to = to[1:]
  471. length++
  472. }
  473. nBytes := copy(to, bytes)
  474. to = to[nBytes:]
  475. length += nBytes
  476. }
  477. lengthBytes[0] = byte(length >> 24)
  478. lengthBytes[1] = byte(length >> 16)
  479. lengthBytes[2] = byte(length >> 8)
  480. lengthBytes[3] = byte(length)
  481. return to
  482. }
  483. func writeInt(w io.Writer, n *big.Int) {
  484. length := intLength(n)
  485. buf := make([]byte, length)
  486. marshalInt(buf, n)
  487. w.Write(buf)
  488. }
  489. func writeString(w io.Writer, s []byte) {
  490. var lengthBytes [4]byte
  491. lengthBytes[0] = byte(len(s) >> 24)
  492. lengthBytes[1] = byte(len(s) >> 16)
  493. lengthBytes[2] = byte(len(s) >> 8)
  494. lengthBytes[3] = byte(len(s))
  495. w.Write(lengthBytes[:])
  496. w.Write(s)
  497. }
  498. func stringLength(n int) int {
  499. return 4 + n
  500. }
  501. func marshalString(to []byte, s []byte) []byte {
  502. to[0] = byte(len(s) >> 24)
  503. to[1] = byte(len(s) >> 16)
  504. to[2] = byte(len(s) >> 8)
  505. to[3] = byte(len(s))
  506. to = to[4:]
  507. copy(to, s)
  508. return to[len(s):]
  509. }
  510. var bigIntType = reflect.TypeOf((*big.Int)(nil))
  511. // Decode a packet into it's corresponding message.
  512. func decode(packet []byte) interface{} {
  513. var msg interface{}
  514. switch packet[0] {
  515. case msgDisconnect:
  516. msg = new(disconnectMsg)
  517. case msgServiceRequest:
  518. msg = new(serviceRequestMsg)
  519. case msgServiceAccept:
  520. msg = new(serviceAcceptMsg)
  521. case msgKexInit:
  522. msg = new(kexInitMsg)
  523. case msgKexDHInit:
  524. msg = new(kexDHInitMsg)
  525. case msgKexDHReply:
  526. msg = new(kexDHReplyMsg)
  527. case msgUserAuthRequest:
  528. msg = new(userAuthRequestMsg)
  529. case msgUserAuthFailure:
  530. msg = new(userAuthFailureMsg)
  531. case msgUserAuthPubKeyOk:
  532. msg = new(userAuthPubKeyOkMsg)
  533. case msgGlobalRequest:
  534. msg = new(globalRequestMsg)
  535. case msgRequestSuccess:
  536. msg = new(globalRequestSuccessMsg)
  537. case msgRequestFailure:
  538. msg = new(globalRequestFailureMsg)
  539. case msgChannelOpen:
  540. msg = new(channelOpenMsg)
  541. case msgChannelOpenConfirm:
  542. msg = new(channelOpenConfirmMsg)
  543. case msgChannelOpenFailure:
  544. msg = new(channelOpenFailureMsg)
  545. case msgChannelWindowAdjust:
  546. msg = new(windowAdjustMsg)
  547. case msgChannelEOF:
  548. msg = new(channelEOFMsg)
  549. case msgChannelClose:
  550. msg = new(channelCloseMsg)
  551. case msgChannelRequest:
  552. msg = new(channelRequestMsg)
  553. case msgChannelSuccess:
  554. msg = new(channelRequestSuccessMsg)
  555. case msgChannelFailure:
  556. msg = new(channelRequestFailureMsg)
  557. default:
  558. return UnexpectedMessageError{0, packet[0]}
  559. }
  560. if err := unmarshal(msg, packet, packet[0]); err != nil {
  561. return err
  562. }
  563. return msg
  564. }