messages.go 20 KB

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