messages.go 14 KB

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