Debian Codegraph @

internal/format/format.go

raw symbols SCIP
1 // Copyright 2019 The age 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
5 // Package format implements the age file format.
6 package format
7
8 import (
9 "bufio"
10 "bytes"
11 "encoding/base64"
12 "errors"
13 "fmt"
14 "io"
15 "strings"
16 )
17
18 type Header struct {
19 Recipients []*Stanza
20 MAC []byte
21 }
22
23 // Stanza is assignable to age.Stanza, and if this package is made public,
24 // age.Stanza can be made a type alias of this type.
25 type Stanza struct {
26 Type string
27 Args []string
28 Body []byte
29 }
30
31 var b64 = base64.RawStdEncoding.Strict()
32
33 func DecodeString(s string) ([]byte, error) {
34 // CR and LF are ignored by DecodeString, but we don't want any malleability.
35 if strings.ContainsAny(s, "\n\r") {
36 return nil, errors.New(`unexpected newline character`)
37 }
38 return b64.DecodeString(s)
39 }
40
41 var EncodeToString = b64.EncodeToString
42
43 const ColumnsPerLine = 64
44
45 const BytesPerLine = ColumnsPerLine / 4 * 3
46
47 // NewWrappedBase64Encoder returns a WrappedBase64Encoder that writes to dst.
48 func NewWrappedBase64Encoder(enc *base64.Encoding, dst io.Writer) *WrappedBase64Encoder {
49 w := &WrappedBase64Encoder{dst: dst}
50 w.enc = base64.NewEncoder(enc, WriterFunc(w.writeWrapped))
51 return w
52 }
53
54 type WriterFunc func(p []byte) (int, error)
55
56 func (f WriterFunc) Write(p []byte) (int, error) { return f(p) }
57
58 // WrappedBase64Encoder is a standard base64 encoder that inserts an LF
59 // character every ColumnsPerLine bytes. It does not insert a newline neither at
60 // the beginning nor at the end of the stream, but it ensures the last line is
61 // shorter than ColumnsPerLine, which means it might be empty.
62 type WrappedBase64Encoder struct {
63 enc io.WriteCloser
64 dst io.Writer
65 written int
66 buf bytes.Buffer
67 }
68
69 func (w *WrappedBase64Encoder) Write(p []byte) (int, error) { return w.enc.Write(p) }
70
71 func (w *WrappedBase64Encoder) Close() error {
72 return w.enc.Close()
73 }
74
75 func (w *WrappedBase64Encoder) writeWrapped(p []byte) (int, error) {
76 if w.buf.Len() != 0 {
77 panic("age: internal error: non-empty WrappedBase64Encoder.buf")
78 }
79 total := len(p)
80 for len(p) > 0 {
81 toWrite := min(ColumnsPerLine-(w.written%ColumnsPerLine), len(p))
82 n, _ := w.buf.Write(p[:toWrite])
83 w.written += n
84 p = p[n:]
85 if w.written%ColumnsPerLine == 0 {
86 w.buf.Write([]byte("\n"))
87 }
88 }
89 if _, err := w.buf.WriteTo(w.dst); err != nil {
90 // We always return n = 0 on error because it's hard to work back to the
91 // input length that ended up written out. Not ideal, but Write errors
92 // are not recoverable anyway.
93 return 0, err
94 }
95 return total, nil
96 }
97
98 // LastLineIsEmpty returns whether the last output line was empty, either
99 // because no input was written, or because a multiple of BytesPerLine was.
100 //
101 // Calling LastLineIsEmpty before Close is meaningless.
102 func (w *WrappedBase64Encoder) LastLineIsEmpty() bool {
103 return w.written%ColumnsPerLine == 0
104 }
105
106 const intro = "age-encryption.org/v1\n"
107
108 var stanzaPrefix = []byte("->")
109 var footerPrefix = []byte("---")
110
111 func (r *Stanza) Marshal(w io.Writer) error {
112 if !isValidString(r.Type) {
113 return fmt.Errorf("invalid stanza type: %q", r.Type)
114 }
115 for _, a := range r.Args {
116 if !isValidString(a) {
117 return fmt.Errorf("invalid stanza argument: %q", a)
118 }
119 }
120 if _, err := w.Write(stanzaPrefix); err != nil {
121 return err
122 }
123 if _, err := io.WriteString(w, " "+r.Type); err != nil {
124 return err
125 }
126 for _, a := range r.Args {
127 if _, err := io.WriteString(w, " "+a); err != nil {
128 return err
129 }
130 }
131 if _, err := io.WriteString(w, "\n"); err != nil {
132 return err
133 }
134 ww := NewWrappedBase64Encoder(b64, w)
135 if _, err := ww.Write(r.Body); err != nil {
136 return err
137 }
138 if err := ww.Close(); err != nil {
139 return err
140 }
141 _, err := io.WriteString(w, "\n")
142 return err
143 }
144
145 func (h *Header) MarshalWithoutMAC(w io.Writer) error {
146 if len(h.Recipients) == 0 {
147 return errors.New("no recipient stanzas")
148 }
149 if _, err := io.WriteString(w, intro); err != nil {
150 return err
151 }
152 for _, r := range h.Recipients {
153 if err := r.Marshal(w); err != nil {
154 return err
155 }
156 }
157 _, err := fmt.Fprintf(w, "%s", footerPrefix)
158 return err
159 }
160
161 func (h *Header) Marshal(w io.Writer) error {
162 if err := h.MarshalWithoutMAC(w); err != nil {
163 return err
164 }
165 mac := b64.EncodeToString(h.MAC)
166 _, err := fmt.Fprintf(w, " %s\n", mac)
167 return err
168 }
169
170 type StanzaReader struct {
171 r interface {
172 ReadBytes(delim byte) ([]byte, error)
173 }
174 err error
175 }
176
177 func NewStanzaReader(r *bufio.Reader) *StanzaReader {
178 return &StanzaReader{r: r}
179 }
180
181 func (r *StanzaReader) ReadStanza() (s *Stanza, err error) {
182 // Read errors are unrecoverable.
183 if r.err != nil {
184 return nil, r.err
185 }
186 defer func() { r.err = err }()
187
188 s = &Stanza{}
189
190 line, err := r.r.ReadBytes('\n')
191 if err != nil {
192 return nil, fmt.Errorf("failed to read line: %w", err)
193 }
194 if !bytes.HasPrefix(line, stanzaPrefix) {
195 return nil, fmt.Errorf("malformed stanza opening line: %q", line)
196 }
197 prefix, args := splitArgs(line)
198 if prefix != string(stanzaPrefix) || len(args) < 1 {
199 return nil, fmt.Errorf("malformed stanza: %q", line)
200 }
201 s.Type = args[0]
202 s.Args = args[1:]
203
204 for {
205 line, err := r.r.ReadBytes('\n')
206 if err != nil {
207 return nil, fmt.Errorf("failed to read line: %w", err)
208 }
209
210 b, err := DecodeString(strings.TrimSuffix(string(line), "\n"))
211 if err != nil {
212 if bytes.HasPrefix(line, footerPrefix) || bytes.HasPrefix(line, stanzaPrefix) {
213 return nil, fmt.Errorf("malformed body line %q: stanza ended without a short line\nnote: this might be a file encrypted with an old beta version of age or rage; use age v1.0.0-beta6 or rage to decrypt it", line)
214 }
215 return nil, errorf("malformed body line %q: %v", line, err)
216 }
217 if len(b) > BytesPerLine {
218 return nil, errorf("malformed body line %q: too long", line)
219 }
220 s.Body = append(s.Body, b...)
221 if len(b) < BytesPerLine {
222 // A stanza body always ends with a short line.
223 return s, nil
224 }
225 }
226 }
227
228 type ParseError struct {
229 err error
230 }
231
232 const (
233 maxHeaderBytes = 2 << 20
234 maxRecipientStanzas = 1024
235 maxStanzaArgs = 128
236 )
237
238 type headerReader struct {
239 r *bufio.Reader
240 n int
241 }
242
243 func (r *headerReader) ReadBytes(delim byte) ([]byte, error) {
244 var line []byte
245 for {
246 frag, err := r.r.ReadSlice(delim)
247 if len(frag) > maxHeaderBytes-r.n {
248 return nil, errorf("header exceeds 2 MiB")
249 }
250 r.n += len(frag)
251 line = append(line, frag...)
252 if err != bufio.ErrBufferFull {
253 return line, err
254 }
255 }
256 }
257
258 func (r *headerReader) ReadString(delim byte) (string, error) {
259 line, err := r.ReadBytes(delim)
260 return string(line), err
261 }
262
263 func (r *headerReader) Peek(n int) ([]byte, error) {
264 if r.n+n > maxHeaderBytes {
265 return nil, errorf("header exceeds 2 MiB")
266 }
267 return r.r.Peek(n)
268 }
269
270 func (e *ParseError) Error() string {
271 return "parsing age header: " + e.err.Error()
272 }
273
274 func (e *ParseError) Unwrap() error {
275 return e.err
276 }
277
278 func errorf(format string, a ...any) error {
279 return &ParseError{fmt.Errorf(format, a...)}
280 }
281
282 // describeIntro returns a quoted description of a bad intro line, or an empty
283 // string if the line contains recognizable private key material.
284 func describeIntro(line string) string {
285 for _, prefix := range []string{"AGE-SECRET-KEY-", "AGE-PLUGIN-"} {
286 if strings.HasPrefix(line, prefix) {
287 return ""
288 }
289 }
290 // Preserve enough context to diagnose a mangled intro without echoing an
291 // arbitrarily long first line.
292 return fmt.Sprintf("%q", line[:min(len(line), len(intro))])
293 }
294
295 // Parse returns the header and a Reader that begins at the start of the
296 // payload.
297 func Parse(input io.Reader) (*Header, io.Reader, error) {
298 h := &Header{}
299 rr := bufio.NewReader(input)
300 hr := &headerReader{r: rr}
301
302 line, err := hr.ReadString('\n')
303 if err == io.EOF {
304 if len(line) == 0 {
305 return nil, nil, errorf("file is empty")
306 }
307 if description := describeIntro(line); description != "" {
308 return nil, nil, errorf("unexpected EOF reading intro: %s", description)
309 }
310 return nil, nil, errorf("unexpected EOF reading intro, expected %q", intro)
311 } else if err != nil {
312 // headerReader errors are already ParseErrors; don't nest the prefix.
313 if _, ok := err.(*ParseError); ok {
314 return nil, nil, err
315 }
316 return nil, nil, errorf("failed to read intro: %w", err)
317 }
318 if line != intro {
319 if description := describeIntro(line); description != "" {
320 return nil, nil, errorf("unexpected intro: %s", description)
321 }
322 return nil, nil, errorf("unexpected intro, expected %q", intro)
323 }
324
325 sr := &StanzaReader{r: hr}
326 for {
327 peek, err := hr.Peek(len(footerPrefix))
328 if err != nil {
329 // headerReader errors are already ParseErrors; don't nest the prefix.
330 if _, ok := err.(*ParseError); ok {
331 return nil, nil, err
332 }
333 return nil, nil, errorf("failed to read header: %w", err)
334 }
335
336 if bytes.Equal(peek, footerPrefix) {
337 line, err := hr.ReadBytes('\n')
338 if err != nil {
339 return nil, nil, fmt.Errorf("failed to read header: %w", err)
340 }
341
342 prefix, args := splitArgs(line)
343 if prefix != string(footerPrefix) || len(args) != 1 {
344 return nil, nil, errorf("malformed closing line: %q", line)
345 }
346 h.MAC, err = DecodeString(args[0])
347 if err != nil || len(h.MAC) != 32 {
348 return nil, nil, errorf("malformed closing line %q: %v", line, err)
349 }
350 break
351 }
352 if len(h.Recipients) == maxRecipientStanzas {
353 return nil, nil, errorf("header contains more than %d recipient stanzas", maxRecipientStanzas)
354 }
355
356 s, err := sr.ReadStanza()
357 if err != nil {
358 return nil, nil, fmt.Errorf("failed to parse header: %w", err)
359 }
360 h.Recipients = append(h.Recipients, s)
361 }
362 if len(h.Recipients) == 0 {
363 return nil, nil, errorf("no recipient stanzas")
364 }
365
366 // If input is a bufio.Reader, rr might be equal to input because
367 // bufio.NewReader short-circuits. In this case we can just return it (and
368 // we would end up reading the buffer twice if we prepended the peek below).
369 if rr == input {
370 return h, rr, nil
371 }
372 // Otherwise, unwind the bufio overread and return the unbuffered input.
373 buf, err := rr.Peek(rr.Buffered())
374 if err != nil {
375 return nil, nil, errorf("internal error: %v", err)
376 }
377 payload := io.MultiReader(bytes.NewReader(buf), input)
378 return h, payload, nil
379 }
380
381 func splitArgs(line []byte) (string, []string) {
382 l := strings.TrimSuffix(string(line), "\n")
383 prefix, rest, ok := strings.Cut(l, " ")
384 if !ok {
385 return l, nil
386 }
387
388 var args []string
389 for arg := range strings.SplitSeq(rest, " ") {
390 if !isValidString(arg) || len(args) > maxStanzaArgs {
391 return l, nil
392 }
393 args = append(args, arg)
394 }
395 return prefix, args
396 }
397
398 func isValidString(s string) bool {
399 if len(s) == 0 {
400 return false
401 }
402 for _, c := range s {
403 if c < 33 || c > 126 {
404 return false
405 }
406 }
407 return true
408 }