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.
15 // These are SSH message type numbers. They are scattered around several
16 // documents but many were taken from
17 // http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1
32 msgUserAuthRequest = 50
33 msgUserAuthFailure = 51
34 msgUserAuthSuccess = 52
35 msgUserAuthBanner = 53
36 msgUserAuthPubKeyOk = 60
39 msgRequestSuccess = 81
40 msgRequestFailure = 82
43 msgChannelOpenConfirm = 91
44 msgChannelOpenFailure = 92
45 msgChannelWindowAdjust = 93
47 msgChannelExtendedData = 95
50 msgChannelRequest = 98
51 msgChannelSuccess = 99
52 msgChannelFailure = 100
57 // These structures mirror the wire format of the corresponding SSH messages.
58 // They are marshaled using reflection with the marshal and unmarshal functions
59 // in this file. The only wrinkle is that a final member of type []byte with a
60 // ssh tag of "rest" receives the remainder of a packet when unmarshaling.
62 // See RFC 4253, section 11.1.
63 type disconnectMsg struct {
69 // See RFC 4253, section 7.1.
70 type kexInitMsg struct {
73 ServerHostKeyAlgos []string
74 CiphersClientServer []string
75 CiphersServerClient []string
76 MACsClientServer []string
77 MACsServerClient []string
78 CompressionClientServer []string
79 CompressionServerClient []string
80 LanguagesClientServer []string
81 LanguagesServerClient []string
86 // See RFC 4253, section 8.
87 type kexDHInitMsg struct {
91 type kexDHReplyMsg struct {
97 // See RFC 4253, section 10.
98 type serviceRequestMsg struct {
102 // See RFC 4253, section 10.
103 type serviceAcceptMsg struct {
107 // See RFC 4252, section 5.
108 type userAuthRequestMsg struct {
112 Payload []byte `ssh:"rest"`
115 // See RFC 4252, section 5.1
116 type userAuthFailureMsg struct {
121 // See RFC 4254, section 5.1.
122 type channelOpenMsg struct {
127 TypeSpecificData []byte `ssh:"rest"`
130 // See RFC 4254, section 5.1.
131 type channelOpenConfirmMsg struct {
136 TypeSpecificData []byte `ssh:"rest"`
139 // See RFC 4254, section 5.1.
140 type channelOpenFailureMsg struct {
147 // See RFC 4254, section 5.2.
148 type channelData struct {
150 Payload []byte `ssh:"rest"`
153 // See RFC 4254, section 5.2.
154 type channelExtendedData struct {
157 Payload []byte `ssh:"rest"`
160 type channelRequestMsg struct {
164 RequestSpecificData []byte `ssh:"rest"`
167 // See RFC 4254, section 5.4.
168 type channelRequestSuccessMsg struct {
172 // See RFC 4254, section 5.4.
173 type channelRequestFailureMsg struct {
177 // See RFC 4254, section 5.3
178 type channelCloseMsg struct {
182 // See RFC 4254, section 5.3
183 type channelEOFMsg struct {
187 // See RFC 4254, section 4
188 type globalRequestMsg struct {
193 // See RFC 4254, section 5.2
194 type windowAdjustMsg struct {
196 AdditionalBytes uint32
199 // See RFC 4252, section 7
200 type userAuthPubKeyOkMsg struct {
205 // unmarshal parses the SSH wire data in packet into out using reflection.
206 // expectedType is the expected SSH message type. It either returns nil on
207 // success, or a ParseError or UnexpectedMessageError on error.
208 func unmarshal(out interface{}, packet []byte, expectedType uint8) os.Error {
209 if len(packet) == 0 {
210 return ParseError{expectedType}
212 if packet[0] != expectedType {
213 return UnexpectedMessageError{expectedType, packet[0]}
217 v := reflect.ValueOf(out).Elem()
218 structType := v.Type()
220 for i := 0; i < v.NumField(); i++ {
226 return ParseError{expectedType}
228 field.SetBool(packet[0] != 0)
231 if t.Elem().Kind() != reflect.Uint8 {
232 panic("array of non-uint8")
234 if len(packet) < t.Len() {
235 return ParseError{expectedType}
237 for j := 0; j < t.Len(); j++ {
238 field.Index(j).Set(reflect.ValueOf(packet[j]))
240 packet = packet[t.Len():]
243 if u32, packet, ok = parseUint32(packet); !ok {
244 return ParseError{expectedType}
246 field.SetUint(uint64(u32))
249 if s, packet, ok = parseString(packet); !ok {
250 return ParseError{expectedType}
252 field.SetString(string(s))
254 switch t.Elem().Kind() {
256 if structType.Field(i).Tag.Get("ssh") == "rest" {
257 field.Set(reflect.ValueOf(packet))
261 if s, packet, ok = parseString(packet); !ok {
262 return ParseError{expectedType}
264 field.Set(reflect.ValueOf(s))
268 if nl, packet, ok = parseNameList(packet); !ok {
269 return ParseError{expectedType}
271 field.Set(reflect.ValueOf(nl))
273 panic("slice of unknown type")
278 if n, packet, ok = parseInt(packet); !ok {
279 return ParseError{expectedType}
281 field.Set(reflect.ValueOf(n))
283 panic("pointer to unknown type")
286 panic("unknown type")
290 if len(packet) != 0 {
291 return ParseError{expectedType}
297 // marshal serializes the message in msg, using the given message type.
298 func marshal(msgType uint8, msg interface{}) []byte {
300 out = append(out, msgType)
302 v := reflect.ValueOf(msg)
303 structType := v.Type()
304 for i := 0; i < v.NumField(); i++ {
315 if t.Elem().Kind() != reflect.Uint8 {
316 panic("array of non-uint8")
318 for j := 0; j < t.Len(); j++ {
319 out = append(out, byte(field.Index(j).Uint()))
322 u32 := uint32(field.Uint())
323 out = append(out, byte(u32>>24))
324 out = append(out, byte(u32>>16))
325 out = append(out, byte(u32>>8))
326 out = append(out, byte(u32))
329 out = append(out, byte(len(s)>>24))
330 out = append(out, byte(len(s)>>16))
331 out = append(out, byte(len(s)>>8))
332 out = append(out, byte(len(s)))
333 out = append(out, s...)
335 switch t.Elem().Kind() {
337 length := field.Len()
338 if structType.Field(i).Tag.Get("ssh") != "rest" {
339 out = append(out, byte(length>>24))
340 out = append(out, byte(length>>16))
341 out = append(out, byte(length>>8))
342 out = append(out, byte(length))
344 for j := 0; j < length; j++ {
345 out = append(out, byte(field.Index(j).Uint()))
349 for j := 0; j < field.Len(); j++ {
353 length += len(field.Index(j).String())
356 out = append(out, byte(length>>24))
357 out = append(out, byte(length>>16))
358 out = append(out, byte(length>>8))
359 out = append(out, byte(length))
360 for j := 0; j < field.Len(); j++ {
362 out = append(out, ',')
364 out = append(out, field.Index(j).String()...)
367 panic("slice of unknown type")
372 nValue := reflect.ValueOf(&n)
373 nValue.Elem().Set(field)
374 needed := intLength(n)
375 oldLength := len(out)
377 if cap(out)-len(out) < needed {
378 newOut := make([]byte, len(out), 2*(len(out)+needed))
382 out = out[:oldLength+needed]
383 marshalInt(out[oldLength:], n)
385 panic("pointer to unknown type")
393 var bigOne = big.NewInt(1)
395 func parseString(in []byte) (out, rest []byte, ok bool) {
399 length := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
400 if uint32(len(in)) < 4+length {
403 out = in[4 : 4+length]
409 var comma = []byte{','}
411 func parseNameList(in []byte) (out []string, rest []byte, ok bool) {
412 contents, rest, ok := parseString(in)
416 if len(contents) == 0 {
419 parts := bytes.Split(contents, comma)
420 out = make([]string, len(parts))
421 for i, part := range parts {
422 out[i] = string(part)
427 func parseInt(in []byte) (out *big.Int, rest []byte, ok bool) {
428 contents, rest, ok := parseString(in)
434 if len(contents) > 0 && contents[0]&0x80 == 0x80 {
435 // This is a negative number
436 notBytes := make([]byte, len(contents))
437 for i := range notBytes {
438 notBytes[i] = ^contents[i]
440 out.SetBytes(notBytes)
445 out.SetBytes(contents)
451 func parseUint32(in []byte) (out uint32, rest []byte, ok bool) {
455 out = uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
461 const maxPacketSize = 36000
463 func nameListLength(namelist []string) int {
464 length := 4 /* uint32 length prefix */
465 for i, name := range namelist {
474 func intLength(n *big.Int) int {
475 length := 4 /* length bytes */
477 nMinus1 := new(big.Int).Neg(n)
478 nMinus1.Sub(nMinus1, bigOne)
479 bitLen := nMinus1.BitLen()
481 // The number will need 0xff padding
484 length += (bitLen + 7) / 8
485 } else if n.Sign() == 0 {
486 // A zero is the zero length string
490 // The number will need 0x00 padding
493 length += (bitLen + 7) / 8
499 func marshalInt(to []byte, n *big.Int) []byte {
505 // A negative number has to be converted to two's-complement
506 // form. So we'll subtract 1 and invert. If the
507 // most-significant-bit isn't set then we'll need to pad the
508 // beginning with 0xff in order to keep the number negative.
509 nMinus1 := new(big.Int).Neg(n)
510 nMinus1.Sub(nMinus1, bigOne)
511 bytes := nMinus1.Bytes()
512 for i := range bytes {
515 if len(bytes) == 0 || bytes[0]&0x80 == 0 {
520 nBytes := copy(to, bytes)
523 } else if n.Sign() == 0 {
524 // A zero is the zero length string
527 if len(bytes) > 0 && bytes[0]&0x80 != 0 {
528 // We'll have to pad this with a 0x00 in order to
529 // stop it looking like a negative number.
534 nBytes := copy(to, bytes)
539 lengthBytes[0] = byte(length >> 24)
540 lengthBytes[1] = byte(length >> 16)
541 lengthBytes[2] = byte(length >> 8)
542 lengthBytes[3] = byte(length)
546 func writeInt(w io.Writer, n *big.Int) {
547 length := intLength(n)
548 buf := make([]byte, length)
553 func writeString(w io.Writer, s []byte) {
554 var lengthBytes [4]byte
555 lengthBytes[0] = byte(len(s) >> 24)
556 lengthBytes[1] = byte(len(s) >> 16)
557 lengthBytes[2] = byte(len(s) >> 8)
558 lengthBytes[3] = byte(len(s))
559 w.Write(lengthBytes[:])
563 func stringLength(s []byte) int {
567 func marshalString(to []byte, s []byte) []byte {
568 to[0] = byte(len(s) >> 24)
569 to[1] = byte(len(s) >> 16)
570 to[2] = byte(len(s) >> 8)
577 var bigIntType = reflect.TypeOf((*big.Int)(nil))
579 // Decode a packet into it's corresponding message.
580 func decode(packet []byte) interface{} {
584 msg = new(disconnectMsg)
585 case msgServiceRequest:
586 msg = new(serviceRequestMsg)
587 case msgServiceAccept:
588 msg = new(serviceAcceptMsg)
590 msg = new(kexInitMsg)
592 msg = new(kexDHInitMsg)
594 msg = new(kexDHReplyMsg)
595 case msgUserAuthRequest:
596 msg = new(userAuthRequestMsg)
597 case msgUserAuthFailure:
598 msg = new(userAuthFailureMsg)
599 case msgUserAuthPubKeyOk:
600 msg = new(userAuthPubKeyOkMsg)
601 case msgGlobalRequest:
602 msg = new(globalRequestMsg)
603 case msgRequestSuccess:
604 msg = new(channelRequestSuccessMsg)
605 case msgRequestFailure:
606 msg = new(channelRequestFailureMsg)
608 msg = new(channelOpenMsg)
609 case msgChannelOpenConfirm:
610 msg = new(channelOpenConfirmMsg)
611 case msgChannelOpenFailure:
612 msg = new(channelOpenFailureMsg)
613 case msgChannelWindowAdjust:
614 msg = new(windowAdjustMsg)
616 msg = new(channelData)
617 case msgChannelExtendedData:
618 msg = new(channelExtendedData)
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)
630 return UnexpectedMessageError{0, packet[0]}
632 if err := unmarshal(msg, packet, packet[0]); err != nil {