Exemple #1
0
/*************************************************
* Decode a BigInt                                *
*************************************************/
BigInt BigInt::decode(const byte buf[], u32bit length, Base base)
{
    BigInt r;
    if(base == Binary)
        r.binary_decode(buf, length);
#ifndef BOTAN_MINIMAL_BIGINT
    else if(base == Hexadecimal)
    {
        SecureVector<byte> hex;
        for(u32bit j = 0; j != length; ++j)
            if(Hex_Decoder::is_valid(buf[j]))
                hex.append(buf[j]);

        u32bit offset = (hex.size() % 2);
        SecureVector<byte> binary(hex.size() / 2 + offset);

        if(offset)
        {
            byte temp[2] = { '0', hex[0] };
            binary[0] = Hex_Decoder::decode(temp);
        }

        for(u32bit j = offset; j != binary.size(); ++j)
            binary[j] = Hex_Decoder::decode(hex+2*j-offset);
        r.binary_decode(binary, binary.size());
    }
#endif
    else if(base == Decimal || base == Octal)
    {
        const u32bit RADIX = ((base == Decimal) ? 10 : 8);
        for(u32bit j = 0; j != length; ++j)
        {
            byte x = Charset::char2digit(buf[j]);
            if(x >= RADIX)
            {
                if(RADIX == 10)
                    throw Invalid_Argument("BigInt: Invalid decimal string");
                else
                    throw Invalid_Argument("BigInt: Invalid octal string");
            }

            r *= RADIX;
            r += x;
        }
    }
    else
        throw Invalid_Argument("Unknown BigInt decoding method");
    return r;
}
Exemple #2
0
/*
* OSSL_BN Constructor
*/
OSSL_BN::OSSL_BN(const BigInt& in)
   {
   value = BN_new();
   SecureVector<byte> encoding = BigInt::encode(in);
   if(in != 0)
      BN_bin2bn(encoding, encoding.size(), value);
   }
Exemple #3
0
      std::string to_ber() const
         {
         SecureVector<byte> bits = PKCS8::BER_encode(*rsa_key);

         return std::string(reinterpret_cast<const char*>(&bits[0]),
                            bits.size());
         }
