summaryrefslogtreecommitdiff
path: root/libextra/opencdk/main.c
blob: 8eafe3cfc0c2e5095aaf9428bba3e42161a30001 (plain)
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
/* -*- Mode: C; c-file-style: "bsd" -*-
 * main.c
 *       Copyright (C) 2001, 2002, 2003 Timo Schulz 
 *
 * This file is part of OpenCDK.
 *
 * OpenCDK 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 of the License, or 
 * (at your option) any later version. 
 *  
 * OpenCDK 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 OpenCDK; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <errno.h>
#ifdef HAVE_PWD_H
# include <pwd.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

#include "opencdk.h"
#include "main.h"
#include "packet.h"
#include "cipher.h"


#define DEFAULT_CIPHER_ALGO CDK_CIPHER_CAST5
#define DEFAULT_DIGEST_ALGO CDK_MD_SHA1

#define SECMEM_SIZE 32768

static void *(*alloc_func) (size_t n) = gcry_xmalloc;
static void *(*alloc_secure_func) (size_t n) = gcry_malloc_secure;
static void *(*realloc_func) (void *p, size_t n) = gcry_realloc;
static void *(*calloc_func) (size_t m, size_t n) = gcry_calloc;
static void (*free_func) (void *) = gcry_free;
static int malloc_hooks = 0;
static int secmem_init = 0;

static cdk_log_fnc_t log_handler = NULL;
static void *log_handler_value = NULL;
static int log_level = CDK_LOG_NONE;


/**
 * cdk_strerror:
 * @ec: the error number
 *
 * Return an error text for the given id.
 **/
const char *
cdk_strerror (int ec)
{
    static char buf[20];

    switch (ec) {
    case CDK_EOF:              return "End Of File";
    case CDK_Success:          return "No error";
    case CDK_General_Error:    return "General error";
    case CDK_File_Error:       return strerror (errno);
    case CDK_Bad_Sig:          return "Bad signature";
    case CDK_Inv_Packet:       return "Invalid packet";
    case CDK_Inv_Algo:         return "Invalid algorithm";
    case CDK_Not_Implemented:  return "This is not implemented yet";
	/* FIXME: print the actual gcrypt error */
    case CDK_Gcry_Error:       return "Gcrypt error";
    case CDK_Armor_Error:      return "ASCII armor error";
    case CDK_Armor_CRC_Error:  return "ASCII armored damaged (CRC error)";
    case CDK_MPI_Error:        return "Invalid or missformed MPI";
    case CDK_Inv_Value:        return "Invalid parameter or value";
    case CDK_Error_No_Key:     return "No key available or not found";
    case CDK_Chksum_Error:     return "Check for key does not match";
    case CDK_Time_Conflict:    return "Time conflict";
    case CDK_Zlib_Error:       return "ZLIB error";
    case CDK_Weak_Key:         return "Weak key was detected";
    case CDK_Out_Of_Core:      return "Out of core!!";
    case CDK_Wrong_Seckey:     return "Wrong secret key";
    case CDK_Bad_MDC:          return "Manipulated MDC detected";
    case CDK_Inv_Mode:         return "Invalid mode";
    case CDK_Error_No_Keyring: return "No keyring available";
    case CDK_Inv_Packet_Ver:   return "Invalid version for packet";
    case CDK_Too_Short:        return "Buffer or object is too short";
    case CDK_Unusable_Key:     return "Unusable public key";
    default:                   sprintf (buf, "ec=%d", ec); return buf;
    }
    return NULL;
}


static void
out_of_core (size_t n)
{
    fprintf (stderr, "\n ** fatal error: out of memory (%d bytes) **\n", n);
}


/**
 * cdk_set_malloc_hooks: 
 * @new_alloc_func: malloc replacement
 * @new_alloc_secure_func: secure malloc replacement
 * @new_realloc_func: realloc replacement
 * @new_calloc_func: calloc replacement
 * @new_free_func: free replacement
 *
 * Set private memory hooks for the lib.
 */
void
cdk_set_malloc_hooks (void *(*new_alloc_func) (size_t n),
		      void *(*new_alloc_secure_func) (size_t n),
		      void *(*new_realloc_func) (void *p, size_t n),
		      void *(*new_calloc_func) (size_t m, size_t n),
		      void (*new_free_func) (void *))
{
    alloc_func = new_alloc_func;
    alloc_secure_func = new_alloc_secure_func;
    realloc_func = new_realloc_func;
    calloc_func = new_calloc_func;
    free_func = new_free_func;
    malloc_hooks = 1;
}


