summaryrefslogtreecommitdiffstats
path: root/kbx/backend-kbx.c
blob: b48795296263924119ca550f76018bb36926e39b (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
/* backend-kbx.c - Keybox format backend for keyboxd
 * Copyright (C) 2019 g10 Code GmbH
 *
 * This file is part of GnuPG.
 *
 * GnuPG 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 3 of the License, or
 * (at your option) any later version.
 *
 * GnuPG 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, see <https://www.gnu.org/licenses/>.
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#include "keyboxd.h"
#include "../common/i18n.h"
#include "backend.h"
#include "keybox.h"


/* Our definition of the backend handle.  */
struct backend_handle_s
{
  enum database_types db_type; /* Always DB_TYPE_KBX.  */
  unsigned int backend_id;     /* Always the id of the backend.  */

  void *token;  /* Used to create a new KEYBOX_HANDLE.  */
  char filename[1];
};


/* Check that the file FILENAME is a valid keybox file which can be
 * used here.  Common return codes:
 *
 * 0              := Valid keybox file
 * GPG_ERR_ENOENT := No such file
 * GPG_ERR_NO_OBJ := File exists with size zero.
 * GPG_ERR_INV_OBJ:= File exists but is not a keybox file.
 */
static gpg_error_t
check_kbx_file_magic (const char *filename)
{
  gpg_error_t err;
  u32 magic;
  unsigned char verbuf[4];
  estream_t fp;

  fp = es_fopen (filename, "rb");
  if (!fp)
    return gpg_error_from_syserror ();

  err = gpg_error (GPG_ERR_INV_OBJ);
  if (es_fread (&magic, 4, 1, fp) == 1 )
    {
      if (es_fread (&verbuf, 4, 1, fp) == 1
          && verbuf[0] == 1
          && es_fread (&magic, 4, 1, fp) == 1
          && !memcmp (&magic, "KBXf", 4))
        {
          err = 0;
        }
    }
  else /* Maybe empty: Let's create it. */
    err = gpg_error (GPG_ERR_NO_OBJ);

  es_fclose (fp);
  return err;
}


/* Create new keybox file.  This can also be used if the keybox
 * already exists but has a length of zero.  Do not use it in any
 * other cases.  */
static gpg_error_t
create_keybox (const char *filename)
{
  gpg_error_t err;
  dotlock_t lockhd = NULL;
  estream_t fp;

  /* To avoid races with other temporary instances of keyboxd trying
   * to create or update the keybox, we do the next stuff in a locked
   * state. */
  lockhd = dotlock_create (filename, 0);
  if (!lockhd)
    {
      err = gpg_error_from_syserror ();
      /* A reason for this to fail is that the directory is not
       * writable. However, this whole locking stuff does not make
       * sense if this is the case. An empty non-writable directory
       * with no keybox is not really useful at all. */
      if (opt.verbose)
        log_info ("can't allocate lock for '%s': %s\n",
                  filename, gpg_strerror (err));
      return err;
    }

  if ( dotlock_take (lockhd, -1) )
    {
      err = gpg_error_from_syserror ();
      /* This is something bad.  Probably a stale lockfile.  */
      log_info ("can't lock '%s': %s\n", filename, gpg_strerror (err));
      goto leave;
    }

  /* Make sure that at least one record is in a new keybox file, so
   * that the detection magic will work the next time it is used.
   * We always set the OpenPGP blobs maybe available flag.   */
  fp = es_fopen (filename, "w+b,mode=-rw-------");
  if (!fp)
    {
      err = gpg_error_from_syserror ();
      log_error (_("error creating keybox '%s': %s\n"),
                 filename, gpg_strerror (err));
      goto leave;
    }
  err = _keybox_write_header_blob (NULL, fp, 1);
  es_fclose (fp);
  if (err)
    {
      log_error (_("error creating keybox '%s': %s\n"),
                 filename, gpg_strerror (err));
      goto leave;
    }

  if (!opt.quiet)
    log_info (_("keybox '%s' created\n"), filename);
  err = 0;

 leave:
  if (lockhd)
    {
      dotlock_release (lockhd);
      dotlock_destroy (lockhd);
    }
  return err;
}



/* Install a new resource and return a handle for that backend.  */
gpg_error_t
be_kbx_add_resource (ctrl_t ctrl, backend_handle_t *r_hd,
                     const char *filename, int readonly)
{
  gpg_error_t err;
  backend_handle_t hd;
  void *token;

  (void)ctrl;

  *r_hd = NULL;
  hd = xtrycalloc (1, sizeof *hd + strlen (filename));
  if (!hd)
    return gpg_error_from_syserror ();
  hd->db_type = DB_TYPE_KBX;
  strcpy (hd->filename, filename);

  err = check_kbx_file_magic (filename);
  switch (gpg_err_code (err))
    {
    case 0:
      break;
    case GPG_ERR_ENOENT:
    case GPG_ERR_NO_OBJ:
      if (readonly)
        {
          err = gpg_error (GPG_ERR_ENOENT);
          goto leave;
        }
      err = create_keybox (filename);
      if (err)
        goto leave;
      break;
    default:
      goto leave;
    }

  err = keybox_register_file (filename, 0, &token);
  if (err)
    goto leave;

  hd->backend_id = be_new_backend_id ();
  hd->token = token;

  *r_hd = hd;
  hd = NULL;

 leave:
  xfree (hd);
  return err;
}


/* Release the backend handle HD and all its resources.  HD is not
 * valid after a call to this function.  */
void
be_kbx_release_resource (ctrl_t ctrl, backend_handle_t hd)
{
  (void)ctrl;

  if (!hd)
    return;
  hd->db_type = DB_TYPE_NONE;

  xfree (hd);
}


void
be_kbx_release_kbx_hd (KEYBOX_HANDLE kbx_hd)
{
  keybox_release (kbx_hd);
}


/* Helper for be_find_request_part to initialize a kbx request part.  */
gpg_error_t
be_kbx_init_request_part (backend_handle_t backend_hd, db_request_part_t part)
{
  part->kbx_hd = keybox_new_openpgp (backend_hd->token, 0);
  if (!part->kbx_hd)
    return gpg_error_from_syserror ();
  return 0;
}


/* Search for the keys described by (DESC,NDESC) and return them to
 * the caller.  BACKEND_HD is the handle for this backend and REQUEST
 * is the current database request object.  */
gpg_error_t
be_kbx_search (ctrl_t ctrl, backend_handle_t backend_hd, db_request_t request,
               KEYDB_SEARCH_DESC *desc, unsigned int ndesc)
{
  gpg_error_t err;
  db_request_part_t part;
  size_t descindex;
  unsigned long skipped_long_blobs;

  log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX);
  log_assert (request);

  /* Find the specific request part or allocate it.  */
  err = be_find_request_part (backend_hd, request, &part);
  if (err)
    goto leave;

  if (!desc)
    err = keybox_search_reset (part->kbx_hd);
  else
    err = keybox_search (part->kbx_hd, desc, ndesc, KEYBOX_BLOBTYPE_PGP,
                         &descindex, &skipped_long_blobs);
  if (err == -1)
    err = gpg_error (GPG_ERR_EOF);

  if (desc && !err)
    {
      /* Successful search operation.  */
      void *buffer;
      size_t buflen;
      enum pubkey_types pubkey_type;
      unsigned char ubid[UBID_LEN];

      err = keybox_get_data (part->kbx_hd, &buffer, &buflen,
                             &pubkey_type, ubid);
      if (err)
        goto leave;
      /* FIXME: Return the ephemeral flag.  */
      err = be_return_pubkey (ctrl, buffer, buflen, pubkey_type, ubid, 0, 0);
      if (!err)
        be_cache_pubkey (ctrl, ubid, buffer, buflen, pubkey_type);
      xfree (buffer);
    }

 leave:
  return err;
}


