messages.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. if uint32(len(in)) < 4+length {
  418. return
  419. }
  420. out = in[4 : 4+length]
  421. rest = in[4+length:]
  422. ok = true
  423. return
  424. }
  425. var (
  426. comma = []byte{','}
  427. emptyNameList = []string{}
  428. )
  429. func parseNameList(in []byte) (out []string, rest []byte, ok bool) {
  430. contents, rest, ok := parseString(in)
  431. if !ok {
  432. return
  433. }
  434. if len(contents) == 0 {
  435. out = emptyNameList
  436. return
  437. }
  438. parts := bytes.Split(contents, comma)
  439. out = make([]string, len(parts))
  440. for i, part := range parts {
  441. out[i] = string(part)
  442. }
  443. return
  444. }
  445. func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) {
  446. contents, rest, ok := parseString(in)
  447. if !ok {
  448. return
  449. }
  450. out = new(big.Int)
  451. if len(contents) > 0 && contents[0]&0x80 == 0x80 {
  452. // This is a negative number
  453. notBytes := make([]byte, len(contents))
  454. for i := range notBytes {
  455. notBytes[i] = ^contents[i]
  456. }
  457. out.SetBytes(notBytes)
  458. out.Add(out, bigOne)
  459. out.Neg(out)
  460. } else {
  461. // Positive number
  462. out.SetBytes(contents)
  463. }
  464. ok = true
  465. return
  466. }
  467. func parseUint32(in []byte) (uint32, []byte, bool) {
  468. if len(in) < 4 {
  469. return 0, nil, false
  470. }
  471. return binary.BigEndian.Uint32(in), in[4:], true
  472. }
  473. func parseUint64(in []byte) (uint64, []byte, bool) {
  474. if len(in) < 8 {
  475. return 0, nil, false
  476. }
  477. return binary.BigEndian.Uint64(in), in[8:], true
  478. }
  479. func intLength(n *big.Int) int {
  480. length := 4 /* length bytes */
  481. if n.Sign() < 0 {
  482. nMinus1 := new(big.Int).Neg(n)
  483. nMinus1.Sub(nMinus1, bigOne)
  484. bitLen := nMinus1.BitLen()
  485. if bitLen%8 == 0 {
  486. // The number will need 0xff padding
  487. length++
  488. }
  489. length += (bitLen + 7) / 8
  490. } else if n.Sign() == 0 {
  491. // A zero is the zero length string
  492. } else {
  493. bitLen := n.BitLen()
  494. if bitLen%8 == 0 {
  495. // The number will need 0x00 padding
  496. length++
  497. }
  498. length += (bitLen + 7) / 8
  499. }
  500. return length
  501. }
  502. func marshalUint32(to []byte, n uint32) []byte {
  503. binary.BigEndian.PutUint32(to, n)
  504. return to[4:]
  505. }
  506. func marshalUint64(to []byte, n uint64) []byte {
  507. binary.BigEndian.PutUint64(to, n)
  508. return to[8:]
  509. }
  510. func marshalInt(to []byte, n *big.Int) []byte {
  511. lengthBytes := to
  512. to = to[4:]
  513. length := 0
  514. if n.Sign() < 0 {
  515. // A negative number has to be converted to two's-complement
  516. // form. So we'll subtract 1 and invert. If the
  517. // most-significant-bit isn't set then we'll need to pad the
  518. // beginning with 0xff in order to keep the number negative.
  519. nMinus1 := new(big.Int).Neg(n)
  520. nMinus1.Sub(nMinus1, bigOne)
  521. bytes := nMinus1.Bytes()
  522. for i := range bytes {
  523. bytes[i] ^= 0xff
  524. }
  525. if len(bytes) == 0 || bytes[0]&0x80 == 0 {
  526. to[0] = 0xff
  527. to = to[1:]
  528. length++
  529. }
  530. nBytes := copy(to, bytes)
  531. to = to[nBytes:]
  532. length += nBytes
  533. } else if n.Sign() == 0 {
  534. // A zero is the zero length string
  535. } else {
  536. bytes := n.Bytes()
  537. if len(bytes) > 0 && bytes[0]&0x80 != 0 {
  538. // We'll have to pad this with a 0x00 in order to
  539. // stop it looking like a negative number.
  540. to[0] = 0
  541. to = to[1:]
  542. length++
  543. }
  544. nBytes := copy(to, bytes)
  545. to = to[nBytes:]
  546. length += nBytes
  547. }
  548. lengthBytes[0] = byte(length >> 24)
  549. lengthBytes[1] = byte(length >> 16)
  550. lengthBytes[2] = byte(length >> 8)
  551. lengthBytes[3] = byte(length)
  552. return to
  553. }
  554. func writeInt(w io.Writer, n *big.Int) {
  555. length := intLength(n)
  556. buf := make([]byte, length)
  557. marshalInt(buf, n)
  558. w.Write(buf)
  559. }
  560. func writeString(w io.Writer, s []byte) {
  561. var lengthBytes [4]byte
  562. lengthBytes[0] = byte(len(s) >> 24)
  563. lengthBytes[1] = byte(len(s) >> 16)
  564. lengthBytes[2] = byte(len(s) >> 8)
  565. lengthBytes[3] = byte(len(s))
  566. w.Write(lengthBytes[:])
  567. w.Write(s)
  568. }
  569. func stringLength(n int) int {
  570. return 4 + n
  571. }
  572. func marshalString(to []byte, s []byte) []byte {
  573. to[0] = byte(len(s) >> 24)
  574. to[1] = byte(len(s) >> 16)
  575. to[2] = byte(len(s) >> 8)
  576. to[3] = byte(len(s))
  577. to = to[4:]
  578. copy(to, s)
  579. return to[len(s):]
  580. }
  581. var bigIntType = reflect.TypeOf((*big.Int)(nil))
  582. // Decode a packet into its corresponding message.
  583. func decode(packet []byte) (interface{}, error) {
  584. var msg interface{}
  585. switch packet[0] {
  586. case msgDisconnect:
  587. msg = new(disconnectMsg)
  588. case msgServiceRequest:
  589. msg = new(serviceRequestMsg)
  590. case msgServiceAccept:
  591. msg = new(serviceAcceptMsg)
  592. case msgKexInit:
  593. msg = new(kexInitMsg)
  594. case msgKexDHInit:
  595. msg = new(kexDHInitMsg)
  596. case msgKexDHReply:
  597. msg = new(kexDHReplyMsg)
  598. case msgUserAuthRequest:
  599. msg = new(userAuthRequestMsg)
  600. case msgUserAuthFailure:
  601. msg = new(userAuthFailureMsg)
  602. case msgUserAuthPubKeyOk:
  603. msg = new(userAuthPubKeyOkMsg)
  604. case msgGlobalRequest:
  605. msg = new(globalRequestMsg)
  606. case msgRequestSuccess:
  607. msg = new(globalRequestSuccessMsg)
  608. case msgRequestFailure:
  609. msg = new(globalRequestFailureMsg)
  610. case msgChannelOpen:
  611. msg = new(channelOpenMsg)
  612. case msgChannelOpenConfirm:
  613. msg = new(channelOpenConfirmMsg)
  614. case msgChannelOpenFailure:
  615. msg = new(channelOpenFailureMsg)
  616. case msgChannelWindowAdjust:
  617. msg = new(windowAdjustMsg)
  618. case msgChannelEOF:
  619. msg = new(channelEOFMsg)
  620. case msgChannelClose:
  621. msg = new(channelCloseMsg)
  622. case msgChannelRequest:
  623. msg = new(channelRequestMsg)
  624. case msgChannelSuccess:
  625. msg = new(channelRequestSuccessMsg)
  626. case msgChannelFailure:
  627. msg = new(channelRequestFailureMsg)
  628. default:
  629. return nil, unexpectedMessageError(0, packet[0])
  630. }
  631. if err := Unmarshal(packet, msg); err != nil {
  632. return nil, err
  633. }
  634. return msg, nil
  635. }