messages.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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. "errors"
  9. "fmt"
  10. "io"
  11. "math/big"
  12. "reflect"
  13. "strconv"
  14. "strings"
  15. )
  16. // These are SSH message type numbers. They are scattered around several
  17. // documents but many were taken from [SSH-PARAMETERS].
  18. const (
  19. msgIgnore = 2
  20. msgUnimplemented = 3
  21. msgDebug = 4
  22. msgNewKeys = 21
  23. )
  24. // SSH messages:
  25. //
  26. // These structures mirror the wire format of the corresponding SSH messages.
  27. // They are marshaled using reflection with the marshal and unmarshal functions
  28. // in this file. The only wrinkle is that a final member of type []byte with a
  29. // ssh tag of "rest" receives the remainder of a packet when unmarshaling.
  30. // See RFC 4253, section 11.1.
  31. const msgDisconnect = 1
  32. // disconnectMsg is the message that signals a disconnect. It is also
  33. // the error type returned from mux.Wait()
  34. type disconnectMsg struct {
  35. Reason uint32 `sshtype:"1"`
  36. Message string
  37. Language string
  38. }
  39. func (d *disconnectMsg) Error() string {
  40. return fmt.Sprintf("ssh: disconnect, reason %d: %s", d.Reason, d.Message)
  41. }
  42. // See RFC 4253, section 7.1.
  43. const msgKexInit = 20
  44. type kexInitMsg struct {
  45. Cookie [16]byte `sshtype:"20"`
  46. KexAlgos []string
  47. ServerHostKeyAlgos []string
  48. CiphersClientServer []string
  49. CiphersServerClient []string
  50. MACsClientServer []string
  51. MACsServerClient []string
  52. CompressionClientServer []string
  53. CompressionServerClient []string
  54. LanguagesClientServer []string
  55. LanguagesServerClient []string
  56. FirstKexFollows bool
  57. Reserved uint32
  58. }
  59. // See RFC 4253, section 8.
  60. // Diffie-Helman
  61. const msgKexDHInit = 30
  62. type kexDHInitMsg struct {
  63. X *big.Int `sshtype:"30"`
  64. }
  65. const msgKexECDHInit = 30
  66. type kexECDHInitMsg struct {
  67. ClientPubKey []byte `sshtype:"30"`
  68. }
  69. const msgKexECDHReply = 31
  70. type kexECDHReplyMsg struct {
  71. HostKey []byte `sshtype:"31"`
  72. EphemeralPubKey []byte
  73. Signature []byte
  74. }
  75. const msgKexDHReply = 31
  76. type kexDHReplyMsg struct {
  77. HostKey []byte `sshtype:"31"`
  78. Y *big.Int
  79. Signature []byte
  80. }
  81. // See RFC 4253, section 10.
  82. const msgServiceRequest = 5
  83. type serviceRequestMsg struct {
  84. Service string `sshtype:"5"`
  85. }
  86. // See RFC 4253, section 10.
  87. const msgServiceAccept = 6
  88. type serviceAcceptMsg struct {
  89. Service string `sshtype:"6"`
  90. }
  91. // See RFC 4252, section 5.
  92. const msgUserAuthRequest = 50
  93. type userAuthRequestMsg struct {
  94. User string `sshtype:"50"`
  95. Service string
  96. Method string
  97. Payload []byte `ssh:"rest"`
  98. }
  99. // Used for debug printouts of packets.
  100. type userAuthSuccessMsg struct {
  101. }
  102. // See RFC 4252, section 5.1
  103. const msgUserAuthFailure = 51
  104. type userAuthFailureMsg struct {
  105. Methods []string `sshtype:"51"`
  106. PartialSuccess bool
  107. }
  108. // See RFC 4252, section 5.1
  109. const msgUserAuthSuccess = 52
  110. // See RFC 4252, section 5.4
  111. const msgUserAuthBanner = 53
  112. type userAuthBannerMsg struct {
  113. Message string `sshtype:"53"`
  114. // unused, but required to allow message parsing
  115. Language string
  116. }
  117. // See RFC 4256, section 3.2
  118. const msgUserAuthInfoRequest = 60
  119. const msgUserAuthInfoResponse = 61
  120. type userAuthInfoRequestMsg struct {
  121. User string `sshtype:"60"`
  122. Instruction string
  123. DeprecatedLanguage string
  124. NumPrompts uint32
  125. Prompts []byte `ssh:"rest"`
  126. }
  127. // See RFC 4254, section 5.1.
  128. const msgChannelOpen = 90
  129. type channelOpenMsg struct {
  130. ChanType string `sshtype:"90"`
  131. PeersID uint32
  132. PeersWindow uint32
  133. MaxPacketSize uint32
  134. TypeSpecificData []byte `ssh:"rest"`
  135. }
  136. const msgChannelExtendedData = 95
  137. const msgChannelData = 94
  138. // Used for debug print outs of packets.
  139. type channelDataMsg struct {
  140. PeersID uint32 `sshtype:"94"`
  141. Length uint32
  142. Rest []byte `ssh:"rest"`
  143. }
  144. // See RFC 4254, section 5.1.
  145. const msgChannelOpenConfirm = 91
  146. type channelOpenConfirmMsg struct {
  147. PeersID uint32 `sshtype:"91"`
  148. MyID uint32
  149. MyWindow uint32
  150. MaxPacketSize uint32
  151. TypeSpecificData []byte `ssh:"rest"`
  152. }
  153. // See RFC 4254, section 5.1.
  154. const msgChannelOpenFailure = 92
  155. type channelOpenFailureMsg struct {
  156. PeersID uint32 `sshtype:"92"`
  157. Reason RejectionReason
  158. Message string
  159. Language string
  160. }
  161. const msgChannelRequest = 98
  162. type channelRequestMsg struct {
  163. PeersID uint32 `sshtype:"98"`
  164. Request string
  165. WantReply bool
  166. RequestSpecificData []byte `ssh:"rest"`
  167. }
  168. // See RFC 4254, section 5.4.
  169. const msgChannelSuccess = 99
  170. type channelRequestSuccessMsg struct {
  171. PeersID uint32 `sshtype:"99"`
  172. }
  173. // See RFC 4254, section 5.4.
  174. const msgChannelFailure = 100
  175. type channelRequestFailureMsg struct {
  176. PeersID uint32 `sshtype:"100"`
  177. }
  178. // See RFC 4254, section 5.3
  179. const msgChannelClose = 97
  180. type channelCloseMsg struct {
  181. PeersID uint32 `sshtype:"97"`
  182. }
  183. // See RFC 4254, section 5.3
  184. const msgChannelEOF = 96
  185. type channelEOFMsg struct {
  186. PeersID uint32 `sshtype:"96"`
  187. }
  188. // See RFC 4254, section 4
  189. const msgGlobalRequest = 80
  190. type globalRequestMsg struct {
  191. Type string `sshtype:"80"`
  192. WantReply bool
  193. Data []byte `ssh:"rest"`
  194. }
  195. // See RFC 4254, section 4
  196. const msgRequestSuccess = 81
  197. type globalRequestSuccessMsg struct {
  198. Data []byte `ssh:"rest" sshtype:"81"`
  199. }
  200. // See RFC 4254, section 4
  201. const msgRequestFailure = 82
  202. type globalRequestFailureMsg struct {
  203. Data []byte `ssh:"rest" sshtype:"82"`
  204. }
  205. // See RFC 4254, section 5.2
  206. const msgChannelWindowAdjust = 93
  207. type windowAdjustMsg struct {
  208. PeersID uint32 `sshtype:"93"`
  209. AdditionalBytes uint32
  210. }
  211. // See RFC 4252, section 7
  212. const msgUserAuthPubKeyOk = 60
  213. type userAuthPubKeyOkMsg struct {
  214. Algo string `sshtype:"60"`
  215. PubKey []byte
  216. }
  217. // See RFC 4462, section 3
  218. const msgUserAuthGSSAPIResponse = 60
  219. type userAuthGSSAPIResponse struct {
  220. SupportMech []byte `sshtype:"60"`
  221. }
  222. const msgUserAuthGSSAPIToken = 61
  223. type userAuthGSSAPIToken struct {
  224. Token []byte `sshtype:"61"`
  225. }
  226. const msgUserAuthGSSAPIMIC = 66
  227. type userAuthGSSAPIMIC struct {
  228. MIC []byte `sshtype:"66"`
  229. }
  230. // See RFC 4462, section 3.9
  231. const msgUserAuthGSSAPIErrTok = 64
  232. type userAuthGSSAPIErrTok struct {
  233. ErrorToken []byte `sshtype:"64"`
  234. }
  235. // See RFC 4462, section 3.8
  236. const msgUserAuthGSSAPIError = 65
  237. type userAuthGSSAPIError struct {
  238. MajorStatus uint32 `sshtype:"65"`
  239. MinorStatus uint32
  240. Message string
  241. LanguageTag string
  242. }
  243. // typeTags returns the possible type bytes for the given reflect.Type, which
  244. // should be a struct. The possible values are separated by a '|' character.
  245. func typeTags(structType reflect.Type) (tags []byte) {
  246. tagStr := structType.Field(0).Tag.Get("sshtype")
  247. for _, tag := range strings.Split(tagStr, "|") {
  248. i, err := strconv.Atoi(tag)
  249. if err == nil {
  250. tags = append(tags, byte(i))
  251. }
  252. }
  253. return tags
  254. }
  255. func fieldError(t reflect.Type, field int, problem string) error {
  256. if problem != "" {
  257. problem = ": " + problem
  258. }
  259. return fmt.Errorf("ssh: unmarshal error for field %s of type %s%s", t.Field(field).Name, t.Name(), problem)
  260. }
  261. var errShortRead = errors.New("ssh: short read")
  262. // Unmarshal parses data in SSH wire format into a structure. The out
  263. // argument should be a pointer to struct. If the first member of the
  264. // struct has the "sshtype" tag set to a '|'-separated set of numbers
  265. // in decimal, the packet must start with one of those numbers. In
  266. // case of error, Unmarshal returns a ParseError or
  267. // UnexpectedMessageError.
  268. func Unmarshal(data []byte, out interface{}) error {
  269. v := reflect.ValueOf(out).Elem()
  270. structType := v.Type()
  271. expectedTypes := typeTags(structType)
  272. var expectedType byte
  273. if len(expectedTypes) > 0 {
  274. expectedType = expectedTypes[0]
  275. }
  276. if len(data) == 0 {
  277. return parseError(expectedType)
  278. }
  279. if len(expectedTypes) > 0 {
  280. goodType := false
  281. for _, e := range expectedTypes {
  282. if e > 0 && data[0] == e {
  283. goodType = true
  284. break
  285. }
  286. }
  287. if !goodType {
  288. return fmt.Errorf("ssh: unexpected message type %d (expected one of %v)", data[0], expectedTypes)
  289. }
  290. data = data[1:]
  291. }
  292. var ok bool
  293. for i := 0; i < v.NumField(); i++ {
  294. field := v.Field(i)
  295. t := field.Type()
  296. switch t.Kind() {
  297. case reflect.Bool:
  298. if len(data) < 1 {
  299. return errShortRead
  300. }
  301. field.SetBool(data[0] != 0)
  302. data = data[1:]
  303. case reflect.Array:
  304. if t.Elem().Kind() != reflect.Uint8 {
  305. return fieldError(structType, i, "array of unsupported type")
  306. }
  307. if len(data) < t.Len() {
  308. return errShortRead
  309. }
  310. for j, n := 0, t.Len(); j < n; j++ {
  311. field.Index(j).Set(reflect.ValueOf(data[j]))
  312. }
  313. data = data[t.Len():]
  314. case reflect.Uint64:
  315. var u64 uint64
  316. if u64, data, ok = parseUint64(data); !ok {
  317. return errShortRead
  318. }
  319. field.SetUint(u64)
  320. case reflect.Uint32:
  321. var u32 uint32
  322. if u32, data, ok = parseUint32(data); !ok {
  323. return errShortRead
  324. }
  325. field.SetUint(uint64(u32))
  326. case reflect.Uint8:
  327. if len(data) < 1 {
  328. return errShortRead
  329. }
  330. field.SetUint(uint64(data[0]))
  331. data = data[1:]
  332. case reflect.String:
  333. var s []byte
  334. if s, data, ok = parseString(data); !ok {
  335. return fieldError(structType, i, "")
  336. }
  337. field.SetString(string(s))
  338. case reflect.Slice:
  339. switch t.Elem().Kind() {
  340. case reflect.Uint8:
  341. if structType.Field(i).Tag.Get("ssh") == "rest" {
  342. field.Set(reflect.ValueOf(data))
  343. data = nil
  344. } else {
  345. var s []byte
  346. if s, data, ok = parseString(data); !ok {
  347. return errShortRead
  348. }
  349. field.Set(reflect.ValueOf(s))
  350. }
  351. case reflect.String:
  352. var nl []string
  353. if nl, data, ok = parseNameList(data); !ok {
  354. return errShortRead
  355. }
  356. field.Set(reflect.ValueOf(nl))
  357. default:
  358. return fieldError(structType, i, "slice of unsupported type")
  359. }
  360. case reflect.Ptr:
  361. if t == bigIntType {
  362. var n *big.Int
  363. if n, data, ok = parseInt(data); !ok {
  364. return errShortRead
  365. }
  366. field.Set(reflect.ValueOf(n))
  367. } else {
  368. return fieldError(structType, i, "pointer to unsupported type")
  369. }
  370. default:
  371. return fieldError(structType, i, fmt.Sprintf("unsupported type: %v", t))
  372. }
  373. }
  374. if len(data) != 0 {
  375. return parseError(expectedType)
  376. }
  377. return nil
  378. }
  379. // Marshal serializes the message in msg to SSH wire format. The msg
  380. // argument should be a struct or pointer to struct. If the first
  381. // member has the "sshtype" tag set to a number in decimal, that
  382. // number is prepended to the result. If the last of member has the
  383. // "ssh" tag set to "rest", its contents are appended to the output.
  384. func Marshal(msg interface{}) []byte {
  385. out := make([]byte, 0, 64)
  386. return marshalStruct(out, msg)
  387. }
  388. func marshalStruct(out []byte, msg interface{}) []byte {
  389. v := reflect.Indirect(reflect.ValueOf(msg))
  390. msgTypes := typeTags(v.Type())
  391. if len(msgTypes) > 0 {
  392. out = append(out, msgTypes[0])
  393. }
  394. for i, n := 0, v.NumField(); i < n; i++ {
  395. field := v.Field(i)
  396. switch t := field.Type(); t.Kind() {
  397. case reflect.Bool:
  398. var v uint8
  399. if field.Bool() {
  400. v = 1
  401. }
  402. out = append(out, v)
  403. case reflect.Array:
  404. if t.Elem().Kind() != reflect.Uint8 {
  405. panic(fmt.Sprintf("array of non-uint8 in field %d: %T", i, field.Interface()))
  406. }
  407. for j, l := 0, t.Len(); j < l; j++ {
  408. out = append(out, uint8(field.Index(j).Uint()))
  409. }
  410. case reflect.Uint32:
  411. out = appendU32(out, uint32(field.Uint()))
  412. case reflect.Uint64:
  413. out = appendU64(out, uint64(field.Uint()))
  414. case reflect.Uint8:
  415. out = append(out, uint8(field.Uint()))
  416. case reflect.String:
  417. s := field.String()
  418. out = appendInt(out, len(s))
  419. out = append(out, s...)
  420. case reflect.Slice:
  421. switch t.Elem().Kind() {
  422. case reflect.Uint8:
  423. if v.Type().Field(i).Tag.Get("ssh") != "rest" {
  424. out = appendInt(out, field.Len())
  425. }
  426. out = append(out, field.Bytes()...)
  427. case reflect.String:
  428. offset := len(out)
  429. out = appendU32(out, 0)
  430. if n := field.Len(); n > 0 {
  431. for j := 0; j < n; j++ {
  432. f := field.Index(j)
  433. if j != 0 {
  434. out = append(out, ',')
  435. }
  436. out = append(out, f.String()...)
  437. }
  438. // overwrite length value
  439. binary.BigEndian.PutUint32(out[offset:], uint32(len(out)-offset-4))
  440. }
  441. default:
  442. panic(fmt.Sprintf("slice of unknown type in field %d: %T", i, field.Interface()))
  443. }
  444. case reflect.Ptr:
  445. if t == bigIntType {
  446. var n *big.Int
  447. nValue := reflect.ValueOf(&n)
  448. nValue.Elem().Set(field)
  449. needed := intLength(n)
  450. oldLength := len(out)
  451. if cap(out)-len(out) < needed {
  452. newOut := make([]byte, len(out), 2*(len(out)+needed))
  453. copy(newOut, out)
  454. out = newOut
  455. }
  456. out = out[:oldLength+needed]
  457. marshalInt(out[oldLength:], n)
  458. } else {
  459. panic(fmt.Sprintf("pointer to unknown type in field %d: %T", i, field.Interface()))
  460. }
  461. }
  462. }
  463. return out
  464. }
  465. var bigOne = big.NewInt(1)
  466. func parseString(in []byte) (out, rest []byte, ok bool) {
  467. if len(in) < 4 {
  468. return
  469. }
  470. length := binary.BigEndian.Uint32(in)
  471. in = in[4:]
  472. if uint32(len(in)) < length {
  473. return
  474. }
  475. out = in[:length]
  476. rest = in[length:]
  477. ok = true
  478. return
  479. }
  480. var (
  481. comma = []byte{','}
  482. emptyNameList = []string{}
  483. )
  484. func parseNameList(in []byte) (out []string, rest []byte, ok bool) {
  485. contents, rest, ok := parseString(in)
  486. if !ok {
  487. return
  488. }
  489. if len(contents) == 0 {
  490. out = emptyNameList
  491. return
  492. }
  493. parts := bytes.Split(contents, comma)
  494. out = make([]string, len(parts))
  495. for i, part := range parts {
  496. out[i] = string(part)
  497. }
  498. return
  499. }
  500. func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) {
  501. contents, rest, ok := parseString(in)
  502. if !ok {
  503. return
  504. }
  505. out = new(big.Int)
  506. if len(contents) > 0 && contents[0]&0x80 == 0x80 {
  507. // This is a negative number
  508. notBytes := make([]byte, len(contents))
  509. for i := range notBytes {
  510. notBytes[i] = ^contents[i]
  511. }
  512. out.SetBytes(notBytes)
  513. out.Add(out, bigOne)
  514. out.Neg(out)
  515. } else {
  516. // Positive number
  517. out.SetBytes(contents)
  518. }
  519. ok = true
  520. return
  521. }
  522. func parseUint32(in []byte) (uint32, []byte, bool) {
  523. if len(in) < 4 {
  524. return 0, nil, false
  525. }
  526. return binary.BigEndian.Uint32(in), in[4:], true
  527. }
  528. func parseUint64(in []byte) (uint64, []byte, bool) {
  529. if len(in) < 8 {
  530. return 0, nil, false
  531. }
  532. return binary.BigEndian.Uint64(in), in[8:], true
  533. }
  534. func intLength(n *big.Int) int {
  535. length := 4 /* length bytes */
  536. if n.Sign() < 0 {
  537. nMinus1 := new(big.Int).Neg(n)
  538. nMinus1.Sub(nMinus1, bigOne)
  539. bitLen := nMinus1.BitLen()
  540. if bitLen%8 == 0 {
  541. // The number will need 0xff padding
  542. length++
  543. }
  544. length += (bitLen + 7) / 8
  545. } else if n.Sign() == 0 {
  546. // A zero is the zero length string
  547. } else {
  548. bitLen := n.BitLen()
  549. if bitLen%8 == 0 {
  550. // The number will need 0x00 padding
  551. length++
  552. }
  553. length += (bitLen + 7) / 8
  554. }
  555. return length
  556. }
  557. func marshalUint32(to []byte, n uint32) []byte {
  558. binary.BigEndian.PutUint32(to, n)
  559. return to[4:]
  560. }
  561. func marshalUint64(to []byte, n uint64) []byte {
  562. binary.BigEndian.PutUint64(to, n)
  563. return to[8:]
  564. }
  565. func marshalInt(to []byte, n *big.Int) []byte {
  566. lengthBytes := to
  567. to = to[4:]
  568. length := 0
  569. if n.Sign() < 0 {
  570. // A negative number has to be converted to two's-complement
  571. // form. So we'll subtract 1 and invert. If the
  572. // most-significant-bit isn't set then we'll need to pad the
  573. // beginning with 0xff in order to keep the number negative.
  574. nMinus1 := new(big.Int).Neg(n)
  575. nMinus1.Sub(nMinus1, bigOne)
  576. bytes := nMinus1.Bytes()
  577. for i := range bytes {
  578. bytes[i] ^= 0xff
  579. }
  580. if len(bytes) == 0 || bytes[0]&0x80 == 0 {
  581. to[0] = 0xff
  582. to = to[1:]
  583. length++
  584. }
  585. nBytes := copy(to, bytes)
  586. to = to[nBytes:]
  587. length += nBytes
  588. } else if n.Sign() == 0 {
  589. // A zero is the zero length string
  590. } else {
  591. bytes := n.Bytes()
  592. if len(bytes) > 0 && bytes[0]&0x80 != 0 {
  593. // We'll have to pad this with a 0x00 in order to
  594. // stop it looking like a negative number.
  595. to[0] = 0
  596. to = to[1:]
  597. length++
  598. }
  599. nBytes := copy(to, bytes)
  600. to = to[nBytes:]
  601. length += nBytes
  602. }
  603. lengthBytes[0] = byte(length >> 24)
  604. lengthBytes[1] = byte(length >> 16)
  605. lengthBytes[2] = byte(length >> 8)
  606. lengthBytes[3] = byte(length)
  607. return to
  608. }
  609. func writeInt(w io.Writer, n *big.Int) {
  610. length := intLength(n)
  611. buf := make([]byte, length)
  612. marshalInt(buf, n)
  613. w.Write(buf)
  614. }
  615. func writeString(w io.Writer, s []byte) {
  616. var lengthBytes [4]byte
  617. lengthBytes[0] = byte(len(s) >> 24)
  618. lengthBytes[1] = byte(len(s) >> 16)
  619. lengthBytes[2] = byte(len(s) >> 8)
  620. lengthBytes[3] = byte(len(s))
  621. w.Write(lengthBytes[:])
  622. w.Write(s)
  623. }
  624. func stringLength(n int) int {
  625. return 4 + n
  626. }
  627. func marshalString(to []byte, s []byte) []byte {
  628. to[0] = byte(len(s) >> 24)
  629. to[1] = byte(len(s) >> 16)
  630. to[2] = byte(len(s) >> 8)
  631. to[3] = byte(len(s))
  632. to = to[4:]
  633. copy(to, s)
  634. return to[len(s):]
  635. }
  636. var bigIntType = reflect.TypeOf((*big.Int)(nil))
  637. // Decode a packet into its corresponding message.
  638. func decode(packet []byte) (interface{}, error) {
  639. var msg interface{}
  640. switch packet[0] {
  641. case msgDisconnect:
  642. msg = new(disconnectMsg)
  643. case msgServiceRequest:
  644. msg = new(serviceRequestMsg)
  645. case msgServiceAccept:
  646. msg = new(serviceAcceptMsg)
  647. case msgKexInit:
  648. msg = new(kexInitMsg)
  649. case msgKexDHInit:
  650. msg = new(kexDHInitMsg)
  651. case msgKexDHReply:
  652. msg = new(kexDHReplyMsg)
  653. case msgUserAuthRequest:
  654. msg = new(userAuthRequestMsg)
  655. case msgUserAuthSuccess:
  656. return new(userAuthSuccessMsg), nil
  657. case msgUserAuthFailure:
  658. msg = new(userAuthFailureMsg)
  659. case msgUserAuthPubKeyOk:
  660. msg = new(userAuthPubKeyOkMsg)
  661. case msgGlobalRequest:
  662. msg = new(globalRequestMsg)
  663. case msgRequestSuccess:
  664. msg = new(globalRequestSuccessMsg)
  665. case msgRequestFailure:
  666. msg = new(globalRequestFailureMsg)
  667. case msgChannelOpen:
  668. msg = new(channelOpenMsg)
  669. case msgChannelData:
  670. msg = new(channelDataMsg)
  671. case msgChannelOpenConfirm:
  672. msg = new(channelOpenConfirmMsg)
  673. case msgChannelOpenFailure:
  674. msg = new(channelOpenFailureMsg)
  675. case msgChannelWindowAdjust:
  676. msg = new(windowAdjustMsg)
  677. case msgChannelEOF:
  678. msg = new(channelEOFMsg)
  679. case msgChannelClose:
  680. msg = new(channelCloseMsg)
  681. case msgChannelRequest:
  682. msg = new(channelRequestMsg)
  683. case msgChannelSuccess:
  684. msg = new(channelRequestSuccessMsg)
  685. case msgChannelFailure:
  686. msg = new(channelRequestFailureMsg)
  687. case msgUserAuthGSSAPIToken:
  688. msg = new(userAuthGSSAPIToken)
  689. case msgUserAuthGSSAPIMIC:
  690. msg = new(userAuthGSSAPIMIC)
  691. case msgUserAuthGSSAPIErrTok:
  692. msg = new(userAuthGSSAPIErrTok)
  693. case msgUserAuthGSSAPIError:
  694. msg = new(userAuthGSSAPIError)
  695. default:
  696. return nil, unexpectedMessageError(0, packet[0])
  697. }
  698. if err := Unmarshal(packet, msg); err != nil {
  699. return nil, err
  700. }
  701. return msg, nil
  702. }
  703. var packetTypeNames = map[byte]string{
  704. msgDisconnect: "disconnectMsg",
  705. msgServiceRequest: "serviceRequestMsg",
  706. msgServiceAccept: "serviceAcceptMsg",
  707. msgKexInit: "kexInitMsg",
  708. msgKexDHInit: "kexDHInitMsg",
  709. msgKexDHReply: "kexDHReplyMsg",
  710. msgUserAuthRequest: "userAuthRequestMsg",
  711. msgUserAuthSuccess: "userAuthSuccessMsg",
  712. msgUserAuthFailure: "userAuthFailureMsg",
  713. msgUserAuthPubKeyOk: "userAuthPubKeyOkMsg",
  714. msgGlobalRequest: "globalRequestMsg",
  715. msgRequestSuccess: "globalRequestSuccessMsg",
  716. msgRequestFailure: "globalRequestFailureMsg",
  717. msgChannelOpen: "channelOpenMsg",
  718. msgChannelData: "channelDataMsg",
  719. msgChannelOpenConfirm: "channelOpenConfirmMsg",
  720. msgChannelOpenFailure: "channelOpenFailureMsg",
  721. msgChannelWindowAdjust: "windowAdjustMsg",
  722. msgChannelEOF: "channelEOFMsg",
  723. msgChannelClose: "channelCloseMsg",
  724. msgChannelRequest: "channelRequestMsg",
  725. msgChannelSuccess: "channelRequestSuccessMsg",
  726. msgChannelFailure: "channelRequestFailureMsg",
  727. }