messages.go 14 KB

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