Exemple #4
0
OctetString pbkdf2_hmac_hash(const std::string& password, const SecureVector& salt, int desiredKeyLength, int iterations)
{
    T hashObject;
    Botan::HMAC hmac(&hashObject);
    Botan::PKCS5_PBKDF2 pbkdf2(&hmac);
    return pbkdf2.derive_key(desiredKeyLength, password, salt.data(), salt.size(), iterations);
}
SecureVector<Botan::byte> ne7ssh_keys::generateRSASignature (Botan::SecureVector<Botan::byte>& sessionID, Botan::SecureVector<Botan::byte>& signingData)
{
  SecureVector<Botan::byte> sigRaw;
  ne7ssh_string sigData, sig;

  sigData.addVectorField (sessionID);
  sigData.addVector (signingData);
  if (!rsaPrivateKey)
  {
    ne7ssh::errors()->push (-1, "Private RSA key not initialized.");
    return sig.value();
  }

  PK_Signer *RSASigner = get_pk_signer (*rsaPrivateKey, "EMSA3(SHA-1)");
#if BOTAN_PRE_18 || BOTAN_PRE_15
  sigRaw = RSASigner->sign_message(sigData.value());
#else
  sigRaw = RSASigner->sign_message(sigData.value(), *ne7ssh::rng);
#endif
  if (!sigRaw.size())
  {
    ne7ssh::errors()->push (-1, "Failure while generating RSA signature.");
    delete RSASigner;
    return sig.value();
  }

  delete RSASigner;
  sig.addString ("ssh-rsa");
  sig.addVectorField (sigRaw);
  return (sig.value());
}
void ne7ssh_string::addBigInt(const Botan::BigInt& bn)
{
    SecureVector<Botan::byte> converted;
    bn2vector(converted, bn);
    uint32 nLen = htonl(converted.size());

    _buffer += SecureVector<Botan::byte>((Botan::byte*)&nLen, sizeof(uint32));
    _buffer += SecureVector<Botan::byte>(converted);
}
Exemple #7
0
/*
* Split up and process handshake messages
*/
void TLS_Server::read_handshake(byte rec_type,
                                const MemoryRegion<byte>& rec_buf)
   {
   if(rec_type == HANDSHAKE)
      {
      if(!state)
         state = new Handshake_State;
      state->queue.write(&rec_buf[0], 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 size_t 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[0], 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;
      }
   }
SecureVector<Botan::byte> ne7ssh_keys::generateDSASignature (Botan::SecureVector<Botan::byte>& sessionID, Botan::SecureVector<Botan::byte>& signingData)
{
  SecureVector<Botan::byte> sigRaw;
  ne7ssh_string sigData, sig;

  sigData.addVectorField (sessionID);
  sigData.addVector (signingData);
  if (!dsaPrivateKey)
  {
    ne7ssh::errors()->push (-1, "Private DSA key not initialized.");
    return sig.value();
  }

  PK_Signer *DSASigner = get_pk_signer (*dsaPrivateKey, "EMSA1(SHA-1)");
#if BOTAN_PRE_18 || BOTAN_PRE_15
  sigRaw = DSASigner->sign_message(sigData.value());
#else
  sigRaw = DSASigner->sign_message(sigData.value(), *ne7ssh::rng);
#endif

  if (!sigRaw.size())
  {
    ne7ssh::errors()->push (-1, "Failure to generate DSA signature.");
    delete DSASigner;
    return sig.value();
  }

  if (sigRaw.size() != 40)
  {
    ne7ssh::errors()->push (-1, "DSS signature block <> 320 bits. Make sure you are using 1024 bit keys for authentication!");
    sig.clear();
    return sig.value();
  }

  delete DSASigner;
  sig.addString ("ssh-dss");
  sig.addVectorField (sigRaw);
  return (sig.value());
}
int main()
   {
   Botan::LibraryInitializer init;

   AutoSeeded_RNG rng;

   std::string passphrase = "secret";

   std::ifstream infile("readme.txt");
   std::ofstream outfile("readme.txt.enc");

   PKCS5_PBKDF2 pbkdf2(new HMAC(new SHA_160));

   pbkdf2.set_iterations(4096);
   pbkdf2.new_random_salt(rng, 8);
   SecureVector<byte> the_salt = pbkdf2.current_salt();

   SecureVector<byte> master_key = pbkdf2.derive_key(48, passphrase).bits_of();

   KDF* kdf = get_kdf("KDF2(SHA-1)");

   SymmetricKey key = kdf->derive_key(20, master_key, "cipher key");
   SymmetricKey mac_key = kdf->derive_key(20, master_key, "hmac key");
   InitializationVector iv = kdf->derive_key(8, master_key, "cipher iv");

   Pipe pipe(new Fork(
                new Chain(
                   get_cipher("Blowfish/CBC/PKCS7", key, iv, ENCRYPTION),
                   new Base64_Encoder,
                   new DataSink_Stream(outfile)
                   ),
                new Chain(
                   new MAC_Filter("HMAC(SHA-1)", mac_key),
                   new Hex_Encoder)
                )
      );

   outfile.write((const char*)the_salt.begin(), the_salt.size());

   pipe.start_msg();
   infile >> pipe;
   pipe.end_msg();

   SecureVector<byte> hmac = pipe.read_all(1);
   outfile.write((const char*)hmac.begin(), hmac.size());
   }
int main()
   {
   Botan::LibraryInitializer init;

   try {

      X509_Certificate mycert("mycert.pem");
      X509_Certificate mycert2("mycert2.pem");
      X509_Certificate yourcert("yourcert.pem");
      X509_Certificate cacert("cacert.pem");
      X509_Certificate int_ca("int_ca.pem");

      AutoSeeded_RNG rng;

      X509_Store store;
      store.add_cert(mycert);
      store.add_cert(mycert2);
      store.add_cert(yourcert);
      store.add_cert(int_ca);
      store.add_cert(cacert, true);

      const std::string msg = "prioncorp: we don't toy\n";

      CMS_Encoder encoder(msg);

      encoder.compress("Zlib");
      encoder.digest();
      encoder.encrypt(rng, mycert);

      /*
      PKCS8_PrivateKey* mykey = PKCS8::load_key("mykey.pem", rng, "cut");
      encoder.sign(store, *mykey);
      */

      SecureVector<byte> raw = encoder.get_contents();
      std::ofstream out("out.der");

      out.write((const char*)raw.begin(), raw.size());
   }
   catch(std::exception& e)
      {
      std::cerr << e.what() << std::endl;
      }
   return 0;
   }
QByteArray SshAbstractCryptoFacility::generateHash(const SshKeyExchange &kex,
    char c, quint32 length)
{
    const QByteArray &k = kex.k();
    const QByteArray &h = kex.h();
    QByteArray data(k);
    data.append(h).append(c).append(m_sessionId);
    SecureVector<byte> key
        = kex.hash()->process(convertByteArray(data), data.size());
    while (key.size() < length) {
        SecureVector<byte> tmpKey;
        tmpKey += SecureVector<byte>(convertByteArray(k), k.size());
        tmpKey += SecureVector<byte>(convertByteArray(h), h.size());
        tmpKey += key;
        key += kex.hash()->process(tmpKey);
    }
    return QByteArray(reinterpret_cast<const char *>(key.begin()), length);
}
Exemple #12
0
void Address::encode_address(uint64_t version, uint64_t stream, const SecureVector& ripe)
{
    if(ripe.size() != 20)
        throw SizeException(__FILE__, __FUNCTION__, __LINE__, "The ripe length is not 20");

    SecureVector ripex;

    if(ripe[0] == 0x00 && ripe[1] == 0x00)
        std::copy(ripe.begin() + 2, ripe.end(), std::back_inserter(ripex));
    else if(ripe[0] == 0x00)
        std::copy(ripe.begin() + 1, ripe.end(), std::back_inserter(ripex));
    else ripex = ripe;

    SecureVector bm_addr = encode::varint(version);
    bm_addr += encode::varint(stream);
    bm_addr += ripex;

    SecureVector checksum = hash::sha512(hash::sha512(bm_addr));
    std::copy(checksum.begin(), checksum.begin() + 4, std::back_inserter(bm_addr));

    m_address = encode::base58(bm_addr);
}
void SshKeyExchange::sendNewKeysPacket(const SshIncomingPacket &dhReply,
    const QByteArray &clientId)
{

    const SshKeyExchangeReply &reply
        = dhReply.extractKeyExchangeReply(m_serverHostKeyAlgo);
    if (m_dhKey && (reply.f <= 0 || reply.f >= m_dhKey->group_p())) {
        throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_KEY_EXCHANGE_FAILED,
            "Server sent invalid f.");
    }

    QByteArray concatenatedData = AbstractSshPacket::encodeString(clientId);
    concatenatedData += AbstractSshPacket::encodeString(m_serverId);
    concatenatedData += AbstractSshPacket::encodeString(m_clientKexInitPayload);
    concatenatedData += AbstractSshPacket::encodeString(m_serverKexInitPayload);
    concatenatedData += reply.k_s;
    SecureVector<byte> encodedK;
    if (m_dhKey) {
        concatenatedData += AbstractSshPacket::encodeMpInt(m_dhKey->get_y());
        concatenatedData += AbstractSshPacket::encodeMpInt(reply.f);
        DH_KA_Operation dhOp(*m_dhKey);
        SecureVector<byte> encodedF = BigInt::encode(reply.f);
        encodedK = dhOp.agree(encodedF, encodedF.size());
    } else {
        Q_ASSERT(m_ecdhKey);
        concatenatedData // Q_C.
                += AbstractSshPacket::encodeString(convertByteArray(m_ecdhKey->public_value()));
        concatenatedData += AbstractSshPacket::encodeString(reply.q_s);
        ECDH_KA_Operation ecdhOp(*m_ecdhKey);
        encodedK = ecdhOp.agree(convertByteArray(reply.q_s), reply.q_s.count());
    }
    const BigInt k = BigInt::decode(encodedK);
    m_k = AbstractSshPacket::encodeMpInt(k); // Roundtrip, as Botan encodes BigInts somewhat differently.
    concatenatedData += m_k;

    m_hash.reset(get_hash(botanHMacAlgoName(hashAlgoForKexAlgo())));
    const SecureVector<byte> &hashResult = m_hash->process(convertByteArray(concatenatedData),
                                                           concatenatedData.size());
    m_h = convertByteArray(hashResult);

#ifdef CREATOR_SSH_DEBUG
    printData("Client Id", AbstractSshPacket::encodeString(clientId));
    printData("Server Id", AbstractSshPacket::encodeString(m_serverId));
    printData("Client Payload", AbstractSshPacket::encodeString(m_clientKexInitPayload));
    printData("Server payload", AbstractSshPacket::encodeString(m_serverKexInitPayload));
    printData("K_S", reply.k_s);
    printData("y", AbstractSshPacket::encodeMpInt(m_dhKey->get_y()));
    printData("f", AbstractSshPacket::encodeMpInt(reply.f));
    printData("K", m_k);
    printData("Concatenated data", concatenatedData);
    printData("H", m_h);
#endif // CREATOR_SSH_DEBUG

    QScopedPointer<Public_Key> sigKey;
    if (m_serverHostKeyAlgo == SshCapabilities::PubKeyDss) {
        const DL_Group group(reply.parameters.at(0), reply.parameters.at(1),
            reply.parameters.at(2));
        DSA_PublicKey * const dsaKey
            = new DSA_PublicKey(group, reply.parameters.at(3));
        sigKey.reset(dsaKey);
    } else if (m_serverHostKeyAlgo == SshCapabilities::PubKeyRsa) {
        RSA_PublicKey * const rsaKey
            = new RSA_PublicKey(reply.parameters.at(1), reply.parameters.at(0));
        sigKey.reset(rsaKey);
    } else if (m_serverHostKeyAlgo == SshCapabilities::PubKeyEcdsa) {
        const PointGFp point = OS2ECP(convertByteArray(reply.q), reply.q.count(),
                                      m_ecdhKey->domain().get_curve());
        ECDSA_PublicKey * const ecdsaKey = new ECDSA_PublicKey(m_ecdhKey->domain(), point);
        sigKey.reset(ecdsaKey);
    } else {
        Q_ASSERT(!"Impossible: Neither DSS nor RSA nor ECDSA!");
    }

    const byte * const botanH = convertByteArray(m_h);
    const Botan::byte * const botanSig = convertByteArray(reply.signatureBlob);
    PK_Verifier verifier(*sigKey, botanEmsaAlgoName(m_serverHostKeyAlgo));
    if (!verifier.verify_message(botanH, m_h.size(), botanSig, reply.signatureBlob.size())) {
        throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_KEY_EXCHANGE_FAILED,
            "Invalid signature in key exchange reply packet.");
    }

    checkHostKey(reply.k_s);

    m_sendFacility.sendNewKeysPacket();
    m_dhKey.reset(nullptr);
    m_ecdhKey.reset(nullptr);
}
/*!
    Decrypts \a data using \a password as the passphrase.

    \param data The data to decrypt, encoded in base 64.
    \param password The passphrase used to decrypt \a data.
    \param error If this parameter is non-\c NULL, it will be set to DatabaseCrypto::NoError if the
    decryption process succeeded, or one of the other DatabaseCrypto::CryptoStatus enumeration
    constants if an error occurred.
    \param extendedErrorInformation If this parameter is non-\c NULL, it will be set to a string
    containing detailed information about any errors that occurred.

    \return The decrypted data, or an empty string if an error occurred.
 */
