Files
Nik fe6d52ce3c Add encoding support to JCEKS package (#349)
This commit adds a JCEKS encoder to the `jceks` package.
Previously, the package was only capable of reading JCEKS files.

Internally, this commmit effectively rewrites the package.

These changes are backward compatible with the previous package API
and thus do not require a new major version. However, there are
several behavioral changes that have the potential to break
existing code that relied on edge cases:

- The package now returns an error when attempting to parse a JCEKS
  file that contains an invalid X.509 certificate (either as a
  trusted certificate entry, or as part of the chain for a private
  key entry). Previously, the package silently ignored these
  certificates. JCEKS files containing invalid certificates are
  invalid, so affected files should be repaired.
- The package now returns an error by default when parsing a JCEKS
  file containing a certificate or private key larger than 20MiB.
  This limit guards against trivial memory exhaustion denial of
  service attacks from malicious files, but the default is very
  generous. Callers that need to parse larger certificates or
  private keys can override the defaults using the new
  `KeyStore.ParseWithOptions` method with appropriate options.

The internal changes to the package introduced by this commit are
substantial. Some of the highlights include:
- Fixed a bug with modified UTF-8 parsing.
- `testdata` is now generated by `go generate`, rather than
  shelling out to `openssl` and `keytool` at unit test time.
- PKCS#5 padding is now removed when parsing.
- Tests are now far more comprehensive, including fuzz tests.
- General code cleanup and linter fixes.
2025-08-07 11:06:42 -04:00

144 lines
3.4 KiB
Go

// Copyright 2025 Block, Inc.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jceks
import (
"crypto/x509"
"encoding/binary"
"fmt"
"io"
"time"
)
// readBytes reads a byte array from the reader. The encoding provides a 4-byte prefix indicating the number of bytes
// that follow.
func readBytes(r io.Reader, maxLen uint) ([]byte, error) {
length, err := readInt32(r)
if err != nil {
return nil, err
}
if length < 0 {
return nil, ErrInvalidJCEKSData
}
if uint(length) > maxLen {
return nil, fmt.Errorf("%w: data field of size %d bytes exceeds maximimum length of %d",
ErrJCEKSDataTooLarge, length, maxLen)
}
buf := make([]byte, length)
_, err = io.ReadFull(r, buf)
if err != nil {
return nil, err
}
return buf, nil
}
func writeBytes(w io.Writer, b []byte) error {
if err := binary.Write(w, binary.BigEndian, uint32(len(b))); err != nil {
return err
}
if _, err := w.Write(b); err != nil {
return err
}
return nil
}
func readInt32(r io.Reader) (int32, error) {
var v int32
err := binary.Read(r, binary.BigEndian, &v)
return v, err
}
func writeInt32(w io.Writer, v int32) error {
return binary.Write(w, binary.BigEndian, v)
}
func readUint32(r io.Reader) (uint32, error) {
var v uint32
err := binary.Read(r, binary.BigEndian, &v)
return v, err
}
func writeUint32(w io.Writer, v uint32) error {
return binary.Write(w, binary.BigEndian, v)
}
func readDate(r io.Reader) (time.Time, error) {
var v int64
err := binary.Read(r, binary.BigEndian, &v)
if err != nil {
return time.Time{}, err
}
return time.UnixMilli(v), nil
}
func writeDate(w io.Writer, v time.Time) error {
return binary.Write(w, binary.BigEndian, v.UnixMilli())
}
// readString reads a length-prefixed modified UTF-8 string.
func readString(r io.Reader) (string, error) {
var length uint16
err := binary.Read(r, binary.BigEndian, &length)
if err != nil {
return "", err
}
return readModifiedUTF8(io.LimitReader(r, int64(length)))
}
func writeString(w io.Writer, str string) error {
if err := binary.Write(w, binary.BigEndian, uint16(len(str))); err != nil {
return err
}
if err := writeModifiedUTF8(w, str); err != nil {
return err
}
return nil
}
func readCertificate(r io.Reader, maxLen uint) (*x509.Certificate, error) {
certType, err := readString(r)
if err != nil {
return nil, err
}
if certType != x509CertTag {
return nil, fmt.Errorf("%w: unable to handle certificate type: %s", ErrUnsupportedJCEKSData, certType)
}
certDER, err := readBytes(r, maxLen)
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
return nil, fmt.Errorf("failed to parse certificate: %w", err)
}
return cert, nil
}
func writeCertificate(w io.Writer, certDER []byte) error {
if err := writeString(w, x509CertTag); err != nil {
return err
}
if err := writeBytes(w, certDER); err != nil {
return err
}
return nil
}