summaryrefslogtreecommitdiffstats
path: root/konversation/src/sslsocket.cpp
blob: e22fe7befad4f45d842832fadabf9fab6205cad6 (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
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
/*
    Copyright (c) 2004,2005 by İsmail Dönmez <ismail.donmez@boun.edu.tr>

    based on the code by :
    Copyright (c) 2004      by Jason Keirstead <jason@keirstead.org>
    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * 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.                                   *
*                                                                       *
*************************************************************************
*/

#include "sslsocket.h"

#include <tdelocale.h>
#include <kdebug.h>
#include <kssl.h>
#include <ksslinfodlg.h>
#include <ksslpeerinfo.h>
#include <ksslcertchain.h>
#include <ksslcertificatecache.h>
#include <tdemessagebox.h>
#include <tdesocketdevice.h>


struct SSLSocketPrivate
{
    int m_sslCertState;
    TQString remoteHost;
    TQString url;
    TQString m_sslCertErrors;

    KSSL* kssl;
    KSSLCertificateCache* cc;
};

SSLSocket::SSLSocket(TQWidget* serverParent, TQObject* parent, const char* name)
: KStreamSocket(0L,0L,parent,name), m_serverParent(serverParent)
{
    d = new SSLSocketPrivate;
    d->kssl = 0L;
    d->cc = new KSSLCertificateCache;
    d->cc->reload();

}

SSLSocket::~SSLSocket()
{
    // Close stream socket
    close();

    // close ssl socket
    if( d->kssl ) d->kssl->close();

    delete d->kssl;
    delete d->cc;
    delete d;
}

TQ_LONG SSLSocket::writeBlock(const char *data, TQ_ULONG len)
{
    if (d->kssl && KSSL::doesSSLWork() && state() == KNetwork::KClientSocketBase::Connected)
        return d->kssl->write( data,len );
    else
        return 0;
}

TQ_LONG SSLSocket::readBlock(char *data, TQ_ULONG maxlen)
{
    int err = d->kssl->read( data, maxlen );
    return err;
}

void SSLSocket::stateChanging(KClientSocketBase::SocketState newState)
{
    if(newState == KClientSocketBase::Connected)
    {
        KClientSocketBase::stateChanging(KClientSocketBase::Connected);
        connected();
    }
    else
        KClientSocketBase::stateChanging(newState);
}

const TQString SSLSocket::details()
{
    int strength = d->kssl->connectionInfo().getCipherUsedBits();

    TQString details = i18n("Connection is secured with %1 bit SSL.").arg(strength);

    return details;
}

void SSLSocket::connected()
{

    if( KSSL::doesSSLWork() )
    {
        if( !d->kssl )
        {
            d->kssl = new KSSL();
            if( d->kssl->connect( socketDevice()->socket() ) )
            {
                if( verifyCertificate() != 1 )
                {
                    close();
                }
                else
                    emit sslInitDone();
            }
        }
        else
        {
            d->kssl->reInitialize();
        }
    }
    else
    {
        kdError() << "SSL not functional!" << endl;
        emit sslFailure(i18n("The functionality to connect to servers using encrypted SSL communications is not available to Konversation because OpenSSL support was not enabled at compile time. You will need to get new version of TDE that has SSL support."));
        close();
    }
}

void SSLSocket::showInfoDialog()
{
    if( state() == KNetwork::KClientSocketBase::Connected )
    {
        showSSLInfoDialog();
    }
}

void SSLSocket::showSSLInfoDialog()
{

    KSSLInfoDlg* sslInfoDlg = new KSSLInfoDlg(true, m_serverParent, "sslInfoDlg", true);
    sslInfoDlg->setCertState( d->m_sslCertErrors );
    sslInfoDlg->setup( *(d->kssl),
        (const TQString&) d->remoteHost,
        (const TQString&) d->url
        );
    sslInfoDlg->exec();
}

int SSLSocket::verifyCertificate()
{
    int rc = 0;
    int result;
    bool permacache = false;
    bool ipMatchesCN = false;
    bool doAddHost = false;
    TQString hostname;
    KSSLCertificate::KSSLValidation validation;

    d->remoteHost = peerAddress().nodeName();
    d->url = "irc://"+d->remoteHost+':'+peerAddress().serviceName();

    KSSLCertificate& peerCertificate = d->kssl->peerInfo().getPeerCertificate();

    validation = peerCertificate.validate();
    if(validation == KSSLCertificate::Unknown )
    {
        emit sslFailure(i18n("The SSL certificate returned from the server was not recognized.  Maybe this server does not support SSL on the given port?  If this server supports normal, non-SSL communications as well, then SSL will be on a different port."));
        return 0;
    }

    KSSLX509Map certinfo(peerCertificate.getSubject());
    hostname = certinfo.getValue("CN");

    KSSLCertificate::KSSLValidationList validationList
        = peerCertificate.validateVerbose(KSSLCertificate::SSLServer);

    ipMatchesCN = d->kssl->peerInfo().certMatchesAddress();

    validation = KSSLCertificate::Ok;

    if (!validationList.isEmpty())
        validation = validationList.first();

    for(KSSLCertificate::KSSLValidationList::ConstIterator it = validationList.begin();
        it != validationList.end(); ++it)
    {
        d->m_sslCertErrors += TQString::number(*it)+':';
    }

    if (peerCertificate.chain().isValid() && peerCertificate.chain().depth() > 1)
    {
        TQString theChain;
        TQPtrList<KSSLCertificate> chain = peerCertificate.chain().getChain();
        for (KSSLCertificate *c = chain.first(); c; c = chain.next())
        {
            theChain += c->toString();
            theChain += '\n';
        }
    }

    d->m_sslCertState = validation;

    if (validation == KSSLCertificate::Ok)
        rc = 1;

    //  - Read from cache and see if there is a policy for this
    KSSLCertificateCache::KSSLCertificatePolicy cp = d->cc->getPolicyByCertificate(peerCertificate);

    //  - validation code
    if (validation != KSSLCertificate::Ok)
    {
        if( cp == KSSLCertificateCache::Unknown || cp == KSSLCertificateCache::Ambiguous)
        {
            cp = KSSLCertificateCache::Prompt;
        }
        else
        {
            // A policy was already set so let's honor that.
            permacache = d->cc->isPermanent(peerCertificate);
        }

        if (!ipMatchesCN && cp == KSSLCertificateCache::Accept )
        {
            do
            {
                TQString msg = i18n("The IP address of the host %1 "
                    "does not match the one the "
                    "certificate was issued to.");
                result = KMessageBox::warningYesNoCancel( m_serverParent,
                    msg.arg(hostname),
                    i18n("Server Authentication"),
                    KGuiItem(i18n("Details")),
                    KGuiItem(i18n("Continue")),
                    "SslIpCNMismatch");
                if(result == KMessageBox::Yes)
                    showInfoDialog();
                else if(result == KMessageBox::Cancel)
                {
                    return 0;
                }
            }
            while ( result == KMessageBox::Yes );

        }

        // Precondition: cp is one of Reject, Accept or Prompt
        switch (cp)
        {
            case KSSLCertificateCache::Accept:
                rc = 1;
                break;

            case KSSLCertificateCache::Reject:
                rc = -1;
                break;

            case KSSLCertificateCache::Prompt:
            {
                do
                {
                    if (validation == KSSLCertificate::InvalidHost)
                    {
                        TQString msg = i18n("The IP address of the host %1 "
                            "does not match the one the "
                            "certificate was issued to.");
                        result = KMessageBox::warningYesNoCancel( m_serverParent,
                            msg.arg(hostname),
                            i18n("Server Authentication"),
                            KGuiItem(i18n("Details")),
                            KGuiItem(i18n("Continue")),
			    TQString(),
			    KMessageBox::Dangerous);
                    }
                    else
                    {
                        TQString msg = i18n("The server (%1) certificate failed the "
                            "authenticity test.");
                        result = KMessageBox::warningYesNoCancel( m_serverParent,
                            msg.arg(hostname),
                            i18n("Server Authentication"),
                            KGuiItem(i18n("Details")),
                            KGuiItem(i18n("Continue")),
			    TQString(),
			    KMessageBox::Dangerous);
                    }

                    if (result == KMessageBox::Yes)
                    {
                        showInfoDialog();
                    }
                    else if(result == KMessageBox::Cancel)
                    {
                        return 0;
                    }
                }
                while (result == KMessageBox::Yes);

                if (result == KMessageBox::No)
                {
                    rc = 1;
                    cp = KSSLCertificateCache::Accept;
                    doAddHost = true;
                    result = KMessageBox::warningYesNo( m_serverParent,
                        i18n("Would you like to accept this "
                        "certificate forever without "
                        "being prompted?"),
                        i18n("Server Authentication"),
                        KGuiItem(i18n("&Forever")),
                        KGuiItem(i18n("&Current Sessions Only"))
                        );

                    if (result == KMessageBox::Yes)
                        permacache = true;
                    else
                        permacache = false;
                }
                else
                {
                    rc = -1;
                    cp = KSSLCertificateCache::Prompt;
                }

                break;
            }
            default:
                kdDebug() << "SSL error in cert code." << endl;
                break;
        }
    }

    //  - cache the results
    d->cc->addCertificate(peerCertificate, cp, permacache);
    if (doAddHost)
        d->cc->addHost(peerCertificate, d->remoteHost);

    if (rc == -1)
        return rc;
    /*
    kdDebug() << "SSL connection information follows:" << endl
        << "+-----------------------------------------------" << endl
        << "| Cipher: " << d->kssl->connectionInfo().getCipher() << endl
        << "| Description: " << d->kssl->connectionInfo().getCipherDescription() << endl
        << "| Version: " << d->kssl->connectionInfo().getCipherVersion() << endl
        << "| Strength: " << d->kssl->connectionInfo().getCipherUsedBits()
        << " of " << d->kssl->connectionInfo().getCipherBits()
        << " bits used." << endl
        << "| PEER:" << endl
        << "| Subject: " << d->kssl->peerInfo().getPeerCertificate().getSubject() << endl
        << "| Issuer: " << d->kssl->peerInfo().getPeerCertificate().getIssuer() << endl
        << "| Validation: " << (int) validation << endl
        << "+-----------------------------------------------"
        << endl;
    */
    return rc;
}

#include "sslsocket.moc"