You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

766 lines
17 KiB

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