/**
 * cdk_malloc_hook_initialized:
 *
 * Return if the malloc hooks are already initialized.
 **/
int
cdk_malloc_hook_initialized (void)
{
    return malloc_hooks;
}


void *
cdk_malloc (size_t size)
{
    void * p = alloc_func (size);
    if (!p)
        out_of_core (size);
    return p;
}


void *
cdk_calloc (size_t n, size_t m)
{
    void * p = calloc_func (n, m);
    if (!p)
        out_of_core (m);
    return p;
}


static void
_secmem_init (size_t size)
{
    if (!size) {
        gcry_control (GCRYCTL_DROP_PRIVS);
        return;
    }
    if (secmem_init == 1)
        return;
    if (size >= SECMEM_SIZE)
        size = SECMEM_SIZE;
    gcry_control (GCRYCTL_INIT_SECMEM, size, 0);
    gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
    gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
    secmem_init = 1;
}


static void
_secmem_end (void)
{
    gcry_control (GCRYCTL_TERM_SECMEM);
    secmem_init = 0;
}


void *
cdk_salloc (size_t size, int clear)
{
/*  static size_t n = 0; */
    void * p;
  
    if (!secmem_init) {
        _secmem_init (SECMEM_SIZE);
        secmem_init = 1;
    }
    if (secmem_init == 1) {
        _secmem_init (0);
        secmem_init = 2;
    }
    /*
    n += size;
    _cdk_log_debug ("\ncdk_salloc (%d)\n", n);
    */
    p = alloc_secure_func (size);
    if (!p)
        out_of_core (size);
    if (clear)
        memset (p, 0, size);
    return p;
}


void *
cdk_realloc (void *ptr, size_t size)
{
    void * p = realloc_func (ptr, size);
    if (!p)
        out_of_core (size);
    return p;
}


char *
cdk_strdup (const char * ptr)
{
    char * p = cdk_malloc (strlen (ptr) + 1);
    if (p)
        strcpy (p, ptr);
    return p;
}


void
cdk_free (void * ptr)
{
    if (ptr)
        free_func (ptr);
}


void
_cdk_sec_free( void * ptr, size_t size )
{
    if( ptr ) {
        memset( ptr, 0xff, size );
        memset( ptr, 0xaa, size );
        memset( ptr, 0x55, size );
        memset( ptr, 0x00, size );
        free_func( ptr );
    }
}


static void
_cdk_logv (int level, const char *fmt, va_list arg_ptr)
{

    if (log_handler)
        log_handler (log_handler_value, level, fmt, arg_ptr);
    else {
        switch (level) {
        case CDK_LOG_INFO : break;
        case CDK_LOG_DEBUG: fputs ("DBG: ", stderr); break;
        case CDK_LOG_NONE : return; 
        }
        vfprintf (stderr, fmt, arg_ptr); 
    }
}


/**
 * cdk_set_log_handler: 
 * @logfnc: the function pointer
 * @opaque: a private values for the function
 *
 * set a private handler for logging.
 */
void
cdk_set_log_handler( cdk_log_fnc_t logfnc, void * opaque )
{
    log_handler = logfnc;
    log_handler_value = opaque; 
}


/**
 * cdk_set_log_level: 
 * @lvl: the level
 *
 * set the verbosity level.
 **/
void
cdk_set_log_level (int lvl)
{
  log_level = lvl;
}


int
_cdk_get_log_level (void)
{
    return log_level;
}


void
_cdk_log_info (const char *fmt, ...)
{
    va_list arg;

    if (log_level == CDK_LOG_NONE)
        return;
    va_start (arg, fmt);
    _cdk_logv (CDK_LOG_INFO, fmt, arg);
    va_end (arg);
}


void
_cdk_log_debug (const char *fmt, ...)
{
    va_list arg;
  
    if (log_level < CDK_LOG_DEBUG)
        return;
    va_start (arg, fmt);
    _cdk_logv (CDK_LOG_DEBUG, fmt, arg);
    va_end (arg);
}

#include <getpass.h>

char *
_cdk_passphrase_get( cdk_ctx_t hd, const char * prompt )
{
    char * p, * pass = NULL;
    
    if( hd->passphrase )
        return hd->passphrase( hd->passphrase_value, prompt );
    p = getpass( prompt );
    if( p )
        pass = cdk_strdup( p );
    return pass;
}


