Passwordfile library  3.1.3
C++ library to read/write passwords from/to encrypted files
passwordfile.cpp
Go to the documentation of this file.
1 #include "./passwordfile.h"
2 #include "./cryptoexception.h"
3 #include "./parsingexception.h"
4 #include "./entry.h"
5 
6 #include <c++utilities/io/catchiofailure.h>
7 
8 #include <openssl/conf.h>
9 #include <openssl/err.h>
10 #include <openssl/evp.h>
11 #include <openssl/rand.h>
12 
13 #include <zlib.h>
14 
15 #include <streambuf>
16 #include <sstream>
17 #include <cstring>
18 #include <memory>
19 #include <functional>
20 
21 using namespace std;
22 using namespace IoUtilities;
23 
24 namespace Io {
25 
26 const unsigned int aes256cbcIvSize = 16U;
27 
37 PasswordFile::PasswordFile() :
38  m_freader(BinaryReader(&m_file)),
39  m_fwriter(BinaryWriter(&m_file))
40 {
41  m_file.exceptions(ios_base::failbit | ios_base::badbit);
42  clearPassword();
43 }
44 
48 PasswordFile::PasswordFile(const string &path, const string &password) :
49  m_freader(BinaryReader(&m_file)),
50  m_fwriter(BinaryWriter(&m_file))
51 {
52  m_file.exceptions(ios_base::failbit | ios_base::badbit);
53  setPath(path);
54  setPassword(password);
55 }
56 
61  m_path(other.m_path),
62  m_freader(BinaryReader(&m_file)),
63  m_fwriter(BinaryWriter(&m_file))
64 {
65  m_file.exceptions(ios_base::failbit | ios_base::badbit);
66  setPath(other.path());
67  memcpy(m_password, other.m_password, 32);
68 }
69 
74 {
75  close();
76 }
77 
82 void PasswordFile::open(bool readOnly)
83 {
84  close();
85  if(m_path.empty()) {
86  throwIoFailure("Unable to open file because path is emtpy.");
87  }
88  m_file.open(m_path, readOnly ? ios_base::in | ios_base::binary : ios_base::in | ios_base::out | ios_base::binary);
89  m_file.seekg(0, ios_base::end);
90  if(m_file.tellg() == 0) {
91  throwIoFailure("File is empty.");
92  } else {
93  m_file.seekg(0);
94  }
95 }
96 
101 {
102  if(!m_rootEntry) {
103  m_rootEntry.reset(new NodeEntry("accounts"));
104  }
105 }
106 
112 {
113  close();
114  if(m_path.empty()) {
115  throwIoFailure("Unable to create file because path is empty.");
116  }
117  m_file.open(m_path, fstream::out | fstream::trunc | fstream::binary);
118 }
119 
129 {
130  if(!m_file.is_open()) {
131  open();
132  }
133  m_file.seekg(0);
134  // check magic number
135  if(m_freader.readUInt32LE() != 0x7770616DU) {
136  throw ParsingException("Signature not present.");
137  }
138  // check version and flags (used in version 0x3 only)
139  uint32 version = m_freader.readUInt32LE();
140  if(version != 0x0U && version != 0x1U && version != 0x2U && version != 0x3U && version != 0x4U && version != 0x5U) {
141  throw ParsingException("Version is unknown.");
142  }
143  bool decrypterUsed;
144  bool ivUsed;
145  bool compressionUsed;
146  if(version == 0x3U) {
147  byte flags = m_freader.readByte();
148  decrypterUsed = flags & 0x80;
149  ivUsed = flags & 0x40;
150  compressionUsed = flags & 0x20;
151  } else {
152  decrypterUsed = version >= 0x1U;
153  ivUsed = version == 0x2U;
154  compressionUsed = false;
155  }
156  // skip extended header
157  // the extended header might be used in further versions to
158  // add additional information without breaking compatibility
159  if(version >= 0x4U) {
160  uint16 extendedHeaderSize = m_freader.readUInt16BE();
161  m_extendedHeader = m_freader.readString(extendedHeaderSize);
162  }
163  // get length
164  fstream::pos_type headerSize = m_file.tellg();
165  m_file.seekg(0, ios_base::end);
166  fstream::pos_type size = m_file.tellg();
167  m_file.seekg(headerSize, ios_base::beg);
168  size -= headerSize;
169  // read file
170  unsigned char iv[aes256cbcIvSize] = {0};
171  if(decrypterUsed && ivUsed) {
172  if(size < aes256cbcIvSize) {
173  throw ParsingException("Initiation vector not present.");
174  }
175  m_file.read(reinterpret_cast<char *>(iv), aes256cbcIvSize);
176  size -= aes256cbcIvSize;
177  }
178  if(size <= 0) {
179  throw ParsingException("No contents found.");
180  }
181  // decrypt contents
182  vector<char> rawbuff;
183  m_freader.read(rawbuff, size);
184  vector<char> decbuff;
185  if(decrypterUsed) {
186  // initiate ctx
187  EVP_CIPHER_CTX *ctx = nullptr;
188  decbuff.resize(size + static_cast<fstream::pos_type>(32));
189  int outlen1, outlen2;
190  if ((ctx = EVP_CIPHER_CTX_new()) == nullptr
191  || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, reinterpret_cast<unsigned const char *>(m_password), iv) != 1
192  || EVP_DecryptUpdate(ctx, reinterpret_cast<unsigned char *>(decbuff.data()), &outlen1, reinterpret_cast<unsigned char *>(rawbuff.data()), size) != 1
193  || EVP_DecryptFinal_ex(ctx, reinterpret_cast<unsigned char *>(decbuff.data()) + outlen1, &outlen2) != 1) {
194  if(ctx) {
195  EVP_CIPHER_CTX_free(ctx);
196  }
197  string msg;
198  unsigned long errorCode = ERR_get_error();
199  while(errorCode != 0) {
200  if(!msg.empty()) {
201  msg += "\n";
202  }
203  msg += ERR_error_string(errorCode, 0);
204  errorCode = ERR_get_error();
205  }
206  throw CryptoException(msg);
207  } else { // decryption suceeded
208  if(ctx) {
209  EVP_CIPHER_CTX_free(ctx);
210  }
211  size = outlen1 + outlen2;
212  }
213  } else { // file is not crypted
214  decbuff.swap(rawbuff);
215  }
216  // decompress
217  if(compressionUsed) {
218  if(size < 8) {
219  throw ParsingException("File is truncated (decompressed size expected).");
220  }
221  uLongf decompressedSize = ConversionUtilities::LE::toUInt64(decbuff.data());
222  rawbuff.resize(decompressedSize);
223  switch(uncompress(reinterpret_cast<Bytef *>(rawbuff.data()), &decompressedSize, reinterpret_cast<Bytef *>(decbuff.data() + 8), size - static_cast<fstream::pos_type>(8))) {
224  case Z_MEM_ERROR:
225  throw ParsingException("Decompressing failed. The source buffer was too small.");
226  case Z_BUF_ERROR:
227  throw ParsingException("Decompressing failed. The destination buffer was too small.");
228  case Z_DATA_ERROR:
229  throw ParsingException("Decompressing failed. The input data was corrupted or incomplete.");
230  case Z_OK:
231  decbuff.swap(rawbuff); // decompression successful
232  size = decompressedSize;
233  }
234  }
235  // parse contents
236  stringstream buffstr(stringstream::in | stringstream::out | stringstream::binary);
237  buffstr.write(decbuff.data(), static_cast<streamsize>(size));
238  decbuff.resize(0);
239  buffstr.seekg(0, ios_base::beg);
240  if(version >= 0x5u) {
241  uint16 extendedHeaderSize = m_freader.readUInt16BE();
242  m_encryptedExtendedHeader = m_freader.readString(extendedHeaderSize);
243  }
244  m_rootEntry.reset(new NodeEntry(buffstr));
245 }
246 
255 void PasswordFile::save(bool useEncryption, bool useCompression)
256 {
257  if(!m_rootEntry) {
258  throw runtime_error("Root entry has not been created.");
259  }
260  // open file
261  if(m_file.is_open()) {
262  m_file.close();
263  m_file.clear();
264  }
265  m_file.open(m_path, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
266  // write header
267  m_fwriter.writeUInt32LE(0x7770616DU); // write magic number
268  // write version, extended header requires version 4, encrypted extended header required version 5
269  m_fwriter.writeUInt32LE(m_extendedHeader.empty() && m_encryptedExtendedHeader.empty() ? 0x3U : (m_encryptedExtendedHeader.empty() ? 0x4U : 0x5U));
270  byte flags = 0x00;
271  if(useEncryption) {
272  flags |= 0x80 | 0x40;
273  }
274  if(useCompression) {
275  flags |= 0x20;
276  }
277  m_fwriter.writeByte(flags);
278  // write extened header
279  if(!m_extendedHeader.empty()) {
280  m_fwriter.writeUInt16BE(m_extendedHeader.size());
281  m_fwriter.writeString(m_extendedHeader);
282  }
283  // serialize root entry and descendants
284  stringstream buffstr(stringstream::in | stringstream::out | stringstream::binary);
285  buffstr.exceptions(ios_base::failbit | ios_base::badbit);
286  // write encrypted extened header
287  if(!m_encryptedExtendedHeader.empty()) {
288  m_fwriter.writeUInt16BE(m_encryptedExtendedHeader.size());
289  m_fwriter.writeString(m_encryptedExtendedHeader);
290  }
291  m_rootEntry->make(buffstr);
292  buffstr.seekp(0, ios_base::end);
293  stringstream::pos_type size = buffstr.tellp();
294  // write the data to a buffer
295  buffstr.seekg(0);
296  vector<char> decbuff(size, 0);
297  buffstr.read(decbuff.data(), size);
298  vector<char> encbuff;
299  // compress data
300  if(useCompression) {
301  uLongf compressedSize = compressBound(size);
302  encbuff.resize(8 + compressedSize);
303  ConversionUtilities::LE::getBytes(static_cast<uint64>(size), encbuff.data());
304  switch(compress(reinterpret_cast<Bytef *>(encbuff.data() + 8), &compressedSize, reinterpret_cast<Bytef *>(decbuff.data()), size)) {
305  case Z_MEM_ERROR:
306  throw runtime_error("Decompressing failed. The source buffer was too small.");
307  case Z_BUF_ERROR:
308  throw runtime_error("Decompressing failed. The destination buffer was too small.");
309  case Z_OK:
310  encbuff.swap(decbuff); // decompression successful
311  size = 8 + compressedSize;
312  }
313  }
314  // encrypt data
315  if(useEncryption) {
316  // initiate ctx
317  EVP_CIPHER_CTX *ctx = nullptr;
318  unsigned char iv[aes256cbcIvSize];
319  int outlen1, outlen2;
320  encbuff.resize(size + static_cast<fstream::pos_type>(32));
321  if (RAND_bytes(iv, aes256cbcIvSize) != 1
322  || (ctx = EVP_CIPHER_CTX_new()) == nullptr
323  || EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, reinterpret_cast<unsigned const char *>(m_password), iv) != 1
324  || EVP_EncryptUpdate(ctx, reinterpret_cast<unsigned char *>(encbuff.data()), &outlen1, reinterpret_cast<unsigned char *>(decbuff.data()), size) != 1
325  || EVP_EncryptFinal_ex(ctx, reinterpret_cast<unsigned char *>(encbuff.data()) + outlen1, &outlen2) != 1) {
326  if(ctx) {
327  EVP_CIPHER_CTX_free(ctx);
328  }
329  string msg;
330  unsigned long errorCode = ERR_get_error();
331  while(errorCode != 0) {
332  if(!msg.empty()) {
333  msg += "\n";
334  }
335  msg += ERR_error_string(errorCode, 0);
336  errorCode = ERR_get_error();
337  }
338  throw CryptoException(msg);
339  } else { // decryption succeeded
340  if(ctx) {
341  EVP_CIPHER_CTX_free(ctx);
342  }
343  // write encrypted data to file
344  m_file.write(reinterpret_cast<char *>(iv), aes256cbcIvSize);
345  m_file.write(encbuff.data(), static_cast<streamsize>(outlen1 + outlen2));
346  }
347  } else {
348  // write data to file
349  m_file.write(decbuff.data(), static_cast<streamsize>(size));
350  }
351  m_file.flush();
352 }
353 
358 {
359  m_rootEntry.reset();
360 }
361 
366 {
367  close();
368  clearPath();
369  clearPassword();
370  clearEntries();
371  m_extendedHeader.clear();
372  m_encryptedExtendedHeader.clear();
373 }
374 
381 void PasswordFile::exportToTextfile(const string &targetPath) const
382 {
383  if(!m_rootEntry) {
384  throw runtime_error("Root entry has not been created.");
385  }
386  fstream output(targetPath.c_str(), ios_base::out);
387  function<void (int level)> indention = [&output] (int level) {
388  for(int i = 0; i < level; ++i) {
389  output << " ";
390  }
391  };
392  function<void (const Entry *entry, int level)> printNode;
393  printNode = [&output, &printNode, &indention] (const Entry *entry, int level) {
394  indention(level);
395  output << " - " << entry->label() << endl;
396  switch(entry->type()) {
397  case EntryType::Node:
398  for(const Entry *child : static_cast<const NodeEntry *>(entry)->children()) {
399  printNode(child, level + 1);
400  }
401  break;
402  case EntryType::Account:
403  for(const Field &field : static_cast<const AccountEntry *>(entry)->fields()) {
404  indention(level);
405  output << " " << field.name();
406  for(int i = field.name().length(); i < 15; ++i) {
407  output << ' ';
408  }
409  output << field.value() << endl;
410  }
411  }
412  };
413  printNode(m_rootEntry.get(), 0);
414  output.close();
415 }
416 
422 {
423  if(!isOpen()) {
424  open();
425  }
426  m_file.seekg(0, ios_base::end);
427  if(m_file.tellg()) {
428  m_file.seekg(0);
429  fstream backupFile(m_path + ".backup", ios::out | ios::trunc | ios::binary);
430  backupFile.exceptions(ios_base::failbit | ios_base::badbit);
431  backupFile << m_file.rdbuf();
432  backupFile.close();
433  } else {
434  // the current file is empty anyways
435  }
436 }
437 
444 {
445  return m_rootEntry != nullptr;
446 }
447 
452 {
453  return m_rootEntry.get();
454 }
455 
460 {
461  return m_rootEntry.get();
462 }
463 
468 {
469  if(m_file.is_open()) {
470  m_file.close();
471  }
472  m_file.clear();
473 }
474 
478 const string &PasswordFile::path() const
479 {
480  return m_path;
481 }
482 
486 void PasswordFile::setPath(const string &value)
487 {
488  close();
489  m_path = value;
490 }
491 
496 {
497  close();
498  m_path.clear();
499 }
500 
504 const char *PasswordFile::password() const
505 {
506  return m_password;
507 }
508 
512 void PasswordFile::setPassword(const string &value)
513 {
514  clearPassword();
515  value.copy(m_password, 32, 0);
516 }
517 
522 {
523  memset(m_password, 0, 32);
524 }
525 
530 {
531  if(!isOpen()) {
532  return false;
533  }
534  m_file.seekg(0);
535  //check magic number
536  if(m_freader.readUInt32LE() != 0x7770616DU) {
537  return false;
538  }
539  //check version
540  uint32 version = m_freader.readUInt32LE();
541  if(version == 0x1U || version == 0x2U) {
542  return true;
543  } else if(version == 0x3U) {
544  return m_freader.readByte() & 0x80;
545  } else {
546  return false;
547  }
548 }
549 
554 {
555  return m_file.is_open();
556 }
557 
562 {
563  if(!isOpen()) {
564  return 0;
565  }
566  m_file.seekg(0, ios::end);
567  return m_file.tellg();
568 }
569 
570 }
const std::string & path() const
Returns the current file path.
PasswordFile()
Constructs a new password file.
bool hasRootEntry() const
Returns an indication whether a root entry is present.
void clear()
Closes the file if opened.
The NodeEntry class acts as parent for other entries.
Definition: entry.h:97
The PasswordFile class holds account information in the form of Entry and Field instances and provide...
Definition: passwordfile.h:18
void load()
Reads the contents of the file.
void open(bool readOnly=false)
Opens the file.
STL namespace.
void close()
Closes the file if currently opened.
void doBackup()
Creates a backup of the file.
Contains all IO related classes.
const NodeEntry * rootEntry() const
Returns the root entry if present or nullptr otherwise.
void exportToTextfile(const std::string &targetPath) const
Writes the current root entry to a plain text file.
bool isOpen() const
Returns an indication whether the file is open.
The Field class holds field information which consists of a name and a value and is able to serialize...
Definition: field.h:19
void clearPath()
Clears the current path.
bool isEncryptionUsed()
Returns an indication whether encryption is used if the file is open; returns always false otherwise...
const unsigned int aes256cbcIvSize
~PasswordFile()
Closes the file if still opened and destroys the instance.
void setPath(const std::string &value)
Sets the current file path.
void create()
Creates the file.
size_t size()
Returns the size of the file if the file is open; returns always zero otherwise.
void generateRootEntry()
Generates a new root entry for the file.
const char * password() const
Returns the current password.
The exception that is thrown when an encryption/decryption error occurs.
void setPassword(const std::string &value)
Sets the current password.
void save(bool useEncryption=true, bool useCompression=true)
Writes the current root entry to the file.
The exception that is thrown when a parsing error occurs.
void clearPassword()
Clears the current password.
void clearEntries()
Removes the root element if one is present.
Instances of the Entry class form a hierarchic data strucutre used to store account information...
Definition: entry.h:26