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());
}
예제 #2
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);
}
예제 #3
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);
   }
예제 #4
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());
         }
예제 #5
0
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);
}
예제 #6
0
파일: crypt.cpp 프로젝트: skotopes/ssh-bot
void ne7ssh_crypt::decompressData (Botan::SecureVector<Botan::byte> &buffer)
{
  SecureVector<Botan::byte> tmpVar;
  if (!decompress) return;
  
  tmpVar.swap (buffer);
  decompress->process_msg (tmpVar);
  tmpVar = decompress->read_all (compress->message_count() - 1);
  buffer = Botan::SecureVector<Botan::byte>(tmpVar);
}
예제 #7
0
/**
* Serialize a Certificate Verify message
*/
SecureVector<byte> Certificate_Verify::serialize() const
   {
   SecureVector<byte> buf;

   const u16bit sig_len = signature.size();
   buf.push_back(get_byte(0, sig_len));
   buf.push_back(get_byte(1, sig_len));
   buf += signature;

   return buf;
   }
예제 #8
0
uint64_t Address::extract_stream_number(const std::string& address)
{
    if(!check::address(address))
        throw ParseException(__FILE__, __FUNCTION__, __LINE__, "Invalid address checksum");

    int nb;
    std::string addr = utils::remove_prefix(address, "BM-");
    SecureVector bytes = decode::base58(addr);

    decode::varint(bytes.data(), nb);
    return decode::varint(&bytes[nb], nb);
}
예제 #9
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;
      }
   }
예제 #10
0
파일: big_code.cpp 프로젝트: pbek/qca
/*************************************************
* 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;
}
예제 #11
0
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());
   }
예제 #12
0
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;
   }
예제 #13
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);
}
예제 #14
0
bool password_hash_ok(const std::string& pass, const std::string& hash)
   {
   Pipe pipe(new Base64_Decoder);
   pipe.start_msg();
   pipe.write(hash);
   pipe.end_msg();

   SecureVector<byte> hash_bin = pipe.read_all();

   PKCS5_PBKDF2 kdf(new HMAC(new SHA_160));

   kdf.set_iterations(10000);
   kdf.change_salt(hash_bin, 6);

   SecureVector<byte> cmp = kdf.derive_key(12, pass).bits_of();

   return same_mem(cmp.begin(), hash_bin.begin() + 6, 12);
   }
예제 #15
0
void ne7ssh_string::bn2vector(Botan::SecureVector<Botan::byte>& result, const Botan::BigInt& bi)
{
    int high;
    Botan::byte zero = '\0';

    SecureVector<Botan::byte> strVector = BigInt::encode(bi);

    high = (*(strVector.begin()) & 0x80) ? 1 : 0;

    if (high)
    {
        result = SecureVector<Botan::byte>(&zero, 1);
    }
    else
    {
        result.clear();
    }
    result += strVector;
}
예제 #16
0
파일: bip39.cpp 프로젝트: prapun77/monoeci
// passphrase must be at most 256 characters or code may crash
void CMnemonic::ToSeed(SecureString mnemonic, SecureString passphrase, SecureVector& seedRet)
{
    SecureString ssSalt = SecureString("mnemonic") + passphrase;
    SecureVector vchSalt(ssSalt.begin(), ssSalt.end());
    seedRet.resize(64);
    // int PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
    //                    const unsigned char *salt, int saltlen, int iter,
    //                    const EVP_MD *digest,
    //                    int keylen, unsigned char *out);
    PKCS5_PBKDF2_HMAC(mnemonic.c_str(), mnemonic.size(), &vchSalt[0], vchSalt.size(), 2048, EVP_sha512(), 64, &seedRet[0]);
}
예제 #17
0
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());
}
예제 #18
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);
}
예제 #19
0
// encoding and decoding
SecureVector<byte> EC2OSP(const PointGFp& point, byte format)
   {
   if(point.is_zero())
      return SecureVector<byte>(1); // single 0 byte

   const size_t p_bytes = point.get_curve().get_p().bytes();

   BigInt x = point.get_affine_x();
   BigInt y = point.get_affine_y();

   SecureVector<byte> bX = BigInt::encode_1363(x, p_bytes);
   SecureVector<byte> bY = BigInt::encode_1363(y, p_bytes);

   if(format == PointGFp::UNCOMPRESSED)
      {
      SecureVector<byte> result;
      result.push_back(0x04);

      result += bX;
      result += bY;

      return result;
      }
   else if(format == PointGFp::COMPRESSED)
      {
      SecureVector<byte> result;
      result.push_back(0x02 | static_cast<byte>(y.get_bit(0)));

      result += bX;

      return result;
      }
   else if(format == PointGFp::HYBRID)
      {
      SecureVector<byte> result;
      result.push_back(0x06 | static_cast<byte>(y.get_bit(0)));

      result += bX;
      result += bY;

      return result;
      }
   else
      throw Invalid_Argument("illegal point encoding format specification");
   }
예제 #20
0
/*!
    Encrypts \a data using \a password as the passphrase.

    \param data The data to encrypt.
    \param password The passphrase used to encrypt \a data.
    \param compressionLevel The level of compression to use on \a data. See Database::compression.
    \param error If this parameter is non-\c NULL, it will be set to DatabaseCrypto::NoError if the
    encryption 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 encrypted data encoded in base 64, or an empty string if an error occurred.
 */
QString DatabaseCrypto::encrypt(const QString &data, const QString &password, int compressionLevel, 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();

    // Holds the output data
    QString out;

    try
    {
        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(); // TODO: AES block size is always 128 bit, verify this
        const bool compressed = compressionLevel != 0;
        const u32bit iterations = 8192;

        AutoSeeded_RNG rng;
        SecureVector<Botan::byte> salt(8);
        rng.randomize(&salt[0], salt.size());

        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);

        // Write the standard file header and the salt encoded in base64
        out += QString("%1 %2 %3\n").arg(header).arg(Database::version())
               .arg(compressed ? COMPRESSED : UNCOMPRESSED);
        out += QString::fromStdString(b64_encode(salt)) + "\n";

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

        // Write our input data to the pipe to process it - if compressionLevel = 0,
        // nothing will be compressed
        pipe.start_msg();
        QByteArray qCompressedData = qCompress(data.toUtf8(), compressionLevel);
        SecureVector<Botan::byte> rawCompressedData;
        rawCompressedData.resize(qCompressedData.length());
        for (int i = 0; i < qCompressedData.length(); i++)
        {
            rawCompressedData[i] = qCompressedData[i];
        }

        pipe.write(rawCompressedData);
        pipe.end_msg();

        // Get the encrypted data back from the pipe and write it to our output variable
        out += QString::fromStdString(pipe.read_all_as_string(0)) + "\n";
        out += QString::fromStdString(pipe.read_all_as_string(1));

        return out;
    }
    catch (Algorithm_Not_Found &e)
    {
        if (extendedErrorInformation)
        {
            *extendedErrorInformation = QString(e.what());
        }

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

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

    return QString();
}
예제 #21
0
/*!
    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();
}
예제 #22
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);
   }

}
	void TearDownBase()
	{
		encryptor_.SetIsPlainText();
		buffer_.clear();
		remove(temp_file_.c_str());
	}
예제 #24
0
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;

}
예제 #25
0
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);
}
	void SetUpBase()
	{
		initial_string_.resize(text_to_encrypt_.size());
		initial_string_.copy(reinterpret_cast<const byte*>(text_to_encrypt_.c_str()), text_to_encrypt_.size());
	}