gunk-dev/the-valley

wire.go

sourcefe4ab5bf3cabmain's published tip history
1.7 KiB
1package sigverify
2
3import (
4 "encoding/binary"
5 "errors"
6 "math/big"
7)
8
9var errShort = errors.New("ends early")
10
11// reader reads the SSH wire encoding of RFC 4251 section 5. A string is a
12// four-byte big-endian length followed by that many bytes.
13//
14// The first failed read records an error. Every later read then returns a
15// zero value, so a parser reads all of its fields and checks err once.
16type reader struct {
17 rest []byte
18 err error
19}
20
21func (r *reader) take(n int) []byte {
22 if r.err != nil {
23 return nil
24 }
25 if n < 0 || len(r.rest) < n {
26 r.err = errShort
27 return nil
28 }
29 b := r.rest[:n]
30 r.rest = r.rest[n:]
31 return b
32}
33
34func (r *reader) u8() byte {
35 b := r.take(1)
36 if b == nil {
37 return 0
38 }
39 return b[0]
40}
41
42func (r *reader) u32() uint32 {
43 b := r.take(4)
44 if b == nil {
45 return 0
46 }
47 return binary.BigEndian.Uint32(b)
48}
49
50func (r *reader) str() []byte {
51 n := r.u32()
52 if r.err != nil {
53 return nil
54 }
55 if uint64(n) > uint64(len(r.rest)) {
56 r.err = errShort
57 return nil
58 }
59 return r.take(int(n))
60}
61
62// mpint reads a non-negative multiple-precision integer. OpenSSH refuses
63// negative values, and so does this.
64func (r *reader) mpint() *big.Int {
65 b := r.str()
66 if r.err != nil {
67 return nil
68 }
69 if len(b) > 0 && b[0]&0x80 != 0 {
70 r.err = errors.New("holds a negative integer")
71 return nil
72 }
73 return new(big.Int).SetBytes(b)
74}
75
76// end reports the first failure, or trailing bytes that nothing read.
77func (r *reader) end() error {
78 if r.err != nil {
79 return r.err
80 }
81 if len(r.rest) != 0 {
82 return errors.New("has trailing bytes")
83 }
84 return nil
85}
86
87// appendString appends b in the wire encoding of a string.
88func appendString(dst, b []byte) []byte {
89 dst = binary.BigEndian.AppendUint32(dst, uint32(len(b)))
90 return append(dst, b...)
91}