messages.go 20 KB

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