1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
|
/*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2021 Gothel Software e.K.
* Copyright (c) 2021 ZAFENA AB
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JAU_CIPHERPACK_HPP_
#define JAU_CIPHERPACK_HPP_
#include <string>
#include <cstdint>
#include <functional>
#include <botan_all.h>
#include <jau/basic_types.hpp>
#include <jau/file_util.hpp>
#include <jau/byte_stream.hpp>
#include <jau/io_util.hpp>
#include <jau/environment.hpp>
#include <jau/java_uplink.hpp>
/**
* @anchor cipherpack_overview
* ### Cipherpack Overview
* Cipherpack, a secure packaging utility utilizing RSA encryption and signatures to ensure
* privacy and authenticity of the package's source.
*
* The package's header handle the personalized public- and private-key mechanism,
* securing the high-performance symmetric encryption for the high volume payload.
*
* Implementation uses an Authenticated Encryption with Additional Data (AEAD) encryption+MAC cipher algo,
* i.e. {@link cipherpack::constants::aead_cipher_algo}.
*
* ### Cipherpack Implementation
* #### Implementation Status
* READY TO USE
*
* #### Cipherpack Operations
* The following RSA encryption + signature and symmetric payload operations are performed:
* - Writing a DER Header-1, containing the encrypted symmetric file-keys for each public terminal key and further {@link PackInfo} details.
* - Writing a DER Header-2, containing the DER-Header-1 signature using.
* - The encrypted payload, i.e. the ciphertext using the symmetric file-key for encryption + MAC via AEAD `ChaCha20Poly1305`.
*
* Implementation performs all operation `in-place` without redundant copies.
*
* @anchor cipherpack_stream
* #### Cipherpack Data Stream
* The cipherpack stream will be produced as follows:
* ```
* DER Header 1 {
* ASN1_Type::OctetString package_magic
* ASN1_Type::OctetString target_path // designated target path for file
* ASN1_Type::Integer content_size // plain content size, i.e. decrypted payload
* ASN1_Type::Integer creation_timestamp_sec
* ASN1_Type::OctetString intention // designated intention of payload for application
* ASN1_Type::OctetString payload_version
* ASN1_Type::OctetString payload_version_parent
* ASN1_Type::OctetString pk_type // public-key type: "RSA"
* ASN1_Type::OctetString pk_fingerprt_hash_algo // public-key fingerprint hash: "SHA-256"
* ASN1_Type::OctetString pk_enc_padding_algo // public-key encryption padding: "OAEP"
* ASN1_Type::OctetString pk_enc_hash_algo // public-key encryption hash: "SHA-256"
* ASN1_Type::OctetString pk_sign_algo // "EMSA1(SHA-256)",
* ASN1_Type::ObjectId sym_enc_mac_oid // "ChaCha20Poly1305",
* ASN1_Type::OctetString nonce,
* ASN1_Type::OctetString fingerprt_host // fingerprint of public host key used for header signature
* ASN1_Type::Integer encrypted_fkey_count, // number of encrypted file-keys
* ASN1_Type::OctetString fingerprt_term_1, // fingerprint of public terminal key_1 used for encrypted_fkey_term_1
* ASN1_Type::OctetString encrypted_fkey_term_1, // encrypted file-key with public terminal key_1, decrypted with secret terminal key_1
* ASN1_Type::OctetString fingerprt_term_2, // fingerprint of public terminal key_1 used for encrypted_fkey_term_2
* ASN1_Type::OctetString encrypted_fkey_term_2, // encrypted file-key with public terminal key_1, decrypted with secret terminal key_1
* ....
* },
* DER Header 2 {
* ASN1_Type::OctetString header_sign_host // signed with secret host key and using public host key to verify, matching fingerprt_host
* },
* uint8_t encrypted_data[]
* ```
*
* @see encryptThenSign()
* @see checkSignThenDecrypt()
*
*/
namespace cipherpack {
#define JAVA_MAIN_PACKAGE "org/cipherpack/"
class Environment {
public:
static void env_init() noexcept;
};
/**
* CryptoConfig, contains crypto algorithms settings given at encryption wired via the @see @ref cipherpack_stream "Cipherpack Data Stream",
* hence received and used at decryption if matching keys are available.
*/
struct CryptoConfig {
std::string pk_type;
std::string pk_fingerprt_hash_algo;
std::string pk_enc_padding_algo;
std::string pk_enc_hash_algo;
std::string pk_sign_algo;
std::string sym_enc_algo;
size_t sym_enc_nonce_bytes;
/**
* - Public-Key type is {@code RSA}.
* - Public key fingerprint hash algorithm is {@code SHA-256}.
* - Public-Key padding algorithm is {@code OAEP}.
* - Public-Key hash algorithm is {@code SHA-256}.
* - Public-Key hash algorithm is {@code EMSA1(SHA-256)}.
* - Symmetric Authenticated Encryption with Additional Data (AEAD) encryption+MAC cipher algo is {@code ChaCha20Poly1305}.
* - Symmetric AEAD ChaCha Nonce Sizes are usually: 64-bit classic, 96-bit IETF, 192-bit big for one message per file-key.
*/
static CryptoConfig getDefault() noexcept;
CryptoConfig() noexcept
: pk_type(),
pk_fingerprt_hash_algo(),
pk_enc_padding_algo(),
pk_enc_hash_algo(),
pk_sign_algo(),
sym_enc_algo(),
sym_enc_nonce_bytes(0)
{ }
CryptoConfig(const std::string& pk_type_,
const std::string& pk_fingerprt_hash_algo_,
const std::string& pk_enc_padding_algo_,
const std::string& pk_enc_hash_algo_,
const std::string& pk_sign_algo_,
const std::string& sym_enc_algo_,
const size_t sym_enc_nonce_bytes_) noexcept
: pk_type(pk_type_),
pk_fingerprt_hash_algo(pk_fingerprt_hash_algo_),
pk_enc_padding_algo(pk_enc_padding_algo_),
pk_enc_hash_algo(pk_enc_hash_algo_),
pk_sign_algo(pk_sign_algo_),
sym_enc_algo(sym_enc_algo_),
sym_enc_nonce_bytes(sym_enc_nonce_bytes_)
{ }
bool valid() const noexcept;
std::string to_string() const noexcept;
};
class Constants {
public:
/** Intermediate copy buffer size of {@code 4096 bytes}, usually the page-size. */
constexpr static const size_t buffer_size = 4096;
/**
* Package magic {@code CIPHERPACK_0002}.
*/
static const std::string package_magic;
};
/**
* Cipherpack header less encrypted keys or signatures as described in @ref cipherpack_stream "Cipherpack Data Stream"
*
* @see @ref cipherpack_overview "Cipherpack Overview"
*/
class PackHeader {
private:
std::string target_path;
uint64_t content_size;
jau::fraction_timespec ts_creation;
std::string intention;
std::string payload_version;
std::string payload_version_parent;
CryptoConfig crypto_cfg;
std::string host_key_fingerprint;
std::vector<std::string> term_keys_fingerprint;
ssize_t term_key_fingerprint_used_idx;
bool valid;
public:
/** default ctor, denoting an invalid package header. */
PackHeader()
: target_path("none"),
content_size(0),
ts_creation( jau::getWallClockTime() ),
intention("none"),
payload_version(),
payload_version_parent(),
crypto_cfg(),
host_key_fingerprint(),
term_keys_fingerprint(),
term_key_fingerprint_used_idx(-1),
valid(false)
{ }
/** ctor, denoting an invalid package header. */
PackHeader(const jau::fraction_timespec& ts_creation_)
: target_path("none"),
content_size(0),
ts_creation( ts_creation_ ),
intention("none"),
payload_version(),
payload_version_parent(),
crypto_cfg(),
host_key_fingerprint(),
term_keys_fingerprint(),
term_key_fingerprint_used_idx(-1),
valid(false)
{ }
/** Complete ctor, denoting a complete package header, see @ref cipherpack_stream "Cipherpack Data Stream". */
PackHeader(const std::string& target_path_,
const uint64_t& content_size_,
const jau::fraction_timespec& ts_creation_,
const std::string& intention_,
const std::string& pversion, const std::string& pversion_parent,
const CryptoConfig& crypto_cfg_,
const std::string& host_key_fingerprint_,
const std::vector<std::string>& term_keys_fingerprint_,
const size_t term_key_fingerprint_used_idx_,
const bool valid_)
: target_path(target_path_),
content_size(content_size_),
ts_creation(ts_creation_),
intention(intention_),
payload_version(pversion), payload_version_parent(pversion_parent),
crypto_cfg(crypto_cfg_),
host_key_fingerprint(host_key_fingerprint_),
term_keys_fingerprint(term_keys_fingerprint_),
term_key_fingerprint_used_idx(term_key_fingerprint_used_idx_),
valid(valid_)
{ }
/** Returns the designated decrypted target path of the file from DER-Header-1, see @ref cipherpack_stream "Cipherpack Data Stream". */
const std::string& getTargetPath() const noexcept { return target_path; }
/** Returns the plaintext content size in bytes, i.e. decrypted payload size, see @ref cipherpack_stream "Cipherpack Data Stream". */
uint64_t getContentSize() const noexcept { return content_size; }
/** Returns the creation time since Unix epoch, see @ref cipherpack_stream "Cipherpack Data Stream". */
constexpr const jau::fraction_timespec& getCreationTime() const noexcept { return ts_creation; }
/** Returns the intention of the file from DER-Header-1, see @ref cipherpack_stream "Cipherpack Data Stream". */
constexpr const std::string& getIntention() const noexcept { return intention; }
/** Returns the payload version, see @ref cipherpack_stream "Cipherpack Data Stream". */
constexpr const std::string& getPayloadVersion() const noexcept { return payload_version;}
/** Returns the payload's parent version, see @ref cipherpack_stream "Cipherpack Data Stream". */
constexpr const std::string& getPayloadVersionParent() const noexcept { return payload_version_parent;}
constexpr const CryptoConfig& getCryptoConfig() const noexcept { return crypto_cfg; }
/**
* Return the used host key fingerprint used to sign, see @ref cipherpack_stream "Cipherpack Data Stream".
*/
const std::string& getHostKeyFingerprint() const noexcept { return host_key_fingerprint; }
/**
* Return the list of public keys fingerprints used to encrypt the file-key, see @ref cipherpack_stream "Cipherpack Data Stream".
*/
const std::vector<std::string>& getTermKeysFingerprint() const noexcept { return term_keys_fingerprint; }
/**
* Return the index of the matching public key fingerprints used to decrypt the file-key, see @ref cipherpack_stream "Cipherpack Data Stream".
*
* @return the fingerprint index of getTermKeysFingerprint(), or -1 if not found or performing the encryption operation.
*/
ssize_t getUsedTermKeyFingerprintIndex() const noexcept { return term_key_fingerprint_used_idx; }
/**
* Return a string representation
* @param show_crypto_algos pass true if used crypto algos shall be shown, otherwise suppressed (default).
* @param force_all_fingerprints if true always show all getTermKeysFingerprint(), otherwise show only the getTermKeysFingerprint() if >= 0 (default).
* @return string representation
*/
std::string toString(const bool show_crypto_algos=false, const bool force_all_fingerprints=false) const noexcept;
void setValid(const bool v) { valid = v; }
bool isValid() const noexcept { return valid; }
};
inline std::string to_string(const PackHeader& ph) noexcept { return ph.toString(true, true); }
std::shared_ptr<Botan::Public_Key> load_public_key(const std::string& pubkey_fname);
std::shared_ptr<Botan::Private_Key> load_private_key(const std::string& privatekey_fname, const std::string& passphrase);
class CipherpackListener : public jau::JavaUplink {
public:
/**
* Informal user notification about an error via text message.
*
* This message will be send before a subsequent notifyHeader() and notifyEnd() with an error indication.
* @param decrypt_mode true if sender is decrypting, otherwise sender is encrypting
* @param msg the error message
*/
virtual void notifyError(const bool decrypt_mode, const std::string& msg) noexcept {
(void)decrypt_mode;
(void)msg;
}
/**
* User notification of PackHeader
* @param decrypt_mode true if sender is decrypting, otherwise sender is encrypting
* @param header the PackHeader
* @param verified true if header signature is verified and deemed valid, otherwise false regardless of true == PackHeader::isValid().
*/
virtual void notifyHeader(const bool decrypt_mode, const PackHeader& header, const bool verified) noexcept {
(void)decrypt_mode;
(void)header;
(void)verified;
}
/**
* User notification about content streaming progress.
*
* In case contentProcessed() gets called, notifyProgress() is called thereafter.
*
* @param decrypt_mode true if sender is decrypting, otherwise sender is encrypting
* @param content_size the unencrypted content size
* @param bytes_processed the number of unencrypted bytes processed
* @see contentProcessed()
*/
virtual void notifyProgress(const bool decrypt_mode, const uint64_t content_size, const uint64_t bytes_processed) noexcept {
(void)decrypt_mode;
(void)content_size;
(void)bytes_processed;
}
/**
* User notification of process completion.
* @param decrypt_mode true if sender is decrypting, otherwise sender is encrypting
* @param header the PackHeader
* @param success true if process has successfully completed and result is deemed valid, otherwise result is invalid regardless of true == PackHeader::isValid().
*/
virtual void notifyEnd(const bool decrypt_mode, const PackHeader& header, const bool success) noexcept {
(void)decrypt_mode;
(void)header;
(void)success;
}
/**
* User provided information whether process shall send the processed content via contentProcessed() or not
* @param decrypt_mode true if sender is decrypting, otherwise sender is encrypting
* @return true if process shall call contentProcessed(), otherwise false (default)
* @see contentProcessed()
*/
virtual bool getSendContent(const bool decrypt_mode) const noexcept {
(void)decrypt_mode;
return false;
}
/**
* User callback to receive the actual processed content, either the generated cipherpack or plaintext content depending on decrypt_mode.
*
* This callback is only enabled if getSendContent() returns true.
*
* In case contentProcessed() gets called, notifyProgress() is called thereafter.
*
* @param decrypt_mode true if sender is decrypting, otherwise sender is encrypting
* @param is_header true if passed data is part of the header, otherwise false. Always false if decrypt_mode is true.
* @param data the processed content, either the generated cipherpack or plaintext content depending on decrypt_mode.
* @param is_final true if this is the last content call, otherwise false
* @return true to signal continuation, false to end streaming.
* @see getSendContent()
*/
virtual bool contentProcessed(const bool decrypt_mode, const bool is_header, jau::io::secure_vector<uint8_t>& data, const bool is_final) noexcept {
(void)decrypt_mode;
(void)is_header;
(void)data;
(void)is_final;
return true;
}
~CipherpackListener() noexcept override {}
std::string toString() const noexcept override { return "CipherpackListener["+jau::to_hexstring(this)+"]"; }
std::string get_java_class() const noexcept override {
return java_class();
}
static std::string java_class() noexcept {
return std::string(JAVA_MAIN_PACKAGE "CipherpackListener");
}
/**
* Default comparison operator, merely testing for same memory reference.
* <p>
* Specializations may override.
* </p>
*/
virtual bool operator==(const CipherpackListener& rhs) const noexcept
{ return this == &rhs; }
bool operator!=(const CipherpackListener& rhs) const noexcept
{ return !(*this == rhs); }
};
typedef std::shared_ptr<CipherpackListener> CipherpackListenerRef;
/**
* Encrypt then sign the source producing a cipherpack destination file.
*
* @param crypto_cfg The used CryptoConfig, consider using CryptoConfig::getDefault()
* @param enc_pub_keys The public keys of the receiver (terminal device), used to encrypt the file-key for multiple parties.
* @param sign_sec_key_fname The private key of the host (pack provider), used to sign the DER-Header-1 incl encrypted file-key for authenticity.
* @param passphrase The passphrase for `sign_sec_key_fname`, may be an empty string for no passphrase.
* @param source The source jau::io::ByteInStream of the plaintext payload.
* @param designated_fname The designated filename for the decrypted file as written in the DER-Header-1
* @param payload_version The version of this payload
* @param payload_version_parent The version of this payload's parent
* @param listener The CipherpackListener listener used for notifications and optionally
* to send the ciphertext destination bytes via CipherpackListener::contentProcessed()
* @param destination_fname Optional filename of the ciphertext destination file, not used if empty (default). If not empty and file already exists, file will be overwritten.
* @return PackHeader, where true == PackHeader::isValid() if successful, otherwise not.
*
* @see @ref cipherpack_stream "Cipherpack Data Stream"
* @see checkSignThenDecrypt()
*/
PackHeader encryptThenSign(const CryptoConfig& crypto_cfg,
const std::vector<std::string>& enc_pub_keys,
const std::string& sign_sec_key_fname, const std::string& passphrase,
jau::io::ByteInStream& source,
const std::string& target_path, const std::string& intention,
const std::string& payload_version,
const std::string& payload_version_parent,
CipherpackListenerRef listener,
const std::string destination_fname = "");
/**
* Check cipherpack signature of the source then decrypt into the plaintext destination file.
*
* @param sign_pub_keys The potential public keys used by the host (pack provider) to verify the DER-Header-1 signature
* and hence the authenticity of the encrypted file-key. Proves authenticity of the file.
* @param dec_sec_key_fname The private key of the receiver (terminal device), used to decrypt the file-key.
* It shall match one of the keys used to encrypt.
* @param passphrase The passphrase for `dec_sec_key_fname`, may be an empty string for no passphrase.
* @param source The source jau::io::ByteInStream of the cipherpack containing the encrypted payload.
* @param listener The CipherpackListener listener used for notifications and optionally
* to send the plaintext destination bytes via CipherpackListener::contentProcessed()
* @param destination_fname Optional filename of the plaintext destination file, not used if empty (default). If not empty and file already exists, file will be overwritten.
* @return PackHeader, where true == PackHeader::isValid() if successful, otherwise not.
*
* @see @ref cipherpack_stream "Cipherpack Data Stream"
* @see encryptThenSign()
*
*/
PackHeader checkSignThenDecrypt(const std::vector<std::string>& sign_pub_keys,
const std::string &dec_sec_key_fname, const std::string &passphrase,
jau::io::ByteInStream &source,
CipherpackListenerRef listener,
const std::string destination_fname = "");
} // namespace cipherpack
#endif /* JAU_CIPHERPACK_HPP_ */
|