File: SSLSocket.cpp

package info (click to toggle)
eiskaltdcpp 2.4.2-1.3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 25,676 kB
  • sloc: cpp: 97,597; ansic: 5,004; perl: 1,897; xml: 1,440; sh: 1,313; php: 661; javascript: 257; makefile: 39
file content (267 lines) | stat: -rw-r--r-- 7,064 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2001-2012 Jacek Sieka, arnetheduck on gmail point com
 *
 * 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.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "stdinc.h"
#include "SSLSocket.h"

#include "format.h"
#include "CryptoManager.h"
#include "LogManager.h"
#include "SettingsManager.h"

#include <openssl/err.h>

namespace dcpp {

#if OPENSSL_VERSION_NUMBER >= 0x10002000L
static const unsigned char alpn_protos_nmdc[] = {
	4, 'n', 'm', 'd', 'c',
};
static const unsigned char alpn_protos_adc[] = {
	3, 'a', 'd', 'c',
};
#endif

SSLSocket::SSLSocket(SSL_CTX* context, Socket::Protocol proto) : ctx(context), ssl(0), nextProto(proto) {

}

void SSLSocket::connect(const string& aIp, const string& aPort) {
    Socket::connect(aIp, aPort);

    waitConnected(0);
}

#if OPENSSL_VERSION_NUMBER < 0x10002000L
static inline int SSL_is_server(SSL *s)
{
    return s->server;
}
#endif

bool SSLSocket::waitConnected(uint32_t millis) {
    if(!ssl) {
        if(!Socket::waitConnected(millis)) {
            return false;
        }
        ssl.reset(SSL_new(ctx));
        if(!ssl)
            checkSSL(-1);

        checkSSL(SSL_set_fd(ssl, sock));
    }

#if OPENSSL_VERSION_NUMBER >= 0x10002000L
    if (nextProto == Socket::PROTO_NMDC) {
        SSL_set_alpn_protos(ssl, alpn_protos_nmdc, sizeof(alpn_protos_nmdc));
    } else if (nextProto == Socket::PROTO_ADC) {
        SSL_set_alpn_protos(ssl, alpn_protos_adc, sizeof(alpn_protos_adc));
    }
#endif

    if(SSL_is_init_finished(ssl)) {
        return true;
    }

    while(true) {
        int ret = SSL_is_server(ssl)?SSL_accept(ssl):SSL_connect(ssl);
        if(ret == 1) {
            dcdebug("Connected to SSL server using %s as %s\n",
                    SSL_get_cipher(ssl), SSL_is_server(ssl) ? "server" : "client");

#if OPENSSL_VERSION_NUMBER >= 0x10002000L
            if (SSL_is_server(ssl)) return true;

            const unsigned char* protocol = 0;
            unsigned int len = 0;
            SSL_get0_alpn_selected(ssl, &protocol, &len);
            if (len != 0)
            {
                if (len == 3 && !memcmp(protocol, "adc", len))
                    proto = PROTO_ADC;
                else if (len == 4 && !memcmp(protocol, "nmdc", len))
                    proto = PROTO_NMDC;
                dcdebug("ALPN negotiated %.*s (%d)\n", len, protocol, proto);
            }
#endif
            return true;
        }
        if(!waitWant(ret, millis)) {
            return false;
        }
    }
}

void SSLSocket::accept(const Socket& listeningSocket) {
    Socket::accept(listeningSocket);

    waitAccepted(0);
}

bool SSLSocket::waitAccepted(uint32_t millis) {
    if(!ssl) {
        if(!Socket::waitAccepted(millis)) {
            return false;
        }
        ssl.reset(SSL_new(ctx));
        if(!ssl)
            checkSSL(-1);

        checkSSL(SSL_set_fd(ssl, sock));
    }

    if(SSL_is_init_finished(ssl)) {
        return true;
    }

    while(true) {
        int ret = SSL_accept(ssl);
        if(ret == 1) {
            dcdebug("Connected to SSL client using %s\n", SSL_get_cipher(ssl));
            return true;
        }
        if(!waitWant(ret, millis)) {
            return false;
        }
    }
}

bool SSLSocket::waitWant(int ret, uint32_t millis) {
    int err = SSL_get_error(ssl, ret);
    switch(err) {
    case SSL_ERROR_WANT_READ:
        return wait(millis, Socket::WAIT_READ) == WAIT_READ;
    case SSL_ERROR_WANT_WRITE:
        return wait(millis, Socket::WAIT_WRITE) == WAIT_WRITE;
        // Check if this is a fatal error...
    default: checkSSL(ret);
    }
    dcdebug("SSL: Unexpected fallthrough");
    // There was no error?
    return true;
}

int SSLSocket::read(void* aBuffer, int aBufLen) {
    if(!ssl) {
        return -1;
    }
    int len = checkSSL(SSL_read(ssl, aBuffer, aBufLen));

    if(len > 0) {
        stats.totalDown += len;
        //dcdebug("In(s): %.*s\n", len, (char*)aBuffer);
    }
    return len;
}

int SSLSocket::write(const void* aBuffer, int aLen) {
    if(!ssl) {
        return -1;
    }
    int ret = checkSSL(SSL_write(ssl, aBuffer, aLen));
    if(ret > 0) {
        stats.totalUp += ret;
        //dcdebug("Out(s): %.*s\n", ret, (char*)aBuffer);
    }
    return ret;
}

int SSLSocket::checkSSL(int ret) {
    if(!ssl) {
        return -1;
    }
    if(ret <= 0) {
        /* inspired by boost.asio (asio/ssl/detail/impl/engine.ipp, function engine::perform) and
           the SSL_get_error doc at <https://www.openssl.org/docs/ssl/SSL_get_error.html>. */
        auto err = SSL_get_error(ssl, ret);
        switch(err) {
        case SSL_ERROR_NONE:        // Fallthrough - YaSSL doesn't for example return an openssl compatible error on recv fail
        case SSL_ERROR_WANT_READ:   // Fallthrough
        case SSL_ERROR_WANT_WRITE:
            return -1;
        case SSL_ERROR_ZERO_RETURN:
            throw SocketException(_("Connection closed"));
        default:
        {
            ssl.reset();
            // @todo replace 80 with MAX_ERROR_SZ or whatever's appropriate for yaSSL in some nice way...
            char errbuf[80];
            throw SSLSocketException(str(F_("SSL Error: %1% (%2%, %3%)") % ERR_error_string(err, errbuf) % ret % err));
        }
        }
    }
    return ret;
}

int SSLSocket::wait(uint32_t millis, int waitFor) {
    if(ssl && (waitFor & Socket::WAIT_READ)) {
        /** @todo Take writing into account as well if reading is possible? */
        char c;
        if(SSL_peek(ssl, &c, 1) > 0)
            return WAIT_READ;
    }
    return Socket::wait(millis, waitFor);
}

bool SSLSocket::isTrusted() const noexcept {
    if(!ssl) {
        return false;
    }

    if(SSL_get_verify_result(ssl) != X509_V_OK) {
        return false;
    }

    X509* cert = SSL_get_peer_certificate(ssl);
    if(!cert) {
        return false;
    }
    X509_free(cert);
    return true;
}

std::string SSLSocket::getCipherName() const noexcept {
    if(!ssl)
        return Util::emptyString;

    return SSL_get_cipher_name(ssl);
}

ByteVector SSLSocket::getKeyprint() const noexcept {
    if(!ssl)
        return ByteVector();
    X509* x509 = SSL_get_peer_certificate(ssl);
    if(!x509)
        return ByteVector();

    return ssl::X509_digest(x509, EVP_sha256());
}

void SSLSocket::shutdown() noexcept {
    if(ssl)
        SSL_shutdown(ssl);
}

void SSLSocket::close() noexcept {
    if(ssl) {
        ssl.reset();
    }
    Socket::shutdown();
    Socket::close();
}

} // namespace dcpp