/* Seek in the keybox to the given UBID (if UBID is not NULL) or to
 * the primary fingerprint specified by (FPR,FPRLEN).  BACKEND_HD is
 * the handle for this backend and REQUEST is the current database
 * request object.  This does a dummy read so that the next search
 * operation starts right after that UBID. */
gpg_error_t
be_kbx_seek (ctrl_t ctrl, backend_handle_t backend_hd,
             db_request_t request, const unsigned char *ubid)
{
  gpg_error_t err;
  db_request_part_t part;
  size_t descindex;
  unsigned long skipped_long_blobs;
  KEYDB_SEARCH_DESC desc;

  (void)ctrl;

  log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX);
  log_assert (request);

  memset (&desc, 0, sizeof desc);
  desc.mode = KEYDB_SEARCH_MODE_UBID;
  memcpy (desc.u.ubid, ubid, UBID_LEN);

  /* Find the specific request part or allocate it.  */
  err = be_find_request_part (backend_hd, request, &part);
  if (err)
    goto leave;

  err = keybox_search_reset (part->kbx_hd);
  if (!err)
    err = keybox_search (part->kbx_hd, &desc, 1, 0,
                         &descindex, &skipped_long_blobs);
  if (err == -1)
    err = gpg_error (GPG_ERR_EOF);

 leave:
  return err;
}


