diff options
36 files changed, 4477 insertions, 1 deletions
diff --git a/configure.py b/configure.py index e1b1df7c2..60f86f931 100755 --- a/configure.py +++ b/configure.py @@ -42,7 +42,7 @@ class BuildConfigurationInformation(object): version_minor = 9 version_patch = 4 version_so_patch = 4 - version_suffix = '-dev' + version_suffix = '-ssl-dev' version_string = '%d.%d.%d%s' % ( version_major, version_minor, version_patch, version_suffix) diff --git a/doc/examples/tls_client.cpp b/doc/examples/tls_client.cpp new file mode 100644 index 000000000..20fde6354 --- /dev/null +++ b/doc/examples/tls_client.cpp @@ -0,0 +1,55 @@ +/* +* (C) 2008 Jack Lloyd +* +* Distributed under the terms of the Botan license +*/ + +#include <botan/init.h> +#include <botan/tls_client.h> +#include <botan/unx_sock.h> + +using namespace Botan; + +#include <stdio.h> +#include <string> +#include <iostream> +#include <memory> + +int main() + { + try + { + LibraryInitializer init; + + Unix_Socket sock("randombit.net", 443); + + std::auto_ptr<Botan::RandomNumberGenerator> rng( + Botan::RandomNumberGenerator::make_rng()); + + TLS_Client tls(*rng, sock); + + printf("Connection open\n"); + + while(true) + { + if(tls.is_closed()) + break; + + std::string str; + std::getline(std::cin, str); + str += "\n"; + tls.write((const byte*)str.c_str(), str.length()); + + byte buf[4096] = { 0 }; + tls.read(buf, sizeof(buf)); + printf("%s", buf); + fflush(0); + } + } + catch(std::exception& e) + { + printf("%s\n", e.what()); + return 1; + } + return 0; + } diff --git a/doc/examples/tls_server.cpp b/doc/examples/tls_server.cpp new file mode 100644 index 000000000..d5cb77a84 --- /dev/null +++ b/doc/examples/tls_server.cpp @@ -0,0 +1,71 @@ +/* +* (C) 2008 Jack Lloyd +* +* Distributed under the terms of the Botan license +*/ + +#include <botan/init.h> +#include <botan/tls_server.h> +#include <botan/unx_sock.h> + +#include <botan/rsa.h> +#include <botan/dsa.h> +#include <botan/x509self.h> + +using namespace Botan; + +#include <stdio.h> +#include <string> +#include <iostream> +#include <memory> + +int main() + { + try + { + LibraryInitializer init; + + std::auto_ptr<RandomNumberGenerator> rng( + RandomNumberGenerator::make_rng()); + + RSA_PrivateKey key(*rng, 512); + //DSA_PrivateKey key(get_dl_group("DSA-1024")); + + X509_Cert_Options options( + "www.randombit.net/US/Syn Ack Labs/Mathematical Munitions Dept"); + + X509_Certificate cert = + X509::create_self_signed_cert(options, key, "SHA-1", *rng); + + Unix_Server_Socket listener(4433); + + printf("Now listening...\n"); + + while(true) + { + try { + Socket* sock = listener.accept(); + + printf("Got new connection\n"); + + TLS_Server tls(*rng, *sock, cert, key); + + char msg[] = "Foo\nBar\nBaz\nQuux\n"; + tls.write((const byte*)msg, strlen(msg)); + + char buf[10] = { 0 }; + u32bit got = tls.read((byte*)buf, 9); + printf("%d: '%s'\n", got, buf); + + tls.close(); + } + catch(std::exception& e) { printf("%s\n", e.what()); } + } + } + catch(std::exception& e) + { + printf("%s\n", e.what()); + return 1; + } + return 0; + } diff --git a/src/ssl/c_kex.cpp b/src/ssl/c_kex.cpp new file mode 100644 index 000000000..298b22a89 --- /dev/null +++ b/src/ssl/c_kex.cpp @@ -0,0 +1,174 @@ +/** +* Client Key Exchange Message Source File +* (C) 2004-2008 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_messages.h> +#include <botan/dh.h> +#include <botan/rsa.h> +#include <botan/rng.h> +#include <botan/look_pk.h> +#include <botan/loadstor.h> +#include <memory> + +namespace Botan { + +/** +* Create a new Client Key Exchange message +*/ +Client_Key_Exchange::Client_Key_Exchange(RandomNumberGenerator& rng, + Record_Writer& writer, + HandshakeHash& hash, + const X509_PublicKey* pub_key, + Version_Code using_version, + Version_Code pref_version) + { + const DH_PublicKey* dh_pub = dynamic_cast<const DH_PublicKey*>(pub_key); + const RSA_PublicKey* rsa_pub = dynamic_cast<const RSA_PublicKey*>(pub_key); + + include_length = true; + + if(dh_pub) + { + DH_PrivateKey priv_key(rng, dh_pub->get_domain()); + pre_master = priv_key.derive_key(dh_pub->get_y()); + key_material = priv_key.public_value(); + } + else if(rsa_pub) + { + pre_master.resize(48); + rng.randomize(pre_master, 48); + pre_master[0] = (pref_version >> 8) & 0xFF; + pre_master[1] = (pref_version ) & 0xFF; + + std::auto_ptr<PK_Encryptor> encryptor(get_pk_encryptor(*rsa_pub, + "PKCS1v15")); + + key_material = encryptor->encrypt(pre_master, rng); + + if(using_version == SSL_V3) + include_length = false; + } + else + throw Invalid_Argument("Client_Key_Exchange: Key not RSA or DH"); + + send(writer, hash); + } + +/** +* Read a Client Key Exchange message +*/ +Client_Key_Exchange::Client_Key_Exchange(const MemoryRegion<byte>& contents, + const CipherSuite& suite, + Version_Code using_version) + { + include_length = true; + + if(using_version == SSL_V3 && + (suite.kex_type() == CipherSuite::NO_KEX || + suite.kex_type() == CipherSuite::RSA_KEX)) + include_length = false; + + deserialize(contents); + } + +/** +* Serialize a Client Key Exchange message +*/ +SecureVector<byte> Client_Key_Exchange::serialize() const + { + SecureVector<byte> buf; + + if(include_length) + { + u16bit key_size = key_material.size(); + buf.append(get_byte(0, key_size)); + buf.append(get_byte(1, key_size)); + } + buf.append(key_material); + + return buf; + } + +/** +* Deserialize a Client Key Exchange message +*/ +void Client_Key_Exchange::deserialize(const MemoryRegion<byte>& buf) + { + if(include_length) + { + if(buf.size() < 2) + throw Decoding_Error("Client_Key_Exchange: Packet corrupted"); + + u32bit size = make_u16bit(buf[0], buf[1]); + if(size + 2 != buf.size()) + throw Decoding_Error("Client_Key_Exchange: Packet corrupted"); + + key_material.set(buf + 2, size); + } + else + key_material = buf; + } + +/** +* Return the pre_master_secret +*/ +SecureVector<byte> +Client_Key_Exchange::pre_master_secret(RandomNumberGenerator& rng, + const PKCS8_PrivateKey* priv_key, + Version_Code version) + { + const DH_PrivateKey* dh_priv = dynamic_cast<const DH_PrivateKey*>(priv_key); + const RSA_PrivateKey* rsa_priv = + dynamic_cast<const RSA_PrivateKey*>(priv_key); + + if(dh_priv) + { + try { + pre_master = dh_priv->derive_key(key_material, key_material.size()); + } + catch(std::exception& e) + { + pre_master.resize(dh_priv->public_value().size()); + rng.randomize(pre_master, pre_master.size()); + } + + return pre_master; + } + else if(rsa_priv) + { + std::auto_ptr<PK_Decryptor> decryptor(get_pk_decryptor(*rsa_priv, + "PKCS1v15")); + + try { + pre_master = decryptor->decrypt(key_material); + + if(pre_master.size() != 48 || + make_u16bit(pre_master[0], pre_master[1]) != version) + throw Decoding_Error("Client_Key_Exchange: Secret corrupted"); + } + catch(std::exception) + { + pre_master.resize(48); + rng.randomize(pre_master, pre_master.size()); + pre_master[0] = (version >> 8) & 0xFF; + pre_master[1] = (version ) & 0xFF; + } + + return pre_master; + } + else + throw Invalid_Argument("Client_Key_Exchange: Bad key for decrypt"); + } + +/** +* Return the pre_master_secret +*/ +SecureVector<byte> Client_Key_Exchange::pre_master_secret() const + { + return pre_master; + } + +} diff --git a/src/ssl/cert_req.cpp b/src/ssl/cert_req.cpp new file mode 100644 index 000000000..fcd161c95 --- /dev/null +++ b/src/ssl/cert_req.cpp @@ -0,0 +1,156 @@ +/** +* Certificate Request Message Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_messages.h> +#include <botan/der_enc.h> +#include <botan/ber_dec.h> +#include <botan/loadstor.h> +#include <botan/secqueue.h> + +namespace Botan { + +/** +* Create a new Certificate Request message +*/ +Certificate_Req::Certificate_Req(Record_Writer& writer, + HandshakeHash& hash, + const std::vector<X509_Certificate>& certs) + { + for(u32bit j = 0; j != certs.size(); j++) + names.push_back(certs[j].subject_dn()); + + // FIXME: should be able to choose what to ask for + types.push_back(RSA_CERT); + types.push_back(DSS_CERT); + + send(writer, hash); + } + +/** +* Serialize a Certificate Request message +*/ +SecureVector<byte> Certificate_Req::serialize() const + { + SecureVector<byte> buf; + + buf.append(types.size()); + for(u32bit j = 0; j != types.size(); j++) + buf.append(types[j]); + + DER_Encoder encoder; + for(u32bit j = 0; j != names.size(); j++) + encoder.encode(names[j]); + + SecureVector<byte> der_names = encoder.get_contents(); + u16bit names_size = der_names.size(); + + buf.append(get_byte(0, names_size)); + buf.append(get_byte(1, names_size)); + buf.append(der_names); + + return buf; + } + +/** +* Deserialize a Certificate Request message +*/ +void Certificate_Req::deserialize(const MemoryRegion<byte>& buf) + { + if(buf.size() < 4) + throw Decoding_Error("Certificate_Req: Bad certificate request"); + + u32bit types_size = buf[0]; + + if(buf.size() < types_size + 3) + throw Decoding_Error("Certificate_Req: Bad certificate request"); + + for(u32bit j = 0; j != types_size; j++) + types.push_back(static_cast<Certificate_Type>(buf[j+1])); + + u32bit names_size = make_u16bit(buf[types_size+2], buf[types_size+3]); + + if(buf.size() != names_size + types_size + 3) + throw Decoding_Error("Certificate_Req: Bad certificate request"); + + BER_Decoder decoder(buf.begin() + types_size + 3, names_size); + + while(decoder.more_items()) + { + X509_DN name; + decoder.decode(name); + names.push_back(name); + } + } + +/** +* Create a new Certificate message +*/ +Certificate::Certificate(Record_Writer& writer, + const std::vector<X509_Certificate>& cert_list, + HandshakeHash& hash) + { + certs = cert_list; + send(writer, hash); + } + +/** +* Serialize a Certificate message +*/ +SecureVector<byte> Certificate::serialize() const + { + SecureVector<byte> buf(3); + + for(u32bit j = 0; j != certs.size(); j++) + { + SecureVector<byte> raw_cert = certs[j].BER_encode(); + u32bit cert_size = raw_cert.size(); + for(u32bit j = 0; j != 3; j++) + buf.append(get_byte(j+1, cert_size)); + buf.append(raw_cert); + } + + u32bit buf_size = buf.size() - 3; + for(u32bit j = 0; j != 3; j++) + buf[j] = get_byte(j+1, buf_size); + + return buf; + } + +/** +* Deserialize a Certificate message +*/ +void Certificate::deserialize(const MemoryRegion<byte>& buf) + { + if(buf.size() < 3) + throw Decoding_Error("Certificate: Message malformed"); + + u32bit total_size = make_u32bit(0, buf[0], buf[1], buf[2]); + + SecureQueue queue; + queue.write(buf + 3, buf.size() - 3); + + if(queue.size() != total_size) + throw Decoding_Error("Certificate: Message malformed"); + + while(queue.size()) + { + if(queue.size() < 3) + throw Decoding_Error("Certificate: Message malformed"); + + byte len[3]; + queue.read(len, 3); + u32bit cert_size = make_u32bit(0, len[0], len[1], len[2]); + + u32bit original_size = queue.size(); + X509_Certificate cert(queue); + if(queue.size() + cert_size != original_size) + throw Decoding_Error("Certificate: Message malformed"); + certs.push_back(cert); + } + } + +} diff --git a/src/ssl/cert_ver.cpp b/src/ssl/cert_ver.cpp new file mode 100644 index 000000000..3ea6db685 --- /dev/null +++ b/src/ssl/cert_ver.cpp @@ -0,0 +1,109 @@ +/** +* Certificate Verify Message Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_messages.h> +#include <botan/look_pk.h> +#include <botan/loadstor.h> +#include <botan/rsa.h> +#include <botan/dsa.h> +#include <memory> + +namespace Botan { + +/** +* Create a new Certificate Verify message +*/ +Certificate_Verify::Certificate_Verify(RandomNumberGenerator& rng, + Record_Writer& writer, + HandshakeHash& hash, + const PKCS8_PrivateKey* priv_key) + { + const PK_Signing_Key* sign_key = + dynamic_cast<const PK_Signing_Key*>(priv_key); + + if(sign_key) + { + PK_Signer* signer = 0; + try + { + if(dynamic_cast<const RSA_PrivateKey*>(sign_key)) + signer = get_pk_signer(*sign_key, "EMSA3(TLS.Digest.0)"); + else if(dynamic_cast<const DSA_PrivateKey*>(sign_key)) + signer = get_pk_signer(*sign_key, "EMSA1(SHA-1)"); + else + throw Invalid_Argument("Unknown PK algo for TLS signature"); + + signature = signer->sign_message(hash.final(), rng); + delete signer; + } + catch(...) + { + delete signer; + throw; + } + + send(writer, hash); + } + } + +/** +* Serialize a Certificate Verify message +*/ +SecureVector<byte> Certificate_Verify::serialize() const + { + SecureVector<byte> buf; + + u16bit sig_len = signature.size(); + buf.append(get_byte(0, sig_len)); + buf.append(get_byte(1, sig_len)); + buf.append(signature); + + return buf; + } + +/** +* Deserialize a Certificate Verify message +*/ +void Certificate_Verify::deserialize(const MemoryRegion<byte>& buf) + { + if(buf.size() < 2) + throw Decoding_Error("Certificate_Verify: Corrupted packet"); + + u32bit sig_len = make_u16bit(buf[0], buf[1]); + if(buf.size() != 2 + sig_len) + throw Decoding_Error("Certificate_Verify: Corrupted packet"); + + signature.set(buf + 2, sig_len); + } + +/** +* Verify a Certificate Verify message +*/ +bool Certificate_Verify::verify(const X509_Certificate& cert, + HandshakeHash& hash) + { + // FIXME: duplicate of Server_Key_Exchange::verify + + std::auto_ptr<X509_PublicKey> key(cert.subject_public_key()); + + DSA_PublicKey* dsa_pub = dynamic_cast<DSA_PublicKey*>(key.get()); + RSA_PublicKey* rsa_pub = dynamic_cast<RSA_PublicKey*>(key.get()); + + std::auto_ptr<PK_Verifier> verifier; + + if(dsa_pub) + verifier.reset(get_pk_verifier(*dsa_pub, "EMSA1(SHA-1)", DER_SEQUENCE)); + else if(rsa_pub) + verifier.reset(get_pk_verifier(*rsa_pub, "EMSA3(TLS.Digest.0)")); + else + throw Invalid_Argument("Client did not provide a RSA/DSA cert"); + + // FIXME: WRONG + return verifier->verify_message(hash.final(), signature); + } + +} diff --git a/src/ssl/finished.cpp b/src/ssl/finished.cpp new file mode 100644 index 000000000..91193c6be --- /dev/null +++ b/src/ssl/finished.cpp @@ -0,0 +1,100 @@ +/** +* Finished Message Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_messages.h> +#include <botan/prf_tls.h> + +namespace Botan { + +/** +* Create a new Finished message +*/ +Finished::Finished(Record_Writer& writer, + Version_Code version, Connection_Side side, + const MemoryRegion<byte>& master_secret, + HandshakeHash& hash) + { + verification_data = compute_verify(master_secret, hash, side, version); + send(writer, hash); + } + +/** +* Serialize a Finished message +*/ +SecureVector<byte> Finished::serialize() const + { + return verification_data; + } + +/** +* Deserialize a Finished message +*/ +void Finished::deserialize(const MemoryRegion<byte>& buf) + { + verification_data = buf; + } + +/** +* Verify a Finished message +*/ +bool Finished::verify(const MemoryRegion<byte>& secret, Version_Code version, + const HandshakeHash& hash, Connection_Side side) + { + SecureVector<byte> computed = compute_verify(secret, hash, side, version); + if(computed == verification_data) + return true; + return false; + } + +/** +* Compute the verify_data +*/ +SecureVector<byte> Finished::compute_verify(const MemoryRegion<byte>& secret, + HandshakeHash hash, + Connection_Side side, + Version_Code version) + { + if(version == SSL_V3) + { + const byte SSL_CLIENT_LABEL[] = { 0x43, 0x4C, 0x4E, 0x54 }; + const byte SSL_SERVER_LABEL[] = { 0x53, 0x52, 0x56, 0x52 }; + + SecureVector<byte> ssl3_finished; + + if(side == CLIENT) + hash.update(SSL_CLIENT_LABEL, sizeof(SSL_CLIENT_LABEL)); + else + hash.update(SSL_SERVER_LABEL, sizeof(SSL_SERVER_LABEL)); + + return hash.final_ssl3(secret); + } + else if(version == TLS_V10) + { + const byte TLS_CLIENT_LABEL[] = { + 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x20, 0x66, 0x69, 0x6E, 0x69, + 0x73, 0x68, 0x65, 0x64 }; + + const byte TLS_SERVER_LABEL[] = { + 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x66, 0x69, 0x6E, 0x69, + 0x73, 0x68, 0x65, 0x64 }; + + TLS_PRF prf; + + SecureVector<byte> input; + if(side == CLIENT) + input.append(TLS_CLIENT_LABEL, sizeof(TLS_CLIENT_LABEL)); + else + input.append(TLS_SERVER_LABEL, sizeof(TLS_SERVER_LABEL)); + input.append(hash.final()); + + return prf.derive_key(12, secret, input); + } + else + throw Invalid_Argument("Finished message: Unknown protocol version"); + } + +} diff --git a/src/ssl/handshake_hash.cpp b/src/ssl/handshake_hash.cpp new file mode 100644 index 000000000..9690a0edb --- /dev/null +++ b/src/ssl/handshake_hash.cpp @@ -0,0 +1,60 @@ +/** +* TLS Handshake Hash Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/handshake_hash.h> +#include <botan/md5.h> +#include <botan/sha160.h> +#include <memory> + +namespace Botan { + +/** +* Return a TLS Handshake Hash +*/ +SecureVector<byte> HandshakeHash::final() + { + MD5 md5; + SHA_160 sha1; + + md5.update(data); + sha1.update(data); + + return SecureVector<byte>(md5.final(), sha1.final()); + } + +/** +* Return a SSLv3 Handshake Hash +*/ +SecureVector<byte> HandshakeHash::final_ssl3(const MemoryRegion<byte>& secret) + { + const byte PAD_INNER = 0x36, PAD_OUTER = 0x5C; + + MD5 md5; + SHA_160 sha1; + + md5.update(data); + sha1.update(data); + + md5.update(secret); + sha1.update(secret); + + for(u32bit j = 0; j != 48; j++) md5.update(PAD_INNER); + for(u32bit j = 0; j != 40; j++) sha1.update(PAD_INNER); + + SecureVector<byte> inner_md5 = md5.final(), inner_sha1 = sha1.final(); + + md5.update(secret); + sha1.update(secret); + for(u32bit j = 0; j != 48; j++) md5.update(PAD_OUTER); + for(u32bit j = 0; j != 40; j++) sha1.update(PAD_OUTER); + md5.update(inner_md5); + sha1.update(inner_sha1); + + return SecureVector<byte>(md5.final(), sha1.final()); + } + +} diff --git a/src/ssl/handshake_hash.h b/src/ssl/handshake_hash.h new file mode 100644 index 000000000..4e7c1f528 --- /dev/null +++ b/src/ssl/handshake_hash.h @@ -0,0 +1,38 @@ +/** +* TLS Handshake Hash Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_HANDSHAKE_HASH__ +#define BOTAN_HANDSHAKE_HASH__ + +#include <botan/secmem.h> + +namespace Botan { + +using namespace Botan; + +/** +* TLS Handshake Hash +*/ +class BOTAN_DLL HandshakeHash + { + public: + void update(const byte in[], u32bit length) + { data.append(in, length); } + void update(const MemoryRegion<byte>& in) + { update(in.begin(), in.size()); } + void update(byte in) + { update(&in, 1); } + + SecureVector<byte> final(); + SecureVector<byte> final_ssl3(const MemoryRegion<byte>&); + private: + SecureVector<byte> data; + }; + +} + +#endif diff --git a/src/ssl/handshake_state.cpp b/src/ssl/handshake_state.cpp new file mode 100644 index 000000000..82d901921 --- /dev/null +++ b/src/ssl/handshake_state.cpp @@ -0,0 +1,59 @@ +/** +* TLS Handshaking Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_state.h> + +namespace Botan { + +/** +* Initialize the SSL/TLS Handshake State +*/ +Handshake_State::Handshake_State() + { + client_hello = 0; + server_hello = 0; + server_certs = 0; + server_kex = 0; + cert_req = 0; + server_hello_done = 0; + + client_certs = 0; + client_kex = 0; + client_verify = 0; + client_finished = 0; + server_finished = 0; + + kex_pub = 0; + kex_priv = 0; + + do_client_auth = got_client_ccs = got_server_ccs = false; + version = SSL_V3; + } + +/** +* Destroy the SSL/TLS Handshake State +*/ +Handshake_State::~Handshake_State() + { + delete client_hello; + delete server_hello; + delete server_certs; + delete server_kex; + delete cert_req; + delete server_hello_done; + + delete client_certs; + delete client_kex; + delete client_verify; + delete client_finished; + delete server_finished; + + delete kex_pub; + delete kex_priv; + } + +} diff --git a/src/ssl/hello.cpp b/src/ssl/hello.cpp new file mode 100644 index 000000000..ba30ec5f7 --- /dev/null +++ b/src/ssl/hello.cpp @@ -0,0 +1,267 @@ +/** +* TLS Hello Messages +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_messages.h> +#include <botan/tls_exceptn.h> +#include <botan/loadstor.h> +#include <botan/exceptn.h> + +namespace Botan { + +/** +* Encode and send a Handshake message +*/ +void HandshakeMessage::send(Record_Writer& writer, HandshakeHash& hash) const + { + SecureVector<byte> buf = serialize(); + SecureVector<byte> send_buf(4); + + u32bit buf_size = buf.size(); + + send_buf[0] = type(); + send_buf[1] = get_byte(1, buf_size); + send_buf[2] = get_byte(2, buf_size); + send_buf[3] = get_byte(3, buf_size); + + send_buf.append(buf); + + hash.update(send_buf); + + writer.send(HANDSHAKE, send_buf, send_buf.size()); + writer.flush(); + } + +/** +* Create a new Hello Request message +*/ +Hello_Request::Hello_Request(Record_Writer& writer) + { + HandshakeHash dummy; // FIXME: *UGLY* + send(writer, dummy); + } + +/** +* Serialize a Hello Request message +*/ +SecureVector<byte> Hello_Request::serialize() const + { + return SecureVector<byte>(); + } + +/** +* Deserialize a Hello Request message +*/ +void Hello_Request::deserialize(const MemoryRegion<byte>& buf) + { + if(buf.size()) + throw Decoding_Error("Hello_Request: Must be empty, and is not"); + } + +/** +* Create a new Client Hello message +*/ +Client_Hello::Client_Hello(RandomNumberGenerator& rng, + Record_Writer& writer, const Policy* policy, + HandshakeHash& hash) + { + c_random.resize(32); + rng.randomize(c_random, c_random.size()); + + suites = policy->ciphersuites(); + comp_algos = policy->compression(); + c_version = policy->pref_version(); + + send(writer, hash); + } + +/** +* Serialize a Client Hello message +*/ +SecureVector<byte> Client_Hello::serialize() const + { + SecureVector<byte> buf; + + buf.append(static_cast<byte>(c_version >> 8)); + buf.append(static_cast<byte>(c_version )); + buf.append(c_random); + buf.append(static_cast<byte>(sess_id.size())); + buf.append(sess_id); + + u16bit suites_size = 2*suites.size(); + + buf.append(get_byte(0, suites_size)); + buf.append(get_byte(1, suites_size)); + for(u32bit j = 0; j != suites.size(); j++) + { + buf.append(get_byte(0, suites[j])); + buf.append(get_byte(1, suites[j])); + } + + buf.append(static_cast<byte>(comp_algos.size())); + for(u32bit j = 0; j != comp_algos.size(); j++) + buf.append(comp_algos[j]); + + return buf; + } + +/** +* Deserialize a Client Hello message +*/ +void Client_Hello::deserialize(const MemoryRegion<byte>& buf) + { + if(buf.size() == 0) + throw Decoding_Error("Client_Hello: Packet corrupted"); + + if(buf.size() < 41) + throw Decoding_Error("Client_Hello: Packet corrupted"); + + c_version = static_cast<Version_Code>(make_u16bit(buf[0], buf[1])); + if(c_version != SSL_V3 && c_version != TLS_V10) + throw TLS_Exception(PROTOCOL_VERSION, "Client_Hello: Bad version code"); + + c_random.set(buf + 2, 32); + + u32bit session_id_len = buf[34]; + if(session_id_len > 32 || session_id_len + 41 > buf.size()) + throw Decoding_Error("Client_Hello: Packet corrupted"); + sess_id.copy(buf + 35, session_id_len); + + u32bit offset = 2+32+1+session_id_len; + + u16bit suites_size = make_u16bit(buf[offset], buf[offset+1]); + offset += 2; + if(suites_size % 2 == 1 || offset + suites_size + 2 > buf.size()) + throw Decoding_Error("Client_Hello: Packet corrupted"); + + for(u32bit j = 0; j != suites_size; j += 2) + { + u16bit suite = make_u16bit(buf[offset+j], buf[offset+j+1]); + suites.push_back(suite); + } + offset += suites_size; + + byte comp_algo_size = buf[offset]; + offset += 1; + if(offset + comp_algo_size > buf.size()) + throw Decoding_Error("Client_Hello: Packet corrupted"); + + for(u32bit j = 0; j != comp_algo_size; j++) + comp_algos.push_back(buf[offset+j]); + } + +/** +* Check if we offered this ciphersuite +*/ +bool Client_Hello::offered_suite(u16bit ciphersuite) const + { + for(u32bit j = 0; j != suites.size(); j++) + if(suites[j] == ciphersuite) + return true; + return false; + } + +/** +* Create a new Server Hello message +*/ +Server_Hello::Server_Hello(RandomNumberGenerator& rng, + Record_Writer& writer, const Policy* policy, + const std::vector<X509_Certificate>& certs, + const Client_Hello& c_hello, Version_Code ver, + HandshakeHash& hash) + { + bool have_rsa = false, have_dsa = false; + for(u32bit j = 0; j != certs.size(); j++) + { + X509_PublicKey* key = certs[j].subject_public_key(); + if(key->algo_name() == "RSA") have_rsa = true; + if(key->algo_name() == "DSA") have_dsa = true; + } + + suite = policy->choose_suite(c_hello.ciphersuites(), have_rsa, have_dsa); + comp_algo = policy->choose_compression(c_hello.compression_algos()); + + s_version = ver; + s_random.resize(32); + rng.randomize(s_random, s_random.size()); + + send(writer, hash); + } + +/** +* Serialize a Server Hello message +*/ +SecureVector<byte> Server_Hello::serialize() const + { + SecureVector<byte> buf; + + buf.append(static_cast<byte>(s_version >> 8)); + buf.append(static_cast<byte>(s_version )); + buf.append(s_random); + buf.append(static_cast<byte>(sess_id.size())); + buf.append(sess_id); + + buf.append(get_byte(0, suite)); + buf.append(get_byte(1, suite)); + + buf.append(comp_algo); + + return buf; + } + +/** +* Deserialize a Server Hello message +*/ +void Server_Hello::deserialize(const MemoryRegion<byte>& buf) + { + if(buf.size() < 38) + throw Decoding_Error("Server_Hello: Packet corrupted"); + + s_version = static_cast<Version_Code>(make_u16bit(buf[0], buf[1])); + if(s_version != SSL_V3 && s_version != TLS_V10) + throw TLS_Exception(PROTOCOL_VERSION, + "Server_Hello: Unsupported server version"); + + s_random.set(buf + 2, 32); + + u32bit session_id_len = buf[2+32]; + if(session_id_len > 32 || session_id_len + 38 != buf.size()) + throw Decoding_Error("Server_Hello: Packet corrupted"); + sess_id.copy(buf + 2 + 32 + 1, session_id_len); + + suite = make_u16bit(buf[2+32+1+session_id_len], + buf[2+32+1+session_id_len+1]); + comp_algo = buf[2+32+1+session_id_len+2]; + } + + +/** +* Create a new Server Hello Done message +*/ +Server_Hello_Done::Server_Hello_Done(Record_Writer& writer, + HandshakeHash& hash) + { + send(writer, hash); + } + +/** +* Serialize a Server Hello Done message +*/ +SecureVector<byte> Server_Hello_Done::serialize() const + { + return SecureVector<byte>(); + } + +/** +* Deserialize a Server Hello Done message +*/ +void Server_Hello_Done::deserialize(const MemoryRegion<byte>& buf) + { + if(buf.size()) + throw Decoding_Error("Server_Hello_Done: Must be empty, and is not"); + } + +} diff --git a/src/ssl/info.txt b/src/ssl/info.txt new file mode 100644 index 000000000..73e4207d8 --- /dev/null +++ b/src/ssl/info.txt @@ -0,0 +1 @@ +define SSL_TLS diff --git a/src/ssl/rec_read.cpp b/src/ssl/rec_read.cpp new file mode 100644 index 000000000..f6cedb2b7 --- /dev/null +++ b/src/ssl/rec_read.cpp @@ -0,0 +1,204 @@ +/** +* TLS Record Reading Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_record.h> +#include <botan/tls_exceptn.h> +#include <botan/loadstor.h> +#include <botan/lookup.h> + +namespace Botan { + +/** +* Record_Reader Constructor +*/ +Record_Reader::Record_Reader(Socket& sock) : socket(sock) + { + reset(); + } + +/** +* Reset the state +*/ +void Record_Reader::reset() + { + compress.reset(); + cipher.reset(); + mac.reset(); + do_compress = false; + mac_size = pad_amount = 0; + major = minor = 0; + seq_no = 0; + } + +/** +* Set the version to use +*/ +void Record_Reader::set_version(Version_Code version) + { + if(version != SSL_V3 && version != TLS_V10) + throw Invalid_Argument("Record_Reader: Invalid protocol version"); + + major = (version >> 8) & 0xFF; + minor = (version & 0xFF); + } + +/** +* Set the compression algorithm +*/ +void Record_Reader::set_compressor(Filter* compressor) + { + compress.append(compressor); + do_compress = true; + } + +/** +* Set the keys for reading +*/ +void Record_Reader::set_keys(const CipherSuite& suite, const SessionKeys& keys, + Connection_Side side) + { + cipher.reset(); + mac.reset(); + + SymmetricKey mac_key, cipher_key; + InitializationVector iv; + + if(side == CLIENT) + { + cipher_key = keys.server_cipher_key(); + iv = keys.server_iv(); + mac_key = keys.server_mac_key(); + } + else + { + cipher_key = keys.client_cipher_key(); + iv = keys.client_iv(); + mac_key = keys.client_mac_key(); + } + + const std::string cipher_algo = suite.cipher_algo(); + const std::string mac_algo = suite.mac_algo(); + + if(have_block_cipher(cipher_algo)) + { + cipher.append(get_cipher( + cipher_algo + "/CBC/NoPadding", + cipher_key, iv, DECRYPTION) + ); + pad_amount = block_size_of(cipher_algo); + } + else if(have_stream_cipher(cipher_algo)) + { + cipher.append(get_cipher(cipher_algo, cipher_key, DECRYPTION)); + pad_amount = 0; + } + else + throw Invalid_Argument("Record_Reader: Unknown cipher " + cipher_algo); + + if(have_hash(mac_algo)) + { + if(major == 3 && minor == 0) + mac.append(new MAC_Filter("SSL3-MAC(" + mac_algo + ")", mac_key)); + else + mac.append(new MAC_Filter("HMAC(" + mac_algo + ")", mac_key)); + + mac_size = output_length_of(mac_algo); + } + else + throw Invalid_Argument("Record_Reader: Unknown hash " + mac_algo); + } + +/** +* Retrieve the next record +*/ +SecureVector<byte> Record_Reader::get_record(byte& msg_type) + { + byte header[5] = { 0 }; + + u32bit got = socket.read(header, sizeof(header)); + + if(got == 0) + { + msg_type = CONNECTION_CLOSED; + return SecureVector<byte>(); + } + else if(got != sizeof(header)) + throw Decoding_Error("Record_Reader: Record truncated"); + + msg_type = header[0]; + + const u16bit version = make_u16bit(header[1], header[2]); + + if(major && (header[1] != major || header[2] != minor)) + throw TLS_Exception(PROTOCOL_VERSION, + "Record_Reader: Got unexpected version"); + + SecureVector<byte> buffer(make_u16bit(header[3], header[4])); + if(socket.read(buffer, buffer.size()) != buffer.size()) + throw Decoding_Error("Record_Reader: Record truncated"); + + if(mac_size == 0) + return buffer; + + cipher.process_msg(buffer); + SecureVector<byte> plaintext = cipher.read_all(Pipe::LAST_MESSAGE); + + u32bit pad_size = 0; + if(pad_amount) + { + byte pad_value = plaintext[plaintext.size()-1]; + pad_size = pad_value + 1; + + if(version == SSL_V3) + { + if(pad_value > pad_amount) + throw TLS_Exception(BAD_RECORD_MAC, + "Record_Reader: Bad padding"); + } + else + { + for(u32bit j = 0; j != pad_size; j++) + if(plaintext[plaintext.size()-j-1] != pad_value) + throw TLS_Exception(BAD_RECORD_MAC, + "Record_Reader: Bad padding"); + } + } + + if(plaintext.size() < mac_size + pad_size) + throw Decoding_Error("Record_Reader: Record truncated"); + + const u32bit mac_offset = plaintext.size() - (mac_size + pad_size); + SecureVector<byte> recieved_mac(plaintext.begin() + mac_offset, + mac_size); + + const u16bit plain_length = plaintext.size() - (mac_size + pad_size); + + mac.start_msg(); + for(u32bit j = 0; j != 8; j++) + mac.write(get_byte(j, seq_no)); + mac.write(msg_type); + + if(version != SSL_V3) + for(u32bit j = 0; j != 2; j++) + mac.write(get_byte(j, version)); + + for(u32bit j = 0; j != 2; j++) + mac.write(get_byte(j, plain_length)); + mac.write(plaintext, plain_length); + mac.end_msg(); + + seq_no++; + + SecureVector<byte> computed_mac = mac.read_all(Pipe::LAST_MESSAGE); + + if(recieved_mac != computed_mac) + throw TLS_Exception(BAD_RECORD_MAC, "Record_Reader: MAC failure"); + + return SecureVector<byte>(plaintext, mac_offset); + } + +} diff --git a/src/ssl/rec_wri.cpp b/src/ssl/rec_wri.cpp new file mode 100644 index 000000000..e48c9c571 --- /dev/null +++ b/src/ssl/rec_wri.cpp @@ -0,0 +1,259 @@ +/** +* TLS Record Writing Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_record.h> +#include <botan/tls_exceptn.h> +#include <botan/handshake_hash.h> +#include <botan/lookup.h> +#include <botan/loadstor.h> + +namespace Botan { + +/** +* Record_Writer Constructor +*/ +Record_Writer::Record_Writer(Socket& sock) : + socket(sock), buffer(DEFAULT_BUFFERSIZE) + { + reset(); + } + +/** +* Reset the state +*/ +void Record_Writer::reset() + { + compress.reset(); + cipher.reset(); + mac.reset(); + buffer.clear(); + do_compress = false; + major = minor = buf_type = 0; + pad_amount = mac_size = buf_pos = 0; + seq_no = 0; + } + +/** +* Set the version to use +*/ +void Record_Writer::set_version(Version_Code version) + { + if(version != SSL_V3 && version != TLS_V10) + throw Invalid_Argument("Record_Writer: Invalid protocol version"); + + major = (version >> 8) & 0xFF; + minor = (version & 0xFF); + } + +/** +* Set the compression algorithm +*/ +void Record_Writer::set_compressor(Filter* compressor) + { + throw TLS_Exception(INTERNAL_ERROR, "Compression not implemented (FIXME)"); + compress.append(compressor); + } + +/** +* Set the keys for writing +*/ +void Record_Writer::set_keys(const CipherSuite& suite, const SessionKeys& keys, + Connection_Side side) + { + cipher.reset(); + mac.reset(); + + SymmetricKey mac_key, cipher_key; + InitializationVector iv; + + if(side == CLIENT) + { + cipher_key = keys.client_cipher_key(); + iv = keys.client_iv(); + mac_key = keys.client_mac_key(); + } + else + { + cipher_key = keys.server_cipher_key(); + iv = keys.server_iv(); + mac_key = keys.server_mac_key(); + } + + const std::string cipher_algo = suite.cipher_algo(); + const std::string mac_algo = suite.mac_algo(); + + if(have_block_cipher(cipher_algo)) + { + cipher.append(get_cipher( + cipher_algo + "/CBC/NoPadding", + cipher_key, iv, ENCRYPTION) + ); + pad_amount = block_size_of(cipher_algo); + } + else if(have_stream_cipher(cipher_algo)) + { + cipher.append(get_cipher(cipher_algo, cipher_key, ENCRYPTION)); + pad_amount = 0; + } + else + throw Invalid_Argument("Record_Writer: Unknown cipher " + cipher_algo); + + if(have_hash(mac_algo)) + { + if(major == 3 && minor == 0) + mac.append(new MAC_Filter("SSL3-MAC(" + mac_algo + ")", mac_key)); + else + mac.append(new MAC_Filter("HMAC(" + mac_algo + ")", mac_key)); + + mac_size = output_length_of(mac_algo); + } + else + throw Invalid_Argument("Record_Writer: Unknown hash " + mac_algo); + } + +/** +* Send one or more records to the other side +*/ +void Record_Writer::send(byte type, byte input) + { + send(type, &input, 1); + } + +/** +* Send one or more records to the other side +*/ +void Record_Writer::send(byte type, const byte input[], u32bit length) + { + if(type != buf_type) + flush(); + + const u32bit BUFFER_SIZE = buffer.size(); + buf_type = type; + + // FIXME: compression right here + + buffer.copy(buf_pos, input, length); + if(buf_pos + length >= BUFFER_SIZE) + { + send_record(buf_type, buffer, length); + input += (BUFFER_SIZE - buf_pos); + length -= (BUFFER_SIZE - buf_pos); + while(length >= BUFFER_SIZE) + { + send_record(buf_type, input, BUFFER_SIZE); + input += BUFFER_SIZE; + length -= BUFFER_SIZE; + } + buffer.copy(input, length); + buf_pos = 0; + } + buf_pos += length; + } + +/** +* Split buffer into records, and send them all +*/ +void Record_Writer::flush() + { + const byte* buf_ptr = buffer.begin(); + u32bit offset = 0; + + while(offset != buf_pos) + { + u32bit record_size = buf_pos - offset; + if(record_size > MAX_PLAINTEXT_SIZE) + record_size = MAX_PLAINTEXT_SIZE; + + send_record(buf_type, buf_ptr + offset, record_size); + offset += record_size; + } + buf_type = 0; + buf_pos = 0; + } + +/** +* Encrypt and send the record +*/ +void Record_Writer::send_record(byte type, const byte buf[], u32bit length) + { + if(length >= MAX_COMPRESSED_SIZE) + throw TLS_Exception(INTERNAL_ERROR, + "Record_Writer: Compressed packet is too big"); + + if(mac_size == 0) + send_record(type, major, minor, buf, length); + else + { + mac.start_msg(); + for(u32bit j = 0; j != 8; j++) + mac.write(get_byte(j, seq_no)); + mac.write(type); + + if(major > 3 || (major == 3 && minor != 0)) + { + mac.write(major); + mac.write(minor); + } + + mac.write(get_byte(2, length)); + mac.write(get_byte(3, length)); + mac.write(buf, length); + mac.end_msg(); + + SecureVector<byte> buf_mac = mac.read_all(Pipe::LAST_MESSAGE); + + cipher.start_msg(); + cipher.write(buf, length); + cipher.write(buf_mac); + if(pad_amount) + { + u32bit pad_val = + (pad_amount - (1 + length + buf_mac.size())) % pad_amount; + + for(u32bit j = 0; j != pad_val + 1; j++) + cipher.write(pad_val); + } + cipher.end_msg(); + + SecureVector<byte> output = cipher.read_all(Pipe::LAST_MESSAGE); + + send_record(type, major, minor, output, output.size()); + + seq_no++; + } + } + +/** +* Send a final record packet +*/ +void Record_Writer::send_record(byte type, byte major, byte minor, + const byte out[], u32bit length) + { + if(length >= MAX_CIPHERTEXT_SIZE) + throw TLS_Exception(INTERNAL_ERROR, + "Record_Writer: Record is too big"); + + byte header[5] = { type, major, minor, 0 }; + for(u32bit j = 0; j != 2; j++) + header[j+3] = get_byte<u16bit>(j, length); + + // FIXME: tradoff of TCP/syscall overhead vs copy overhead + socket.write(header, 5); + socket.write(out, length); + } + +/** +* Send an alert +*/ +void Record_Writer::alert(Alert_Level level, Alert_Type type) + { + byte alert[2] = { level, type }; + send(ALERT, alert, sizeof(alert)); + flush(); + } + +} diff --git a/src/ssl/s_kex.cpp b/src/ssl/s_kex.cpp new file mode 100644 index 000000000..e1decfe84 --- /dev/null +++ b/src/ssl/s_kex.cpp @@ -0,0 +1,195 @@ +/** +* Server Key Exchange Message Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_messages.h> +#include <botan/dh.h> +#include <botan/rsa.h> +#include <botan/dsa.h> +#include <botan/look_pk.h> +#include <botan/loadstor.h> +#include <memory> + +namespace Botan { + +/** +* Create a new Server Key Exchange message +*/ +Server_Key_Exchange::Server_Key_Exchange(RandomNumberGenerator& rng, + Record_Writer& writer, + const X509_PublicKey* kex_key, + const PKCS8_PrivateKey* priv_key, + const MemoryRegion<byte>& c_random, + const MemoryRegion<byte>& s_random, + HandshakeHash& hash) + { + const DH_PublicKey* dh_pub = dynamic_cast<const DH_PublicKey*>(kex_key); + const RSA_PublicKey* rsa_pub = dynamic_cast<const RSA_PublicKey*>(kex_key); + + if(dh_pub) + { + params.push_back(dh_pub->get_domain().get_p()); + params.push_back(dh_pub->get_domain().get_g()); + params.push_back(BigInt::decode(dh_pub->public_value())); + } + else if(rsa_pub) + { + params.push_back(rsa_pub->get_n()); + params.push_back(rsa_pub->get_e()); + } + else + throw Invalid_Argument("Bad key for TLS key exchange: not DH or RSA"); + + // FIXME: dup of stuff in cert_ver.cpp + // FIXME: it's OK for the server to be anonymous.... + const PK_Signing_Key* sign_key = + dynamic_cast<const PK_Signing_Key*>(priv_key); + + if(!sign_key) + throw Invalid_Argument("Server Kex: Private key not for signing"); + + PK_Signer* signer = 0; + try { + if(dynamic_cast<const RSA_PrivateKey*>(sign_key)) + signer = get_pk_signer(*sign_key, "EMSA3(TLS.Digest.0)"); + else if(dynamic_cast<const DSA_PrivateKey*>(sign_key)) + { + signer = get_pk_signer(*sign_key, "EMSA1(SHA-1)"); + signer->set_output_format(DER_SEQUENCE); + } + else + throw Invalid_Argument("Bad key for TLS signature: not RSA or DSA"); + + signer->update(c_random); + signer->update(s_random); + signer->update(serialize_params()); + signature = signer->signature(rng); + + delete signer; + } + catch(...) + { + delete signer; + throw; + } + + send(writer, hash); + } + +/** +* Serialize a Server Key Exchange message +*/ +SecureVector<byte> Server_Key_Exchange::serialize() const + { + SecureVector<byte> buf = serialize_params(); + u16bit sig_len = signature.size(); + buf.append(get_byte(0, sig_len)); + buf.append(get_byte(1, sig_len)); + buf.append(signature); + return buf; + } + +/** +* Serialize the ServerParams structure +*/ +SecureVector<byte> Server_Key_Exchange::serialize_params() const + { + SecureVector<byte> buf; + for(u32bit j = 0; j != params.size(); j++) + { + SecureVector<byte> param = BigInt::encode(params[j]); + u16bit param_size = param.size(); + + buf.append(get_byte(0, param_size)); + buf.append(get_byte(1, param_size)); + buf.append(param); + } + return buf; + } + +/** +* Deserialize a Server Key Exchange message +*/ +void Server_Key_Exchange::deserialize(const MemoryRegion<byte>& buf) + { + if(buf.size() < 6) + throw Decoding_Error("Server_Key_Exchange: Packet corrupted"); + + SecureVector<byte> values[4]; + u32bit so_far = 0; + + for(u32bit j = 0; j != 4; j++) + { + u16bit len = make_u16bit(buf[so_far], buf[so_far+1]); + so_far += 2; + + if(len + so_far > buf.size()) + throw Decoding_Error("Server_Key_Exchange: Packet corrupted"); + + values[j].set(buf + so_far, len); + so_far += len; + + if(j == 2 && so_far == buf.size()) + break; + } + + params.push_back(BigInt::decode(values[0])); + params.push_back(BigInt::decode(values[1])); + if(values[3].size()) + { + params.push_back(BigInt::decode(values[2])); + signature = values[3]; + } + else + signature = values[2]; + } + +/** +* Return the public key +*/ +X509_PublicKey* Server_Key_Exchange::key() const + { + if(params.size() == 2) + return new RSA_PublicKey(params[0], params[1]); + else if(params.size() == 3) + return new DH_PublicKey(DL_Group(params[0], params[1]), params[2]); + else + throw Internal_Error("Server_Key_Exchange::key: No key set"); + } + +/** +* Verify a Server Key Exchange message +*/ +bool Server_Key_Exchange::verify(const X509_Certificate& cert, + const MemoryRegion<byte>& c_random, + const MemoryRegion<byte>& s_random) const + { + std::auto_ptr<X509_PublicKey> key(cert.subject_public_key()); + + DSA_PublicKey* dsa_pub = dynamic_cast<DSA_PublicKey*>(key.get()); + RSA_PublicKey* rsa_pub = dynamic_cast<RSA_PublicKey*>(key.get()); + + std::auto_ptr<PK_Verifier> verifier; + + if(dsa_pub) + { + verifier.reset(get_pk_verifier(*dsa_pub, "EMSA1(SHA-1)", DER_SEQUENCE)); + verifier->set_input_format(DER_SEQUENCE); + } + else if(rsa_pub) + verifier.reset(get_pk_verifier(*rsa_pub, "EMSA3(TLS.Digest.0)")); + else + throw Invalid_Argument("Server did not provide a RSA/DSA cert"); + + SecureVector<byte> params_got = serialize_params(); + verifier->update(c_random); + verifier->update(s_random); + verifier->update(params_got); + + return verifier->check_signature(signature, signature.size()); + } + +} diff --git a/src/ssl/socket.h b/src/ssl/socket.h new file mode 100644 index 000000000..ca358919c --- /dev/null +++ b/src/ssl/socket.h @@ -0,0 +1,49 @@ +/** +* Socket Interface Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_SOCKET_H__ +#define BOTAN_SOCKET_H__ + +#include <botan/types.h> +#include <string> + +namespace Botan { + +/** +* Socket Base Class +*/ +class BOTAN_DLL Socket + { + public: + virtual u32bit read(byte[], u32bit) = 0; + virtual void write(const byte[], u32bit) = 0; + + u32bit read(byte& x) { return read(&x, 1); } + void write(byte x) { write(&x, 1); } + + virtual std::string peer_id() const = 0; + + virtual void close() = 0; + + virtual ~Socket() {} + }; + +/** +* Server Socket Base Class +*/ +class BOTAN_DLL Server_Socket + { + public: + virtual Socket* accept() = 0; + virtual void close() = 0; + + virtual ~Server_Socket() {} + }; + +} + +#endif diff --git a/src/ssl/tls_alerts.h b/src/ssl/tls_alerts.h new file mode 100644 index 000000000..9051e052f --- /dev/null +++ b/src/ssl/tls_alerts.h @@ -0,0 +1,46 @@ +/** +* Alert Message Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_ALERT_H__ +#define BOTAN_ALERT_H__ + +#include <botan/exceptn.h> + +namespace Botan { + +/** +* SSL/TLS Alert Message +*/ +class BOTAN_DLL Alert + { + public: + bool is_fatal() const { return fatal; } + Alert_Type type() const { return type_code; } + + /** + * Deserialize an Alert message + */ + Alert(const MemoryRegion<byte>& buf) + { + if(buf.size() != 2) + throw Decoding_Error("Alert: Bad size for alert message"); + + if(buf[0] == 1) fatal = false; + else if(buf[0] == 2) fatal = true; + else + throw Decoding_Error("Alert: Bad type code for alert level"); + + type_code = static_cast<Alert_Type>(buf[1]); + } + private: + bool fatal; + Alert_Type type_code; + }; + +} + +#endif diff --git a/src/ssl/tls_client.cpp b/src/ssl/tls_client.cpp new file mode 100644 index 000000000..e4dc90761 --- /dev/null +++ b/src/ssl/tls_client.cpp @@ -0,0 +1,574 @@ +/** +* TLS Client Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_client.h> +#include <botan/tls_alerts.h> +#include <botan/tls_state.h> +#include <botan/tls_exceptn.h> + +#include <botan/loadstor.h> + +#include <botan/rsa.h> +#include <botan/dh.h> +#include <botan/dsa.h> + +namespace Botan { + +namespace { + +// FIXME: checks are wrong for session reuse (add a flag for that) +/** +* Verify the state transition is allowed +*/ +void client_check_state(Handshake_Type new_msg, Handshake_State* state) + { + class State_Transition_Error : public Unexpected_Message + { + public: + State_Transition_Error(const std::string& err) : + Unexpected_Message("State transition error from " + err) {} + }; + + if(new_msg == HELLO_REQUEST) + { + if(state->client_hello) + throw State_Transition_Error("HelloRequest"); + } + else if(new_msg == SERVER_HELLO) + { + if(!state->client_hello || state->server_hello) + throw State_Transition_Error("ServerHello"); + } + else if(new_msg == CERTIFICATE) + { + if(!state->server_hello || state->server_kex || + state->cert_req || state->server_hello_done) + throw State_Transition_Error("ServerCertificate"); + } + else if(new_msg == SERVER_KEX) + { + if(!state->server_hello || state->server_kex || + state->cert_req || state->server_hello_done) + throw State_Transition_Error("ServerKeyExchange"); + } + else if(new_msg == CERTIFICATE_REQUEST) + { + if(!state->server_certs || state->cert_req || state->server_hello_done) + throw State_Transition_Error("CertificateRequest"); + } + else if(new_msg == SERVER_HELLO_DONE) + { + if(!state->server_hello || state->server_hello_done) + throw State_Transition_Error("ServerHelloDone"); + } + else if(new_msg == HANDSHAKE_CCS) + { + if(!state->client_finished || state->server_finished) + throw State_Transition_Error("ServerChangeCipherSpec"); + } + else if(new_msg == FINISHED) + { + if(!state->got_server_ccs) + throw State_Transition_Error("ServerFinished"); + } + else + throw Unexpected_Message("Unexpected message in handshake"); + } + +} + +/** +* TLS Client Constructor +*/ +TLS_Client::TLS_Client(RandomNumberGenerator& r, + Socket& sock, const Policy* pol) : + rng(r), writer(sock), reader(sock), policy(pol ? pol : new Policy) + { + peer_id = sock.peer_id(); + + initialize(); + } + +/** +* TLS Client Constructor +*/ +TLS_Client::TLS_Client(RandomNumberGenerator& r, + Socket& sock, const X509_Certificate& cert, + const PKCS8_PrivateKey& key, const Policy* pol) : + rng(r), writer(sock), reader(sock), policy(pol ? pol : new Policy) + { + peer_id = sock.peer_id(); + + certs.push_back(cert); + keys.push_back(PKCS8::copy_key(key, rng)); + + initialize(); + } + +/** +* TLS Client Destructor +*/ +TLS_Client::~TLS_Client() + { + close(); + for(u32bit j = 0; j != keys.size(); j++) + delete keys[j]; + delete policy; + delete state; + } + +/** +* Initialize a TLS client connection +*/ +void TLS_Client::initialize() + { + Alert_Type error_type = NO_ALERT_TYPE; + + try { + state = 0; + active = false; + writer.set_version(policy->pref_version()); + do_handshake(); + } + catch(TLS_Exception& e) + { + error_type = e.type(); + } + catch(std::exception& e) + { + error_type = HANDSHAKE_FAILURE; + } + + if(error_type != NO_ALERT_TYPE) + { + if(active) + { + active = false; + reader.reset(); + + writer.alert(FATAL, error_type); + writer.reset(); + } + + if(state) + { + delete state; + state = 0; + } + + throw Stream_IO_Error("TLS_Client: Handshake failed"); + } + } + +/** +* Return the peer's certificate chain +*/ +std::vector<X509_Certificate> TLS_Client::peer_cert_chain() const + { + return peer_certs; + } + +/** +* Write to a TLS connection +*/ +void TLS_Client::write(const byte buf[], u32bit length) + { + if(!active) + throw TLS_Exception(INTERNAL_ERROR, + "TLS_Client::write called while closed"); + + writer.send(APPLICATION_DATA, buf, length); + } + +/** +* Read from a TLS connection +*/ +u32bit TLS_Client::read(byte out[], u32bit length) + { + if(!active) + return 0; + + writer.flush(); + + while(read_buf.size() == 0) + { + state_machine(); + if(active == false) + break; + } + + u32bit got = std::min(read_buf.size(), length); + read_buf.read(out, got); + return got; + } + +/** +* Close a TLS connection +*/ +void TLS_Client::close() + { + close(WARNING, CLOSE_NOTIFY); + } + +/** +* Check connection status +*/ +bool TLS_Client::is_closed() const + { + if(!active) + return true; + return false; + } + +/** +* Close a TLS connection +*/ +void TLS_Client::close(Alert_Level level, Alert_Type alert_code) + { + if(active) + { + try { + writer.alert(level, alert_code); + writer.flush(); + } + catch(...) {} + + active = false; + } + } + +/** +* Iterate the TLS state machine +*/ +void TLS_Client::state_machine() + { + byte rec_type; + SecureVector<byte> record = reader.get_record(rec_type); + + if(rec_type == CONNECTION_CLOSED) + { + active = false; + reader.reset(); + writer.reset(); + } + else if(rec_type == APPLICATION_DATA) + { + if(active) + read_buf.write(record, record.size()); + else + throw Unexpected_Message("Application data before handshake done"); + } + else if(rec_type == HANDSHAKE || rec_type == CHANGE_CIPHER_SPEC) + read_handshake(rec_type, record); + else if(rec_type == ALERT) + { + Alert alert(record); + + if(alert.is_fatal() || alert.type() == CLOSE_NOTIFY) + { + if(alert.type() == CLOSE_NOTIFY) + writer.alert(WARNING, CLOSE_NOTIFY); + + reader.reset(); + writer.reset(); + active = false; + if(state) + { + delete state; + state = 0; + } + } + } + else + throw Unexpected_Message("Unknown message type recieved"); + } + +/** +* Split up and process handshake messages +*/ +void TLS_Client::read_handshake(byte rec_type, + const MemoryRegion<byte>& rec_buf) + { + if(rec_type == HANDSHAKE) + state->queue.write(rec_buf, rec_buf.size()); + + while(true) + { + Handshake_Type type = HANDSHAKE_NONE; + SecureVector<byte> contents; + + if(rec_type == HANDSHAKE) + { + if(state->queue.size() >= 4) + { + byte head[4] = { 0 }; + state->queue.peek(head, 4); + + const u32bit length = make_u32bit(0, head[1], head[2], head[3]); + + if(state->queue.size() >= length + 4) + { + type = static_cast<Handshake_Type>(head[0]); + contents.resize(length); + state->queue.read(head, 4); + state->queue.read(contents, contents.size()); + } + } + } + else if(rec_type == CHANGE_CIPHER_SPEC) + { + if(state->queue.size() == 0 && rec_buf.size() == 1 && rec_buf[0] == 1) + type = HANDSHAKE_CCS; + else + throw Decoding_Error("Malformed ChangeCipherSpec message"); + } + else + throw Decoding_Error("Unknown message type in handshake processing"); + + if(type == HANDSHAKE_NONE) + break; + + process_handshake_msg(type, contents); + + if(type == HANDSHAKE_CCS || !state) + break; + } + } + +/** +* Process a handshake message +*/ +void TLS_Client::process_handshake_msg(Handshake_Type type, + const MemoryRegion<byte>& contents) + { + if(type == HELLO_REQUEST) + { + if(state == 0) + state = new Handshake_State(); + else + return; + } + + if(state == 0) + throw Unexpected_Message("Unexpected handshake message"); + + if(type != HANDSHAKE_CCS && type != HELLO_REQUEST && type != FINISHED) + { + state->hash.update(static_cast<byte>(type)); + const u32bit record_length = contents.size(); + for(u32bit j = 0; j != 3; j++) + state->hash.update(get_byte(j+1, record_length)); + state->hash.update(contents); + } + + if(type == HELLO_REQUEST) + { + client_check_state(type, state); + + Hello_Request hello_request(contents); + state->client_hello = new Client_Hello(rng, writer, policy, state->hash); + } + else if(type == SERVER_HELLO) + { + client_check_state(type, state); + + state->server_hello = new Server_Hello(contents); + + if(!state->client_hello->offered_suite( + state->server_hello->ciphersuite() + ) + ) + throw TLS_Exception(HANDSHAKE_FAILURE, + "Server reply w/ bad ciphersuite"); + + state->version = state->server_hello->version(); + + if(state->version > state->client_hello->version()) + throw TLS_Exception(HANDSHAKE_FAILURE, + "Server replied with bad version"); + + if(state->version < policy->min_version()) + throw TLS_Exception(PROTOCOL_VERSION, + "Server is too old for specified policy"); + + writer.set_version(state->version); + reader.set_version(state->version); + + state->suite = CipherSuite(state->server_hello->ciphersuite()); + } + else if(type == CERTIFICATE) + { + client_check_state(type, state); + + if(state->suite.sig_type() == CipherSuite::NO_SIG) + throw Unexpected_Message("Recived certificate from anonymous server"); + + state->server_certs = new Certificate(contents); + + peer_certs = state->server_certs->cert_chain(); + if(peer_certs.size() == 0) + throw TLS_Exception(HANDSHAKE_FAILURE, + "No certificates sent by server"); + + if(!policy->check_cert(peer_certs, peer_id)) + throw TLS_Exception(BAD_CERTIFICATE, + "Server certificate is not valid"); + + state->kex_pub = peer_certs[0].subject_public_key(); + + bool is_dsa = false, is_rsa = false; + + if(dynamic_cast<DSA_PublicKey*>(state->kex_pub)) + is_dsa = true; + else if(dynamic_cast<RSA_PublicKey*>(state->kex_pub)) + is_rsa = true; + else + throw TLS_Exception(UNSUPPORTED_CERTIFICATE, + "Unknown key type recieved in server kex"); + + if((is_dsa && state->suite.sig_type() != CipherSuite::DSA_SIG) || + (is_rsa && state->suite.sig_type() != CipherSuite::RSA_SIG)) + throw TLS_Exception(ILLEGAL_PARAMETER, + "Certificate key type did not match ciphersuite"); + } + else if(type == SERVER_KEX) + { + client_check_state(type, state); + + if(state->suite.kex_type() == CipherSuite::NO_KEX) + throw Unexpected_Message("Unexpected key exchange from server"); + + state->server_kex = new Server_Key_Exchange(contents); + + if(state->kex_pub) + delete state->kex_pub; + + state->kex_pub = state->server_kex->key(); + + bool is_dh = false, is_rsa = false; + + if(dynamic_cast<DH_PublicKey*>(state->kex_pub)) + is_dh = true; + else if(dynamic_cast<RSA_PublicKey*>(state->kex_pub)) + is_rsa = true; + else + throw TLS_Exception(HANDSHAKE_FAILURE, + "Unknown key type recieved in server kex"); + + if((is_dh && state->suite.kex_type() != CipherSuite::DH_KEX) || + (is_rsa && state->suite.kex_type() != CipherSuite::RSA_KEX)) + throw TLS_Exception(ILLEGAL_PARAMETER, + "Certificate key type did not match ciphersuite"); + + if(state->suite.sig_type() != CipherSuite::NO_SIG) + { + if(!state->server_kex->verify(peer_certs[0], + state->client_hello->random(), + state->server_hello->random())) + throw TLS_Exception(DECRYPT_ERROR, + "Bad signature on server key exchange"); + } + } + else if(type == CERTIFICATE_REQUEST) + { + client_check_state(type, state); + + state->cert_req = new Certificate_Req(contents); + state->do_client_auth = true; + } + else if(type == SERVER_HELLO_DONE) + { + client_check_state(type, state); + + state->server_hello_done = new Server_Hello_Done(contents); + + if(state->do_client_auth) + { + std::vector<X509_Certificate> send_certs; + + std::vector<Certificate_Type> types = + state->cert_req->acceptable_types(); + + // FIXME: Fill in useful certs here, if any + state->client_certs = new Certificate(writer, send_certs, + state->hash); + } + + state->client_kex = + new Client_Key_Exchange(rng, writer, state->hash, + state->kex_pub, state->version, + state->client_hello->version()); + + if(state->do_client_auth) + { + PKCS8_PrivateKey* key_matching_cert = 0; // FIXME + state->client_verify = new Certificate_Verify(rng, + writer, state->hash, + key_matching_cert); + } + + state->keys = SessionKeys(state->suite, state->version, + state->client_kex->pre_master_secret(), + state->client_hello->random(), + state->server_hello->random()); + + writer.send(CHANGE_CIPHER_SPEC, 1); + writer.flush(); + + writer.set_keys(state->suite, state->keys, CLIENT); + + state->client_finished = new Finished(writer, state->version, CLIENT, + state->keys.master_secret(), + state->hash); + } + else if(type == HANDSHAKE_CCS) + { + client_check_state(type, state); + + reader.set_keys(state->suite, state->keys, CLIENT); + state->got_server_ccs = true; + } + else if(type == FINISHED) + { + client_check_state(type, state); + + state->server_finished = new Finished(contents); + + if(!state->server_finished->verify(state->keys.master_secret(), + state->version, state->hash, SERVER)) + throw TLS_Exception(DECRYPT_ERROR, + "Finished message didn't verify"); + + delete state; + state = 0; + active = true; + } + else + throw Unexpected_Message("Unknown handshake message recieved"); + } + +/** +* Perform a client-side TLS handshake +*/ +void TLS_Client::do_handshake() + { + state = new Handshake_State; + + state->client_hello = new Client_Hello(rng, writer, policy, state->hash); + + while(true) + { + if(active && !state) + break; + if(!active && !state) + throw TLS_Exception(HANDSHAKE_FAILURE, "Handshake failed"); + + state_machine(); + } + } + +} diff --git a/src/ssl/tls_client.h b/src/ssl/tls_client.h new file mode 100644 index 000000000..720531c67 --- /dev/null +++ b/src/ssl/tls_client.h @@ -0,0 +1,71 @@ +/** +* TLS Client Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_CLIENT_H__ +#define BOTAN_CLIENT_H__ + +#include <botan/tls_connection.h> +#include <botan/tls_state.h> +#include <vector> +#include <string> + +namespace Botan { + +/** +* TLS Client +*/ + +// FIXME: much of this can probably be moved up to TLS_Connection +class BOTAN_DLL TLS_Client : public TLS_Connection + { + public: + u32bit read(byte[], u32bit); + void write(const byte[], u32bit); + + std::vector<X509_Certificate> peer_cert_chain() const; + + void close(); + bool is_closed() const; + + TLS_Client(RandomNumberGenerator& rng, + Socket&, const Policy* = 0); + + // FIXME: support multiple cert/key pairs + TLS_Client(RandomNumberGenerator& rng, + Socket&, const X509_Certificate&, const PKCS8_PrivateKey&, + const Policy* = 0); + + ~TLS_Client(); + private: + void close(Alert_Level, Alert_Type); + + void initialize(); + void do_handshake(); + + void state_machine(); + void read_handshake(byte, const MemoryRegion<byte>&); + void process_handshake_msg(Handshake_Type, const MemoryRegion<byte>&); + + RandomNumberGenerator& rng; + + Record_Writer writer; + Record_Reader reader; + const Policy* policy; + + std::vector<X509_Certificate> certs, peer_certs; + std::vector<PKCS8_PrivateKey*> keys; + + Handshake_State* state; + SecureVector<byte> session_id; + SecureQueue read_buf; + std::string peer_id; + bool active; + }; + +} + +#endif diff --git a/src/ssl/tls_connection.h b/src/ssl/tls_connection.h new file mode 100644 index 000000000..aa46b5847 --- /dev/null +++ b/src/ssl/tls_connection.h @@ -0,0 +1,36 @@ +/** +* TLS Connection Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_CONNECTION_H__ +#define BOTAN_CONNECTION_H__ + +#include <botan/x509cert.h> +#include <vector> + +namespace Botan { + +/** +* TLS Connection +*/ +class BOTAN_DLL TLS_Connection + { + public: + virtual u32bit read(byte[], u32bit) = 0; + virtual void write(const byte[], u32bit) = 0; + u32bit read(byte& in) { return read(&in, 1); } + void write(byte out) { write(&out, 1); } + + virtual std::vector<X509_Certificate> peer_cert_chain() const = 0; + + virtual void close() = 0; + + virtual ~TLS_Connection() {} + }; + +} + +#endif diff --git a/src/ssl/tls_exceptn.h b/src/ssl/tls_exceptn.h new file mode 100644 index 000000000..15f52b19a --- /dev/null +++ b/src/ssl/tls_exceptn.h @@ -0,0 +1,37 @@ +/* +* SSL Exceptions +* (C) 2004-2010 Jack Lloyd +* +* Distributed under the terms of the Botan license +*/ + +#ifndef BOTAN_SSL_EXCEPTION_H__ +#define BOTAN_SSL_EXCEPTION_H__ + +#include <botan/tls_magic.h> +#include <botan/exceptn.h> + +namespace Botan { + +struct BOTAN_DLL TLS_Exception : public Exception + { + public: + Alert_Type type() const { return alert_type; } + + TLS_Exception(Alert_Type type, const std::string& msg) : + Exception("SSL/TLS error: " + msg), alert_type(type) + {} + + private: + Alert_Type alert_type; + }; + +struct BOTAN_DLL Unexpected_Message : public TLS_Exception + { + Unexpected_Message(const std::string& err) : + TLS_Exception(UNEXPECTED_MESSAGE, err) {} + }; + +} + +#endif diff --git a/src/ssl/tls_magic.h b/src/ssl/tls_magic.h new file mode 100644 index 000000000..2b894a862 --- /dev/null +++ b/src/ssl/tls_magic.h @@ -0,0 +1,118 @@ +/** +* SSL/TLS Protocol Constants Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_PROTOCOL_MAGIC_H__ +#define BOTAN_PROTOCOL_MAGIC_H__ + +namespace Botan { + +/** +* Protocol Constants for SSL/TLS +*/ +enum Size_Limits { + MAX_PLAINTEXT_SIZE = 16*1024, + MAX_COMPRESSED_SIZE = MAX_PLAINTEXT_SIZE + 1024, + MAX_CIPHERTEXT_SIZE = MAX_COMPRESSED_SIZE + 1024 +}; + +enum Version_Code { + NO_VERSION_SET = 0x0000, + SSL_V3 = 0x0300, + TLS_V10 = 0x0301, + TLS_V11 = 0x0302 +}; + +enum Connection_Side { CLIENT, SERVER }; + +enum Record_Type { + CONNECTION_CLOSED = 0, + + CHANGE_CIPHER_SPEC = 20, + ALERT = 21, + HANDSHAKE = 22, + APPLICATION_DATA = 23 +}; + +enum Handshake_Type { + HELLO_REQUEST = 0, + CLIENT_HELLO = 1, + SERVER_HELLO = 2, + CERTIFICATE = 11, + SERVER_KEX = 12, + CERTIFICATE_REQUEST = 13, + SERVER_HELLO_DONE = 14, + CERTIFICATE_VERIFY = 15, + CLIENT_KEX = 16, + FINISHED = 20, + + HANDSHAKE_CCS = 100, + HANDSHAKE_NONE = 101 +}; + +enum Alert_Level { + WARNING = 1, + FATAL = 2 +}; + +enum Alert_Type { + CLOSE_NOTIFY = 0, + UNEXPECTED_MESSAGE = 10, + BAD_RECORD_MAC = 20, + DECRYPTION_FAILED = 21, + RECORD_OVERFLOW = 22, + DECOMPRESSION_FAILURE = 30, + HANDSHAKE_FAILURE = 40, + BAD_CERTIFICATE = 42, + UNSUPPORTED_CERTIFICATE = 43, + CERTIFICATE_REVOKED = 44, + CERTIFICATE_EXPIRED = 45, + CERTIFICATE_UNKNOWN = 46, + ILLEGAL_PARAMETER = 47, + UNKNOWN_CA = 48, + ACCESS_DENIED = 49, + DECODE_ERROR = 50, + DECRYPT_ERROR = 51, + EXPORT_RESTRICTION = 60, + PROTOCOL_VERSION = 70, + INSUFFICIENT_SECURITY = 71, + INTERNAL_ERROR = 80, + USER_CANCELED = 90, + NO_RENEGOTIATION = 100, + + NO_ALERT_TYPE = 0xFFFF +}; + +enum Certificate_Type { + RSA_CERT = 1, + DSS_CERT = 2, + DH_RSA_CERT = 3, + DH_DSS_CERT = 4 +}; + +enum Ciphersuite_Code { + RSA_RC4_MD5 = 0x0004, + RSA_RC4_SHA = 0x0005, + RSA_3DES_SHA = 0x000A, + RSA_AES128_SHA = 0x002F, + RSA_AES256_SHA = 0x0035, + + DHE_RSA_3DES_SHA = 0x0016, + DHE_RSA_AES128_SHA = 0x0033, + DHE_RSA_AES256_SHA = 0x0039, + + DHE_DSS_3DES_SHA = 0x0013, + DHE_DSS_AES128_SHA = 0x0032, + DHE_DSS_AES256_SHA = 0x0038 +}; + +enum Compression_Algo { + NO_COMPRESSION = 0x00 +}; + +} + +#endif diff --git a/src/ssl/tls_messages.h b/src/ssl/tls_messages.h new file mode 100644 index 000000000..977dfbbc3 --- /dev/null +++ b/src/ssl/tls_messages.h @@ -0,0 +1,277 @@ +/** +* TLS Messages +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_TLS_MESSAGES_H__ +#define BOTAN_TLS_MESSAGES_H__ + +#include <botan/tls_record.h> +#include <botan/tls_policy.h> +#include <botan/handshake_hash.h> +#include <botan/bigint.h> +#include <botan/pkcs8.h> +#include <botan/x509cert.h> +#include <vector> + +namespace Botan { + +/** +* TLS Handshake Message Base Class +*/ +class BOTAN_DLL HandshakeMessage + { + public: + void send(Record_Writer&, HandshakeHash&) const; + + virtual Handshake_Type type() const = 0; + + virtual ~HandshakeMessage() {} + private: + HandshakeMessage& operator=(const HandshakeMessage&) { return (*this); } + virtual SecureVector<byte> serialize() const = 0; + virtual void deserialize(const MemoryRegion<byte>&) = 0; + }; + +/** +* Client Hello Message +*/ +class BOTAN_DLL Client_Hello : public HandshakeMessage + { + public: + Handshake_Type type() const { return CLIENT_HELLO; } + Version_Code version() const { return c_version; } + SecureVector<byte> session_id() const { return sess_id; } + std::vector<u16bit> ciphersuites() const { return suites; } + std::vector<byte> compression_algos() const { return comp_algos; } + + SecureVector<byte> random() const { return c_random; } + + bool offered_suite(u16bit) const; + + Client_Hello(RandomNumberGenerator& rng, + Record_Writer&, const Policy*, HandshakeHash&); + + Client_Hello(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + + Version_Code c_version; + SecureVector<byte> sess_id, c_random; + std::vector<u16bit> suites; + std::vector<byte> comp_algos; + }; + +/** +* Client Key Exchange Message +*/ +class BOTAN_DLL Client_Key_Exchange : public HandshakeMessage + { + public: + Handshake_Type type() const { return CLIENT_KEX; } + + SecureVector<byte> pre_master_secret() const; + SecureVector<byte> pre_master_secret(RandomNumberGenerator&, + const PKCS8_PrivateKey*, + Version_Code); + + Client_Key_Exchange(RandomNumberGenerator&, + Record_Writer&, HandshakeHash&, + const X509_PublicKey*, Version_Code, Version_Code); + + Client_Key_Exchange(const MemoryRegion<byte>&, const CipherSuite&, + Version_Code); + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + + SecureVector<byte> key_material, pre_master; + bool include_length; + }; + +/** +* Certificate Message +*/ +class BOTAN_DLL Certificate : public HandshakeMessage + { + public: + Handshake_Type type() const { return CERTIFICATE; } + std::vector<X509_Certificate> cert_chain() const { return certs; } + + Certificate(Record_Writer&, const std::vector<X509_Certificate>&, + HandshakeHash&); + Certificate(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + std::vector<X509_Certificate> certs; + }; + +/** +* Certificate Request Message +*/ +class BOTAN_DLL Certificate_Req : public HandshakeMessage + { + public: + Handshake_Type type() const { return CERTIFICATE_REQUEST; } + + std::vector<Certificate_Type> acceptable_types() const { return types; } + std::vector<X509_DN> acceptable_CAs() const { return names; } + + /* TODO + Certificate_Req(Record_Writer&, HandshakeHash&, + const X509_Certificate&); + */ + Certificate_Req(Record_Writer&, HandshakeHash&, + const std::vector<X509_Certificate>&); + + Certificate_Req(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + + std::vector<X509_DN> names; + std::vector<Certificate_Type> types; + }; + +/** +* Certificate Verify Message +*/ +class BOTAN_DLL Certificate_Verify : public HandshakeMessage + { + public: + Handshake_Type type() const { return CERTIFICATE_VERIFY; } + + bool verify(const X509_Certificate&, HandshakeHash&); + + Certificate_Verify(RandomNumberGenerator& rng, + Record_Writer&, HandshakeHash&, + const PKCS8_PrivateKey*); + + Certificate_Verify(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + + SecureVector<byte> signature; + }; + +/** +* Finished Message +*/ +class BOTAN_DLL Finished : public HandshakeMessage + { + public: + Handshake_Type type() const { return FINISHED; } + + bool verify(const MemoryRegion<byte>&, Version_Code, + const HandshakeHash&, Connection_Side); + + Finished(Record_Writer&, Version_Code, Connection_Side, + const MemoryRegion<byte>&, HandshakeHash&); + Finished(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + + SecureVector<byte> compute_verify(const MemoryRegion<byte>&, + HandshakeHash, Connection_Side, + Version_Code); + + Connection_Side side; + SecureVector<byte> verification_data; + }; + +/** +* Hello Request Message +*/ +class BOTAN_DLL Hello_Request : public HandshakeMessage + { + public: + Handshake_Type type() const { return HELLO_REQUEST; } + + Hello_Request(Record_Writer&); + Hello_Request(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + }; + +/** +* Server Hello Message +*/ +class BOTAN_DLL Server_Hello : public HandshakeMessage + { + public: + Handshake_Type type() const { return SERVER_HELLO; } + Version_Code version() { return s_version; } + SecureVector<byte> session_id() const { return sess_id; } + u16bit ciphersuite() const { return suite; } + byte compression_algo() const { return comp_algo; } + + SecureVector<byte> random() const { return s_random; } + + Server_Hello(RandomNumberGenerator& rng, + Record_Writer&, const Policy*, + const std::vector<X509_Certificate>&, + const Client_Hello&, Version_Code, HandshakeHash&); + + Server_Hello(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + + Version_Code s_version; + SecureVector<byte> sess_id, s_random; + u16bit suite; + byte comp_algo; + }; + +/** +* Server Key Exchange Message +*/ +class BOTAN_DLL Server_Key_Exchange : public HandshakeMessage + { + public: + Handshake_Type type() const { return SERVER_KEX; } + X509_PublicKey* key() const; + + bool verify(const X509_Certificate&, const MemoryRegion<byte>&, + const MemoryRegion<byte>&) const; + + Server_Key_Exchange(RandomNumberGenerator& rng, + Record_Writer&, const X509_PublicKey*, + const PKCS8_PrivateKey*, const MemoryRegion<byte>&, + const MemoryRegion<byte>&, HandshakeHash&); + + Server_Key_Exchange(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + SecureVector<byte> serialize_params() const; + void deserialize(const MemoryRegion<byte>&); + + std::vector<BigInt> params; + SecureVector<byte> signature; + }; + +/** +* Server Hello Done Message +*/ +class BOTAN_DLL Server_Hello_Done : public HandshakeMessage + { + public: + Handshake_Type type() const { return SERVER_HELLO_DONE; } + + Server_Hello_Done(Record_Writer&, HandshakeHash&); + Server_Hello_Done(const MemoryRegion<byte>& buf) { deserialize(buf); } + private: + SecureVector<byte> serialize() const; + void deserialize(const MemoryRegion<byte>&); + }; + +} + +#endif diff --git a/src/ssl/tls_policy.cpp b/src/ssl/tls_policy.cpp new file mode 100644 index 000000000..42e855379 --- /dev/null +++ b/src/ssl/tls_policy.cpp @@ -0,0 +1,178 @@ +/** +* Policies Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_policy.h> +#include <botan/tls_exceptn.h> + +namespace Botan { + +/** +* Return allowed ciphersuites +*/ +std::vector<u16bit> Policy::ciphersuites() const + { + return suite_list(allow_static_rsa(), allow_edh_rsa(), allow_edh_dsa()); + } + +/** +* Return allowed ciphersuites +*/ +std::vector<u16bit> Policy::suite_list(bool use_rsa, bool use_edh_rsa, + bool use_edh_dsa) const + { + std::vector<u16bit> suites; + + if(use_edh_dsa) + { + suites.push_back(DHE_DSS_AES256_SHA); + suites.push_back(DHE_DSS_AES128_SHA); + suites.push_back(DHE_DSS_3DES_SHA); + } + + if(use_edh_rsa) + { + suites.push_back(DHE_RSA_AES256_SHA); + suites.push_back(DHE_RSA_AES128_SHA); + suites.push_back(DHE_RSA_3DES_SHA); + } + + if(use_rsa) + { + suites.push_back(RSA_AES256_SHA); + suites.push_back(RSA_AES128_SHA); + suites.push_back(RSA_3DES_SHA); + suites.push_back(RSA_RC4_SHA); + suites.push_back(RSA_RC4_MD5); + } + + if(suites.size() == 0) + throw TLS_Exception(INTERNAL_ERROR, + "Policy error: All ciphersuites disabled"); + + return suites; + } + +/** +* Return allowed compression algorithms +*/ +std::vector<byte> Policy::compression() const + { + std::vector<byte> algs; + algs.push_back(NO_COMPRESSION); + return algs; + } + +/** +* Choose which ciphersuite to use +*/ +u16bit Policy::choose_suite(const std::vector<u16bit>& c_suites, + bool have_rsa, bool have_dsa) const + { + bool use_static_rsa = allow_static_rsa() && have_rsa; + bool use_edh_rsa = allow_edh_rsa() && have_rsa; + bool use_edh_dsa = allow_edh_dsa() && have_dsa; + + std::vector<u16bit> s_suites = suite_list(use_static_rsa, use_edh_rsa, + use_edh_dsa); + + for(u32bit j = 0; j != s_suites.size(); j++) + for(u32bit k = 0; k != c_suites.size(); k++) + if(s_suites[j] == c_suites[k]) + return s_suites[j]; + + return 0; + } + +/** +* Choose which compression algorithm to use +*/ +byte Policy::choose_compression(const std::vector<byte>& c_comp) const + { + std::vector<byte> s_comp = compression(); + + for(u32bit j = 0; j != s_comp.size(); j++) + for(u32bit k = 0; k != c_comp.size(); k++) + if(s_comp[j] == c_comp[k]) + return s_comp[j]; + + return NO_COMPRESSION; + } + +/** +* Return the minimum acceptable SSL/TLS version +*/ +Version_Code Policy::min_version() const + { + return SSL_V3; + } + +/** +* Return the preferable SSL/TLS version +*/ +Version_Code Policy::pref_version() const + { + return TLS_V10; + } + +/** +* Check if static RSA keying is allowed +*/ +bool Policy::allow_static_rsa() const + { + return true; + } + +/** +* Check if RSA with empheral DH is allowed +*/ +bool Policy::allow_edh_rsa() const + { + return true; + } + +/** +* Check if DSA with empheral DH is allowed +*/ +bool Policy::allow_edh_dsa() const + { + return true; + } + +/** +* Check if client authentication is required +*/ +bool Policy::require_client_auth() const + { + return false; + } + +/** +* Return the group to use for empheral DH +*/ +DL_Group Policy::dh_group() const + { + return DL_Group("IETF-1024"); + } + +/** +* Return the size to use for an empheral RSA key +*/ +u32bit Policy::rsa_export_keysize() const + { + return 512; + } + +/** +* Default certificate check +*/ +bool Policy::check_cert(const std::vector<X509_Certificate>&, + const std::string&) const + { + return true; + } + +} diff --git a/src/ssl/tls_policy.h b/src/ssl/tls_policy.h new file mode 100644 index 000000000..3e3ba9d73 --- /dev/null +++ b/src/ssl/tls_policy.h @@ -0,0 +1,52 @@ +/** +* Policies Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_POLICY_H__ +#define BOTAN_POLICY_H__ + +#include <botan/x509cert.h> +#include <botan/dl_group.h> +#include <botan/tls_magic.h> +#include <vector> + +namespace Botan { + +/** +* Policy Base Class +*/ +class BOTAN_DLL Policy + { + public: + std::vector<u16bit> ciphersuites() const; + virtual std::vector<byte> compression() const; + + virtual u16bit choose_suite(const std::vector<u16bit>&, + bool, bool) const; + virtual byte choose_compression(const std::vector<byte>&) const; + + virtual bool allow_static_rsa() const; + virtual bool allow_edh_rsa() const; + virtual bool allow_edh_dsa() const; + virtual bool require_client_auth() const; + + virtual DL_Group dh_group() const; + virtual u32bit rsa_export_keysize() const; + + virtual Version_Code min_version() const; + virtual Version_Code pref_version() const; + + virtual bool check_cert(const std::vector<X509_Certificate>&, + const std::string&) const; + + virtual ~Policy() {} + private: + virtual std::vector<u16bit> suite_list(bool, bool, bool) const; + }; + +} + +#endif diff --git a/src/ssl/tls_record.h b/src/ssl/tls_record.h new file mode 100644 index 000000000..b362d3fb7 --- /dev/null +++ b/src/ssl/tls_record.h @@ -0,0 +1,79 @@ +/** +* TLS Record Handling Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_RECORDS_H__ +#define BOTAN_RECORDS_H__ + +#include <botan/tls_session_key.h> +#include <botan/tls_suites.h> +#include <botan/socket.h> +#include <botan/pipe.h> +#include <vector> + +namespace Botan { + +/** +* TLS Record Writer +*/ +class BOTAN_DLL Record_Writer + { + public: + void send(byte, const byte[], u32bit); + void send(byte, byte); + void flush(); + + void alert(Alert_Level, Alert_Type); + + void set_keys(const CipherSuite&, const SessionKeys&, Connection_Side); + void set_compressor(Filter*); + + void set_version(Version_Code); + + void reset(); + + Record_Writer(Socket&); + private: + void send_record(byte, const byte[], u32bit); + void send_record(byte, byte, byte, const byte[], u32bit); + + Socket& socket; + Pipe compress, cipher, mac; + SecureVector<byte> buffer; + u32bit pad_amount, mac_size, buf_pos; + u64bit seq_no; + byte major, minor, buf_type; + bool do_compress; + }; + +/** +* TLS Record Reader +*/ +class BOTAN_DLL Record_Reader + { + public: + SecureVector<byte> get_record(byte&); + + void set_keys(const CipherSuite&, const SessionKeys&, Connection_Side); + void set_compressor(Filter*); + + void set_version(Version_Code); + + void reset(); + + Record_Reader(Socket&); + private: + Socket& socket; + Pipe compress, cipher, mac; + u32bit pad_amount, mac_size; + u64bit seq_no; + byte major, minor; + bool do_compress; + }; + +} + +#endif diff --git a/src/ssl/tls_server.cpp b/src/ssl/tls_server.cpp new file mode 100644 index 000000000..a530d04dd --- /dev/null +++ b/src/ssl/tls_server.cpp @@ -0,0 +1,466 @@ +/** +* TLS Server Source File +* (C) 2004-2008 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_server.h> +#include <botan/tls_alerts.h> +#include <botan/tls_exceptn.h> +#include <botan/loadstor.h> +#include <botan/rsa.h> +#include <botan/dh.h> + +namespace Botan { + +namespace { + +/** +* Choose what version to respond with +*/ +Version_Code choose_version(Version_Code client, Version_Code minimum) + { + if(client < minimum) + throw TLS_Exception(PROTOCOL_VERSION, + "Client's protocol is unacceptable by policy"); + + if(client == SSL_V3 || client == TLS_V10) + return client; + return TLS_V10; + } + +// FIXME: checks are wrong for session reuse (add a flag for that) +/** +* Verify the state transition is allowed +*/ +void server_check_state(Handshake_Type new_msg, Handshake_State* state) + { + class State_Transition_Error : public Unexpected_Message + { + public: + State_Transition_Error(const std::string& err) : + Unexpected_Message("State transition error from " + err) {} + }; + + if(new_msg == CLIENT_HELLO) + { + if(state->server_hello) + throw State_Transition_Error("ClientHello"); + } + else if(new_msg == CERTIFICATE) + { + if(!state->do_client_auth || !state->cert_req || + !state->server_hello_done || state->client_kex) + throw State_Transition_Error("ClientCertificate"); + } + else if(new_msg == CLIENT_KEX) + { + if(!state->server_hello_done || state->client_verify || + state->got_client_ccs) + throw State_Transition_Error("ClientKeyExchange"); + } + else if(new_msg == CERTIFICATE_VERIFY) + { + if(!state->cert_req || !state->client_certs || !state->client_kex || + state->got_client_ccs) + throw State_Transition_Error("CertificateVerify"); + } + else if(new_msg == HANDSHAKE_CCS) + { + if(!state->client_kex || state->client_finished) + throw State_Transition_Error("ClientChangeCipherSpec"); + } + else if(new_msg == FINISHED) + { + if(!state->got_client_ccs) + throw State_Transition_Error("ClientFinished"); + } + else + throw Unexpected_Message("Unexpected message in handshake"); + } + +} + +/** +* TLS Server Constructor +*/ +TLS_Server::TLS_Server(RandomNumberGenerator& r, + Socket& sock, const X509_Certificate& cert, + const PKCS8_PrivateKey& key, const Policy* pol) : + rng(r), writer(sock), reader(sock), policy(pol ? pol : new Policy) + { + peer_id = sock.peer_id(); + + state = 0; + + cert_chain.push_back(cert); + private_key = PKCS8::copy_key(key, rng); + + try { + active = false; + writer.set_version(TLS_V10); + do_handshake(); + active = true; + } + catch(std::exception& e) + { + if(state) + { + delete state; + state = 0; + } + + writer.alert(FATAL, HANDSHAKE_FAILURE); + throw Stream_IO_Error("TLS_Server: Handshake failed"); + } + } + +/** +* TLS Server Destructor +*/ +TLS_Server::~TLS_Server() + { + close(); + delete private_key; + delete policy; + delete state; + } + +/** +* Return the peer's certificate chain +*/ +std::vector<X509_Certificate> TLS_Server::peer_cert_chain() const + { + return peer_certs; + } + +/** +* Write to a TLS connection +*/ +void TLS_Server::write(const byte buf[], u32bit length) + { + if(!active) + throw Internal_Error("TLS_Server::write called while closed"); + + writer.send(APPLICATION_DATA, buf, length); + } + +/** +* Read from a TLS connection +*/ +u32bit TLS_Server::read(byte out[], u32bit length) + { + if(!active) + throw Internal_Error("TLS_Server::read called while closed"); + + writer.flush(); + + while(read_buf.size() == 0) + { + state_machine(); + if(active == false) + break; + } + + u32bit got = std::min(read_buf.size(), length); + read_buf.read(out, got); + return got; + } + +/** +* Check connection status +*/ +bool TLS_Server::is_closed() const + { + if(!active) + return true; + return false; + } + +/** +* Close a TLS connection +*/ +void TLS_Server::close() + { + close(WARNING, CLOSE_NOTIFY); + } + +/** +* Close a TLS connection +*/ +void TLS_Server::close(Alert_Level level, Alert_Type alert_code) + { + if(active) + { + try { + active = false; + writer.alert(level, alert_code); + writer.flush(); + } + catch(...) {} + } + } + +/** +* Iterate the TLS state machine +*/ +void TLS_Server::state_machine() + { + byte rec_type; + SecureVector<byte> record = reader.get_record(rec_type); + + if(rec_type == CONNECTION_CLOSED) + { + active = false; + reader.reset(); + writer.reset(); + } + else if(rec_type == APPLICATION_DATA) + { + if(active) + read_buf.write(record, record.size()); + else + throw Unexpected_Message("Application data before handshake done"); + } + else if(rec_type == HANDSHAKE || rec_type == CHANGE_CIPHER_SPEC) + read_handshake(rec_type, record); + else if(rec_type == ALERT) + { + Alert alert(record); + + if(alert.is_fatal() || alert.type() == CLOSE_NOTIFY) + { + if(alert.type() == CLOSE_NOTIFY) + writer.alert(WARNING, CLOSE_NOTIFY); + + reader.reset(); + writer.reset(); + active = false; + } + } + else + throw Unexpected_Message("Unknown message type recieved"); + } + +/** +* Split up and process handshake messages +*/ +void TLS_Server::read_handshake(byte rec_type, + const MemoryRegion<byte>& rec_buf) + { + if(rec_type == HANDSHAKE) + state->queue.write(rec_buf, rec_buf.size()); + + while(true) + { + Handshake_Type type = HANDSHAKE_NONE; + SecureVector<byte> contents; + + if(rec_type == HANDSHAKE) + { + if(state->queue.size() >= 4) + { + byte head[4] = { 0 }; + state->queue.peek(head, 4); + + const u32bit length = make_u32bit(0, head[1], head[2], head[3]); + + if(state->queue.size() >= length + 4) + { + type = static_cast<Handshake_Type>(head[0]); + contents.resize(length); + state->queue.read(head, 4); + state->queue.read(contents, contents.size()); + } + } + } + else if(rec_type == CHANGE_CIPHER_SPEC) + { + if(state->queue.size() == 0 && rec_buf.size() == 1 && rec_buf[0] == 1) + type = HANDSHAKE_CCS; + else + throw Decoding_Error("Malformed ChangeCipherSpec message"); + } + else + throw Decoding_Error("Unknown message type in handshake processing"); + + if(type == HANDSHAKE_NONE) + break; + + process_handshake_msg(type, contents); + + if(type == HANDSHAKE_CCS || !state) + break; + } + } + +/** +* Process a handshake message +*/ +void TLS_Server::process_handshake_msg(Handshake_Type type, + const MemoryRegion<byte>& contents) + { + if(type == CLIENT_HELLO) + { + if(state == 0) + state = new Handshake_State(); + else + return; + } + + if(state == 0) + throw Unexpected_Message("Unexpected handshake message"); + + if(type != HANDSHAKE_CCS && type != FINISHED) + { + state->hash.update(static_cast<byte>(type)); + u32bit record_length = contents.size(); + for(u32bit j = 0; j != 3; j++) + state->hash.update(get_byte(j+1, record_length)); + state->hash.update(contents); + } + + if(type == CLIENT_HELLO) + { + server_check_state(type, state); + + state->client_hello = new Client_Hello(contents); + + state->version = choose_version(state->client_hello->version(), + policy->min_version()); + + writer.set_version(state->version); + reader.set_version(state->version); + + state->server_hello = new Server_Hello(rng, writer, + policy, cert_chain, + *(state->client_hello), + state->version, state->hash); + + state->suite = CipherSuite(state->server_hello->ciphersuite()); + + if(state->suite.sig_type() != CipherSuite::NO_SIG) + { + // FIXME: should choose certs based on sig type + state->server_certs = new Certificate(writer, cert_chain, + state->hash); + } + + state->kex_priv = PKCS8::copy_key(*private_key, rng); + if(state->suite.kex_type() != CipherSuite::NO_KEX) + { + if(state->suite.kex_type() == CipherSuite::RSA_KEX) + { + state->kex_priv = new RSA_PrivateKey(rng, + policy->rsa_export_keysize()); + } + else if(state->suite.kex_type() == CipherSuite::DH_KEX) + { + state->kex_priv = new DH_PrivateKey(rng, policy->dh_group()); + } + else + throw Internal_Error("TLS_Server: Unknown ciphersuite kex type"); + + state->server_kex = + new Server_Key_Exchange(rng, writer, + state->kex_priv, private_key, + state->client_hello->random(), + state->server_hello->random(), + state->hash); + } + + if(policy->require_client_auth()) + { + state->do_client_auth = true; + throw Internal_Error("Client auth not implemented"); + // FIXME: send client auth request here + } + + state->server_hello_done = new Server_Hello_Done(writer, state->hash); + } + else if(type == CERTIFICATE) + { + server_check_state(type, state); + // FIXME: process this + } + else if(type == CLIENT_KEX) + { + server_check_state(type, state); + + state->client_kex = new Client_Key_Exchange(contents, state->suite, + state->version); + + SecureVector<byte> pre_master = + state->client_kex->pre_master_secret(rng, state->kex_priv, + state->server_hello->version()); + + state->keys = SessionKeys(state->suite, state->version, pre_master, + state->client_hello->random(), + state->server_hello->random()); + } + else if(type == CERTIFICATE_VERIFY) + { + server_check_state(type, state); + // FIXME: process this + } + else if(type == HANDSHAKE_CCS) + { + server_check_state(type, state); + + reader.set_keys(state->suite, state->keys, SERVER); + state->got_client_ccs = true; + } + else if(type == FINISHED) + { + server_check_state(type, state); + + state->client_finished = new Finished(contents); + + if(!state->client_finished->verify(state->keys.master_secret(), + state->version, state->hash, CLIENT)) + throw TLS_Exception(DECRYPT_ERROR, + "Finished message didn't verify"); + + state->hash.update(static_cast<byte>(type)); + u32bit record_length = contents.size(); + for(u32bit j = 0; j != 3; j++) + state->hash.update(get_byte(j+1, record_length)); + state->hash.update(contents); + + writer.send(CHANGE_CIPHER_SPEC, 1); + writer.flush(); + + writer.set_keys(state->suite, state->keys, SERVER); + + state->server_finished = new Finished(writer, state->version, SERVER, + state->keys.master_secret(), + state->hash); + + delete state; + state = 0; + active = true; + } + else + throw Unexpected_Message("Unknown handshake message recieved"); + } + +/** +* Perform a server-side TLS handshake +*/ +void TLS_Server::do_handshake() + { + while(true) + { + if(active && !state) + break; + + state_machine(); + + if(!active && !state) + throw TLS_Exception(HANDSHAKE_FAILURE, + "TLS_Server: Handshake failed"); + } + } + +} diff --git a/src/ssl/tls_server.h b/src/ssl/tls_server.h new file mode 100644 index 000000000..2cc7f0601 --- /dev/null +++ b/src/ssl/tls_server.h @@ -0,0 +1,69 @@ +/** +* TLS Server Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_SERVER_H__ +#define BOTAN_SERVER_H__ + +#include <botan/tls_connection.h> +#include <botan/tls_state.h> +#include <vector> + +namespace Botan { + +/** +* TLS Server +*/ + +// FIXME: much of this can probably be moved up to TLS_Connection +class BOTAN_DLL TLS_Server + { + public: + u32bit read(byte[], u32bit); + void write(const byte[], u32bit); + + std::vector<X509_Certificate> peer_cert_chain() const; + + void close(); + bool is_closed() const; + + // FIXME: support cert chains (!) + // FIXME: support anonymous servers + TLS_Server(RandomNumberGenerator& rng, + Socket&, + const X509_Certificate&, const PKCS8_PrivateKey&, + const Policy* = 0); + + ~TLS_Server(); + private: + void close(Alert_Level, Alert_Type); + + void do_handshake(); + void state_machine(); + void read_handshake(byte, const MemoryRegion<byte>&); + + void process_handshake_msg(Handshake_Type, const MemoryRegion<byte>&); + + RandomNumberGenerator& rng; + + Record_Writer writer; + Record_Reader reader; + const Policy* policy; + + // FIXME: rename to match TLS_Client + std::vector<X509_Certificate> cert_chain, peer_certs; + PKCS8_PrivateKey* private_key; + + Handshake_State* state; + SecureVector<byte> session_id; + SecureQueue read_buf; + std::string peer_id; + bool active; + }; + +} + +#endif diff --git a/src/ssl/tls_session_key.cpp b/src/ssl/tls_session_key.cpp new file mode 100644 index 000000000..15dc24072 --- /dev/null +++ b/src/ssl/tls_session_key.cpp @@ -0,0 +1,170 @@ +/** +* TLS Session Key Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_session_key.h> +#include <botan/prf_ssl3.h> +#include <botan/prf_tls.h> +#include <botan/lookup.h> + +namespace Botan { + +/** +* Return the client cipher key +*/ +SymmetricKey SessionKeys::client_cipher_key() const + { + return c_cipher; + } + +/** +* Return the server cipher key +*/ +SymmetricKey SessionKeys::server_cipher_key() const + { + return s_cipher; + } + +/** +* Return the client MAC key +*/ +SymmetricKey SessionKeys::client_mac_key() const + { + return c_mac; + } + +/** +* Return the server MAC key +*/ +SymmetricKey SessionKeys::server_mac_key() const + { + return s_mac; + } + +/** +* Return the client cipher IV +*/ +InitializationVector SessionKeys::client_iv() const + { + return c_iv; + } + +/** +* Return the server cipher IV +*/ +InitializationVector SessionKeys::server_iv() const + { + return s_iv; + } + +/** +* Return the TLS master secret +*/ +SecureVector<byte> SessionKeys::master_secret() const + { + return master_sec; + } + +/** +* Generate SSLv3 session keys +*/ +SymmetricKey SessionKeys::ssl3_keygen(u32bit prf_gen, + const MemoryRegion<byte>& pre_master, + const MemoryRegion<byte>& client_random, + const MemoryRegion<byte>& server_random) + { + SSL3_PRF prf; + + SecureVector<byte> salt; + salt.append(client_random); + salt.append(server_random); + + master_sec = prf.derive_key(48, pre_master, salt); + + salt.destroy(); + salt.append(server_random); + salt.append(client_random); + + return prf.derive_key(prf_gen, master_sec, salt); + } + +/** +* Generate TLS 1.0 session keys +*/ +SymmetricKey SessionKeys::tls1_keygen(u32bit prf_gen, + const MemoryRegion<byte>& pre_master, + const MemoryRegion<byte>& client_random, + const MemoryRegion<byte>& server_random) + { + const byte MASTER_SECRET_MAGIC[] = { + 0x6D, 0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x73, 0x65, 0x63, 0x72, 0x65, + 0x74 }; + const byte KEY_GEN_MAGIC[] = { + 0x6B, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6E, 0x73, 0x69, 0x6F, + 0x6E }; + + TLS_PRF prf; + + SecureVector<byte> salt; + salt.append(MASTER_SECRET_MAGIC, sizeof(MASTER_SECRET_MAGIC)); + salt.append(client_random); + salt.append(server_random); + + master_sec = prf.derive_key(48, pre_master, salt); + + salt.destroy(); + salt.append(KEY_GEN_MAGIC, sizeof(KEY_GEN_MAGIC)); + salt.append(server_random); + salt.append(client_random); + + return prf.derive_key(prf_gen, master_sec, salt); + } + +/** +* SessionKeys Constructor +*/ +SessionKeys::SessionKeys(const CipherSuite& suite, Version_Code version, + const MemoryRegion<byte>& pre_master_secret, + const MemoryRegion<byte>& c_random, + const MemoryRegion<byte>& s_random) + { + if(version != SSL_V3 && version != TLS_V10) + throw Invalid_Argument("SessionKeys: Unknown version code"); + + const u32bit mac_keylen = output_length_of(suite.mac_algo()); + u32bit cipher_keylen = suite.cipher_keylen(); + + u32bit cipher_ivlen = 0; + if(have_block_cipher(suite.cipher_algo())) + cipher_ivlen = block_size_of(suite.cipher_algo()); + + const u32bit prf_gen = 2 * (mac_keylen + cipher_keylen + cipher_ivlen); + + SymmetricKey keyblock = (version == SSL_V3) ? + ssl3_keygen(prf_gen, pre_master_secret, c_random, s_random) : + tls1_keygen(prf_gen, pre_master_secret, c_random, s_random); + + const byte* key_data = keyblock.begin(); + + c_mac = SymmetricKey(key_data, mac_keylen); + key_data += mac_keylen; + + s_mac = SymmetricKey(key_data, mac_keylen); + key_data += mac_keylen; + + c_cipher = SymmetricKey(key_data, cipher_keylen); + key_data += cipher_keylen; + + s_cipher = SymmetricKey(key_data, cipher_keylen); + key_data += cipher_keylen; + + c_iv = InitializationVector(key_data, cipher_ivlen); + key_data += cipher_ivlen; + + s_iv = InitializationVector(key_data, cipher_ivlen); + } + +} diff --git a/src/ssl/tls_session_key.h b/src/ssl/tls_session_key.h new file mode 100644 index 000000000..f3feee86e --- /dev/null +++ b/src/ssl/tls_session_key.h @@ -0,0 +1,52 @@ +/** +* TLS Session Key Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_SESSION_KEYS_H__ +#define BOTAN_SESSION_KEYS_H__ + +#include <botan/tls_suites.h> +#include <botan/tls_magic.h> +#include <botan/symkey.h> + +namespace Botan { + +/** +* TLS Session Keys +*/ +class BOTAN_DLL SessionKeys + { + public: + SymmetricKey client_cipher_key() const; + SymmetricKey server_cipher_key() const; + + SymmetricKey client_mac_key() const; + SymmetricKey server_mac_key() const; + + InitializationVector client_iv() const; + InitializationVector server_iv() const; + + SecureVector<byte> master_secret() const; + + SessionKeys() {} + SessionKeys(const CipherSuite&, Version_Code, const MemoryRegion<byte>&, + const MemoryRegion<byte>&, const MemoryRegion<byte>&); + private: + SymmetricKey ssl3_keygen(u32bit, const MemoryRegion<byte>&, + const MemoryRegion<byte>&, + const MemoryRegion<byte>&); + SymmetricKey tls1_keygen(u32bit, const MemoryRegion<byte>&, + const MemoryRegion<byte>&, + const MemoryRegion<byte>&); + + SecureVector<byte> master_sec; + SymmetricKey c_cipher, s_cipher, c_mac, s_mac; + InitializationVector c_iv, s_iv; + }; + +} + +#endif diff --git a/src/ssl/tls_state.h b/src/ssl/tls_state.h new file mode 100644 index 000000000..fd192c9ae --- /dev/null +++ b/src/ssl/tls_state.h @@ -0,0 +1,53 @@ +/** +* TLS Handshaking Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_HANDSHAKE_H__ +#define BOTAN_HANDSHAKE_H__ + +#include <botan/tls_messages.h> +#include <botan/secqueue.h> + +namespace Botan { + +/** +* SSL/TLS Handshake State +*/ +class BOTAN_DLL Handshake_State + { + public: + Client_Hello* client_hello; + Server_Hello* server_hello; + Certificate* server_certs; + Server_Key_Exchange* server_kex; + Certificate_Req* cert_req; + Server_Hello_Done* server_hello_done; + + Certificate* client_certs; + Client_Key_Exchange* client_kex; + Certificate_Verify* client_verify; + Finished* client_finished; + Finished* server_finished; + + X509_PublicKey* kex_pub; + PKCS8_PrivateKey* kex_priv; + + CipherSuite suite; + SessionKeys keys; + HandshakeHash hash; + + SecureQueue queue; + + Version_Code version; + bool got_client_ccs, got_server_ccs, do_client_auth; + + Handshake_State(); + ~Handshake_State(); + }; + +} + +#endif diff --git a/src/ssl/tls_suites.cpp b/src/ssl/tls_suites.cpp new file mode 100644 index 000000000..f5c1ceacc --- /dev/null +++ b/src/ssl/tls_suites.cpp @@ -0,0 +1,76 @@ +/** +* TLS Cipher Suites Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/tls_suites.h> +#include <botan/tls_exceptn.h> +#include <botan/tls_magic.h> +#include <botan/parsing.h> + +namespace Botan { + +namespace { + +/** +* Convert an SSL/TLS ciphersuite to a string +*/ +std::string lookup_ciphersuite(u16bit suite) + { + if(suite == RSA_RC4_MD5) return "RSA/NONE/ARC4/16/MD5"; + if(suite == RSA_RC4_SHA) return "RSA/NONE/ARC4/16/SHA1"; + if(suite == RSA_3DES_SHA) return "RSA/NONE/3DES/24/SHA1"; + if(suite == RSA_AES128_SHA) return "RSA/NONE/AES/16/SHA1"; + if(suite == RSA_AES256_SHA) return "RSA/NONE/AES/32/SHA1"; + + if(suite == DHE_RSA_3DES_SHA) return "RSA/DH/3DES/24/SHA1"; + if(suite == DHE_RSA_AES128_SHA) return "RSA/DH/AES/16/SHA1"; + if(suite == DHE_RSA_AES256_SHA) return "RSA/DH/AES/32/SHA1"; + + if(suite == DHE_DSS_3DES_SHA) return "DSA/DH/3DES/24/SHA1"; + if(suite == DHE_DSS_AES128_SHA) return "DSA/DH/AES/16/SHA1"; + if(suite == DHE_DSS_AES256_SHA) return "DSA/DH/AES/32/SHA1"; + + return ""; + } + +} + +/** +* CipherSuite Constructor +*/ +CipherSuite::CipherSuite(u16bit suite_code) + { + if(suite_code == 0) + return; + + std::string suite_string = lookup_ciphersuite(suite_code); + + if(suite_string == "") + throw Invalid_Argument("Unknown ciphersuite: " + + to_string(suite_code)); + + std::vector<std::string> suite_info = split_on(suite_string, '/'); + + if(suite_info[0] == "RSA") sig_algo = RSA_SIG; + else if(suite_info[0] == "DSA") sig_algo = DSA_SIG; + else if(suite_info[0] == "NONE") sig_algo = NO_SIG; + else + throw TLS_Exception(INTERNAL_ERROR, + "CipherSuite: Unknown sig type " + suite_info[0]); + + if(suite_info[1] == "DH") kex_algo = DH_KEX; + else if(suite_info[1] == "RSA") kex_algo = RSA_KEX; + else if(suite_info[1] == "NONE") kex_algo = NO_KEX; + else + throw TLS_Exception(INTERNAL_ERROR, + "CipherSuite: Unknown kex type " + suite_info[1]); + + cipher = suite_info[2]; + cipher_key_length = to_u32bit(suite_info[3]); + mac = suite_info[4]; + } + +} diff --git a/src/ssl/tls_suites.h b/src/ssl/tls_suites.h new file mode 100644 index 000000000..a967655ff --- /dev/null +++ b/src/ssl/tls_suites.h @@ -0,0 +1,42 @@ +/** +* Cipher Suites Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_CIPHERSUITES_H__ +#define BOTAN_CIPHERSUITES_H__ + +#include <botan/types.h> +#include <string> + +namespace Botan { + +/** +* Ciphersuite Information +*/ +class BOTAN_DLL CipherSuite + { + public: + enum Kex_Type { NO_KEX, RSA_KEX, DH_KEX }; + enum Sig_Type { NO_SIG, RSA_SIG, DSA_SIG }; + + std::string cipher_algo() const { return cipher; } + std::string mac_algo() const { return mac; } + + u32bit cipher_keylen() const { return cipher_key_length; } + Kex_Type kex_type() const { return kex_algo; } + Sig_Type sig_type() const { return sig_algo; } + + CipherSuite(u16bit = 0); + private: + Kex_Type kex_algo; + Sig_Type sig_algo; + std::string cipher, mac; + u32bit cipher_key_length; + }; + +} + +#endif diff --git a/src/ssl/unix_socket/info.txt b/src/ssl/unix_socket/info.txt new file mode 100644 index 000000000..205d0c700 --- /dev/null +++ b/src/ssl/unix_socket/info.txt @@ -0,0 +1,21 @@ +define UNIX_SOCKET + +<source> +unx_sock.cpp +</source> + +<header:public> +unx_sock.h +</header:public> + +<requires> +ssl +</requires> + +<os> +linux +freebsd +netbsd +openbsd +solaris +</os> diff --git a/src/ssl/unix_socket/unx_sock.cpp b/src/ssl/unix_socket/unx_sock.cpp new file mode 100644 index 000000000..fd99e9015 --- /dev/null +++ b/src/ssl/unix_socket/unx_sock.cpp @@ -0,0 +1,200 @@ +/** +* Unix Socket Source File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#include <botan/unx_sock.h> +#include <botan/exceptn.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/time.h> +#include <netdb.h> +#include <unistd.h> +#include <errno.h> +#include <string.h> + +namespace Botan { + +/** +* Unix Socket Constructor +*/ +Unix_Socket::Unix_Socket(const std::string& host, u16bit port) : peer(host) + { + sockfd = -1; + + hostent* host_addr = ::gethostbyname(host.c_str()); + + if(host_addr == 0) + throw Stream_IO_Error("Unix_Socket: gethostbyname failed for " + host); + if(host_addr->h_addrtype != AF_INET) // FIXME + throw Stream_IO_Error("Unix_Socket: " + host + " has IPv6 address"); + + int fd = ::socket(PF_INET, SOCK_STREAM, 0); + if(fd == -1) + throw Stream_IO_Error("Unix_Socket: Unable to acquire socket"); + + sockaddr_in socket_info; + ::memset(&socket_info, 0, sizeof(socket_info)); + socket_info.sin_family = AF_INET; + socket_info.sin_port = htons(port); + socket_info.sin_addr = *(struct in_addr*)host_addr->h_addr; // FIXME + + if(::connect(fd, (sockaddr*)&socket_info, sizeof(struct sockaddr)) != 0) + { + ::close(fd); + throw Stream_IO_Error("Unix_Socket: connect failed"); + } + + sockfd = fd; + } + +/** +* Unix Socket Constructor +*/ +Unix_Socket::Unix_Socket(int fd, const std::string& peer_id) + { + sockfd = fd; + peer = peer_id; + } + +/** +* Read from a Unix socket +*/ +u32bit Unix_Socket::read(byte buf[], u32bit length) + { + if(sockfd == -1) + throw Stream_IO_Error("Unix_Socket::read: Socket not connected"); + + u32bit got = 0; + + while(length) + { + ssize_t this_time = ::recv(sockfd, buf + got, length, MSG_NOSIGNAL); + + if(this_time == 0) + break; + + if(this_time == -1) + { + if(errno == EINTR) + this_time = 0; + else + throw Stream_IO_Error("Unix_Socket::read: Socket read failed"); + } + + got += this_time; + length -= this_time; + } + return got; + } + +/** +* Write to a Unix socket +*/ +void Unix_Socket::write(const byte buf[], u32bit length) + { + if(sockfd == -1) + throw Stream_IO_Error("Unix_Socket::write: Socket not connected"); + + u32bit offset = 0; + while(length) + { + ssize_t sent = ::send(sockfd, buf + offset, length, MSG_NOSIGNAL); + + if(sent == -1) + { + if(errno == EINTR) + sent = 0; + else + throw Stream_IO_Error("Unix_Socket::write: Socket write failed"); + } + + offset += sent; + length -= sent; + } + } + +/** +* Close a Unix socket +*/ +void Unix_Socket::close() + { + if(sockfd != -1) + { + if(::close(sockfd) != 0) + throw Stream_IO_Error("Unix_Socket::close failed"); + sockfd = -1; + } + } + +/** +* Return the peer's name +*/ +std::string Unix_Socket::peer_id() const + { + return peer; + } + +/** +* Unix Server Socket Constructor +*/ +Unix_Server_Socket::Unix_Server_Socket(u16bit port) + { + sockfd = -1; + + int fd = ::socket(PF_INET, SOCK_STREAM, 0); + if(fd == -1) + throw Stream_IO_Error("Unix_Server_Socket: Unable to acquire socket"); + + sockaddr_in socket_info; + ::memset(&socket_info, 0, sizeof(socket_info)); + socket_info.sin_family = AF_INET; + socket_info.sin_port = htons(port); + + // FIXME: support limiting listeners + socket_info.sin_addr.s_addr = INADDR_ANY; + + if(::bind(fd, (sockaddr*)&socket_info, sizeof(struct sockaddr)) != 0) + { + ::close(fd); + throw Stream_IO_Error("Unix_Server_Socket: bind failed"); + } + + if(listen(fd, 100) != 0) // FIXME: totally arbitrary + { + ::close(fd); + throw Stream_IO_Error("Unix_Server_Socket: listen failed"); + } + + sockfd = fd; + } + +/** +* Close a Unix socket +*/ +void Unix_Server_Socket::close() + { + if(sockfd != -1) + { + if(::close(sockfd) != 0) + throw Stream_IO_Error("Unix_Server_Socket::close failed"); + sockfd = -1; + } + } + +/** +* Accept a new connection +*/ +Socket* Unix_Server_Socket::accept() + { + // FIXME: grab IP of remote side, use gethostbyaddr, store as peer_id + int retval = ::accept(sockfd, 0, 0); + if(retval == -1) + throw Stream_IO_Error("Unix_Server_Socket: accept failed"); + return new Unix_Socket(retval); + } + +} diff --git a/src/ssl/unix_socket/unx_sock.h b/src/ssl/unix_socket/unx_sock.h new file mode 100644 index 000000000..91c70ce80 --- /dev/null +++ b/src/ssl/unix_socket/unx_sock.h @@ -0,0 +1,62 @@ +/** +* Unix Socket Header File +* (C) 2004-2006 Jack Lloyd +* +* Released under the terms of the Botan license +*/ + +#ifndef BOTAN_UNIX_SOCKET_H__ +#define BOTAN_UNIX_SOCKET_H__ + +#include <botan/socket.h> + +namespace Botan { + +/** + FIXME: the current socket interface is totally unusable + It has to handle (cleanly): + - TCP, UDP, and SCTP, where UDP is only usable with DTLS and + TCP/SCTP is only usable with TLS. + - Alternate socket interfaces (ACE, Netxx, whatever) with + minimal wrapping needed. +*/ + + +/** +* Unix Socket Base Class +*/ +class BOTAN_DLL Unix_Socket : public Socket + { + public: + u32bit read(byte[], u32bit); + void write(const byte[], u32bit); + + std::string peer_id() const; + + void close(); + Unix_Socket(int, const std::string& = ""); + Unix_Socket(const std::string&, u16bit); + ~Unix_Socket() { close(); } + private: + std::string peer; + int sockfd; + }; + +/** +* Unix Server Socket Base Class +*/ +class BOTAN_DLL Unix_Server_Socket : public Server_Socket + { + public: + Socket* accept(); + void close(); + + Unix_Server_Socket(u16bit); + ~Unix_Server_Socket() { close(); } + private: + int sockfd; + }; + +} + +#endif |