QString DatabaseCrypto::decrypt(const QString &data, const QString &password, CryptoStatus *error, QString *extendedErrorInformation)
{
    const std::string algo = ALGO;
    const QString header = HEADER;

    Botan::LibraryInitializer init;
    Q_UNUSED(init);

    if (error)
    {
        *error = NoError;
    }

    std::string passphrase = password.toStdString();

    // Create a stream to read the input data
    QString dataCopy = data;
    QTextStream in(&dataCopy, QIODevice::ReadOnly);

    try
    {
        // Read the actual header line and store the expected prefix
        QString actualHeaderLine = in.readLine();
        QString headerLine = QString("%1 ").arg(header);

        // If the actual header is less than (or equal!) to our expected one, there is no version
        // and is thus invalid, OR if the actual header doesn't start with our header, it's invalid
        if (actualHeaderLine.length() <= headerLine.length() || !actualHeaderLine.startsWith(headerLine))
        {
            if (error)
            {
                *error = MissingHeader;
            }

            return QString();
        }

        // Everything after the "SILVERLOCK DATABASE FILE"
        QStringList theRest = actualHeaderLine.right(actualHeaderLine.length() - headerLine.length())
                              .split(' ', QString::SkipEmptyParts);
        if (theRest.count() == 2)
        {
            QString version(theRest[0]);
            if (version.simplified() != Database::version())
            {
                if (error)
                {
                    *error = UnsupportedVersion;
                }

                return QString();
            }
        }
        else
        {
            if (error)
            {
                *error = MissingHeader;
            }

            return QString();
        }

        std::string salt_str = in.readLine().toStdString();
        std::string mac_str = in.readLine().toStdString();

        //std::cout << "Salt in file: " << salt_str << std::endl;
        //std::cout << "MAC in file: " << mac_str << std::endl;

        const BlockCipher* cipher_proto = global_state().algorithm_factory().prototype_block_cipher(algo);
        const u32bit key_len = cipher_proto->maximum_keylength();
        const u32bit iv_len = cipher_proto->block_size();
        const u32bit iterations = 8192;

        //std::cout << "Key length: " << key_len << " bytes" << std::endl;
        //std::cout << "IV length: " << iv_len << " bytes" << std::endl;

        SecureVector<Botan::byte> salt = b64_decode(salt_str);

        std::auto_ptr<PBKDF> pbkdf(get_pbkdf("PBKDF2(SHA-1)"));
        SymmetricKey bc_key = pbkdf->derive_key(key_len, "BLK" + passphrase, &salt[0], salt.size(), iterations);
        InitializationVector iv = pbkdf->derive_key(iv_len, "IVL" + passphrase, &salt[0], salt.size(), iterations);
        SymmetricKey mac_key = pbkdf->derive_key(16, "MAC" + passphrase, &salt[0], salt.size(), iterations);

        //std::cout << "BC Key: " << bc_key.as_string() << std::endl;
        //std::cout << "IV: " << iv.as_string() << std::endl;
        //std::cout << "MAC: " << mac_key.as_string() << std::endl;

        Pipe pipe(
            new Base64_Decoder,
            get_cipher(algo + "/CBC/PKCS7", bc_key, iv, DECRYPTION),
            new Fork(
                NULL,
                new Chain(
                    new MAC_Filter("HMAC(SHA-1)", mac_key),
                    new Base64_Encoder)));

        // Read all our data into the pipe for decryption
        pipe.start_msg();
        pipe.write(in.readAll().toStdString());
        pipe.end_msg();

        // Read the message authentication code from the pipe
        // and verify that it matches what was in the file
        std::string generatedMacStr = pipe.read_all_as_string(1);
        //std::cout << generatedMacStr << std::endl;
        if (generatedMacStr != mac_str)
        {
            if (error)
            {
                *error = VerificationFailed;
            }

            return QString();
        }

        // No errors were encountered; return the decrypted data
        SecureVector<Botan::byte> rawDecryptedData = pipe.read_all(0);
        //qDebug() << rawDecryptedData.size();
        QByteArray qDecryptedData(rawDecryptedData.size(), '\0');
        for (int i = 0; i < qDecryptedData.size(); i++)
        {
            qDecryptedData[i] = rawDecryptedData[i];
        }

        return QString::fromUtf8(qUncompress(qDecryptedData));
    }
    catch (Algorithm_Not_Found &e)
    {
        if (extendedErrorInformation)
        {
            *extendedErrorInformation = QString(e.what());
        }

        if (error)
        {
            *error = UnknownError;
        }
    }
    catch (Decoding_Error &e)
    {
        if (extendedErrorInformation)
        {
            *extendedErrorInformation = QString(e.what());
        }

        if (error)
        {
            *error = DecodingError;
        }
    }
    catch (std::exception &e)
    {
        if (extendedErrorInformation)
        {
            *extendedErrorInformation = QString(e.what());
        }

        if (error)
        {
            *error = UnknownError;
        }
    }

    return QString();
}
Exemple #15
0
* Encrypt in EAX mode
*/
void EAX_Encryption::write(const byte input[], size_t length)
   {
   while(length)
      {
      size_t copied = std::min<size_t>(length, ctr_buf.size());

      ctr->cipher(input, &ctr_buf[0], copied);
      cmac->update(&ctr_buf[0], copied);

      send(ctr_buf, copied);
      input += copied;
      length -= copied;
      }
   }

