| 1 | // Modified by 42wim |
| 2 | // |
| 3 | // Copyright 2009 The Go Authors. All rights reserved. |
| 4 | // Use of this source code is governed by a BSD-style |
| 5 | // license that can be found in the LICENSE file. |
| 6 | |
| 7 | // Package pem implements the PEM data encoding, which originated in Privacy |
| 8 | // Enhanced Mail. The most common use of PEM encoding today is in TLS keys and |
| 9 | // certificates. See RFC 1421. |
| 10 | package pem |
| 11 | |
| 12 | import ( |
| 13 | "bytes" |
| 14 | "encoding/base64" |
| 15 | "errors" |
| 16 | "io" |
| 17 | "sort" |
| 18 | "strings" |
| 19 | ) |
| 20 | |
| 21 | // A Block represents a PEM encoded structure. |
| 22 | // |
| 23 | // The encoded form is: |
| 24 | // -----BEGIN Type----- |
| 25 | // Headers |
| 26 | // base64-encoded Bytes |
| 27 | // -----END Type----- |
| 28 | // where Headers is a possibly empty sequence of Key: Value lines. |
| 29 | type Block struct { |
| 30 | Type string // The type, taken from the preamble (i.e. "RSA PRIVATE KEY"). |
| 31 | Headers map[string]string // Optional headers. |
| 32 | Bytes []byte // The decoded bytes of the contents. Typically a DER encoded ASN.1 structure. |
| 33 | } |
| 34 | |
| 35 | // getLine results the first \r\n or \n delineated line from the given byte |
| 36 | // array. The line does not include trailing whitespace or the trailing new |
| 37 | // line bytes. The remainder of the byte array (also not including the new line |
| 38 | // bytes) is also returned and this will always be smaller than the original |
| 39 | // argument. |
| 40 | func getLine(data []byte) (line, rest []byte) { |
| 41 | i := bytes.IndexByte(data, '\n') |
| 42 | var j int |
| 43 | if i < 0 { |
| 44 | i = len(data) |
| 45 | j = i |
| 46 | } else { |
| 47 | j = i + 1 |
| 48 | if i > 0 && data[i-1] == '\r' { |
| 49 | i-- |
| 50 | } |
| 51 | } |
| 52 | return bytes.TrimRight(data[0:i], " \t"), data[j:] |
| 53 | } |
| 54 | |
| 55 | // removeSpacesAndTabs returns a copy of its input with all spaces and tabs |
| 56 | // removed, if there were any. Otherwise, the input is returned unchanged. |
| 57 | // |
| 58 | // The base64 decoder already skips newline characters, so we don't need to |
| 59 | // filter them out here. |
| 60 | func removeSpacesAndTabs(data []byte) []byte { |
| 61 | if !bytes.ContainsAny(data, " \t") { |
| 62 | // Fast path; most base64 data within PEM contains newlines, but |
| 63 | // no spaces nor tabs. Skip the extra alloc and work. |
| 64 | return data |
| 65 | } |
| 66 | result := make([]byte, len(data)) |
| 67 | n := 0 |
| 68 | |
| 69 | for _, b := range data { |
| 70 | if b == ' ' || b == '\t' { |
| 71 | continue |
| 72 | } |
| 73 | result[n] = b |
| 74 | n++ |
| 75 | } |
| 76 | |
| 77 | return result[0:n] |
| 78 | } |
| 79 | |
| 80 | var ( |
| 81 | pemStart = []byte("\n-----BEGIN ") |
| 82 | pemEnd = []byte("\n-----END ") |
| 83 | pemEndOfLine = []byte("-----") |
| 84 | ) |
| 85 | |
| 86 | // Decode will find the next PEM formatted block (certificate, private key |
| 87 | // etc) in the input. It returns that block and the remainder of the input. If |
| 88 | // no PEM data is found, p is nil and the whole of the input is returned in |
| 89 | // rest. |
| 90 | func Decode(data []byte) (p *Block, rest []byte) { |
| 91 | // pemStart begins with a newline. However, at the very beginning of |
| 92 | // the byte array, we'll accept the start string without it. |
| 93 | rest = data |
| 94 | if bytes.HasPrefix(data, pemStart[1:]) { |
| 95 | rest = rest[len(pemStart)-1 : len(data)] |
| 96 | } else if i := bytes.Index(data, pemStart); i >= 0 { |
| 97 | rest = rest[i+len(pemStart) : len(data)] |
| 98 | } else { |
| 99 | return nil, data |
| 100 | } |
| 101 | |
| 102 | typeLine, rest := getLine(rest) |
| 103 | if !bytes.HasSuffix(typeLine, pemEndOfLine) { |
| 104 | return decodeError(data, rest) |
| 105 | } |
| 106 | typeLine = typeLine[0 : len(typeLine)-len(pemEndOfLine)] |
| 107 | |
| 108 | p = &Block{ |
| 109 | Headers: make(map[string]string), |
| 110 | Type: string(typeLine), |
| 111 | } |
| 112 | |
| 113 | for { |
| 114 | // This loop terminates because getLine's second result is |
| 115 | // always smaller than its argument. |
| 116 | if len(rest) == 0 { |
| 117 | return nil, data |
| 118 | } |
| 119 | line, next := getLine(rest) |
| 120 | |
| 121 | i := bytes.IndexByte(line, ':') |
| 122 | if i == -1 { |
| 123 | break |
| 124 | } |
| 125 | |
| 126 | // TODO(agl): need to cope with values that spread across lines. |
| 127 | key, val := line[:i], line[i+1:] |
| 128 | key = bytes.TrimSpace(key) |
| 129 | val = bytes.TrimSpace(val) |
| 130 | p.Headers[string(key)] = string(val) |
| 131 | rest = next |
| 132 | } |
| 133 | |
| 134 | var endIndex, endTrailerIndex int |
| 135 | |
| 136 | // If there were no headers, the END line might occur |
| 137 | // immediately, without a leading newline. |
| 138 | if len(p.Headers) == 0 && bytes.HasPrefix(rest, pemEnd[1:]) { |
| 139 | endIndex = 0 |
| 140 | endTrailerIndex = len(pemEnd) - 1 |
| 141 | } else { |
| 142 | endIndex = bytes.Index(rest, pemEnd) |
| 143 | endTrailerIndex = endIndex + len(pemEnd) |
| 144 | } |
| 145 | |
| 146 | if endIndex < 0 { |
| 147 | return decodeError(data, rest) |
| 148 | } |
| 149 | |
| 150 | // After the "-----" of the ending line, there should be the same type |
| 151 | // and then a final five dashes. |
| 152 | endTrailer := rest[endTrailerIndex:] |
| 153 | endTrailerLen := len(typeLine) + len(pemEndOfLine) |
| 154 | if len(endTrailer) < endTrailerLen { |
| 155 | return decodeError(data, rest) |
| 156 | } |
| 157 | |
| 158 | restOfEndLine := endTrailer[endTrailerLen:] |
| 159 | endTrailer = endTrailer[:endTrailerLen] |
| 160 | if !bytes.HasPrefix(endTrailer, typeLine) || |
| 161 | !bytes.HasSuffix(endTrailer, pemEndOfLine) { |
| 162 | return decodeError(data, rest) |
| 163 | } |
| 164 | |
| 165 | // The line must end with only whitespace. |
| 166 | if s, _ := getLine(restOfEndLine); len(s) != 0 { |
| 167 | return decodeError(data, rest) |
| 168 | } |
| 169 | |
| 170 | base64Data := removeSpacesAndTabs(rest[:endIndex]) |
| 171 | p.Bytes = make([]byte, base64.StdEncoding.DecodedLen(len(base64Data))) |
| 172 | n, err := base64.StdEncoding.Decode(p.Bytes, base64Data) |
| 173 | if err != nil { |
| 174 | return decodeError(data, rest) |
| 175 | } |
| 176 | p.Bytes = p.Bytes[:n] |
| 177 | |
| 178 | // the -1 is because we might have only matched pemEnd without the |
| 179 | // leading newline if the PEM block was empty. |
| 180 | _, rest = getLine(rest[endIndex+len(pemEnd)-1:]) |
| 181 | |
| 182 | return |
| 183 | } |
| 184 | |
| 185 | func decodeError(data, rest []byte) (*Block, []byte) { |
| 186 | // If we get here then we have rejected a likely looking, but |
| 187 | // ultimately invalid PEM block. We need to start over from a new |
| 188 | // position. We have consumed the preamble line and will have consumed |
| 189 | // any lines which could be header lines. However, a valid preamble |
| 190 | // line is not a valid header line, therefore we cannot have consumed |
| 191 | // the preamble line for the any subsequent block. Thus, we will always |
| 192 | // find any valid block, no matter what bytes precede it. |
| 193 | // |
| 194 | // For example, if the input is |
| 195 | // |
| 196 | // -----BEGIN MALFORMED BLOCK----- |
| 197 | // junk that may look like header lines |
| 198 | // or data lines, but no END line |
| 199 | // |
| 200 | // -----BEGIN ACTUAL BLOCK----- |
| 201 | // realdata |
| 202 | // -----END ACTUAL BLOCK----- |
| 203 | // |
| 204 | // we've failed to parse using the first BEGIN line |
| 205 | // and now will try again, using the second BEGIN line. |
| 206 | p, rest := Decode(rest) |
| 207 | if p == nil { |
| 208 | rest = data |
| 209 | } |
| 210 | return p, rest |
| 211 | } |
| 212 | |
| 213 | // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.sshsig#L20-L21 |
| 214 | // Should be on 76 chars, but strangely enough ssh breaks on 70 |
| 215 | const pemLineLength = 70 |
| 216 | |
| 217 | type lineBreaker struct { |
| 218 | line [pemLineLength]byte |
| 219 | used int |
| 220 | out io.Writer |
| 221 | } |
| 222 | |
| 223 | var nl = []byte{'\n'} |
| 224 | |
| 225 | func (l *lineBreaker) Write(b []byte) (n int, err error) { |
| 226 | if l.used+len(b) < pemLineLength { |
| 227 | copy(l.line[l.used:], b) |
| 228 | l.used += len(b) |
| 229 | return len(b), nil |
| 230 | } |
| 231 | |
| 232 | n, err = l.out.Write(l.line[0:l.used]) |
| 233 | if err != nil { |
| 234 | return |
| 235 | } |
| 236 | excess := pemLineLength - l.used |
| 237 | l.used = 0 |
| 238 | |
| 239 | n, err = l.out.Write(b[0:excess]) |
| 240 | if err != nil { |
| 241 | return |
| 242 | } |
| 243 | |
| 244 | n, err = l.out.Write(nl) |
| 245 | if err != nil { |
| 246 | return |
| 247 | } |
| 248 | |
| 249 | return l.Write(b[excess:]) |
| 250 | } |
| 251 | |
| 252 | func (l *lineBreaker) Close() (err error) { |
| 253 | if l.used > 0 { |
| 254 | _, err = l.out.Write(l.line[0:l.used]) |
| 255 | if err != nil { |
| 256 | return |
| 257 | } |
| 258 | _, err = l.out.Write(nl) |
| 259 | } |
| 260 | |
| 261 | return |
| 262 | } |
| 263 | |
| 264 | func writeHeader(out io.Writer, k, v string) error { |
| 265 | _, err := out.Write([]byte(k + ": " + v + "\n")) |
| 266 | return err |
| 267 | } |
| 268 | |
| 269 | // Encode writes the PEM encoding of b to out. |
| 270 | func Encode(out io.Writer, b *Block) error { |
| 271 | // Check for invalid block before writing any output. |
| 272 | for k := range b.Headers { |
| 273 | if strings.Contains(k, ":") { |
| 274 | return errors.New("pem: cannot encode a header key that contains a colon") |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // All errors below are relayed from underlying io.Writer, |
| 279 | // so it is now safe to write data. |
| 280 | |
| 281 | if _, err := out.Write(pemStart[1:]); err != nil { |
| 282 | return err |
| 283 | } |
| 284 | if _, err := out.Write([]byte(b.Type + "-----\n")); err != nil { |
| 285 | return err |
| 286 | } |
| 287 | |
| 288 | if len(b.Headers) > 0 { |
| 289 | const procType = "Proc-Type" |
| 290 | h := make([]string, 0, len(b.Headers)) |
| 291 | hasProcType := false |
| 292 | for k := range b.Headers { |
| 293 | if k == procType { |
| 294 | hasProcType = true |
| 295 | continue |
| 296 | } |
| 297 | h = append(h, k) |
| 298 | } |
| 299 | // The Proc-Type header must be written first. |
| 300 | // See RFC 1421, section 4.6.1.1 |
| 301 | if hasProcType { |
| 302 | if err := writeHeader(out, procType, b.Headers[procType]); err != nil { |
| 303 | return err |
| 304 | } |
| 305 | } |
| 306 | // For consistency of output, write other headers sorted by key. |
| 307 | sort.Strings(h) |
| 308 | for _, k := range h { |
| 309 | if err := writeHeader(out, k, b.Headers[k]); err != nil { |
| 310 | return err |
| 311 | } |
| 312 | } |
| 313 | if _, err := out.Write(nl); err != nil { |
| 314 | return err |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | var breaker lineBreaker |
| 319 | breaker.out = out |
| 320 | |
| 321 | b64 := base64.NewEncoder(base64.StdEncoding, &breaker) |
| 322 | if _, err := b64.Write(b.Bytes); err != nil { |
| 323 | return err |
| 324 | } |
| 325 | b64.Close() |
| 326 | breaker.Close() |
| 327 | |
| 328 | if _, err := out.Write(pemEnd[1:]); err != nil { |
| 329 | return err |
| 330 | } |
| 331 | _, err := out.Write([]byte(b.Type + "-----\n")) |
| 332 | return err |
| 333 | } |
| 334 | |
| 335 | // EncodeToMemory returns the PEM encoding of b. |
| 336 | // |
| 337 | // If b has invalid headers and cannot be encoded, |
| 338 | // EncodeToMemory returns nil. If it is important to |
| 339 | // report details about this error case, use Encode instead. |
| 340 | func EncodeToMemory(b *Block) []byte { |
| 341 | var buf bytes.Buffer |
| 342 | if err := Encode(&buf, b); err != nil { |
| 343 | return nil |
| 344 | } |
| 345 | return buf.Bytes() |
| 346 | } |