-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpwsafe.cpp
3462 lines (3055 loc) · 108 KB
/
pwsafe.cpp
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
pwsafe - commandline tool compatible with Counterpane's Passwordsafe
Copyright (C) 2004-2005 Nicolas S. Dade
$Id: pwsafe.cpp,v 1.57 2007/08/12 12:33:06 ndade Exp $
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if HAVE_SIGNAL_H
#include <signal.h>
#endif
#if HAVE_GETOPT_H // freebsd for example doesn't have getopt.h but includes getopt() inside unistd.h
#include <getopt.h>
#endif
#if HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <errno.h>
#include <pwd.h>
#include <regex.h>
#if HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#include <limits.h>
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#if HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#if HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#include <string>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
#include <memory>
#include <fstream>
#include "system.h"
#include <termios.h>
#if WITH_READLINE
// fix a few things that system.h setup and that readline.h isn't going to like
#undef ISDIGIT
#undef IN_CTYPE_DOMAIN
#if READLINE_H_NEEDS_EXTERN_C
extern "C" {
#endif
#include <readline/readline.h>
#if READLINE_H_NEEDS_EXTERN_C
} // terminate extern "C"
#endif
#include <curses.h>
#ifdef erase
// some imbecile C programers #define erase() in [n]curses.h, which breaks std::<container>::erase(...)
#undef erase
#endif
#else // WITH_READLINE
// our cheap substitute for readline
static char* readline(const char*);
#endif // WITH_READLINE
#ifndef HAS_GETOPT_LONG
// our cheap substitute for getopt_long
// for testing we might have included a getopt.h that did include getopt_long, so
#ifdef no_argument
#undef no_argument
#undef required_argument
#undef optional_argument
#endif
struct long_option {
const char* name;
int has_arg;
int* flag;
int val;
};
static const int no_argument = 0;
static const int required_argument = 1;
// we don't support optional_argument in our cheap getopt_long
static int getopt_long(int, char*const[], const char*, const long_option*, int*);
#else
typedef struct option long_option;
#endif
#include <netinet/in.h> // for ntohl() to figure out the endianess
#include <openssl/sha.h>
#include <openssl/blowfish.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#ifndef X_DISPLAY_MISSING
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xmu/Atoms.h>
#include <X11/Xmu/WinUtil.h>
#endif
#ifndef HAVE_SOCKLEN_T
typedef int socklen_t;
#endif
#ifndef HAS_GETLINE
static ssize_t getline(char**,size_t*,FILE*);
#endif
// ---- secalloc and secstring classes ------------------------------------
// an (SGI style) allocator class that allocates from secure (non-swapable) storage
class secalloc {
public:
static size_t pagesize;
const static size_t alignsize;
private:
struct Pool {
Pool* next;
char* top;
char* bottom;
char* level;
Pool(size_t);
~Pool();
};
static Pool* pools;
public:
explicit secalloc();
static void init();
static void cleanup();
static void* allocate(size_t);
static void deallocate(void*, size_t);
static void* reallocate(void*, size_t, size_t);
bool operator==(const secalloc&) const { return true; }
bool operator!=(const secalloc&) const { return false; }
// a struct that takes care of calling secalloc::cleanup() when it is destroyed (usefull to ensure that cleanup() is always called)
struct Cleanup {
Cleanup() { secalloc::init(); }
~Cleanup() { secalloc::cleanup(); }
};
};
static secalloc::Cleanup cleanup_secalloc; // so secalloc::cleanup() is always called. Carefull, this must be the first global object so that global secstrings are destroyed first
// There are 4 different allocator interfaces I know of used by g++. g++ 2.9, 3.0, 3.x, x>=1, and 3.4.2.
// I used to try and use std::basic_string, but now I give up and implement my own stupid string
// class. Thank goodness for standards :-(
// a string class for handling strings that must not be swapped out---we use the secure allocator
class secstring {
public:
typedef int size_type;
static const size_type npos = -1;
private:
char* txt;
size_type len; // length of text
size_type res; // length of buffer
static char null_string;
void construct(const char*, size_type, const char*, size_type);
void deallocate() {
if (txt != &null_string)
secalloc::deallocate(txt,res+1);
}
public:
secstring() : txt(&null_string), len(0), res(0) {}
secstring(const secstring&);
secstring(const char*);
secstring(const char*, size_type);
secstring(const char*, const char*);
secstring(const char*, size_type, const char*, size_type);
~secstring();
bool operator == (const secstring&) const;
bool operator != (const secstring& s) const { return ! operator==(s); }
bool operator < (const secstring&) const;
size_type find(char);
size_type find_first_not_of(char);
size_type find_last_not_of(char);
const char& operator[] (size_t i) const { return txt[i]; }
char& operator[] (size_t i) { return txt[i]; }
const char* c_str() const { return txt; }
const char* data() const { return txt; }
size_t length() const { return len; }
bool empty() const { return len == 0; }
secstring& assign(const char*, size_type);
secstring& assign(const char* t) { return assign(t,strlen(t)); }
secstring& operator = (const char* t) { return assign(t); }
secstring& operator = (const secstring& s) { return assign(s.c_str(),s.len); }
secstring& append(const char*, size_type);
secstring& operator += (char c) { return append(&c,1); }
secstring& operator += (const char* t) { return append(t,strlen(t)); }
secstring& operator += (const secstring& s) { return append(s.c_str(),s.len); }
secstring substr(size_type, size_type);
void erase() { operator=(&null_string); }
void reserve(size_type);
void resize(size_type);
typedef const char* const_iterator;
const_iterator begin() const { return txt; }
const_iterator end() const { return txt+len; }
};
char secstring::null_string = '\0';
secstring::secstring(const secstring& s) : txt(&null_string), len(0), res(0) {
assign(s.c_str(),s.length());
}
secstring::secstring(const char* t) : txt(&null_string), len(0), res(0) {
assign(t);
}
secstring::secstring(const char* t, size_type l) : txt(&null_string), len(0), res(0) {
assign(t,l);
}
secstring::secstring(const char* t1, const char* t2) : txt(&null_string), len(0), res(0) {
construct(t1,strlen(t1),t2,strlen(t2));
}
secstring::secstring(const char* t1, size_type l1, const char* t2, size_type l2) : txt(&null_string), len(0), res(0) {
construct(t1,l1,t2,l2);
}
void secstring::construct(const char* t1, size_type l1, const char* t2, size_type l2) {
res = len = l1 + l2;
txt = reinterpret_cast<char*>(secalloc::allocate(res+1));
memcpy(txt,t1,l1);
memcpy(txt+l1,t2,l2);
txt[len] = '\0';
}
secstring::~secstring() {
deallocate();
}
secstring& secstring::assign(const char* t, size_type l) {
if (t != txt) {
deallocate();
res = len = l;
txt = reinterpret_cast<char*>(secalloc::allocate(res+1));
memcpy(txt,t,len);
txt[len] = '\0';
}
return *this;
}
secstring& secstring::append(const char* t, size_type l) {
if (len+l > res)
reserve(len+l);
memcpy(txt+len,t,l);
len += l;
txt[len] = '\0';
return *this;
}
secstring secstring::substr(size_type s, size_type e) {
if (e == npos)
e = len;
return secstring(txt+s,e-s);
}
void secstring::reserve(size_type r) {
if (res < r) {
char* t = reinterpret_cast<char*>(secalloc::allocate(r+1));
memcpy(t,txt,len+1);
deallocate();
txt = t;
res = r;
}
}
void secstring::resize(size_type r) {
reserve(r);
len = r;
txt[r] = '\0';
}
bool secstring::operator==(const secstring& s) const {
return this == &s ||
(len == s.len &&
memcmp(txt,s.txt,len) == 0);
}
bool secstring::operator<(const secstring& s) const {
return strcmp(txt,s.txt) < 0;
}
secstring::size_type secstring::find(char c) {
char* p = strchr(txt,c);
return p ? p-txt : npos;
}
secstring::size_type secstring::find_first_not_of(char c) {
for (size_type p = 0; p < len; p++)
if (txt[p] != c)
return p;
return npos;
}
secstring::size_type secstring::find_last_not_of(char c) {
for (size_type p = len-1; p >= 0; p--)
if (txt[p] != c)
return p;
return npos;
}
secstring operator+(const secstring& t1, const secstring& t2) {
return secstring(t1.c_str(),t1.length(),t2.c_str(),t2.length());
}
secstring operator+(const char* t1, const secstring& t2) {
return secstring(t1,strlen(t1),t2.c_str(),t2.length());
}
secstring operator+(const secstring& t1, const char* t2) {
return secstring(t1.c_str(),t1.length(),t2,strlen(t2));
}
secstring operator+(const secstring& t1, char c) {
return secstring(t1.c_str(),t1.length(),&c,1);
}
// ------ end of fixups for various systems; on to the real program ------
//#define INTERACTIVE_MODE // enable experimental interactive mode
// The name the program was run with, stripped of any leading path
const char *program_name = "pwsafe"; // make sure program_name always points to something valid so we can use it in constructors of globals
uid_t saved_uid;
gid_t saved_gid;
// database version
enum Version { VERSION_UNKNOWN, VERSION_1_7, VERSION_2_0 };
const static char*const VERSION_NAME[] = { "<unknown>", "1.7", "2.0" };
// Option flags and variables
const char* arg_dbname = NULL;
Version arg_dbversion = VERSION_UNKNOWN;
const char* arg_mergedb = NULL;
const char* arg_name = NULL;
enum OP {
OP_NOP, OP_CREATEDB, OP_EXPORTDB, OP_MERGEDB, OP_PASSWD, OP_LIST, OP_EMIT, OP_ADD, OP_EDIT, OP_DELETE,
#ifdef INTERACTIVE_MODE
OP_INTERACT,
#endif
};
OP arg_op = OP_NOP;
//const char* arg_config = NULL;
bool arg_casesensative = false;
bool arg_echo = false;
const char* arg_output = NULL;
FILE* outfile = NULL; // will be arg_output() or stdout
bool arg_username = false;
bool arg_password = false;
bool arg_details = false;
int arg_verbose = 0;
int arg_debug = 0;
#ifndef X_DISPLAY_MISSING
bool arg_xclip = false;
const char* arg_display = NULL;
const char* arg_selection = "both"; // by default copy to primary X selection and clipboard
typedef std::set<std::string> arg_ignore_t;
arg_ignore_t arg_ignore;
static Display* xdisplay = NULL;
#endif
static long_option const long_options[] =
{
// commands
{"createdb", no_argument, 0, 'C'},
{"exportdb", no_argument, 0, 'E'&31},
{"mergedb", required_argument, 0, 'M'&31},
{"passwd", no_argument, 0, 'P'},
{"list", no_argument, 0, 'L'},
{"add", no_argument, 0, 'a'},
{"edit", no_argument, 0, 'e'},
{"delete", no_argument, 0, 'D'},
#ifdef INTERACTIVE_MODE
{"interact", no_argument, 0, 'I'&31},
#endif
// options
// {"config", required_argument, 0, 'F'},
{"file", required_argument, 0, 'f'},
{"case", no_argument, 0 ,'I'},
// options controlling what is outputted
{"long", no_argument, 0, 'l'},
{"username", no_argument, 0, 'u'},
{"password", no_argument, 0, 'p'},
// options controlling where output goes
{"echo", no_argument, 0, 'E'},
{"output", required_argument, 0, 'o'},
{"dbversion", required_argument, 0, 'V'&31},
#ifndef X_DISPLAY_MISSING
{"xclip", no_argument, 0, 'x'},
{"display", required_argument, 0,'d'},
{"selection", required_argument, 0,'s'},
{"ignore", required_argument, 0,'G'},
#endif
// standard stuff
{"quiet", no_argument, 0, 'q'},
{"verbose", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{NULL, 0, NULL, 0}
};
static void usage(bool fail);
static int parse(int argc, char **argv);
static const char* pwsafe_strerror(int err); // decodes errno's as well as our negative error codes
#define PWSAFE_ERR_INVALID_DB -1
static char get1char(const char* prompt, int def_val=-1);
static bool getyn(const char* prompt, int def_val=-1);
static inline char get1char(const std::string& prompt, int def_val=-1) { return get1char(prompt.c_str(), def_val); }
static inline char get1char(const secstring& prompt, int def_val=-1) { return get1char(prompt.c_str(), def_val); }
static inline bool getyn(const std::string& prompt, int def_val=-1) { return getyn(prompt.c_str(), def_val); }
static inline bool getyn(const secstring& prompt, int def_val=-1) { return getyn(prompt.c_str(), def_val); }
struct FailEx {}; // thrown to unwind, cleanup and cause main to return 1
struct ExitEx { const int rc; explicit ExitEx(int c) : rc(c) {} }; // thrown to unwind and exit() with rc
// a blowfish data block (8 bytes)
class Block {
private:
BF_LONG block[2];
static void makeLE(unsigned char[8]);
public:
operator BF_LONG*() { return block; }
Block() {}
~Block();
void zero();
void putInt32AndType(int32_t, uint8_t);
int32_t getInt32() const;
uint8_t getType() const;
Block& operator ^=(const Block&);
void read(const unsigned char*, int len);
void write(unsigned char[8]) const;
bool read(FILE*);
bool write(FILE*) const;
};
class DB {
private:
// the file header, which is kept in secalloc just like the secstrings
struct Header {
unsigned char random[8];
unsigned char hash[SHA_DIGEST_LENGTH]; // 20
unsigned char salt[SHA_DIGEST_LENGTH]; // 20
unsigned char iv[8];
Header();
~Header();
void zero();
bool create();
bool resalt();
bool read(FILE*);
bool write(FILE*) const;
// overload new and delete to the Header is kept in secalloc's memory
void* operator new(size_t n) { return secalloc::allocate(n); }
void operator delete(void* p,size_t n) { secalloc::deallocate(p,n); }
};
Header* header;
// the crypto context (exists only when read/writing the database). also kept in secalloc memory
struct Context {
Block cbc;
BF_KEY bf;
const Version& version; // typically points back to DB's Version
Context(const Header&, const secstring& pw, const Version&);
~Context();
// overload new and delete so Context is kept in secalloc's memory
void* operator new(size_t n) { return secalloc::allocate(n); }
void operator delete(void* p,size_t n) { secalloc::deallocate(p,n); }
};
struct Entry {
public:
typedef std::vector< std::pair<unsigned int,secstring> > extras_t;
private:
// the name+login fields are saved as one string in the file for historical reasons (login was added after 1.0), seperated by magic characters we hope you won't use in a name
const static char SPLIT_CHAR = '\xAD';
const static char*const SPLIT_STR; // = " \xAD "
const static char DEFAULT_USER_CHAR = '\xA0';
// version 2 field types
enum Type { NAME=0, UUID=0x1, GROUP = 0x2, TITLE = 0x3, USER = 0x4, NOTES = 0x5, PASSWORD = 0x6,
// future fields: CTIME = 0x7, MTIME = 0x8, ATIME = 0x9, LTIME = 0xa, POLICY = 0xb,
END = 0xff};
static bool read(FILE*, Context&, uint8_t& type, secstring&);
static bool write(FILE*, Context&, uint8_t type, const secstring&);
static bool write(FILE*, Context&, const extras_t&);
public:
const static char*const MAGIC_V2_NAME; // = " !!!Version 2 File Format!!! ..."
const static char*const MAGIC_V2_PASSWORD; // = "2.0"
static secstring the_default_login;
secstring name;
secstring login;
bool default_login;
secstring password;
secstring notes;
// new v2.0 values
secstring uuid; // I exploit the fact that std::string can contain '\0'
secstring group;
// unknown v2.0+ values are stored as binary, so when the file is saved we can restore them (hopefully this doesn't lead to inconsistencies)
extras_t extras;
static void Init(); // computes the_default_login
Entry();
bool read(FILE*, Context&);
bool write(FILE*, Context&) const;
bool operator!=(const Entry&) const;
bool operator==(const Entry& e) const { return !operator!=(e); }
int diff(const Entry&, secstring& summary) const;
secstring diff(const Entry&) const;
secstring groupname() const;
};
typedef std::map<secstring, Entry> entries_t;
entries_t entries;
typedef std::vector<const Entry*> matches_t;
secstring passphrase;
Version version;
secstring v2_preferences;
bool opened; // true after open() has succeeded
bool changed; // unsaved changes have been made
bool backedup; // true after backup() has succeeded
bool overwritten; // true once we start overwriting dbname
bool getkey(bool test, const char* prompt1="Enter passphrase", const char* prompt2="Reenter passphrase"); // get/verify passphrase
bool testkey(const secstring&);
void hashkey(const secstring&, unsigned char test_hash[]);
bool add(const Entry&); // add entry into database
bool del(const Entry&); // remove entry from database
bool find(matches_t&, const char* regex); // find all entries matching regex
const Entry& find1(const char* regex); // find the one entry either == regex or matching; throw FailEx if 0 or >1 match
public:
const std::string dbname_str;
const char*const dbname;
static void Init();
DB(const char* dbname, Version=VERSION_UNKNOWN);
~DB();
static void createdb(const char* dbname);
bool open(const secstring* pw_to_try=NULL); // call getkey(), read file into entries map
void exportdb();
void mergedb(DB&);
void passwd();
void list(const char* regex);
void emit(const char* regex, bool username, bool password);
void add(const char* name);
void edit(const char* regex);
void del(const char* name);
bool is_changed() const { return changed; }
bool backup(); // create ~ file
bool save(); // write out db file (please backup() first if appropriate)
bool restore(); // copy ~ file back to original (only if an earlier call to backup() suceeded)
static const secstring& defaultlogin() { return Entry::the_default_login; }
};
#ifdef INTERACTIVE_MODE
void interactive(DB& db) {
if (!db.open())
throw FailEx();
const char* db_shortname = strrchr(db.dbname, '/');
if (!db_shortname)
db_shortname = db.dbname;
else
db_shortname++;
char* cmdline = NULL;
size_t cmdline_buflen = 0;
while (true) {
printf("pwsafe:%s> ",db_shortname);
fflush(stdout);
ssize_t cmdlen = getline(&cmdline, &cmdline_buflen, stdin);
if (cmdlen == -1)
throw ExitEx(1);
// break cmdline into argc/argv
int argc = 1;
int argv_len = 1;
char** argv = reinterpret_cast<char**>(malloc(sizeof(argv[0])*(argv_len+1))); // +1 for terminating NULL
if (!argv) {
free(cmdline);
throw ExitEx(1);
}
argv[0] = "pwsafe";
{
char* p = cmdline;
while (p-cmdline < cmdlen && *p != '\0' && *p != '\n') {
// advance to the next non-blank char
while (p-cmdline < cmdlen && *p != '\0' && *p != '\n' && isspace(*p))
++p;
// if we reached the end, stop
if (p-cmdline >= cmdlen || *p == '\0' || *p == '\n')
break;
// make sure there's room in argv[argc]
if (argc >= argv_len) {
int new_argv_len = argv_len*2;
char** new_argv = reinterpret_cast<char**>(realloc(argv,sizeof(argv[0]) * (new_argv_len+1))); // +1 for terminating NULL
if (!new_argv) {
free(argv);
free(cmdline);
throw ExitEx(1);
}
argv = new_argv;
argv_len = new_argv_len;
}
{ // terminate the argument, and handle enclosing "" and '' too, as well as \ sequences
char terminator = ' ';
if (*p == '\'' || *p == '"')
terminator = *p++;
char* q = p;
argv[argc++] = p;
while (p-cmdline < cmdlen && *p != '\0' && *p != '\n' && *p != terminator) {
if (*p == '\\') {
p++;
if (p-cmdline >= cmdlen || *p == '\0' || *p == '\n')
break;
}
*q++ = *p++;
}
// q points just beyond the last char
// skip over the final "" or ''
if (p-cmdline < cmdlen && *p == terminator)
++p;
// terminate the string (which might overwrite the final "" or '')
*q = '\0';
}
}
// terminate argv; getopt_long() expects this
argv[argc] = NULL;
}
// reset some args to default values
arg_mergedb = NULL;
arg_name = NULL;
arg_op = OP_NOP;
arg_casesensative = false;
arg_echo = false;
arg_output = NULL;
arg_username = false;
arg_password = false;
arg_details = false;
#ifndef X_DISPLAY_MISSING
arg_xclip = false;
arg_selection = "both"; // by default copy to primary X selection and clipboard
// leave arg_ignore alone
#endif
// now execute argv
try {
try {
int idx = parse(argc, argv);
if (arg_op == OP_LIST && (arg_username || arg_password))
// this is actually an OP_EMIT and not an OP_LIST
arg_op = OP_EMIT;
if (idx != argc) {
if ((arg_op == OP_LIST || arg_op == OP_EMIT || arg_op == OP_ADD || arg_op == OP_EDIT || arg_op == OP_DELETE) && idx+1 == argc) {
arg_name = argv[idx];
} else {
fprintf(stderr, "%s - Too many arguments\n", program_name);
usage(true);
}
}
if (!arg_dbname) {
// $PWSAFE_DATABASE and $HOME weren't set and -f wasn't used; we have no idea what we should be opening
fprintf(stderr, "$HOME wasn't set; --file must be used\n");
throw FailEx();
}
if (!arg_name && (arg_op == OP_EMIT || arg_op == OP_EDIT || arg_op == OP_DELETE)) {
fprintf(stderr, "An entry must be specified\n");
throw FailEx();
}
if (arg_name && !arg_casesensative) {
// automatically be case sensative of arg_name contains any uppercase chars
const char* p = arg_name;
while (*p)
if (isupper(*p++)) {
arg_casesensative = true;
break;
}
}
#ifndef X_DISPLAY_MISSING
if (arg_xclip && !XDisplayName(arg_display)) {
fprintf(stderr, "$DISPLAY isn't set; use --display\n");
throw FailEx();
}
#endif
// mess around with stdout and outfile so they are intelligently selected
// what we want is usages like "pwsafe | less" to work correctly
if (arg_output) {
outfile = fopen(arg_output,"w");
} else if (!isatty(STDOUT_FILENO) && isatty(STDERR_FILENO)) {
// if stdout is not a tty but stderr is, use stderr to interact with the user, but still write the output to stdout
dup2(STDOUT_FILENO,3);
dup2(STDERR_FILENO,STDOUT_FILENO);
outfile = fdopen(3,"w");
} else {
// use stdout
outfile = fdopen(dup(STDOUT_FILENO),"w");
}
if (!outfile) {
fprintf(stderr, "Can't open %s: %s\n", arg_output, strerror(errno));
throw FailEx();
}
// from this point on stdout points to something we can interact with the user on, and outfile points to where we should put our output
#ifndef X_DISPLAY_MISSING
if (arg_verbose >= 0 && (arg_password || arg_username) && (arg_echo || arg_xclip))
printf("Going to %s %s to %s\n", arg_xclip?"copy":"print", arg_password&&arg_username?"login and password":arg_password?"password":"login", arg_xclip?"X selection":"stdout");
#else
if (arg_verbose >= 0 && (arg_password || arg_username) && (arg_echo))
printf("Going to print %s to stdout\n", arg_password&&arg_username?"login and password":arg_password?"password":"login");
#endif
switch (arg_op) {
case OP_EXPORTDB:
case OP_MERGEDB:
case OP_PASSWD:
case OP_LIST:
case OP_EMIT:
case OP_ADD:
case OP_EDIT:
case OP_DELETE:
{
try {
switch (arg_op) {
case OP_EXPORTDB:
db.exportdb();
break;
case OP_MERGEDB:
{
DB db2(arg_mergedb);
db.mergedb(db2);
}
break;
case OP_PASSWD:
db.passwd();
break;
case OP_LIST:
db.list(arg_name);
break;
case OP_EMIT:
db.emit(arg_name, arg_username, arg_password);
break;
case OP_ADD:
db.add(arg_name);
if (!arg_name) {
// let them add more than one without having to reenter the passphrase
while (getyn("Add another? [n] ", false))
db.add(NULL);
}
break;
case OP_EDIT:
db.edit(arg_name);
break;
case OP_DELETE:
db.del(arg_name);
break;
}
// backup and save if changes have occured
if (db.is_changed()) {
if (arg_verbose > 0) printf("saving changes to %s\n", db.dbname);
if (!(db.backup() && db.save()))
throw FailEx();
}
} catch (const FailEx&) {
// try and restore database from backup if a backup was successfully created
db.restore();
throw;
}
}
break;
}
// first try and close outfile with error checking
if (outfile) {
if (fclose(outfile)) {
fprintf(stderr, "Can't write/close output: %s", strerror(errno));
outfile = NULL;
throw FailEx();
}
outfile = NULL;
}
// and we are done
throw ExitEx(0);
} catch (const FailEx&) {
throw ExitEx(1);
}
} catch (const ExitEx& ex) {
if (outfile)
fclose(outfile);
break;
}
}
}
#endif // INTERACTIVE_MODE
int main(int argc, char **argv) {
program_name = strrchr(argv[0], '/');
if (!program_name)
program_name = argv[0];
else
program_name++;
try {
try {
saved_uid = geteuid();
saved_gid = getegid();
// if we are running suid, drop privileges now; we use seteuid() instead of setuid() so the saved uid remains root and we can become root again in order to mlock()
if (saved_uid != getuid() || saved_gid != getgid()) {
setegid(getgid());
seteuid(getuid());
}
#if WITH_READLINE
rl_readline_name = const_cast<char*>(program_name); // so readline() can parse its config files and handle if (pwsafe) sections; some older readline's type rl_readline_name as char*, hence the const_cast
#endif // WITH_READLINE
// be nice and paranoid
umask(0077);
// init some arguments
{
// use $PWSAFE_DATABASE (which might be a full path or just a filename relative to home), and fall back on ".pwsafe.dat"
const char* datname = getenv("PWSAFE_DATABASE");
if (!datname)
datname = ".pwsafe.dat";
const char* home = getenv("HOME");
if (home && datname[0] != '/') {
char* dbname = reinterpret_cast<char*>(malloc(strlen(home)+1+strlen(datname)+1));
strcpy(dbname, home);
strcat(dbname, "/");
strcat(dbname, datname);
arg_dbname = dbname;
} else {
// datname is already an absolute path
arg_dbname = datname;
}
#ifndef X_DISPLAY_MISSING
if (isatty(STDOUT_FILENO) && (arg_display = XDisplayName(NULL)))
arg_xclip = true;
else
#endif
arg_echo = true;
}
int idx = parse(argc, argv);
#ifndef X_DISPLAY_MISSING
// if no --ignore was specified, use the default
if (arg_ignore.empty()) {
const char* ig = getenv("PWSAFE_IGNORE");
if (!ig) ig = "xclipboard:klipper:wmcliphist";
while (*ig) {
const char*const q = ig;
while (*ig && *ig != ';') ++ig;
arg_ignore.insert(arg_ignore_t::value_type(q,ig-q));
while (*ig == ';') ++ig;
}
}
#endif
if (arg_op == OP_NOP)
// assume --list
arg_op = OP_LIST;
if (arg_op == OP_LIST && (arg_username || arg_password))
// this is actually an OP_EMIT and not an OP_LIST
arg_op = OP_EMIT;
if (idx != argc) {
if ((arg_op == OP_LIST || arg_op == OP_EMIT || arg_op == OP_ADD || arg_op == OP_EDIT || arg_op == OP_DELETE) && idx+1 == argc) {
arg_name = argv[idx];
} else {
fprintf(stderr, "%s - Too many arguments\n", program_name);
usage(true);
}
}
if (!arg_dbname) {
// $PWSAFE_DATABASE and $HOME weren't set and -f wasn't used; we have no idea what we should be opening
fprintf(stderr, "$HOME wasn't set; --file must be used\n");
throw FailEx();
}
if (!arg_name && (arg_op == OP_EMIT || arg_op == OP_EDIT || arg_op == OP_DELETE)) {
fprintf(stderr, "An entry must be specified\n");
throw FailEx();
}
if (arg_name && !arg_casesensative) {
// automatically be case sensative of arg_name contains any uppercase chars
const char* p = arg_name;
while (*p)
if (isupper(*p++)) {
arg_casesensative = true;
break;
}
}
#ifndef X_DISPLAY_MISSING
if (arg_xclip && !XDisplayName(arg_display)) {
fprintf(stderr, "$DISPLAY isn't set; use --display\n");
throw FailEx();
}
#endif
// mess around with stdout and outfile so they are intelligently selected
// what we want is usages like "pwsafe | less" to work correctly