messages.go 16 KB

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