sshkey: Added builder for SSHKEY RSA keys
[strongswan.git] / src / libstrongswan / plugins / sshkey / sshkey_builder.c
1 /*
2 * Copyright (C) 2013 Tobias Brunner
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "sshkey_builder.h"
17
18 #include <bio/bio_reader.h>
19 #include <utils/debug.h>
20
21 /**
22 * Load a generic public key from an SSH key blob
23 */
24 static sshkey_public_key_t *parse_public_key(chunk_t blob)
25 {
26 bio_reader_t *reader;
27 chunk_t format;
28
29 reader = bio_reader_create(blob);
30 if (!reader->read_data32(reader, &format))
31 {
32 DBG1(DBG_LIB, "invalid key format in SSH key");
33 reader->destroy(reader);
34 return NULL;
35 }
36 if (chunk_equals(format, chunk_from_str("ssh-rsa")))
37 {
38 chunk_t n, e;
39
40 if (!reader->read_data32(reader, &e) ||
41 !reader->read_data32(reader, &n))
42 {
43 DBG1(DBG_LIB, "invalid RSA key in SSH key");
44 reader->destroy(reader);
45 return NULL;
46 }
47 reader->destroy(reader);
48 return lib->creds->create(lib->creds, CRED_PUBLIC_KEY, KEY_RSA,
49 BUILD_RSA_MODULUS, n, BUILD_RSA_PUB_EXP, e, BUILD_END);
50 }
51 DBG1(DBG_LIB, "unsupported SSH key format %.*s", (int)format.len,
52 format.ptr);
53 reader->destroy(reader);
54 return NULL;
55 }
56
57 /**
58 * See header.
59 */
60 sshkey_public_key_t *sshkey_public_key_load(key_type_t type, va_list args)
61 {
62 chunk_t blob = chunk_empty;
63
64 while (TRUE)
65 {
66 switch (va_arg(args, builder_part_t))
67 {
68 case BUILD_BLOB_SSHKEY:
69 blob = va_arg(args, chunk_t);
70 continue;
71 case BUILD_END:
72 break;
73 default:
74 return NULL;
75 }
76 break;
77 }
78 if (blob.ptr && type == KEY_ANY)
79 {
80 return parse_public_key(blob);
81 }
82 return NULL;
83 }