void
_cdk_passphrase_free( char *pw, size_t size )
{
    _cdk_sec_free( pw, size );
}


int
_cdk_is_idea_available (void)
{
    int rc = 0;
#ifdef LIBGCRYPT_WITH_IDEA
    rc = 1;
#endif
    return rc;
}


static void
handle_set_cipher (cdk_ctx_t hd, int cipher)
{
    if( !hd )
        return;
    if( cdk_cipher_test_algo( cipher ) )
        cipher = DEFAULT_CIPHER_ALGO;
    hd->cipher_algo = cipher;   
}


static void
handle_set_digest (cdk_ctx_t hd, int digest)
{
    if( !hd )
        return;
    if( cdk_md_test_algo( digest ) )
        digest = DEFAULT_DIGEST_ALGO;
    hd->digest_algo = digest;   
}


static void
handle_set_s2k( cdk_ctx_t hd, int mode, int digest, int cipher )
{
    if( !hd )
        return;
    if( cdk_cipher_test_algo( cipher ) )
        cipher = DEFAULT_CIPHER_ALGO;
    if( cdk_md_test_algo( digest ) )
        digest = DEFAULT_DIGEST_ALGO;
    if( mode != CDK_S2K_SIMPLE
        && mode != CDK_S2K_SALTED
        && mode != CDK_S2K_ITERSALTED )
        mode = CDK_S2K_ITERSALTED;
    hd->_s2k.mode = mode;
    hd->_s2k.digest_algo = digest;
    hd->_s2k.cipher_algo = cipher;
}


static void
handle_set_compat( cdk_ctx_t hd, int val )
{
    if( !hd )
        return;
    hd->opt.compat = val;
    if( !val )
        return;
    hd->opt.mdc = 0;
    hd->opt.rfc1991 = val == -1? 1: 0;
    hd->compress.algo = CDK_COMPRESS_ZIP;
    hd->compress.level = -1;
    hd->cipher_algo = val == -1? CDK_CIPHER_IDEA : DEFAULT_CIPHER_ALGO;
    hd->digest_algo = val == -1? CDK_MD_MD5: DEFAULT_DIGEST_ALGO;
    if( val == -1 )
        handle_set_s2k( hd, 0, hd->digest_algo, hd->cipher_algo );   
}


static void
handle_set_compress( cdk_ctx_t hd, int algo, int level )
{
    if( !hd )
        return;
    if( algo < 0 || algo > 2 )
        algo = 0;
    hd->compress.algo = algo;
    if( !algo )
        hd->opt.compress = 0;
    else {
        if( level > 0 && level < 10 )
            hd->compress.level = level;
        else
            hd->compress.level = 6;
    }
}


/**
 * cdk_handle_control:
 * @hd: session handle
 * @action: flag which indicates whether put or get is requested
 * @cmd: command id
 *
 * Perform various control operations for the current session.
 **/
int
cdk_handle_control( cdk_ctx_t hd, int action, int cmd, ... )
{
    va_list arg_ptr;
    int set = action == CDK_CTLF_SET, val = 0;

    if( !hd )
        return -1;
    if( action != CDK_CTLF_SET && action != CDK_CTLF_GET )
        return -1;
    va_start( arg_ptr, cmd );
    switch( cmd ) {
    case CDK_CTL_ARMOR:
        if( set )
            hd->opt.armor = va_arg( arg_ptr, int );
        else
            val = hd->opt.armor;
        break;

    case CDK_CTL_CIPHER:
        if( set )
            handle_set_cipher( hd, va_arg( arg_ptr, int ) );
        else
            val = hd->cipher_algo;
        break;

    case CDK_CTL_DIGEST:
        if( set )
            handle_set_digest( hd, va_arg( arg_ptr, int ) );
        else
            val = hd->digest_algo;
        break;

    case CDK_CTL_COMPAT:
        if( set )
            handle_set_compat( hd, va_arg( arg_ptr, int ) );
        else
            val = hd->opt.compat;
        break;

    case CDK_CTL_OVERWRITE:
        if( set )
            hd->opt.overwrite = va_arg( arg_ptr, int );
        else
            val = hd->opt.overwrite;
        break;

    case CDK_CTL_COMPRESS:
        if( set ) {
            int algo = va_arg( arg_ptr, int );
            int level = va_arg( arg_ptr, int );
            handle_set_compress( hd, algo, level );
        }
        else
            val = hd->compress.algo;
        break;

    case CDK_CTL_S2K:
        if( set ) {
            int mode = va_arg( arg_ptr, int );
            int digest = va_arg( arg_ptr, int );
            int cipher = va_arg( arg_ptr, int );
            handle_set_s2k( hd, mode, digest, cipher );
        }
        else
            val = hd->_s2k.mode;
        break;

    case CDK_CTL_KEYCACHE_ON:
        if( set )
            hd->cache.on = va_arg( arg_ptr, int );
        else
            val = hd->cache.on;
        break;

    case CDK_CTL_KEYCACHE_FREE:
        _cdk_free_seckey( hd->cache.sk );
        hd->cache.sk = NULL;
        break;

    case CDK_CTL_FORCE_DIGEST:
        if( set )
            hd->opt.force_digest = va_arg( arg_ptr, int );
        else
            val = hd->opt.force_digest;
        break;

    case CDK_CTL_TRUSTMODEL:
        if( set )
            hd->trust_model = va_arg( arg_ptr, int );
        else
            val = hd->trust_model;
        break;

    default:
        val = -1;
        break;
    }
    va_end( arg_ptr );
    return val;
}

            

