NarrowString HTMLEntityCodec::encodeCharacter(const StringArray& immune, const NarrowString& ch) const
  {
    // ASSERT(!immune.empty());
    ASSERT(!ch.empty());

    if(ch.empty())
      return NarrowString();

    // check for immune characters
    StringArray::const_iterator it1 = std::find(immune.begin(), immune.end(), ch);
    if(it1 != immune.end())
      return ch;

    // check for simple alphanumeric characters
    if(ch.length() == 1 && ::isalnum(ch[0]))
      return ch;

    // check for illegal characterss
    //if ( ( c <= 0x1f && c != L'\t' && c != L'\n' && c != L'\r' ) || ( c >= 0x7f && c <= 0x9f ) )
    //{
    // hex = REPLACEMENT_HEX(); // Let's entity encode this instead of returning it
    // c = REPLACEMENT_CHAR();
    //}

    // check if there's a defined entity
    const EntityMap& map = getCharacterToEntityMap();
    EntityMapIterator it2 = map.find(ch);
    if(it2 != map.end())
      return String("&") + it2->second + String(";");

    // return the hex entity as suggested in the spec
    return NarrowString("&#x") + toHex(ch) + NarrowString(";");
  }
 /**
  * Return true if specified cipher mode is one of those specified in the
  * {@code ESAPI.properties} file that supports both confidentiality
  * <b>and</b> authenticity (i.e., a "combined cipher mode" as NIST refers
  * to it).
  * @param cipherMode     The specified cipher mode to be used for the encryption
  *                       or decryption operation.
  * @return     true if the specified cipher mode is in the comma-separated list
  *             of cipher modes supporting both confidentiality and authenticity;
  *             otherwise false.
  * @see org.owasp.esapi.SecurityConfiguration#getCombinedCipherModes()
  */
 bool CryptoHelper::isCombinedCipherMode(const NarrowString& cipherMode)
 {
   ESAPI_ASSERT2( !cipherMode.empty(), "cipherMode is not valid" );
   if(cipherMode.empty())
     throw IllegalArgumentException("Cipher mode is not valid");
       
   DummyConfiguration config;
   const StringList& cipherModes = config.getCombinedCipherModes();
   
   StringList::const_iterator it = std::find(cipherModes.begin(), cipherModes.end(), cipherMode);
   return it != cipherModes.end();
 }
Esempio n. 3
0
status_t UDF_ReadFromReader(Reader& origReader, UniversalDataFormat& out)
{
    BufferedReader reader(origReader, 1024);
    ulong_t lineNo = 0;
    ulong_t controlDataLength = 0;
    bool eof = false;
    out.reset();
    while (!eof)
    {
        NarrowString line;
        status_t error = reader.readLine(eof, line);
        if (errNone != error)
            return error;
            
        if (eof && line.empty()) //writer puts '\n' after last line... 
            break;

        error = parseUniversalDataFormatTextLine(line.data(), line.length(), out, lineNo, controlDataLength);
        if (errNone != error)
            return error;
    }
    assert(controlDataLength == out.dataLength());
    if (controlDataLength != out.dataLength())
        return SocketConnection::errResponseMalformed
        ;
    return errNone;
}
 /**
  * Constructs a secure random number generator (RNG) implementing the named
  * random number algorithm.
  */
 SecureRandomBase::SecureRandomBase(const NarrowString& algorithm, const byte*, size_t)
     : m_catastrophic(false), m_algorithm(algorithm)
 {
     ASSERT( !algorithm.empty() );
     //ASSERT(seed);
     //ASSERT(size); 
 }
 /**
  * Constructs a secure random number generator (RNG) implementing the named
  * random number algorithm if specified
  */
 SecureRandom::SecureRandom(const NarrowString& algorithm)   
     : m_lock(new Mutex),
       m_impl(SecureRandomBase::createInstance(AlgorithmName::normalizeAlgorithm(algorithm), nullptr, 0))    
 {
     ASSERT( !algorithm.empty() );
     ASSERT(m_lock.get() != nullptr);
     ASSERT(m_impl.get() != nullptr);
 }
    /**
     * Returns a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.
     */
    SecureRandom SecureRandom::getInstance(const NarrowString& algorithm)
    {
        ASSERT( !algorithm.empty() );

        const NarrowString alg(AlgorithmName::normalizeAlgorithm(algorithm));
        SecureRandomBase* impl = SecureRandomBase::createInstance(alg, nullptr, 0);
        MEMORY_BARRIER();

        ASSERT(impl != nullptr);
        return SecureRandom(impl);
    }
  /**
   * Generate a random secret key appropriate to the specified cipher algorithm
   * and key size.
   * @param alg        The cipher algorithm or cipher transformation. (If the latter is
   *                   passed, the cipher algorithm is determined from it.) Cannot be empty.
   * @param keyBits    The key size, in bits.
   * @return           A random {@code SecretKey} is returned.
   */
  SecretKey CryptoHelper::generateSecretKey(const NarrowString& alg, unsigned int keyBits)
  {
    ASSERT( !alg.empty() );
    ASSERT( keyBits >= 56 );
    ASSERT( (keyBits % 8) == 0 );

    KeyGenerator kgen(KeyGenerator::getInstance(alg));
    kgen.init(keyBits);

    return kgen.generateKey();
  }
  AlgorithmName::AlgorithmName(const NarrowString& algorithm, bool cipherOnly)
    : m_normal(normalizeAlgorithm(algorithm))
  {
    ASSERT( !algorithm.empty() );

    // We'd prefer to throw in the ctor, but its a limitation, not a feature!
    // Actually, we need to narmalize first (in case of throw), so maybe it is a feature.
    NarrowString cipher;
    getCipher(cipher);

    if(cipherOnly && m_normal != cipher)
      throw NoSuchAlgorithmException(m_normal + " not available");
  }
  /**
  * Returns a KeyGenerator object that generates secret keys for the specified algorithm.
  */
  KeyGenerator KeyGenerator::getInstance(const NarrowString& algorithm)
  {
    ASSERT( !algorithm.empty() );
    KeyGenerator kgen(algorithm);

    // http://download.oracle.com/javase/6/docs/api/javax/crypto/KeyGenerator.html
    // "This class provides the functionality of a secret (symmetric) key generator."
    NarrowString cipher = kgen.getAlgorithm();
    if(cipher != "DES" && cipher != "DES_ede" && cipher != "Blowfish" && cipher != "AES" &&
      cipher != "Camellia" && cipher != "HmacSHA1" && cipher != "HmacSHA224" &&
      cipher != "HmacSHA256" && cipher != "HmacSHA384"&& cipher != "HmacSHA512" &&
      cipher != "HmacWhirlpoo" )
    {
      throw NoSuchAlgorithmException(cipher + " KeyGenerator not available");
    }

    return kgen;
  }
