messages.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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-Hellman
  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. // Transport layer OpenSSH extension. See [PROTOCOL], section 1.9
  272. const msgPing = 192
  273. type pingMsg struct {
  274. Data string `sshtype:"192"`
  275. }
  276. // Transport layer OpenSSH extension. See [PROTOCOL], section 1.9
  277. const msgPong = 193
  278. type pongMsg struct {
  279. Data string `sshtype:"193"`
  280. }
  281. // typeTags returns the possible type bytes for the given reflect.Type, which
  282. // should be a struct. The possible values are separated by a '|' character.
  283. func typeTags(structType reflect.Type) (tags []byte) {
  284. tagStr := structType.Field(0).Tag.Get("sshtype")
  285. for _, tag := range strings.Split(tagStr, "|") {
  286. i, err := strconv.Atoi(tag)
  287. if err == nil {
  288. tags = append(tags, byte(i))
  289. }
  290. }
  291. return tags
  292. }
  293. func fieldError(t reflect.Type, field int, problem string) error {
  294. if problem != "" {
  295. problem = ": " + problem
  296. }
  297. return fmt.Errorf("ssh: unmarshal error for field %s of type %s%s", t.Field(field).Name, t.Name(), problem)
  298. }
  299. var errShortRead = errors.New("ssh: short read")
  300. // Unmarshal parses data in SSH wire format into a structure. The out
  301. // argument should be a pointer to struct. If the first member of the
  302. // struct has the "sshtype" tag set to a '|'-separated set of numbers
  303. // in decimal, the packet must start with one of those numbers. In
  304. // case of error, Unmarshal returns a ParseError or
  305. // UnexpectedMessageError.
  306. func Unmarshal(data []byte, out interface{}) error {
  307. v := reflect.ValueOf(out).Elem()
  308. structType := v.Type()
  309. expectedTypes := typeTags(structType)
  310. var expectedType byte
  311. if len(expectedTypes) > 0 {
  312. expectedType = expectedTypes[0]
  313. }
  314. if len(data) == 0 {
  315. return parseError(expectedType)
  316. }
  317. if len(expectedTypes) > 0 {
  318. goodType := false
  319. for _, e := range expectedTypes {
  320. if e > 0 && data[0] == e {
  321. goodType = true
  322. break
  323. }
  324. }
  325. if !goodType {
  326. return fmt.Errorf("ssh: unexpected message type %d (expected one of %v)", data[0], expectedTypes)
  327. }
  328. data = data[1:]
  329. }
  330. var ok bool
  331. for i := 0; i < v.NumField(); i++ {
  332. field := v.Field(i)
  333. t := field.Type()
  334. switch t.Kind() {
  335. case reflect.Bool:
  336. if len(data) < 1 {
  337. return errShortRead
  338. }
  339. field.SetBool(data[0] != 0)
  340. data = data[1:]
  341. case reflect.Array:
  342. if t.Elem().Kind() != reflect.Uint8 {
  343. return fieldError(structType, i, "array of unsupported type")
  344. }
  345. if len(data) < t.Len() {
  346. return errShortRead
  347. }
  348. for j, n := 0, t.Len(); j < n; j++ {
  349. field.Index(j).Set(reflect.ValueOf(data[j]))
  350. }
  351. data = data[t.Len():]
  352. case reflect.Uint64:
  353. var u64 uint64
  354. if u64, data, ok = parseUint64(data); !ok {
  355. return errShortRead
  356. }
  357. field.SetUint(u64)
  358. case reflect.Uint32:
  359. var u32 uint32
  360. if u32, data, ok = parseUint32(data); !ok {
  361. return errShortRead
  362. }
  363. field.SetUint(uint64(u32))
  364. case reflect.Uint8:
  365. if len(data) < 1 {
  366. return errShortRead
  367. }
  368. field.SetUint(uint64(data[0]))
  369. data = data[1:]
  370. case reflect.String:
  371. var s []byte
  372. if s, data, ok = parseString(data); !ok {
  373. return fieldError(structType, i, "")
  374. }
  375. field.SetString(string(s))
  376. case reflect.Slice:
  377. switch t.Elem().Kind() {
  378. case reflect.Uint8:
  379. if structType.Field(i).Tag.Get("ssh") == "rest" {
  380. field.Set(reflect.ValueOf(data))
  381. data = nil
  382. } else {
  383. var s []byte
  384. if s, data, ok = parseString(data); !ok {
  385. return errShortRead
  386. }
  387. field.Set(reflect.ValueOf(s))
  388. }
  389. case reflect.String:
  390. var nl []string
  391. if nl, data, ok = parseNameList(data); !ok {
  392. return errShortRead
  393. }
  394. field.Set(reflect.ValueOf(nl))
  395. default:
  396. return fieldError(structType, i, "slice of unsupported type")
  397. }
  398. case reflect.Ptr:
  399. if t == bigIntType {
  400. var n *big.Int
  401. if n, data, ok = parseInt(data); !ok {
  402. return errShortRead
  403. }
  404. field.Set(reflect.ValueOf(n))
  405. } else {
  406. return fieldError(structType, i, "pointer to unsupported type")
  407. }
  408. default:
  409. return fieldError(structType, i, fmt.Sprintf("unsupported type: %v", t))
  410. }
  411. }
  412. if len(data) != 0 {
  413. return parseError(expectedType)
  414. }
  415. return nil
  416. }
  417. // Marshal serializes the message in msg to SSH wire format. The msg
  418. // argument should be a struct or pointer to struct. If the first
  419. // member has the "sshtype" tag set to a number in decimal, that
  420. // number is prepended to the result. If the last of member has the
  421. // "ssh" tag set to "rest", its contents are appended to the output.
  422. func Marshal(msg interface{}) []byte {
  423. out := make([]byte, 0, 64)
  424. return marshalStruct(out, msg)
  425. }
  426. func marshalStruct(out []byte, msg interface{}) []byte {
  427. v := reflect.Indirect(reflect.ValueOf(msg))
  428. msgTypes := typeTags(v.Type())
  429. if len(msgTypes) > 0 {
  430. out = append(out, msgTypes[0])
  431. }
  432. for i, n := 0, v.NumField(); i < n; i++ {
  433. field := v.Field(i)
  434. switch t := field.Type(); t.Kind() {
  435. case reflect.Bool:
  436. var v uint8
  437. if field.Bool() {
  438. v = 1
  439. }
  440. out = append(out, v)
  441. case reflect.Array:
  442. if t.Elem().Kind() != reflect.Uint8 {
  443. panic(fmt.Sprintf("array of non-uint8 in field %d: %T", i, field.Interface()))
  444. }
  445. for j, l := 0, t.Len(); j < l; j++ {
  446. out = append(out, uint8(field.Index(j).Uint()))
  447. }
  448. case reflect.Uint32:
  449. out = appendU32(out, uint32(field.Uint()))
  450. case reflect.Uint64:
  451. out = appendU64(out, uint64(field.Uint()))
  452. case reflect.Uint8:
  453. out = append(out, uint8(field.Uint()))
  454. case reflect.String:
  455. s := field.String()
  456. out = appendInt(out, len(s))
  457. out = append(out, s...)
  458. case reflect.Slice:
  459. switch t.Elem().Kind() {
  460. case reflect.Uint8:
  461. if v.Type().Field(i).Tag.Get("ssh") != "rest" {
  462. out = appendInt(out, field.Len())
  463. }
  464. out = append(out, field.Bytes()...)
  465. case reflect.String:
  466. offset := len(out)
  467. out = appendU32(out, 0)
  468. if n := field.Len(); n > 0 {
  469. for j := 0; j < n; j++ {
  470. f := field.Index(j)
  471. if j != 0 {
  472. out = append(out, ',')
  473. }
  474. out = append(out, f.String()...)
  475. }
  476. // overwrite length value
  477. binary.BigEndian.PutUint32(out[offset:], uint32(len(out)-offset-4))
  478. }
  479. default:
  480. panic(fmt.Sprintf("slice of unknown type in field %d: %T", i, field.Interface()))
  481. }
  482. case reflect.Ptr:
  483. if t == bigIntType {
  484. var n *big.Int
  485. nValue := reflect.ValueOf(&n)
  486. nValue.Elem().Set(field)
  487. needed := intLength(n)
  488. oldLength := len(out)
  489. if cap(out)-len(out) < needed {
  490. newOut := make([]byte, len(out), 2*(len(out)+needed))
  491. copy(newOut, out)
  492. out = newOut
  493. }
  494. out = out[:oldLength+needed]
  495. marshalInt(out[oldLength:], n)
  496. } else {
  497. panic(fmt.Sprintf("pointer to unknown type in field %d: %T", i, field.Interface()))
  498. }
  499. }
  500. }
  501. return out
  502. }
  503. var bigOne = big.NewInt(1)
  504. func parseString(in []byte) (out, rest []byte, ok bool) {
  505. if len(in) < 4 {
  506. return
  507. }
  508. length := binary.BigEndian.Uint32(in)
  509. in = in[4:]
  510. if uint32(len(in)) < length {
  511. return
  512. }
  513. out = in[:length]
  514. rest = in[length:]
  515. ok = true
  516. return
  517. }
  518. var (
  519. comma = []byte{','}
  520. emptyNameList = []string{}
  521. )
  522. func parseNameList(in []byte) (out []string, rest []byte, ok bool) {
  523. contents, rest, ok := parseString(in)
  524. if !ok {
  525. return
  526. }
  527. if len(contents) == 0 {
  528. out = emptyNameList
  529. return
  530. }
  531. parts := bytes.Split(contents, comma)
  532. out = make([]string, len(parts))
  533. for i, part := range parts {
  534. out[i] = string(part)
  535. }
  536. return
  537. }
  538. func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) {
  539. contents, rest, ok := parseString(in)
  540. if !ok {
  541. return
  542. }
  543. out = new(big.Int)
  544. if len(contents) > 0 && contents[0]&0x80 == 0x80 {
  545. // This is a negative number
  546. notBytes := make([]byte, len(contents))
  547. for i := range notBytes {
  548. notBytes[i] = ^contents[i]
  549. }
  550. out.SetBytes(notBytes)
  551. out.Add(out, bigOne)
  552. out.Neg(out)
  553. } else {
  554. // Positive number
  555. out.SetBytes(contents)
  556. }
  557. ok = true
  558. return
  559. }
  560. func parseUint32(in []byte) (uint32, []byte, bool) {
  561. if len(in) < 4 {
  562. return 0, nil, false
  563. }
  564. return binary.BigEndian.Uint32(in), in[4:], true
  565. }
  566. func parseUint64(in []byte) (uint64, []byte, bool) {
  567. if len(in) < 8 {
  568. return 0, nil, false
  569. }
  570. return binary.BigEndian.Uint64(in), in[8:], true
  571. }
  572. func intLength(n *big.Int) int {
  573. length := 4 /* length bytes */
  574. if n.Sign() < 0 {
  575. nMinus1 := new(big.Int).Neg(n)
  576. nMinus1.Sub(nMinus1, bigOne)
  577. bitLen := nMinus1.BitLen()
  578. if bitLen%8 == 0 {
  579. // The number will need 0xff padding
  580. length++
  581. }
  582. length += (bitLen + 7) / 8
  583. } else if n.Sign() == 0 {
  584. // A zero is the zero length string
  585. } else {
  586. bitLen := n.BitLen()
  587. if bitLen%8 == 0 {
  588. // The number will need 0x00 padding
  589. length++
  590. }
  591. length += (bitLen + 7) / 8
  592. }
  593. return length
  594. }
  595. func marshalUint32(to []byte, n uint32) []byte {
  596. binary.BigEndian.PutUint32(to, n)
  597. return to[4:]
  598. }
  599. func marshalUint64(to []byte, n uint64) []byte {
  600. binary.BigEndian.PutUint64(to, n)
  601. return to[8:]
  602. }
  603. func marshalInt(to []byte, n *big.Int) []byte {
  604. lengthBytes := to
  605. to = to[4:]
  606. length := 0
  607. if n.Sign() < 0 {
  608. // A negative number has to be converted to two's-complement
  609. // form. So we'll subtract 1 and invert. If the
  610. // most-significant-bit isn't set then we'll need to pad the
  611. // beginning with 0xff in order to keep the number negative.
  612. nMinus1 := new(big.Int).Neg(n)
  613. nMinus1.Sub(nMinus1, bigOne)
  614. bytes := nMinus1.Bytes()
  615. for i := range bytes {
  616. bytes[i] ^= 0xff
  617. }
  618. if len(bytes) == 0 || bytes[0]&0x80 == 0 {
  619. to[0] = 0xff
  620. to = to[1:]
  621. length++
  622. }
  623. nBytes := copy(to, bytes)
  624. to = to[nBytes:]
  625. length += nBytes
  626. } else if n.Sign() == 0 {
  627. // A zero is the zero length string
  628. } else {
  629. bytes := n.Bytes()
  630. if len(bytes) > 0 && bytes[0]&0x80 != 0 {
  631. // We'll have to pad this with a 0x00 in order to
  632. // stop it looking like a negative number.
  633. to[0] = 0
  634. to = to[1:]
  635. length++
  636. }
  637. nBytes := copy(to, bytes)
  638. to = to[nBytes:]
  639. length += nBytes
  640. }
  641. lengthBytes[0] = byte(length >> 24)
  642. lengthBytes[1] = byte(length >> 16)
  643. lengthBytes[2] = byte(length >> 8)
  644. lengthBytes[3] = byte(length)
  645. return to
  646. }
  647. func writeInt(w io.Writer, n *big.Int) {
  648. length := intLength(n)
  649. buf := make([]byte, length)
  650. marshalInt(buf, n)
  651. w.Write(buf)
  652. }
  653. func writeString(w io.Writer, s []byte) {
  654. var lengthBytes [4]byte
  655. lengthBytes[0] = byte(len(s) >> 24)
  656. lengthBytes[1] = byte(len(s) >> 16)
  657. lengthBytes[2] = byte(len(s) >> 8)
  658. lengthBytes[3] = byte(len(s))
  659. w.Write(lengthBytes[:])
  660. w.Write(s)
  661. }
  662. func stringLength(n int) int {
  663. return 4 + n
  664. }
  665. func marshalString(to []byte, s []byte) []byte {
  666. to[0] = byte(len(s) >> 24)
  667. to[1] = byte(len(s) >> 16)
  668. to[2] = byte(len(s) >> 8)
  669. to[3] = byte(len(s))
  670. to = to[4:]
  671. copy(to, s)
  672. return to[len(s):]
  673. }
  674. var bigIntType = reflect.TypeOf((*big.Int)(nil))
  675. // Decode a packet into its corresponding message.
  676. func decode(packet []byte) (interface{}, error) {
  677. var msg interface{}
  678. switch packet[0] {
  679. case msgDisconnect:
  680. msg = new(disconnectMsg)
  681. case msgServiceRequest:
  682. msg = new(serviceRequestMsg)
  683. case msgServiceAccept:
  684. msg = new(serviceAcceptMsg)
  685. case msgExtInfo:
  686. msg = new(extInfoMsg)
  687. case msgKexInit:
  688. msg = new(kexInitMsg)
  689. case msgKexDHInit:
  690. msg = new(kexDHInitMsg)
  691. case msgKexDHReply:
  692. msg = new(kexDHReplyMsg)
  693. case msgUserAuthRequest:
  694. msg = new(userAuthRequestMsg)
  695. case msgUserAuthSuccess:
  696. return new(userAuthSuccessMsg), nil
  697. case msgUserAuthFailure:
  698. msg = new(userAuthFailureMsg)
  699. case msgUserAuthPubKeyOk:
  700. msg = new(userAuthPubKeyOkMsg)
  701. case msgGlobalRequest:
  702. msg = new(globalRequestMsg)
  703. case msgRequestSuccess:
  704. msg = new(globalRequestSuccessMsg)
  705. case msgRequestFailure:
  706. msg = new(globalRequestFailureMsg)
  707. case msgChannelOpen:
  708. msg = new(channelOpenMsg)
  709. case msgChannelData:
  710. msg = new(channelDataMsg)
  711. case msgChannelOpenConfirm:
  712. msg = new(channelOpenConfirmMsg)
  713. case msgChannelOpenFailure:
  714. msg = new(channelOpenFailureMsg)
  715. case msgChannelWindowAdjust:
  716. msg = new(windowAdjustMsg)
  717. case msgChannelEOF:
  718. msg = new(channelEOFMsg)
  719. case msgChannelClose:
  720. msg = new(channelCloseMsg)
  721. case msgChannelRequest:
  722. msg = new(channelRequestMsg)
  723. case msgChannelSuccess:
  724. msg = new(channelRequestSuccessMsg)
  725. case msgChannelFailure:
  726. msg = new(channelRequestFailureMsg)
  727. case msgUserAuthGSSAPIToken:
  728. msg = new(userAuthGSSAPIToken)
  729. case msgUserAuthGSSAPIMIC:
  730. msg = new(userAuthGSSAPIMIC)
  731. case msgUserAuthGSSAPIErrTok:
  732. msg = new(userAuthGSSAPIErrTok)
  733. case msgUserAuthGSSAPIError:
  734. msg = new(userAuthGSSAPIError)
  735. default:
  736. return nil, unexpectedMessageError(0, packet[0])
  737. }
  738. if err := Unmarshal(packet, msg); err != nil {
  739. return nil, err
  740. }
  741. return msg, nil
  742. }
  743. var packetTypeNames = map[byte]string{
  744. msgDisconnect: "disconnectMsg",
  745. msgServiceRequest: "serviceRequestMsg",
  746. msgServiceAccept: "serviceAcceptMsg",
  747. msgExtInfo: "extInfoMsg",
  748. msgKexInit: "kexInitMsg",
  749. msgKexDHInit: "kexDHInitMsg",
  750. msgKexDHReply: "kexDHReplyMsg",
  751. msgUserAuthRequest: "userAuthRequestMsg",
  752. msgUserAuthSuccess: "userAuthSuccessMsg",
  753. msgUserAuthFailure: "userAuthFailureMsg",
  754. msgUserAuthPubKeyOk: "userAuthPubKeyOkMsg",
  755. msgGlobalRequest: "globalRequestMsg",
  756. msgRequestSuccess: "globalRequestSuccessMsg",
  757. msgRequestFailure: "globalRequestFailureMsg",
  758. msgChannelOpen: "channelOpenMsg",
  759. msgChannelData: "channelDataMsg",
  760. msgChannelOpenConfirm: "channelOpenConfirmMsg",
  761. msgChannelOpenFailure: "channelOpenFailureMsg",
  762. msgChannelWindowAdjust: "windowAdjustMsg",
  763. msgChannelEOF: "channelEOFMsg",
  764. msgChannelClose: "channelCloseMsg",
  765. msgChannelRequest: "channelRequestMsg",
  766. msgChannelSuccess: "channelRequestSuccessMsg",
  767. msgChannelFailure: "channelRequestFailureMsg",
  768. }