/**
 * cdk_handle_new:
 * @r_ctx: context to store the handle
 *
 * create a new session handle.
 **/
int
cdk_handle_new( cdk_ctx_t * r_ctx )
{
    cdk_ctx_t c;
  
    if( !r_ctx )
        return CDK_Inv_Value;
    
    c = cdk_calloc( 1, sizeof *c );
    if( !c )
        return CDK_Out_Of_Core;
    /* default */
    c->_s2k.mode = 3;
    c->_s2k.digest_algo = DEFAULT_DIGEST_ALGO;
    c->_s2k.cipher_algo = DEFAULT_CIPHER_ALGO;

    c->opt.mdc = 1;
    c->opt.compress = 1;
    c->opt.armor = 0;
    c->opt.textmode = 0;

    c->digest_algo = DEFAULT_DIGEST_ALGO;
    c->cipher_algo = DEFAULT_CIPHER_ALGO;
    c->compress.algo = CDK_COMPRESS_ZIP;
    c->compress.level = 6;

    *r_ctx = c;
    return 0;
}


/**
 * cdk_handle_set_keydb:
 * @hd: session handle
 * @db: the database handle
 *
 * set the key database handle.
 * the function automatically detects whether this is a public or
 * secret keyring and the right handle is set.
 **/
void
cdk_handle_set_keydb( cdk_ctx_t hd, cdk_keydb_hd_t db )
{
    if( !hd )
        return;
    if( db->secret )
        hd->db.sec = db;
    else
        hd->db.pub = db;
}


/**
 * cdk_handle_get_keydb:
 * @hd: session handle
 * @type: type of the keyring
 *
 * Return the keydb handle from the session handle.
 **/
cdk_keydb_hd_t
cdk_handle_get_keydb( cdk_ctx_t hd, int type )
{
    if( !hd )
        return NULL;
    if( type == CDK_DBTYPE_PK_KEYRING )
        return hd->db.pub;
    else if( type == CDK_DBTYPE_SK_KEYRING )
        return hd->db.sec;
    return NULL;
}


/**
 * cdk_handle_set_callback: 
 * @hd: the handle
 * @cb: the callback function
 * @cb_value: the opaque value for the function
 *
 * set the callback for filter operations.
 **/
void
cdk_handle_set_callback (cdk_ctx_t hd,
                         void (*cb) (void * opaque, int type, const char * s),
                         void * cb_value)
{
    if( !hd )
        return;
    hd->callback = cb;
    hd->callback_value = cb_value;
}


/**
 * cdk_handle_set_passphrase_cb:
 * @hd: session handle
 * @cb: callback function
 * @cb_value: the opaque value for the cb function
 *
 * set the passphrase callback.
 **/
void cdk_handle_set_passphrase_cb( cdk_ctx_t hd,
                                   char *(*cb) (void *opa, const char *prompt),
                                   void * cb_value )
{
    if( !hd )
        return;
    hd->passphrase = cb;
    hd->passphrase_value = cb_value;
}


/**
 * cdk_handle_free:
 * @hd: the handle
 *
 * free the main handle.
 **/
void
cdk_handle_free( cdk_ctx_t hd )
{
    if( !hd )
        return;
    _cdk_result_verify_free( hd->result.verify );
    _cdk_free_seckey( hd->cache.sk );
    cdk_free( hd->s2k );
    cdk_free( hd->dek );
    cdk_free( hd );
}