Esempio n. 10
0
status_t resolve(SocketAddress& out, NetLibrary& netLib, const char* address, ushort_t port, ulong_t timeout)
{
    NarrowString validAddress;
    status_t error = validateAddress(address, validAddress, port);
    if (error)
        return error;
        
    INetSocketAddress addr;
    // TODO: the assumption that the ip address is numeric if the first
    // letter is a digit is incorrect. A symbolic name can also start
    // with a digit. Better test would be to check if the whole name
    // consists of digits or "."
    if (!validAddress.empty() && isDigit(validAddress[0]))
    {
        error=netLib.addrAToIN(validAddress.c_str(), addr);
        if (error)
            return error;
        addr.setPort(port);
        out=addr;
        return errNone;
    }
    return blockingResolve(out, netLib, validAddress, port, timeout);
}
 PushbackString::PushbackString(const NarrowString& input)
   : input(input), varPushback(0), varTemp(0), varIndex(0), varMark(0) {
   ASSERT(!input.empty());
 }
  NarrowString AlgorithmName::normalizeAlgorithm(const NarrowString& algorithm)
  {
    ASSERT(!algorithm.empty());

    NarrowString alg(algorithm), mode, padding, temp;

    // Cut out whitespace
    NarrowString::iterator it = std::remove_if(alg.begin(), alg.end(), ::isspace);
    if(it != alg.end())
      alg.erase(it, alg.end());

    // Save the trimmed string
    NarrowString trimmed(alg);

    // Normalize the case
    std::transform(alg.begin(), alg.end(), alg.begin(), ::tolower);

    std::vector<std::string> parts;
    split(alg, "\\/:", parts);

    if(parts.size() == 0)
      throw NoSuchAlgorithmException("Invalid transformation format: '<empty>'");

    // An algorithm is either CIPHER or CIPHER/MODE/PADDING
    if(!(parts.size() == 1 || parts.size() == 3))
      {
        std::ostringstream oss;
        oss << "Invalid transformation format: '" << trimmed << "'";
        throw NoSuchAlgorithmException(oss.str());
      }

    // Clear algorithm for final processing
    alg = mode = padding = "";

    // We should see a CIPHER (ie, HmacSHA1), or a CIPHER/MODE/PADDING.
    temp = parts[0];

    //////// Symmetric Ciphers ////////

    if(temp == "aes")
      alg = "AES";
    else if(temp == "camellia")
      alg = "Camellia";
    else if(temp == "blowfish")
      alg = "Blowfish";
    else if(temp == "des_ede" || temp == "desede")
      alg = "DES_ede";
    else if(temp == "des")
      alg = "DES";

    //////// Hashes ////////

    else if(temp == "md-5" || temp == "md5")
      alg = "MD5";
    else if(temp == "sha-1" || temp == "sha1" || temp == "sha")
      alg = "SHA-1";
    else if(temp == "sha-224" || temp == "sha224")
      alg = "SHA-224";
    else if(temp == "sha-256" || temp == "sha256")
      alg = "SHA-256";
    else if(temp == "sha-384" || temp == "sha384")
      alg = "SHA-384";
    else if(temp == "sha-512" || temp == "sha512")
      alg = "SHA-512";
    else if(temp == "whirlpoo")
      alg = "Whirlpoo";

    //////// HMACs ////////

    else if(temp == "hmacsha-1" || temp == "hmacsha1" || temp == "hmacsha")
      alg = "HmacSHA1";
    else if(temp == "hmacsha-224" || temp == "hmacsha224")
      alg = "HmacSHA224";
    else if(temp == "hmacsha-256" || temp == "hmacsha256")
      alg = "HmacSHA256";
    else if(temp == "hmacsha-384" || temp == "hmacsha384")
      alg = "HmacSHA384";
    else if(temp == "hmacsha-512" || temp == "hmacsha512")
      alg = "HmacSHA512";
    else if(temp == "hmacwhirlpoo")
      alg = "HmacWhirlpoo";

    //////// PBE Hmacs ////////

    else if(temp == "pbewithsha1")
      alg = "PBEWithSHA1";
    else if(temp == "pbewithsha224")
      alg = "PBEWithSHA224";
    else if(temp == "pbewithsha256")
      alg = "PBEWithSHA256";
    else if(temp == "pbewithsha384")
      alg = "PBEWithSHA384";
    else if(temp == "pbewithsha512")
      alg = "PBEWithSHA512";
    else if(temp == "pbewithwhirlpoo")
      alg = "PBEWithWhirlpoo";

    //////// Key Agreement ////////

    else if(temp == "diffiehellman")
      alg = "DiffieHellman";

    //////// SecureRandom ////////

    else if(temp == "sha1prng")
      alg = "SHA1PRNG";

    //////// Oh shit! ////////

    else {
      std::ostringstream oss;
      oss << "Invalid transformation format: '" << trimmed << "', cipher '" << temp << "'";
      ESAPI_ASSERT2(false, oss.str());
      throw NoSuchAlgorithmException(oss.str());
    }

    if(parts.size() == 1)
      return alg;

    // Mode
    temp = parts[1];

    if(temp == "none")
      mode = "NONE";
    else if(temp == "ecb")
      mode = "ECB";
    else if(temp == "cbc")
      mode = "CBC";
    else if(temp == "ofb")
      mode = "OFB";
    else if(temp == "cfb")
      mode = "CFB";
    else if(temp == "ctr")
      mode = "CTR";
#if 0
    // Uncomment in the future
    else if(temp == "ccm")
      mode = "CCM";
    else if(temp == "gcm")
      mode = "GCM";
    else if(temp == "eax")
      mode = "EAX";
#endif

    else {
      std::ostringstream oss;
      oss << "Invalid transformation format: '" << trimmed << "', mode '" << temp << "'";
      ESAPI_ASSERT2(false, oss.str());
      throw NoSuchAlgorithmException(oss.str());
    }

    // Padding
    temp = parts[2];

    if(temp == "nopadding" || temp == "none")
      padding = "NoPadding";
    else if(temp == "pkcs5padding")
      padding = "PKCS5Padding";
    else if(temp == "ssl3padding")
      padding = "SSL3Padding";

    else {
      std::ostringstream oss;
      oss << "Invalid transformation format: '" << trimmed << "', padding '" << temp << "'";
      ESAPI_ASSERT2(false, oss.str());
      throw NoSuchAlgorithmException(oss.str());
    }

    // Remove if we ever get around to adding SSL3 padding.
    if(padding == "SSL3Padding") {
      std::ostringstream oss;
      oss << "Unsupported transformation format: '" << trimmed << "', padding '" << temp << "'";
      throw NoSuchAlgorithmException(oss.str());
    }

    // Final return string
    alg += "/" + mode;
    alg += "/" + padding;

    return alg;
  }
 MessageDigestImpl<HASH>::MessageDigestImpl(const NarrowString& algorithm)
   : MessageDigestBase(algorithm), m_hash()
 {
   ASSERT( !algorithm.empty() );
 }