/*
* Finish encrypting in EAX mode
*/
void EAX_Encryption::end_msg()
   {
   SecureVector<byte> data_mac = cmac->final();
   xor_buf(data_mac, nonce_mac, data_mac.size());
   xor_buf(data_mac, header_mac, data_mac.size());

   send(data_mac, TAG_SIZE);
   }

}
bool ne7ssh_keys::getKeyPairFromFile (const char* privKeyFileName)
{
  ne7ssh_string privKeyStr;
  char* buffer;
  uint32 pos, i, length;

  if (!privKeyStr.addFile (privKeyFileName))
  {
    ne7ssh::errors()->push (-1, "Cannot read PEM file: '%s'. Permission issues?", privKeyFileName);
    return false;
  }

  buffer = (char*) malloc (privKeyStr.length() + 1);
  memcpy (buffer, (const char*)privKeyStr.value().begin(), privKeyStr.length());
  buffer[privKeyStr.length()] = 0x0;

  length = privKeyStr.length();

  for (i = pos = 0; i < privKeyStr.length(); i++)
  {
    if (isspace(buffer[i]))
    {
      while (i < privKeyStr.length() && isspace (buffer[i]))
      {
        if (buffer[pos] != '\n')
          buffer[pos] = buffer[i];
        if (++i >= privKeyStr.length()) break;
      }
      i--;
      pos++;
      continue;
    }
    buffer[pos] = buffer[i];
    pos++;
  }
  buffer[pos] = 0x00;
  length = pos;

  if ((memcmp (buffer, "-----BEGIN", 10)) ||
     (memcmp (buffer + length - 17, "PRIVATE KEY-----", 16)))
  {
    ne7ssh::errors()->push (-1, "Encountered unknown PEM file format. Perhaps not an SSH private key file: '%s'.", privKeyFileName);
    free (buffer);
    return false;
  }

  if (!memcmp (buffer, "-----BEGIN RSA PRIVATE KEY-----", 31))
    this->keyAlgo = ne7ssh_keys::RSA;
  else if (!memcmp (buffer, "-----BEGIN DSA PRIVATE KEY-----", 31))
    this->keyAlgo = ne7ssh_keys::DSA;
  else
  {
    ne7ssh::errors()->push (-1, "Encountered unknown PEM file format. Perhaps not an SSH private key file: '%s'.", privKeyFileName);
    free (buffer);
    return false;
  }

  SecureVector<Botan::byte> keyVector ((Botan::byte*)buffer, length);
  free (buffer);
  switch (this->keyAlgo)
  {
    case DSA:
      if (!getDSAKeys ((char*)keyVector.begin(), keyVector.size()))
        return false;
      break;

    case RSA:
      if (!getRSAKeys ((char*)keyVector.begin(), keyVector.size()))
        return false;
      break;
  }

  return true;

}