messages.go 14 KB

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