~ubuntu-branches/ubuntu/lucid/konversation/lucid-updates

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
457
458
/*
  This program 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 2 of the License, or
  (at your option) any later version.
*/

/*
  Copyright (C) 1997 Robey Pointer <robeypointer@gmail.com>
  Copyright (C) 2005 Ismail Donmez <ismail@kde.org>
  Copyright (C) 2009 Travis McHenry <tmchenryaz@cox.net>
*/

#include "cipher.h"
#include "preferences.h"

#include <KDebug>


namespace Konversation
{
    Cipher::Cipher()
    {
        m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923");
        setType("blowfish");
    }

    Cipher::Cipher(QByteArray key, QString cipherType)
    {
        m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923");
        setKey(key);
        setType(cipherType);
    }

    Cipher::~Cipher()
    {
    }

    bool Cipher::setKey(QByteArray key)
    {
        if(key.isEmpty())
            return false;

        if(key.mid(0,4).toLower() == "ecb:")
        {
            m_cbc = false;
            m_key = key.mid(4);
        }
        //strip cbc: if included
        else if(key.mid(0,4).toLower() == "cbc:")
        {
            m_cbc = true;
            m_key = key.mid(4);
        }
        else
        {
            if(Preferences::self()->encryptionType())
                m_cbc = true;
            else
                m_cbc = false;
            m_key = key;
        }
        return true;
    }

    bool Cipher::setType(const QString &type)
    {
        //TODO check QCA::isSupported()
        m_type = type;
        return true;
    }

    QByteArray Cipher::decrypt(QByteArray cipherText)
    {
        QByteArray pfx = "(e) ";
        bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type

        //if we get cbc
        if(cipherText.mid(0,5) == "+OK *")
        {
            //if we have cbc
            if(m_cbc)
                cipherText = cipherText.mid(5);
            //if we don't
            else
            {
                cipherText = cipherText.mid(5);
                pfx = "ERROR_NONECB: ";
                error = true;
            }
        }
        //if we get ecb
        else if(cipherText.mid(0,4) == "+OK " || cipherText.mid(0,5) == "mcps ")
        {
            //if we had cbc
            if(m_cbc)
            {
                cipherText = (cipherText.mid(0,4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5);
                pfx = "ERROR_NONCBC: ";
                error = true;
            }
            //if we don't
            else
            {
                if(cipherText.mid(0,4) == "+OK ")
                    cipherText = cipherText.mid(4);
                else
                    cipherText = cipherText.mid(5);
            }
        }
        //all other cases we fail
        else
            return cipherText;

        QByteArray temp;
        // (if cbc and no error we parse cbc) || (if ecb and error we parse cbc)
        if((m_cbc && !error) || (!m_cbc && error))
        {
            cipherText = cipherText;
            temp = blowfishCBC(cipherText, false);

            if(temp == cipherText)
            {
                kDebug() << "Decryption from CBC Failed";
                return "ERROR: "+cipherText+' '+'\n';
            }
            else
                cipherText = temp;
        }
        else
        {
            temp = blowfishECB(cipherText, false);

            if(temp == cipherText)
            {
                kDebug() << "Decryption from ECB Failed";
                return "ERROR: "+cipherText+' '+'\n';
            }
            else
                cipherText = temp;
        }
        // If it's a CTCP we don't want to have the (e) interfering with the processing
        // TODO FIXME the proper fix for this is to show encryption differently e.g. [nick] instead of <nick>
        // don't hate me for the mircryption reference there.
        if (cipherText.at(0) == 1)
            pfx = "\x0";
        cipherText = pfx+cipherText+' '+'\n'; // FIXME(??) why is there an added space here?
        return cipherText;
    }

    QByteArray Cipher::initKeyExchange()
    {
        QCA::Initializer init;
        m_tempKey = QCA::KeyGenerator().createDH(QCA::DLGroup(m_primeNum, QCA::BigInteger(2))).toDH();

        if(m_tempKey.isNull())
            return QByteArray();

        QByteArray publicKey = m_tempKey.toPublicKey().toDH().y().toArray().toByteArray();

        //remove leading 0
        if(publicKey.length() > 135 && publicKey.at(0) == '\0')
            publicKey = publicKey.mid(1);

        return publicKey.toBase64().append('A');
    }

    QByteArray Cipher::parseInitKeyX(QByteArray key)
    {
        QCA::Initializer init;

        if(key.length() != 181)
            return QByteArray();

        QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
        QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
        QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH();

        if(privateKey.isNull())
            return QByteArray();

        QByteArray publicKey = privateKey.y().toArray().toByteArray();

        //remove leading 0
        if(publicKey.length() > 135 && publicKey.at(0) == '\0')
            publicKey = publicKey.mid(1);

        QCA::DHPublicKey remotePub(group, remoteKey);

        if(remotePub.isNull())
            return QByteArray();

        QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray();
        sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();

        //remove trailing = because mircryption and fish think it's a swell idea.
        while(sharedKey.endsWith('=')) sharedKey.chop(1);

        bool success = setKey(sharedKey);

        if(!success)
            return QByteArray();

        return publicKey.toBase64().append('A');
    }

    bool Cipher::parseFinishKeyX(QByteArray key)
    {
        QCA::Initializer init;

        if(key.length() != 181)
            return false;

        QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
        QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));

        QCA::DHPublicKey remotePub(group, remoteKey);

        if(remotePub.isNull())
            return false;

        if(m_tempKey.isNull())
            return false;

        QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray();
        sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();

