summaryrefslogtreecommitdiff
path: root/fish.c
blob: a7c3cfca34def39f74e46a38fab1938cb88847ea (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
/*

  Copyright (c) 2010-2015 Samuel Lidén Borell <samuel@kodafritt.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#include <stdlib.h>
#include <string.h>
#include <openssl/blowfish.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/rand.h>

#include "keystore.h"
#include "fish.h"

#define IB 64
static const char fish_base64[64] = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const signed char fish_unbase64[256] = {
    IB,IB,IB,IB,IB,IB,IB,IB,  IB,IB,IB,IB,IB,IB,IB,IB,
    IB,IB,IB,IB,IB,IB,IB,IB,  IB,IB,IB,IB,IB,IB,IB,IB,
//      !  "  #  $  %  &  '  (    )  *  +  ,  -  .  /
    IB,IB,IB,IB,IB,IB,IB,IB,  IB,IB,IB,IB,IB,IB, 0, 1,
//   0  1  2  3  4  5  6  7    8  9  :  ;  <  =  >  ?
     2, 3, 4, 5, 6, 7, 8, 9,  10,11,IB,IB,IB,IB,IB,IB,
//   @  A  B  C  D  E  F  G    H  I  J  K  L  M  N  O
    IB,38,39,40,41,42,43,44,  45,46,47,48,49,50,51,52,
//   P  Q  R  S  T  U  V  W    X  Y  Z  [  \  ]  ^  _
    53,54,55,56,57,58,59,60,  61,62,63,IB,IB,IB,IB,IB,
//   `  a  b  c  d  e  f  g    h  i  j  k  l  m  n  o
    IB,12,13,14,15,16,17,18,  19,20,21,22,23,24,25,26,
//   p  q  r  s  t  u  v  w    x  y  z  {  |  }  ~  <del>
    27,28,29,30,31,32,33,34,  35,36,37,IB,IB,IB,IB,IB,
};

#define GET_BYTES(dest, source) do { \
    *((dest)++) = ((source) >> 24) & 0xFF; \
    *((dest)++) = ((source) >> 16) & 0xFF; \
    *((dest)++) = ((source) >> 8) & 0xFF; \
    *((dest)++) = (source) & 0xFF; \
} while (0);

/**
 * Encrypts a message in ECB mode.
 */
char *fish_encrypt_ecb(const char *key, size_t keylen, const char *message) {
    BF_KEY bfkey;
    size_t messagelen;
    size_t i;
    int j;
    char *encrypted;
    char *end;
    unsigned char bit;
    unsigned char word;
    unsigned char d;
    BF_set_key(&bfkey, keylen, (const unsigned char*)key);
    
    messagelen = strlen(message);
    if (messagelen == 0) return NULL;
    encrypted = malloc(((messagelen-1)/8)*12 + 12 + 1); // each 8-byte block becomes 12 bytes
    end = encrypted;
    if (!encrypted) return NULL;
     
    while (*message) {
        // Read 8 bytes (a Blowfish block)
        BF_LONG binary[2] = { 0, 0 };
        unsigned char c;
        for (i = 0; i < 8; i++) {
            c = message[i];
            binary[i >> 2] |= c << 8*(3 - (i&3));
            if (c == '\0') break;
        }
        message += 8;
        
        // Encrypt block
        BF_encrypt(binary, &bfkey);
        
        // Emit FiSH-BASE64
        bit = 0;
        word = 1;
        for (j = 0; j < 12; j++) {
            d = fish_base64[(binary[word] >> bit) & 63];
            *(end++) = d;
            bit += 6;
            if (j == 5) {
                bit = 0;
                word = 0;
            }
        }
        
        // Stop if a null terminator was found
        if (c == '\0') break;
    }
    *end = '\0';
    return encrypted;
}

/**
 * Encrypts a message in CBC mode.
 */
char *fish_encrypt_cbc(const char *key, size_t keylen, const char *message) {
    BF_KEY bfkey;
    unsigned char *encrypted = NULL;
    BIO *b64 = NULL;
    BF_set_key(&bfkey, keylen, (const unsigned char*)key);
    
    size_t messagelen = strlen(message);
    if (messagelen == 0) goto err;
    
    // Allocate structure for final encrypted data.
    int cryptlen = 8 + ((messagelen+7)&~7);
    encrypted = malloc(cryptlen);
    if (!encrypted) goto err;
    
    // Generate IV
    unsigned char iv[8];
    RAND_pseudo_bytes(iv, 8);
    memcpy(encrypted, iv, 8);
    
    // Encrypt in CBC mode. The IV is overwritten
    BF_cbc_encrypt((const unsigned char*)message, encrypted+8, messagelen, &bfkey, iv, BF_ENCRYPT);
    
    // Base64 encode
    b64 = BIO_new(BIO_f_base64());
    if (!b64) goto err;
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    BIO *bmem = BIO_new(BIO_s_mem());
    if (!bmem) goto err;
    BIO *bio = BIO_push(b64, bmem);
    if (cryptlen != 0) {
        BIO_write(bio, encrypted, cryptlen);
    }
    free(encrypted);
    encrypted = NULL;
    BIO_flush(bio);
    
    unsigned char *b64enc;
    int b64len = (int)BIO_ctrl(bio, BIO_CTRL_INFO, 0, (char *)&b64enc);
    if (b64len <= 0) goto err;
    
    // Copy the string
    char *encoded = malloc(b64len+2);
    encoded[0] = '*'; // prepended to indicate CBC mode
    memcpy(encoded+1, b64enc, b64len);
    encoded[b64len+1] = '\0'; // null terminator
    BIO_free_all(b64); // data has been copied now
    return encoded;
    
  err:
    free(encrypted);
    BIO_free_all(b64);
    return NULL;
}


/**
 * Decrypts a message in CBC mode. The leading "*" should be included.
 */
static char *fish_decrypt_cbc(const char *key, size_t keylen, const char *data) {
    BF_KEY bfkey;
    unsigned char *decrypted, *bindata = NULL;
    BIO *b64 = NULL;
    BF_set_key(&bfkey, keylen, (const unsigned char*)key);
    
    // Skip leading "*" that indicates that the message is using CBC byte
    if (*data != '*') goto err;
    data++;
    
    // Decode BASE64
    b64 = BIO_new(BIO_f_base64());
    if (!b64) goto err;
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    BIO *bmem = BIO_new(BIO_s_mem());
    if (!bmem) goto err;
    BIO *bio = BIO_push(b64, bmem);
    int datalen = strlen(data);
    if (BIO_write(bmem, data, datalen) != datalen) goto err;
    BIO_flush(bio);

    size_t binlen = BIO_pending(bmem);
    bindata = malloc(binlen+1);
    if (!bindata) goto err;
    int outlen = BIO_read(bio, bindata, BIO_pending(bmem));
    if (outlen < 8) goto err; // Must at least contain an IV
    outlen -= 8;
    outlen &= ~7;
    
    // Decrypt in CBC mode
    decrypted = malloc(outlen+1);
    if (!decrypted) goto err;
    if (outlen) {
        unsigned char *iv = &bindata[0];
        unsigned char *enc = &bindata[8];
        BF_cbc_encrypt(enc, decrypted, outlen, &bfkey, iv, BF_DECRYPT);
    }
    BIO_free_all(b64);
    decrypted[outlen] = '\0';
    return (char*)decrypted;
    
  err:
    BIO_free_all(b64);
    free(bindata);
    return NULL;
}

/**
 * Decrypts in ECB mode.
 */
static char *fish_decrypt_ecb(const char *key, size_t keylen, const char *data) {
    BF_KEY bfkey;
    size_t i;
    char *decrypted;
    char *end;
    unsigned char bit;
    unsigned char word;
    unsigned char d;
    BF_set_key(&bfkey, keylen, (const unsigned char*)key);
    
    decrypted = malloc(strlen(data)+1);
    end = decrypted;
    if (!decrypted) return NULL;
    
    while (*data) {
        // Convert from FiSH-BASE64
        BF_LONG binary[2] = { 0, 0 };
        bit = 0;
        word = 1;
        for (i = 0; i < 12; i++) {
            d = fish_unbase64[(const unsigned char)*(data++)];
            if (d == IB) goto decrypt_end;
            binary[word] |= (unsigned long)d << bit;
            bit += 6;
            if (i == 5) {
                bit = 0;
                word = 0;
            }
        }
        
        // Decrypt block
        BF_decrypt(binary, &bfkey);
        
        // Copy to buffer
        GET_BYTES(end, binary[0]);
        GET_BYTES(end, binary[1]);
    }
    
  decrypt_end:
    *end = '\0';
    return decrypted;
}

/**
 * Decrypts a message using the given key. ECB or CBC mode is autodetected.
 */
char *fish_decrypt(const char *key, size_t keylen, const char *data) {
    if (*data == '*') return fish_decrypt_cbc(key, keylen, data);
    else return fish_decrypt_ecb(key, keylen, data);
}


/**
 * Encrypts a message (see fish_decrypt). The key is searched for in the
 * key store.
 */
char *fish_encrypt_for_nick(const char *nick, const char *data) {
    char *key;
    char *encrypted;
    bool is_cbc;

    // Look for key
    key = keystore_get_key(nick, &is_cbc);
    if (!key) return NULL;
    
    // Encrypt
    encrypted = is_cbc ?
        fish_encrypt_cbc(key, strlen(key), data) :
        fish_encrypt_ecb(key, strlen(key), data);
    
    free(key);
    return encrypted;
}

/**
 * Decrypts a message (see fish_decrypt). The key is searched for in the
 * key store.
 */
char *fish_decrypt_from_nick(const char *nick, const char *data) {
    char *key;
    char *decrypted;
    // Look for key
    key = keystore_get_key(nick, NULL);
    if (!key) return NULL;
    
    // Decrypt
    decrypted = fish_decrypt(key, strlen(key), data);
    
    free(key);
    return decrypted;
}