/* Insert (BLOB,BLOBLEN) into the keybox.  BACKEND_HD is the handle
 * for this backend and REQUEST is the current database request
 * object.  */
gpg_error_t
be_kbx_insert (ctrl_t ctrl, backend_handle_t backend_hd,
               db_request_t request, enum pubkey_types pktype,
               const void *blob, size_t bloblen)
{
  gpg_error_t err;
  db_request_part_t part;
  ksba_cert_t cert = NULL;

  (void)ctrl;

  log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX);
  log_assert (request);

  /* Find the specific request part or allocate it.  */
  err = be_find_request_part (backend_hd, request, &part);
  if (err)
    goto leave;

  if (pktype == PUBKEY_TYPE_OPGP)
    err = keybox_insert_keyblock (part->kbx_hd, blob, bloblen);
  else if (pktype == PUBKEY_TYPE_X509)
    {
      unsigned char sha1[20];

      err = ksba_cert_new (&cert);
      if (err)
        goto leave;
      err = ksba_cert_init_from_mem (cert, blob, bloblen);
      if (err)
        goto leave;
      gcry_md_hash_buffer (GCRY_MD_SHA1, sha1, blob, bloblen);

      err = keybox_insert_cert (part->kbx_hd, cert, sha1);
    }
  else
    err = gpg_error (GPG_ERR_WRONG_BLOB_TYPE);

 leave:
  ksba_cert_release (cert);
  return err;
}


/* Update (BLOB,BLOBLEN) in the keybox.  BACKEND_HD is the handle for
 * this backend and REQUEST is the current database request object.  */
gpg_error_t
be_kbx_update (ctrl_t ctrl, backend_handle_t backend_hd,
               db_request_t request, enum pubkey_types pktype,
               const void *blob, size_t bloblen)
{
  gpg_error_t err;
  db_request_part_t part;
  ksba_cert_t cert = NULL;

  (void)ctrl;

  log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX);
  log_assert (request);

  /* Find the specific request part or allocate it.  */
  err = be_find_request_part (backend_hd, request, &part);
  if (err)
    goto leave;

  /* FIXME: We make use of the fact that we know that the caller
   * already did a keybox search.  This needs to be made more
   * explicit.  */
  if (pktype == PUBKEY_TYPE_OPGP)
    {
      err = keybox_update_keyblock (part->kbx_hd, blob, bloblen);
    }
  else if (pktype == PUBKEY_TYPE_X509)
    {
      unsigned char sha1[20];

      err = ksba_cert_new (&cert);
      if (err)
        goto leave;
      err = ksba_cert_init_from_mem (cert, blob, bloblen);
      if (err)
        goto leave;
      gcry_md_hash_buffer (GCRY_MD_SHA1, sha1, blob, bloblen);

      err = keybox_update_cert (part->kbx_hd, cert, sha1);
    }
  else
    err = gpg_error (GPG_ERR_WRONG_BLOB_TYPE);

 leave:
  ksba_cert_release (cert);
  return err;
}


/* Delete the blob from the keybox.  BACKEND_HD is the handle for
 * this backend and REQUEST is the current database request object.  */
gpg_error_t
be_kbx_delete (ctrl_t ctrl, backend_handle_t backend_hd, db_request_t request)
{
  gpg_error_t err;
  db_request_part_t part;

  (void)ctrl;

  log_assert (backend_hd && backend_hd->db_type == DB_TYPE_KBX);
  log_assert (request);

  /* Find the specific request part or allocate it.  */
  err = be_find_request_part (backend_hd, request, &part);
  if (err)
    goto leave;

  /* FIXME: We make use of the fact that we know that the caller
   * already did a keybox search.  This needs to be made more
   * explicit.  */
  err = keybox_delete (part->kbx_hd);

 leave:
  return err;
}