        //remove trailng = because mircryption and fish think it's a swell idea.
        while(sharedKey.endsWith('=')) sharedKey.chop(1);

        bool success = setKey(sharedKey);

        return success;
    }

    QByteArray Cipher::decryptTopic(QByteArray cipherText)
    {
        if(cipherText.mid(0,4) == "+OK ")// FiSH style topic
            cipherText = cipherText.mid(4);
        else if(cipherText.left(5) == "«m«")
            cipherText = cipherText.mid(5,cipherText.length()-10);
        else
            return "ERROR: "+cipherText;

        QByteArray temp;
        //TODO currently no backwards sanity checks for topic, it seems to use different standards
        //if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings
        if(m_cbc)
            temp = blowfishCBC(cipherText.mid(1), false);
        else
            temp = blowfishECB(cipherText, false);

        if(temp == cipherText)
        {
            return "ERROR: "+cipherText;
        }
        else
            cipherText = temp;

        if(cipherText.mid(0,2) == "@@")
            cipherText = cipherText.mid(2);

        cipherText = "(e) "+cipherText;
        return cipherText;
    }

    bool Cipher::encrypt(QByteArray& cipherText)
    {
        if (cipherText.left(3) == "+p ") //don't encode if...?
            cipherText = cipherText.mid(3);
        else
        {
            if(m_cbc) //encode in ecb or cbc decide how to determine later
            {
                QByteArray temp = blowfishCBC(cipherText, true);

                if(temp == cipherText)
                {
                    kDebug() << "CBC Encoding Failed";
                    return false;
                }

                cipherText = "+OK *" + temp;
            }
            else
            {
                QByteArray temp = blowfishECB(cipherText, true);

                if(temp == cipherText)
                {
                    kDebug() << "ECB Encoding Failed";
                    return false;
                }

                cipherText = "+OK " + temp;
            }
        }
        return true;
    }
    //THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
    QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction)
    {
        QCA::Initializer init;
        QByteArray temp = cipherText;
        if(direction)
        {
            // make sure cipherText is an interval of 8 bits. We do this before so that we
            // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail
            while((temp.length() % 8) != 0) temp.append('\0');

            QCA::InitializationVector iv(8);
            temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
        }
        else
        {
            temp = QByteArray::fromBase64(temp);
            //supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
            //en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
            while((temp.length() % 8) != 0) temp.append('\0');
        }

        QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
        QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0")));
        QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
        temp2 += cipher.final().toByteArray();

        if(!cipher.ok())
            return cipherText;

        if(direction) //send in base64
            temp2 = temp2.toBase64();
        else //cut off the 8bits of IV
            temp2 = temp2.remove(0,8);

        return temp2;
    }

    QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
    {
        QCA::Initializer init;
        QByteArray temp = cipherText;

        //do padding ourselves
        if(direction)
        {
            while((temp.length() % 8) != 0) temp.append('\0');
        }
        else
        {
            temp = b64ToByte(temp);
            while((temp.length() % 8) != 0) temp.append('\0');
        }

        QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
        QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
        QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
        temp2 += cipher.final().toByteArray();

        if(!cipher.ok())
            return cipherText;

        if(direction)
            temp2 = byteToB64(temp2);

        return temp2;
    }

    //Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility
    QByteArray Cipher::byteToB64(QByteArray text)
    {
        int left = 0;
        int right = 0;
        int k = -1;
        int v;
        QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        QByteArray encoded;
        while (k < (text.length() - 1)) {
            k++;
            v=text.at(k); if (v<0) v+=256;
            left = v << 24;
            k++;
            v=text.at(k); if (v<0) v+=256;
            left += v << 16;
            k++;
            v=text.at(k); if (v<0) v+=256;
            left += v << 8;
            k++;
            v=text.at(k); if (v<0) v+=256;
            left += v;

            k++;
            v=text.at(k); if (v<0) v+=256;
            right = v << 24;
            k++;
            v=text.at(k); if (v<0) v+=256;
            right += v << 16;
            k++;
            v=text.at(k); if (v<0) v+=256;
            right += v << 8;
            k++;
            v=text.at(k); if (v<0) v+=256;
            right += v;

            for (int i = 0; i < 6; i++) {
                encoded.append(base64.at(right & 0x3F).toAscii());
                right = right >> 6;
            }
            //TODO make sure the .toascii doesn't break anything

            for (int i = 0; i < 6; i++) {
                encoded.append(base64.at(left & 0x3F).toAscii());
                left = left >> 6;
            }
        }
        return encoded;
    }

    QByteArray Cipher::b64ToByte(QByteArray text)
    {
        QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        QByteArray decoded;
        int k = -1;
        while (k < (text.length() - 1)) {
            int right = 0;
            int left = 0;
            int v = 0;
            int w = 0;
            int z = 0;

            for (int i = 0; i < 6; i++) {
                k++;
                v = base64.indexOf(text.at(k));
                right |= v << (i * 6);
            }

            for (int i = 0; i < 6; i++) {
                k++;
                v = base64.indexOf(text.at(k));
                left |= v << (i * 6);
            }

            for (int i = 0; i < 4; i++) {
                w = ((left & (0xFF << ((3 - i) * 8))));
                z = w >> ((3 - i) * 8);
                if(z < 0) {z = z + 256;}
                decoded.append(z);
            }

            for (int i = 0; i < 4; i++) {
                w = ((right & (0xFF << ((3 - i) * 8))));
                z = w >> ((3 - i) * 8);
                if(z < 0) {z = z + 256;}
                decoded.append(z);
            }
        }
        return decoded;
    }
}