Added SILC SSH2 library providing support for SSH2 public and
[silc.git] / lib / silcssh / silcssh.c
1 /*
2
3   silcssh.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2007 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 #include "silc.h"
21
22 /************************* Static utility functions *************************/
23
24 /* Key fields destructor */
25
26 static void silc_ssh_field_dest(void *key, void *context, void *user_context)
27 {
28   silc_free(key);
29   silc_free(context);
30 }
31
32 /* Parse header line from key.  Doesn't return the line termination
33    characters. */
34
35 SilcBool silc_ssh_parse_line(SilcBuffer key, SilcBuffer line,
36                              SilcBool cont)
37 {
38   char *tmp;
39   int i, data_len;
40   SilcBool valid = cont;
41
42   data_len = silc_buffer_len(key);
43   tmp = silc_buffer_data(key);
44   for (i = 0; i < data_len; i++) {
45     /* All header lines must have ':' character */
46     if (!cont && tmp[i] == ':')
47       valid = TRUE;
48
49     if ((data_len - i >= 1 && tmp[i] == '\r') ||
50         (data_len - i >= 1 && tmp[i] == '\n')) {
51
52       if (!valid)
53         return FALSE;
54
55       if (line)
56         silc_buffer_set(line, tmp, i);
57
58       if (data_len - i >= 2 && tmp[i] == '\r' && tmp[i + 1] == '\n')
59         silc_buffer_pull(key, i + 2);
60       else
61         silc_buffer_pull(key, i + 1);
62
63       return TRUE;
64     }
65   }
66
67   return FALSE;
68 }
69
70 /* Allocate fields hash table */
71
72 SilcHashTable silc_ssh_allocate_fields(void)
73 {
74   return silc_hash_table_alloc(NULL, 0, silc_hash_string, NULL,
75                                silc_hash_string_compare, NULL,
76                                silc_ssh_field_dest, NULL, TRUE);
77 }
78
79 /* Parse key headers and return them into a hash table */
80
81 SilcHashTable silc_ssh_parse_headers(SilcBuffer key)
82 {
83   SilcHashTable fields;
84   unsigned char *field, *value;
85   SilcBufferStruct line, v;
86   SilcBool quoted = FALSE;
87
88   SILC_LOG_DEBUG(("Parsing SSH key headers"));
89
90   fields = silc_ssh_allocate_fields();
91   if (!fields)
92     return NULL;
93
94   /* Parse the fields */
95   while (silc_buffer_len(key) > 0) {
96     if (!silc_ssh_parse_line(key, &line, FALSE))
97       break;
98
99     /* Get field */
100
101     field = strchr(silc_buffer_data(&line), ':');
102     if (!field)
103       goto err;
104     if (field - silc_buffer_data(&line) > 64)
105       goto err;
106     field = silc_memdup(silc_buffer_data(&line),
107                         field - silc_buffer_data(&line));
108     if (!field)
109       goto err;
110
111     /* Skip ':' and following whitespace */
112     if (!silc_buffer_pull(&line, strlen(field) + 2))
113       goto err;
114
115     /* Get value */
116
117     memset(&v, 0, sizeof(v));
118     silc_buffer_format(&v,
119                        SILC_STR_DATA(silc_buffer_data(&line),
120                                      silc_buffer_len(&line)),
121                        SILC_STR_END);
122
123     /* Handle quoted Comment lines by removing the quotation */
124     if (*silc_buffer_data(&v) == '"' && !strcmp(field, "Comment"))
125       quoted = TRUE;
126
127     /* Handle wrapping value lines */
128     while (silc_buffer_len(&v) > 0) {
129       if (*silc_buffer_data(&v) == '\\') {
130         if (!silc_ssh_parse_line(key, &line, TRUE))
131           goto err;
132         silc_buffer_format(&v,
133                            SILC_STR_DATA(silc_buffer_data(&line),
134                                          silc_buffer_len(&line)),
135                            SILC_STR_END);
136         continue;
137       }
138       silc_buffer_pull(&v, 1);
139     }
140     silc_buffer_start(&v);
141
142     if (silc_buffer_len(&v) > 1024)
143       goto err;
144
145     if (quoted) {
146       /* If the last character is quotation also, remove the quotation */
147       if (*(silc_buffer_data(&v) + silc_buffer_len(&v) - 1) == '"') {
148         silc_buffer_pull(&v, 1);
149         silc_buffer_push_tail(&v, 1);
150       }
151     }
152
153     value = silc_memdup(silc_buffer_data(&v), silc_buffer_len(&v));
154     if (!value)
155       goto err;
156     silc_buffer_purge(&v);
157
158     /* Add to hash table */
159     SILC_LOG_DEBUG(("Header '%s' '%s'", field, value));
160     silc_hash_table_add(fields, field, value);
161   }
162
163   return fields;
164
165  err:
166   SILC_LOG_ERROR(("Malformed SSH2 key headers"));
167   silc_hash_table_free(fields);
168   return NULL;
169 }
170
171 /******************************* SILC SSH API *******************************/
172
173 /* Generate key pair */
174
175 SilcBool silc_ssh_generate_key(const char *algorithm,
176                                int bits_len, SilcRng rng,
177                                SilcPublicKey *ret_public_key,
178                                SilcPrivateKey *ret_private_key)
179 {
180   SilcSshPublicKey pubkey;
181   SilcSshPrivateKey privkey;
182   const SilcPKCSAlgorithm *alg;
183   const SilcPKCSObject *pkcs;
184
185   SILC_LOG_DEBUG(("Generating SSH2 %s key pair with key length %d bits",
186                   algorithm, bits_len));
187
188   if (!rng)
189     return FALSE;
190
191   pkcs = silc_pkcs_find_pkcs(SILC_PKCS_SSH2);
192   if (!pkcs)
193     return FALSE;
194
195   /* Allocate SSH public key */
196   pubkey = silc_calloc(1, sizeof(*pubkey));
197   if (!pubkey)
198     return FALSE;
199
200   /* Allocate algorithm */
201   alg = silc_pkcs_find_algorithm(algorithm, "ssh");
202   if (!alg) {
203     SILC_LOG_ERROR(("Public key algorithm %s/ssh not supported", algorithm));
204     silc_free(pubkey);
205     return FALSE;
206   }
207   pubkey->pkcs = alg;
208   pubkey->type = SILC_SSH_KEY_OPENSSH;
209
210   /* Allocate SSH private key */
211   privkey = silc_calloc(1, sizeof(*privkey));
212   if (!privkey) {
213     silc_free(pubkey);
214     return FALSE;
215   }
216   privkey->pkcs = alg;
217   privkey->type = SILC_SSH_KEY_OPENSSH;
218
219   /* Allocate public key */
220   *ret_public_key = silc_calloc(1, sizeof(**ret_public_key));
221   if (!(*ret_public_key)) {
222     silc_free(pubkey);
223     silc_free(privkey);
224     return FALSE;
225   }
226   (*ret_public_key)->pkcs = (SilcPKCSObject *)pkcs;
227   (*ret_public_key)->alg = alg;
228   (*ret_public_key)->public_key = pubkey;
229
230   /* Allocate private key */
231   *ret_private_key = silc_calloc(1, sizeof(**ret_private_key));
232   if (!(*ret_private_key)) {
233     silc_free(pubkey);
234     silc_free(privkey);
235     silc_free(*ret_public_key);
236     return FALSE;
237   }
238   (*ret_private_key)->pkcs = (SilcPKCSObject *)pkcs;
239   (*ret_private_key)->alg = alg;
240   (*ret_private_key)->private_key = privkey;
241
242   /* Generate the algorithm key pair */
243   if (!alg->generate_key(alg, bits_len, rng, &pubkey->public_key,
244                          &privkey->private_key)) {
245     silc_free(pubkey);
246     silc_free(privkey);
247     silc_free(*ret_public_key);
248     silc_free(*ret_private_key);
249     return FALSE;
250   }
251
252   return TRUE;
253 }
254
255 /* Decode SSH public key. */
256
257 int silc_ssh_public_key_decode(unsigned char *key, SilcUInt32 key_len,
258                                SilcSshPublicKey *ret_public_key)
259 {
260   SilcSshPublicKey public_key;
261   const SilcPKCSAlgorithm *alg;
262   SilcBufferStruct keybuf;
263   char *type = NULL;
264
265   SILC_LOG_DEBUG(("Parse SSH2 public key"));
266
267   if (!ret_public_key)
268     return 0;
269
270   public_key = silc_calloc(1, sizeof(*public_key));
271   if (!public_key)
272     return 0;
273
274   silc_buffer_set(&keybuf, key, key_len);
275
276   SILC_LOG_HEXDUMP(("SSH public key, len %d", key_len), key, key_len);
277
278   /* Parse public key type */
279   if (silc_buffer_unformat(&keybuf,
280                            SILC_STR_ADVANCE,
281                            SILC_STR_UI32_STRING_ALLOC(&type),
282                            SILC_STR_END) < 0) {
283     SILC_LOG_ERROR(("Malformed SSH2 public key"));
284     goto err;
285   }
286
287   SILC_LOG_DEBUG(("SSH2 public key type %s", type));
288
289   if (!strcmp(type, "ssh-rsa")) {
290     /* RSA public key */
291     alg = silc_pkcs_find_algorithm("rsa", "ssh");
292     if (!alg) {
293       SILC_LOG_ERROR(("Unsupported SSH2 public key type '%s'", type));
294       goto err;
295     }
296     public_key->pkcs = alg;
297
298   } else if (!strcmp(type, "ssh-dss")) {
299     /* DSS public key */
300     alg = silc_pkcs_find_algorithm("dsa", "ssh");
301     if (!alg) {
302       SILC_LOG_ERROR(("Unsupported SSH2 public key type '%s'", type));
303       goto err;
304     }
305     public_key->pkcs = alg;
306
307   } else {
308     SILC_LOG_ERROR(("Unsupported SSH2 public key type '%s'", type));
309     goto err;
310   }
311
312   /* Parse the algorithm specific public key */
313   if (!alg->import_public_key(alg, silc_buffer_data(&keybuf),
314                               silc_buffer_len(&keybuf),
315                               &public_key->public_key))
316     goto err;
317
318   silc_free(type);
319
320   *ret_public_key = public_key;
321
322   return key_len;
323
324  err:
325   silc_free(type);
326   silc_free(public_key);
327   return 0;
328 }
329
330 /* Encode SSH public key */
331
332 unsigned char *silc_ssh_public_key_encode(SilcStack stack,
333                                           SilcSshPublicKey public_key,
334                                           SilcUInt32 *ret_key_len)
335 {
336   const SilcPKCSAlgorithm *alg = public_key->pkcs;
337   SilcBufferStruct buf;
338   unsigned char *pk = NULL, tmp[16];
339   SilcUInt32 pk_len;
340
341   SILC_LOG_DEBUG(("Encode SSH2 public key"));
342
343   /* Get algorithm name */
344   if (!strcmp(alg->name, "rsa"))
345     silc_snprintf(tmp, sizeof(tmp), "ssh-rsa");
346   else if (!strcmp(alg->name, "dsa"))
347     silc_snprintf(tmp, sizeof(tmp), "ssh-dss");
348   else
349     return NULL;
350
351   /* Export PKCS algorithm public key */
352   if (alg->export_public_key)
353     pk = alg->export_public_key(alg, stack, public_key->public_key, &pk_len);
354   if (!pk) {
355     SILC_LOG_ERROR(("Error exporting PKCS algorithm key"));
356     return NULL;
357   }
358
359   /* Encode public key */
360   memset(&buf, 0, sizeof(buf));
361   if (silc_buffer_sformat(stack, &buf,
362                           SILC_STR_UI_INT(strlen(tmp)),
363                           SILC_STR_UI32_STRING(tmp),
364                           SILC_STR_UI_XNSTRING(pk, pk_len),
365                           SILC_STR_END) < 0) {
366     silc_sfree(stack, pk);
367     return NULL;
368   }
369
370   silc_sfree(stack, pk);
371   pk = silc_buffer_steal(&buf, ret_key_len);
372
373   return pk;
374 }
375
376 /* Free public key */
377
378 void silc_ssh_public_key_free(SilcSshPublicKey public_key)
379 {
380   if (public_key->fields)
381     silc_hash_table_free(public_key->fields);
382   silc_free(public_key);
383 }
384
385 /* Return public key header field value */
386
387 const char *silc_ssh_public_key_get_field(SilcSshPublicKey public_key,
388                                           const char *field)
389 {
390   char *value;
391
392   if (!field || !public_key->fields)
393     return NULL;
394
395   if (!silc_hash_table_find(public_key->fields, (void *)field,
396                             NULL, (void *)&value))
397     return NULL;
398
399   return (const char *)value;
400 }
401
402 /* Add public key header value */
403
404 SilcBool silc_ssh_public_key_add_field(SilcSshPublicKey public_key,
405                                        const char *field,
406                                        const char *value)
407 {
408   if (!field || !value)
409     return FALSE;
410
411   if (!public_key->fields) {
412     public_key->fields =
413       silc_hash_table_alloc(NULL, 0, silc_hash_string, NULL,
414                             silc_hash_string_compare, NULL,
415                             silc_ssh_field_dest, NULL, TRUE);
416     if (!public_key->fields)
417       return FALSE;
418   }
419
420   return silc_hash_table_add(public_key->fields, strdup(field), strdup(value));
421 }
422
423 /* Set public key type */
424
425 void silc_ssh_public_key_set_type(SilcSshPublicKey public_key,
426                                   SilcSshKeyType type)
427 {
428   public_key->type = type;
429 }