| 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. |
| 4 |
|
| 5 |
package openpgp |
| 6 |
|
| 7 |
import ( |
| 8 |
"crypto" |
| 9 |
"hash" |
| 10 |
"io" |
| 11 |
"strconv" |
| 12 |
"time" |
| 13 |
|
| 14 |
"github.com/ProtonMail/go-crypto/openpgp/armor" |
| 15 |
"github.com/ProtonMail/go-crypto/openpgp/errors" |
| 16 |
"github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" |
| 17 |
"github.com/ProtonMail/go-crypto/openpgp/packet" |
| 18 |
) |
| 19 |
|
| 20 |
// DetachSign signs message with the private key from signer (which must |
| 21 |
// already have been decrypted) and writes the signature to w. |
| 22 |
// If config is nil, sensible defaults will be used. |
| 23 |
func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { |
| 24 |
return detachSign(w, signer, message, packet.SigTypeBinary, config) |
| 25 |
} |
| 26 |
|
| 27 |
// ArmoredDetachSign signs message with the private key from signer (which |
| 28 |
// must already have been decrypted) and writes an armored signature to w. |
| 29 |
// If config is nil, sensible defaults will be used. |
| 30 |
func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) { |
| 31 |
return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config) |
| 32 |
} |
| 33 |
|
| 34 |
// DetachSignText signs message (after canonicalising the line endings) with |
| 35 |
// the private key from signer (which must already have been decrypted) and |
| 36 |
// writes the signature to w. |
| 37 |
// If config is nil, sensible defaults will be used. |
| 38 |
func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { |
| 39 |
return detachSign(w, signer, message, packet.SigTypeText, config) |
| 40 |
} |
| 41 |
|
| 42 |
// ArmoredDetachSignText signs message (after canonicalising the line endings) |
| 43 |
// with the private key from signer (which must already have been decrypted) |
| 44 |
// and writes an armored signature to w. |
| 45 |
// If config is nil, sensible defaults will be used. |
| 46 |
func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { |
| 47 |
return armoredDetachSign(w, signer, message, packet.SigTypeText, config) |
| 48 |
} |
| 49 |
|
| 50 |
func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { |
| 51 |
out, err := armor.Encode(w, SignatureType, nil) |
| 52 |
if err != nil { |
| 53 |
return |
| 54 |
} |
| 55 |
err = detachSign(out, signer, message, sigType, config) |
| 56 |
if err != nil { |
| 57 |
return |
| 58 |
} |
| 59 |
return out.Close() |
| 60 |
} |
| 61 |
|
| 62 |
func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { |
| 63 |
signingKey, ok := signer.SigningKeyById(config.Now(), config.SigningKey()) |
| 64 |
if !ok { |
| 65 |
return errors.InvalidArgumentError("no valid signing keys") |
| 66 |
} |
| 67 |
if signingKey.PrivateKey == nil { |
| 68 |
return errors.InvalidArgumentError("signing key doesn't have a private key") |
| 69 |
} |
| 70 |
if signingKey.PrivateKey.Encrypted { |
| 71 |
return errors.InvalidArgumentError("signing key is encrypted") |
| 72 |
} |
| 73 |
if _, ok := algorithm.HashToHashId(config.Hash()); !ok { |
| 74 |
return errors.InvalidArgumentError("invalid hash function") |
| 75 |
} |
| 76 |
|
| 77 |
sig := createSignaturePacket(signingKey.PublicKey, sigType, config) |
| 78 |
|
| 79 |
h, err := sig.PrepareSign(config) |
| 80 |
if err != nil { |
| 81 |
return |
| 82 |
} |
| 83 |
wrappedHash, err := wrapHashForSignature(h, sig.SigType) |
| 84 |
if err != nil { |
| 85 |
return |
| 86 |
} |
| 87 |
if _, err = io.Copy(wrappedHash, message); err != nil { |
| 88 |
return err |
| 89 |
} |
| 90 |
|
| 91 |
err = sig.Sign(h, signingKey.PrivateKey, config) |
| 92 |
if err != nil { |
| 93 |
return |
| 94 |
} |
| 95 |
|
| 96 |
return sig.Serialize(w) |
| 97 |
} |
| 98 |
|
| 99 |
// FileHints contains metadata about encrypted files. This metadata is, itself, |
| 100 |
// encrypted. |
| 101 |
type FileHints struct { |
| 102 |
// IsBinary can be set to hint that the contents are binary data. |
| 103 |
IsBinary bool |
| 104 |
// FileName hints at the name of the file that should be written. It's |
| 105 |
// truncated to 255 bytes if longer. It may be empty to suggest that the |
| 106 |
// file should not be written to disk. It may be equal to "_CONSOLE" to |
| 107 |
// suggest the data should not be written to disk. |
| 108 |
FileName string |
| 109 |
// ModTime contains the modification time of the file, or the zero time if not applicable. |
| 110 |
ModTime time.Time |
| 111 |
} |
| 112 |
|
| 113 |
// SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase. |
| 114 |
// The resulting WriteCloser must be closed after the contents of the file have |
| 115 |
// been written. |
| 116 |
// If config is nil, sensible defaults will be used. |
| 117 |
func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { |
| 118 |
if hints == nil { |
| 119 |
hints = &FileHints{} |
| 120 |
} |
| 121 |
|
| 122 |
key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config) |
| 123 |
if err != nil { |
| 124 |
return |
| 125 |
} |
| 126 |
|
| 127 |
var w io.WriteCloser |
| 128 |
cipherSuite := packet.CipherSuite{ |
| 129 |
Cipher: config.Cipher(), |
| 130 |
Mode: config.AEAD().Mode(), |
| 131 |
} |
| 132 |
w, err = packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), config.AEAD() != nil, cipherSuite, key, config) |
| 133 |
if err != nil { |
| 134 |
return |
| 135 |
} |
| 136 |
|
| 137 |
literalData := w |
| 138 |
if algo := config.Compression(); algo != packet.CompressionNone { |
| 139 |
var compConfig *packet.CompressionConfig |
| 140 |
if config != nil { |
| 141 |
compConfig = config.CompressionConfig |
| 142 |
} |
| 143 |
literalData, err = packet.SerializeCompressed(w, algo, compConfig) |
| 144 |
if err != nil { |
| 145 |
return |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
var epochSeconds uint32 |
| 150 |
if !hints.ModTime.IsZero() { |
| 151 |
epochSeconds = uint32(hints.ModTime.Unix()) |
| 152 |
} |
| 153 |
return packet.SerializeLiteral(literalData, hints.IsBinary, hints.FileName, epochSeconds) |
| 154 |
} |
| 155 |
|
| 156 |
// intersectPreferences mutates and returns a prefix of a that contains only |
| 157 |
// the values in the intersection of a and b. The order of a is preserved. |
| 158 |
func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) { |
| 159 |
var j int |
| 160 |
for _, v := range a { |
| 161 |
for _, v2 := range b { |
| 162 |
if v == v2 { |
| 163 |
a[j] = v |
| 164 |
j++ |
| 165 |
break |
| 166 |
} |
| 167 |
} |
| 168 |
} |
| 169 |
|
| 170 |
return a[:j] |
| 171 |
} |
| 172 |
|
| 173 |
// intersectPreferences mutates and returns a prefix of a that contains only |
| 174 |
// the values in the intersection of a and b. The order of a is preserved. |
| 175 |
func intersectCipherSuites(a [][2]uint8, b [][2]uint8) (intersection [][2]uint8) { |
| 176 |
var j int |
| 177 |
for _, v := range a { |
| 178 |
for _, v2 := range b { |
| 179 |
if v[0] == v2[0] && v[1] == v2[1] { |
| 180 |
a[j] = v |
| 181 |
j++ |
| 182 |
break |
| 183 |
} |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
return a[:j] |
| 188 |
} |
| 189 |
|
| 190 |
func hashToHashId(h crypto.Hash) uint8 { |
| 191 |
v, ok := algorithm.HashToHashId(h) |
| 192 |
if !ok { |
| 193 |
panic("tried to convert unknown hash") |
| 194 |
} |
| 195 |
return v |
| 196 |
} |
| 197 |
|
| 198 |
// EncryptText encrypts a message to a number of recipients and, optionally, |
| 199 |
// signs it. Optional information is contained in 'hints', also encrypted, that |
| 200 |
// aids the recipients in processing the message. The resulting WriteCloser |
| 201 |
// must be closed after the contents of the file have been written. If config |
| 202 |
// is nil, sensible defaults will be used. The signing is done in text mode. |
| 203 |
func EncryptText(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { |
| 204 |
return encrypt(ciphertext, ciphertext, to, signed, hints, packet.SigTypeText, config) |
| 205 |
} |
| 206 |
|
| 207 |
// Encrypt encrypts a message to a number of recipients and, optionally, signs |
| 208 |
// it. hints contains optional information, that is also encrypted, that aids |
| 209 |
// the recipients in processing the message. The resulting WriteCloser must |
| 210 |
// be closed after the contents of the file have been written. |
| 211 |
// If config is nil, sensible defaults will be used. |
| 212 |
func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { |
| 213 |
return encrypt(ciphertext, ciphertext, to, signed, hints, packet.SigTypeBinary, config) |
| 214 |
} |
| 215 |
|
| 216 |
// EncryptSplit encrypts a message to a number of recipients and, optionally, signs |
| 217 |
// it. hints contains optional information, that is also encrypted, that aids |
| 218 |
// the recipients in processing the message. The resulting WriteCloser must |
| 219 |
// be closed after the contents of the file have been written. |
| 220 |
// If config is nil, sensible defaults will be used. |
| 221 |
func EncryptSplit(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { |
| 222 |
return encrypt(keyWriter, dataWriter, to, signed, hints, packet.SigTypeBinary, config) |
| 223 |
} |
| 224 |
|
| 225 |
// EncryptTextSplit encrypts a message to a number of recipients and, optionally, signs |
| 226 |
// it. hints contains optional information, that is also encrypted, that aids |
| 227 |
// the recipients in processing the message. The resulting WriteCloser must |
| 228 |
// be closed after the contents of the file have been written. |
| 229 |
// If config is nil, sensible defaults will be used. |
| 230 |
func EncryptTextSplit(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { |
| 231 |
return encrypt(keyWriter, dataWriter, to, signed, hints, packet.SigTypeText, config) |
| 232 |
} |
| 233 |
|
| 234 |
// writeAndSign writes the data as a payload package and, optionally, signs |
| 235 |
// it. hints contains optional information, that is also encrypted, |
| 236 |
// that aids the recipients in processing the message. The resulting |
| 237 |
// WriteCloser must be closed after the contents of the file have been |
| 238 |
// written. If config is nil, sensible defaults will be used. |
| 239 |
func writeAndSign(payload io.WriteCloser, candidateHashes []uint8, signed *Entity, hints *FileHints, sigType packet.SignatureType, config *packet.Config) (plaintext io.WriteCloser, err error) { |
| 240 |
var signer *packet.PrivateKey |
| 241 |
if signed != nil { |
| 242 |
signKey, ok := signed.SigningKeyById(config.Now(), config.SigningKey()) |
| 243 |
if !ok { |
| 244 |
return nil, errors.InvalidArgumentError("no valid signing keys") |
| 245 |
} |
| 246 |
signer = signKey.PrivateKey |
| 247 |
if signer == nil { |
| 248 |
return nil, errors.InvalidArgumentError("no private key in signing key") |
| 249 |
} |
| 250 |
if signer.Encrypted { |
| 251 |
return nil, errors.InvalidArgumentError("signing key must be decrypted") |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
var hash crypto.Hash |
| 256 |
var salt []byte |
| 257 |
if signer != nil { |
| 258 |
if hash, err = selectHash(candidateHashes, config.Hash(), signer); err != nil { |
| 259 |
return nil, err |
| 260 |
} |
| 261 |
|
| 262 |
var opsVersion = 3 |
| 263 |
if signer.Version == 6 { |
| 264 |
opsVersion = signer.Version |
| 265 |
} |
| 266 |
ops := &packet.OnePassSignature{ |
| 267 |
Version: opsVersion, |
| 268 |
SigType: sigType, |
| 269 |
Hash: hash, |
| 270 |
PubKeyAlgo: signer.PubKeyAlgo, |
| 271 |
KeyId: signer.KeyId, |
| 272 |
IsLast: true, |
| 273 |
} |
| 274 |
if opsVersion == 6 { |
| 275 |
ops.KeyFingerprint = signer.Fingerprint |
| 276 |
salt, err = packet.SignatureSaltForHash(hash, config.Random()) |
| 277 |
if err != nil { |
| 278 |
return nil, err |
| 279 |
} |
| 280 |
ops.Salt = salt |
| 281 |
} |
| 282 |
if err := ops.Serialize(payload); err != nil { |
| 283 |
return nil, err |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
if hints == nil { |
| 288 |
hints = &FileHints{} |
| 289 |
} |
| 290 |
|
| 291 |
w := payload |
| 292 |
if signer != nil { |
| 293 |
// If we need to write a signature packet after the literal |
| 294 |
// data then we need to stop literalData from closing |
| 295 |
// encryptedData. |
| 296 |
w = noOpCloser{w} |
| 297 |
|
| 298 |
} |
| 299 |
var epochSeconds uint32 |
| 300 |
if !hints.ModTime.IsZero() { |
| 301 |
epochSeconds = uint32(hints.ModTime.Unix()) |
| 302 |
} |
| 303 |
literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds) |
| 304 |
if err != nil { |
| 305 |
return nil, err |
| 306 |
} |
| 307 |
|
| 308 |
if signer != nil { |
| 309 |
h, wrappedHash, err := hashForSignature(hash, sigType, salt) |
| 310 |
if err != nil { |
| 311 |
return nil, err |
| 312 |
} |
| 313 |
metadata := &packet.LiteralData{ |
| 314 |
Format: 'u', |
| 315 |
FileName: hints.FileName, |
| 316 |
Time: epochSeconds, |
| 317 |
} |
| 318 |
if hints.IsBinary { |
| 319 |
metadata.Format = 'b' |
| 320 |
} |
| 321 |
return signatureWriter{payload, literalData, hash, wrappedHash, h, salt, signer, sigType, config, metadata}, nil |
| 322 |
} |
| 323 |
return literalData, nil |
| 324 |
} |
| 325 |
|
| 326 |
// encrypt encrypts a message to a number of recipients and, optionally, signs |
| 327 |
// it. hints contains optional information, that is also encrypted, that aids |
| 328 |
// the recipients in processing the message. The resulting WriteCloser must |
| 329 |
// be closed after the contents of the file have been written. |
| 330 |
// If config is nil, sensible defaults will be used. |
| 331 |
func encrypt(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, sigType packet.SignatureType, config *packet.Config) (plaintext io.WriteCloser, err error) { |
| 332 |
if len(to) == 0 { |
| 333 |
return nil, errors.InvalidArgumentError("no encryption recipient provided") |
| 334 |
} |
| 335 |
|
| 336 |
// These are the possible ciphers that we'll use for the message. |
| 337 |
candidateCiphers := []uint8{ |
| 338 |
uint8(packet.CipherAES256), |
| 339 |
uint8(packet.CipherAES128), |
| 340 |
} |
| 341 |
|
| 342 |
// These are the possible hash functions that we'll use for the signature. |
| 343 |
candidateHashes := []uint8{ |
| 344 |
hashToHashId(crypto.SHA256), |
| 345 |
hashToHashId(crypto.SHA384), |
| 346 |
hashToHashId(crypto.SHA512), |
| 347 |
hashToHashId(crypto.SHA3_256), |
| 348 |
hashToHashId(crypto.SHA3_512), |
| 349 |
} |
| 350 |
|
| 351 |
// Prefer GCM if everyone supports it |
| 352 |
candidateCipherSuites := [][2]uint8{ |
| 353 |
{uint8(packet.CipherAES256), uint8(packet.AEADModeGCM)}, |
| 354 |
{uint8(packet.CipherAES256), uint8(packet.AEADModeEAX)}, |
| 355 |
{uint8(packet.CipherAES256), uint8(packet.AEADModeOCB)}, |
| 356 |
{uint8(packet.CipherAES128), uint8(packet.AEADModeGCM)}, |
| 357 |
{uint8(packet.CipherAES128), uint8(packet.AEADModeEAX)}, |
| 358 |
{uint8(packet.CipherAES128), uint8(packet.AEADModeOCB)}, |
| 359 |
} |
| 360 |
|
| 361 |
candidateCompression := []uint8{ |
| 362 |
uint8(packet.CompressionNone), |
| 363 |
uint8(packet.CompressionZIP), |
| 364 |
uint8(packet.CompressionZLIB), |
| 365 |
} |
| 366 |
|
| 367 |
encryptKeys := make([]Key, len(to)) |
| 368 |
|
| 369 |
// AEAD is used only if config enables it and every key supports it |
| 370 |
aeadSupported := config.AEAD() != nil |
| 371 |
|
| 372 |
allPQ := len(to) > 0 |
| 373 |
for i := range to { |
| 374 |
var ok bool |
| 375 |
encryptKeys[i], ok = to[i].EncryptionKey(config.Now()) |
| 376 |
if !ok { |
| 377 |
return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no valid encryption keys") |
| 378 |
} |
| 379 |
|
| 380 |
if !encryptKeys[i].PublicKey.IsPQ() { |
| 381 |
allPQ = false |
| 382 |
} |
| 383 |
|
| 384 |
primarySelfSignature, _ := to[i].PrimarySelfSignature() |
| 385 |
if primarySelfSignature == nil { |
| 386 |
return nil, errors.InvalidArgumentError("entity without a self-signature") |
| 387 |
} |
| 388 |
|
| 389 |
if !primarySelfSignature.SEIPDv2 { |
| 390 |
aeadSupported = false |
| 391 |
} |
| 392 |
|
| 393 |
candidateCiphers = intersectPreferences(candidateCiphers, primarySelfSignature.PreferredSymmetric) |
| 394 |
candidateHashes = intersectPreferences(candidateHashes, primarySelfSignature.PreferredHash) |
| 395 |
candidateCipherSuites = intersectCipherSuites(candidateCipherSuites, primarySelfSignature.PreferredCipherSuites) |
| 396 |
candidateCompression = intersectPreferences(candidateCompression, primarySelfSignature.PreferredCompression) |
| 397 |
} |
| 398 |
|
| 399 |
// In the event that the intersection of supported algorithms is empty we use the ones |
| 400 |
// labelled as MUST that every implementation supports. |
| 401 |
if len(candidateCiphers) == 0 { |
| 402 |
// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.3 |
| 403 |
candidateCiphers = []uint8{uint8(packet.CipherAES128)} |
| 404 |
} |
| 405 |
if len(candidateHashes) == 0 { |
| 406 |
// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#hash-algos |
| 407 |
candidateHashes = []uint8{hashToHashId(crypto.SHA256)} |
| 408 |
} |
| 409 |
if len(candidateCipherSuites) == 0 { |
| 410 |
if allPQ { |
| 411 |
candidateCipherSuites = [][2]uint8{{uint8(packet.CipherAES256), uint8(packet.AEADModeOCB)}} |
| 412 |
} else { |
| 413 |
// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.6 |
| 414 |
candidateCipherSuites = [][2]uint8{{uint8(packet.CipherAES128), uint8(packet.AEADModeOCB)}} |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
cipher := packet.CipherFunction(candidateCiphers[0]) |
| 419 |
aeadCipherSuite := packet.CipherSuite{ |
| 420 |
Cipher: packet.CipherFunction(candidateCipherSuites[0][0]), |
| 421 |
Mode: packet.AEADMode(candidateCipherSuites[0][1]), |
| 422 |
} |
| 423 |
|
| 424 |
// If the cipher specified by config is a candidate, we'll use that. |
| 425 |
configuredCipher := config.Cipher() |
| 426 |
for _, c := range candidateCiphers { |
| 427 |
cipherFunc := packet.CipherFunction(c) |
| 428 |
if cipherFunc == configuredCipher { |
| 429 |
cipher = cipherFunc |
| 430 |
break |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
var symKey []byte |
| 435 |
if aeadSupported { |
| 436 |
symKey = make([]byte, aeadCipherSuite.Cipher.KeySize()) |
| 437 |
} else { |
| 438 |
symKey = make([]byte, cipher.KeySize()) |
| 439 |
} |
| 440 |
|
| 441 |
if _, err := io.ReadFull(config.Random(), symKey); err != nil { |
| 442 |
return nil, err |
| 443 |
} |
| 444 |
|
| 445 |
for _, key := range encryptKeys { |
| 446 |
if err := packet.SerializeEncryptedKeyAEAD(keyWriter, key.PublicKey, cipher, aeadSupported, symKey, config); err != nil { |
| 447 |
return nil, err |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
var payload io.WriteCloser |
| 452 |
payload, err = packet.SerializeSymmetricallyEncrypted(dataWriter, cipher, aeadSupported, aeadCipherSuite, symKey, config) |
| 453 |
if err != nil { |
| 454 |
return |
| 455 |
} |
| 456 |
|
| 457 |
payload, err = handleCompression(payload, candidateCompression, config) |
| 458 |
if err != nil { |
| 459 |
return nil, err |
| 460 |
} |
| 461 |
|
| 462 |
return writeAndSign(payload, candidateHashes, signed, hints, sigType, config) |
| 463 |
} |
| 464 |
|
| 465 |
// Sign signs a message. The resulting WriteCloser must be closed after the |
| 466 |
// contents of the file have been written. hints contains optional information |
| 467 |
// that aids the recipients in processing the message. |
| 468 |
// If config is nil, sensible defaults will be used. |
| 469 |
func Sign(output io.Writer, signed *Entity, hints *FileHints, config *packet.Config) (input io.WriteCloser, err error) { |
| 470 |
if signed == nil { |
| 471 |
return nil, errors.InvalidArgumentError("no signer provided") |
| 472 |
} |
| 473 |
|
| 474 |
// These are the possible hash functions that we'll use for the signature. |
| 475 |
candidateHashes := []uint8{ |
| 476 |
hashToHashId(crypto.SHA256), |
| 477 |
hashToHashId(crypto.SHA384), |
| 478 |
hashToHashId(crypto.SHA512), |
| 479 |
hashToHashId(crypto.SHA3_256), |
| 480 |
hashToHashId(crypto.SHA3_512), |
| 481 |
} |
| 482 |
defaultHashes := candidateHashes[0:1] |
| 483 |
primarySelfSignature, _ := signed.PrimarySelfSignature() |
| 484 |
if primarySelfSignature == nil { |
| 485 |
return nil, errors.StructuralError("signed entity has no self-signature") |
| 486 |
} |
| 487 |
preferredHashes := primarySelfSignature.PreferredHash |
| 488 |
if len(preferredHashes) == 0 { |
| 489 |
preferredHashes = defaultHashes |
| 490 |
} |
| 491 |
candidateHashes = intersectPreferences(candidateHashes, preferredHashes) |
| 492 |
if len(candidateHashes) == 0 { |
| 493 |
return nil, errors.StructuralError("cannot sign because signing key shares no common algorithms with candidate hashes") |
| 494 |
} |
| 495 |
|
| 496 |
return writeAndSign(noOpCloser{output}, candidateHashes, signed, hints, packet.SigTypeBinary, config) |
| 497 |
} |
| 498 |
|
| 499 |
// signatureWriter hashes the contents of a message while passing it along to |
| 500 |
// literalData. When closed, it closes literalData, writes a signature packet |
| 501 |
// to encryptedData and then also closes encryptedData. |
| 502 |
type signatureWriter struct { |
| 503 |
encryptedData io.WriteCloser |
| 504 |
literalData io.WriteCloser |
| 505 |
hashType crypto.Hash |
| 506 |
wrappedHash hash.Hash |
| 507 |
h hash.Hash |
| 508 |
salt []byte // v6 only |
| 509 |
signer *packet.PrivateKey |
| 510 |
sigType packet.SignatureType |
| 511 |
config *packet.Config |
| 512 |
metadata *packet.LiteralData // V5 signatures protect document metadata |
| 513 |
} |
| 514 |
|
| 515 |
func (s signatureWriter) Write(data []byte) (int, error) { |
| 516 |
s.wrappedHash.Write(data) |
| 517 |
switch s.sigType { |
| 518 |
case packet.SigTypeBinary: |
| 519 |
return s.literalData.Write(data) |
| 520 |
case packet.SigTypeText: |
| 521 |
flag := 0 |
| 522 |
return writeCanonical(s.literalData, data, &flag) |
| 523 |
} |
| 524 |
return 0, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(s.sigType))) |
| 525 |
} |
| 526 |
|
| 527 |
func (s signatureWriter) Close() error { |
| 528 |
sig := createSignaturePacket(&s.signer.PublicKey, s.sigType, s.config) |
| 529 |
sig.Hash = s.hashType |
| 530 |
sig.Metadata = s.metadata |
| 531 |
|
| 532 |
if err := sig.SetSalt(s.salt); err != nil { |
| 533 |
return err |
| 534 |
} |
| 535 |
|
| 536 |
if err := sig.Sign(s.h, s.signer, s.config); err != nil { |
| 537 |
return err |
| 538 |
} |
| 539 |
if err := s.literalData.Close(); err != nil { |
| 540 |
return err |
| 541 |
} |
| 542 |
if err := sig.Serialize(s.encryptedData); err != nil { |
| 543 |
return err |
| 544 |
} |
| 545 |
return s.encryptedData.Close() |
| 546 |
} |
| 547 |
|
| 548 |
func selectHashForSigningKey(config *packet.Config, signer *packet.PublicKey) crypto.Hash { |
| 549 |
acceptableHashes := acceptableHashesToWrite(signer) |
| 550 |
hash, ok := algorithm.HashToHashId(config.Hash()) |
| 551 |
if !ok { |
| 552 |
return config.Hash() |
| 553 |
} |
| 554 |
for _, acceptableHashes := range acceptableHashes { |
| 555 |
if acceptableHashes == hash { |
| 556 |
return config.Hash() |
| 557 |
} |
| 558 |
} |
| 559 |
if len(acceptableHashes) > 0 { |
| 560 |
defaultAcceptedHash, ok := algorithm.HashIdToHash(acceptableHashes[0]) |
| 561 |
if ok { |
| 562 |
return defaultAcceptedHash |
| 563 |
} |
| 564 |
} |
| 565 |
return config.Hash() |
| 566 |
} |
| 567 |
|
| 568 |
func createSignaturePacket(signer *packet.PublicKey, sigType packet.SignatureType, config *packet.Config) *packet.Signature { |
| 569 |
sigLifetimeSecs := config.SigLifetime() |
| 570 |
hash := selectHashForSigningKey(config, signer) |
| 571 |
return &packet.Signature{ |
| 572 |
Version: signer.Version, |
| 573 |
SigType: sigType, |
| 574 |
PubKeyAlgo: signer.PubKeyAlgo, |
| 575 |
Hash: hash, |
| 576 |
CreationTime: config.Now(), |
| 577 |
IssuerKeyId: &signer.KeyId, |
| 578 |
IssuerKeyVersion: uint8(signer.Version), |
| 579 |
IssuerFingerprint: signer.Fingerprint, |
| 580 |
Notations: config.Notations(), |
| 581 |
SigLifetimeSecs: &sigLifetimeSecs, |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
// noOpCloser is like an ioutil.NopCloser, but for an io.Writer. |
| 586 |
// TODO: we have two of these in OpenPGP packages alone. This probably needs |
| 587 |
// to be promoted somewhere more common. |
| 588 |
type noOpCloser struct { |
| 589 |
w io.Writer |
| 590 |
} |
| 591 |
|
| 592 |
func (c noOpCloser) Write(data []byte) (n int, err error) { |
| 593 |
return c.w.Write(data) |
| 594 |
} |
| 595 |
|
| 596 |
func (c noOpCloser) Close() error { |
| 597 |
return nil |
| 598 |
} |
| 599 |
|
| 600 |
func handleCompression(compressed io.WriteCloser, candidateCompression []uint8, config *packet.Config) (data io.WriteCloser, err error) { |
| 601 |
data = compressed |
| 602 |
confAlgo := config.Compression() |
| 603 |
if confAlgo == packet.CompressionNone { |
| 604 |
return |
| 605 |
} |
| 606 |
|
| 607 |
// Set algorithm labelled as MUST as fallback |
| 608 |
// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.4 |
| 609 |
finalAlgo := packet.CompressionNone |
| 610 |
// if compression specified by config available we will use it |
| 611 |
for _, c := range candidateCompression { |
| 612 |
if uint8(confAlgo) == c { |
| 613 |
finalAlgo = confAlgo |
| 614 |
break |
| 615 |
} |
| 616 |
} |
| 617 |
|
| 618 |
if finalAlgo != packet.CompressionNone { |
| 619 |
var compConfig *packet.CompressionConfig |
| 620 |
if config != nil { |
| 621 |
compConfig = config.CompressionConfig |
| 622 |
} |
| 623 |
data, err = packet.SerializeCompressed(compressed, finalAlgo, compConfig) |
| 624 |
if err != nil { |
| 625 |
return |
| 626 |
} |
| 627 |
} |
| 628 |
return data, nil |
| 629 |
} |
| 630 |
|
| 631 |
// selectHash selects the preferred hash given the candidateHashes and the configuredHash |
| 632 |
func selectHash(candidateHashes []byte, configuredHash crypto.Hash, signer *packet.PrivateKey) (hash crypto.Hash, err error) { |
| 633 |
acceptableHashes := acceptableHashesToWrite(&signer.PublicKey) |
| 634 |
candidateHashes = intersectPreferences(acceptableHashes, candidateHashes) |
| 635 |
|
| 636 |
for _, hashId := range candidateHashes { |
| 637 |
if h, ok := algorithm.HashIdToHash(hashId); ok && h.Available() { |
| 638 |
hash = h |
| 639 |
break |
| 640 |
} |
| 641 |
} |
| 642 |
|
| 643 |
// If the hash specified by config is a candidate, we'll use that. |
| 644 |
if configuredHash.Available() { |
| 645 |
for _, hashId := range candidateHashes { |
| 646 |
if h, ok := algorithm.HashIdToHash(hashId); ok && h == configuredHash { |
| 647 |
hash = h |
| 648 |
break |
| 649 |
} |
| 650 |
} |
| 651 |
} |
| 652 |
|
| 653 |
if hash == 0 { |
| 654 |
if len(acceptableHashes) > 0 { |
| 655 |
if h, ok := algorithm.HashIdToHash(acceptableHashes[0]); ok { |
| 656 |
hash = h |
| 657 |
} else { |
| 658 |
return 0, errors.UnsupportedError("no candidate hash functions are compiled in.") |
| 659 |
} |
| 660 |
} else { |
| 661 |
return 0, errors.UnsupportedError("no candidate hash functions are compiled in.") |
| 662 |
} |
| 663 |
} |
| 664 |
return |
| 665 |
} |
| 666 |
|
| 667 |
func acceptableHashesToWrite(singingKey *packet.PublicKey) []uint8 { |
| 668 |
switch singingKey.PubKeyAlgo { |
| 669 |
case packet.PubKeyAlgoEd448, packet.PubKeyAlgoMldsa87Ed448, packet.PubKeyAlgoSlhdsaShake256s: |
| 670 |
return []uint8{ |
| 671 |
hashToHashId(crypto.SHA512), |
| 672 |
hashToHashId(crypto.SHA3_512), |
| 673 |
} |
| 674 |
case packet.PubKeyAlgoECDSA, packet.PubKeyAlgoEdDSA: |
| 675 |
if curve, err := singingKey.Curve(); err == nil { |
| 676 |
if curve == packet.Curve448 || |
| 677 |
curve == packet.CurveNistP521 || |
| 678 |
curve == packet.CurveBrainpoolP512 { |
| 679 |
return []uint8{ |
| 680 |
hashToHashId(crypto.SHA512), |
| 681 |
hashToHashId(crypto.SHA3_512), |
| 682 |
} |
| 683 |
} else if curve == packet.CurveBrainpoolP384 || |
| 684 |
curve == packet.CurveNistP384 { |
| 685 |
return []uint8{ |
| 686 |
hashToHashId(crypto.SHA384), |
| 687 |
hashToHashId(crypto.SHA512), |
| 688 |
hashToHashId(crypto.SHA3_512), |
| 689 |
} |
| 690 |
} |
| 691 |
} |
| 692 |
} |
| 693 |
return []uint8{ |
| 694 |
hashToHashId(crypto.SHA256), |
| 695 |
hashToHashId(crypto.SHA384), |
| 696 |
hashToHashId(crypto.SHA512), |
| 697 |
hashToHashId(crypto.SHA3_256), |
| 698 |
hashToHashId(crypto.SHA3_512), |
| 699 |
} |
| 700 |
} |