2 * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file crypt_common.c Crypto functions independent of openssl/libgcrypt. */
15 #include "crypt_backend.h"
17 /** If the key begins with this text, we treat it as an ssh key. */
18 #define KEY_TYPE_TXT "ssh-rsa"
21 * Check if given buffer starts with a ssh rsa key signature.
23 * \param data The buffer.
24 * \param size Number of data bytes.
26 * \return Number of header bytes to be skipped on success, zero if
27 * ssh rsa signature was not found.
29 size_t is_ssh_rsa_key(char *data
, size_t size
)
33 if (size
< strlen(KEY_TYPE_TXT
) + 2)
35 cp
= memchr(data
, ' ', size
);
38 if (strncmp(KEY_TYPE_TXT
, data
, strlen(KEY_TYPE_TXT
)))
41 if (cp
>= data
+ size
)
49 * Read a 4-byte number from a buffer in big-endian format.
51 * \param vp The buffer.
53 * The byte-order of the buffer is expected to be big-endian, unlike read_u32()
54 * of portable_io.h which expects little endian.
56 * \return The 32 bit number given by \a vp.
58 uint32_t read_ssh_u32(const void *vp
)
60 const unsigned char *p
= (const unsigned char *)vp
;
63 v
= (uint32_t)p
[0] << 24;
64 v
|= (uint32_t)p
[1] << 16;
65 v
|= (uint32_t)p
[2] << 8;
72 * Sanity checks for the header of an ssh key.
74 * \param blob The buffer.
75 * \param blen The number of bytes of \a blob.
77 * This performs some checks to make sure we really have an ssh key. It also
78 * computes the offset in bytes of the start of the key values (modulus,
81 * \return The number of bytes to skip until the start of the first encoded
82 * number (usually 11).
84 int check_ssh_key_header(const unsigned char *blob
, int blen
)
86 const unsigned char *p
= blob
, *end
= blob
+ blen
;
90 return -E_SSH_KEY_HEADER
;
91 rlen
= read_ssh_u32(p
);
94 return -E_SSH_KEY_HEADER
;
96 return -E_SSH_KEY_HEADER
;
97 if (rlen
< strlen(KEY_TYPE_TXT
))
98 return -E_SSH_KEY_HEADER
;
99 PARA_DEBUG_LOG("type: %s, rlen: %u\n", p
, rlen
);
100 if (strncmp((char *)p
, KEY_TYPE_TXT
, strlen(KEY_TYPE_TXT
)))
101 return -E_SSH_KEY_HEADER
;
106 * Check existence and permissions of a private key file.
108 * \param file The path of the key file.
110 * This checks whether the file exists and its permissions are restrictive
111 * enough. It is considered an error if we own the file and it is readable for
116 int check_private_key_file(const char *file
)
120 if (stat(file
, &st
) != 0)
121 return -ERRNO_TO_PARA_ERROR(errno
);
122 if ((st
.st_uid
== getuid()) && (st
.st_mode
& 077) != 0)
127 void hash_to_asc(unsigned char *hash
, char *asc
)
130 const char hexchar
[] = "0123456789abcdef";
132 for (i
= 0; i
< HASH_SIZE
; i
++) {
133 asc
[2 * i
] = hexchar
[hash
[i
] >> 4];
134 asc
[2 * i
+ 1] = hexchar
[hash
[i
] & 0xf];
136 asc
[2 * HASH_SIZE
] = '\0';
139 int hash_compare(unsigned char *h1
, unsigned char *h2
)
143 for (i
= 0; i
< HASH_SIZE
; i
++) {