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