Exemplo n.º 1
0
result_t hash_base::ripemd160(Buffer_base *data, obj_ptr<Digest_base> &retVal)
{
    return digest(hash_base::_RIPEMD160, data, retVal);
}
Exemplo n.º 2
0
 fc::ecc::public_key          subscribe_message::signee()const
 {
    return fc::ecc::public_key( sig, digest() ); 
 }
Exemplo n.º 3
0
	std::string digest(const void *buf, size_t bufSize)
	{
		std::string md(SHA256_DIGEST_LENGTH, 0);
		digest(&md[0], md.size(), buf, bufSize);
		return md;
	}
Exemplo n.º 4
0
inline std::size_t hash_bytes(const void *const data,
                              const std::size_t size) noexcept {
  auto hashfn = fnv1a_64{};
  hashfn.update(data, size);
  return hashfn.digest();
}
Exemplo n.º 5
0
decrypted_message&  decrypted_message::sign( const fc::ecc::private_key& from )
{
    sig_time  = fc::time_point::now();
    from_sig  = from.sign_compact( digest() );
    return *this;
}
Exemplo n.º 6
0
 bool signed_block_header::validate_signee( const fc::ecc::public_key& expected_signee )const
 { 
    return fc::ecc::public_key( delegate_signature, digest() ) == expected_signee;
 }
Exemplo n.º 7
0
 void signed_block_header::sign( const fc::ecc::private_key& signer )
 { try {
    delegate_signature = signer.sign_compact( digest() );
 } FC_RETHROW_EXCEPTIONS( warn, "" ) }
Exemplo n.º 8
0
String ApLib::getMachineId()
{
  String sData;

#if defined(WIN32)
  String sVolumeSerialNumber;
  if (Apollo::getConfig("System/MachineIdUseVolumeSerialNumber", 1)) {
    DWORD dwVolumeSerialNumber = 0;
    String sRootPathName = "C:\\";
    if (::GetVolumeInformation(
      sRootPathName, // LPCTSTR lpRootPathName,
      0,// LPTSTR lpVolumeNameBuffer,
      0,// DWORD nVolumeNameSize,
      &dwVolumeSerialNumber, // LPDWORD lpVolumeSerialNumber,
      0,// LPDWORD lpMaximumComponentLength,
      0,// LPDWORD lpFileSystemFlags,
      0,// LPTSTR lpFileSystemNameBuffer,
      0 // DWORD nFileSystemNameSize
      )) {
        sVolumeSerialNumber = String::from(dwVolumeSerialNumber);
    }
  }

  String sComputerName;
  if (Apollo::getConfig("System/MachineIdUseComputerName", 1)) {
    WCHAR pNameBuffer[10240+1];
    DWORD nNameBufferSize = 10240;
    if (::GetComputerName(pNameBuffer, &nNameBufferSize)) {
      pNameBuffer[nNameBufferSize] = 0;
      sComputerName = pNameBuffer;
    }
  }

  String sMacAddress;
  if (Apollo::getConfig("System/MachineIdUseMacAddress", 1)) {
    List lAddress;

    DWORD dwBufLen = 0;
    if (::GetAdaptersInfo(0, &dwBufLen) == ERROR_BUFFER_OVERFLOW) {
      PIP_ADAPTER_INFO pAdapterInfo = (PIP_ADAPTER_INFO) malloc(dwBufLen);
      if (pAdapterInfo != 0) {
        if (GetAdaptersInfo(pAdapterInfo, &dwBufLen) == ERROR_SUCCESS) {
          PIP_ADAPTER_INFO ppAdapterInfo = pAdapterInfo;
          do {
            String sIpAddress = (char*) & (ppAdapterInfo->IpAddressList.IpAddress);
            if (  sIpAddress != "0.0.0.0" 
              &&  sIpAddress != "127.0.0.1"
              //&& !sIpAddress.startsWith("10.")
              //&& !sIpAddress.startsWith("169.254.")
              //&& !sIpAddress.startsWith("192.168.")
              //&& !sIpAddress.startsWith("192.0.2.")
              ) {
              String sMac;
              sMac.appendf("%02X%02X%02X%02X%02X%02X"
                , ppAdapterInfo->Address[0]
                , ppAdapterInfo->Address[1]
                , ppAdapterInfo->Address[2]
                , ppAdapterInfo->Address[3]
                , ppAdapterInfo->Address[4]
                , ppAdapterInfo->Address[5]
                );
                lAddress.AddLast(sMac, (long) ppAdapterInfo->DhcpEnabled);
            }

            ppAdapterInfo = ppAdapterInfo->Next;
          } while (ppAdapterInfo != 0);
        }
        ::free(pAdapterInfo);
        pAdapterInfo = 0;
      }
    }

    for (Elem* e = 0; (e = lAddress.Next(e)) != 0; ) {
      if (e->getInt()) {
        sMacAddress += e->getName();
      }
    }

    if (sMacAddress.empty() && lAddress.length() > 0) {
      sMacAddress = lAddress.First()->getName();
    }
  }

  if (sVolumeSerialNumber.isset()) {
    sData += sVolumeSerialNumber;
  }

  if (sComputerName.isset()) {
    sData += sComputerName;
  }

  if (sMacAddress.isset()) {
    sData += sMacAddress;
  }

#endif

  String sMachineId;

  if (sData != "") {
    //sMachineId = sData;
    Apollo::MessageDigest digest((unsigned char *) sData.c_str(), sData.bytes());
    sMachineId = digest.getSHA1Hex();
  }

  return sMachineId;
}
 public_key_type  signed_delegate_testimony::signee()const
 {
    return fc::ecc::public_key( delegate_signature, digest()  );
 }
Exemplo n.º 10
0
void Client::tcpSocketReadyRead() {

//    qDebug("INFO: Client::tcpSocketReadyRead - reporting");

    QByteArray message = s->readAll();

    if ( message.mid(0,4) == tr("GET ").toUtf8() ) {
//        qDebug("INFO: Client::tcpSocketReadyRead - new Handshake");
//        qDebug(message);
    } else {
//        qDebug("INFO: Client::tcpSocketReadyRead - not Handshake!");
//        qDebug(message);

        if ( message.at(0) == char(0) && message.at(message.size()-1) == char(255) ) {
//            qDebug("INFO: Client::tcpSocketReadyRead - new Message!");
            QByteArray ba = message.mid(1, message.size()-2);
            emit gotMessage(n, ba);
//            qDebug(text.toAscii());
        }

        return;
    }


    QByteArray origin;
    if ( message.contains("Origin:") ) {
        int p = message.indexOf("Origin: ");
        int d = message.indexOf("\r\n", p);
        origin = message.mid(p+8, d-p-8);
    }

    int k1, k2;
    k1 = message.indexOf("Sec-WebSocket-Key1:");
    k2 = message.indexOf("Sec-WebSocket-Key2:");

    if ( k1 != -1 || k2 != -1 ) {
//        qDebug("INFO: Client::tcpSocketReadyRead - keys found");
    } else {
        qDebug("ERROR: Client::tcpSocketReadyRead - Sec-WebSocket keys were not found!");
        return;
    }

    QString kt1, kt2;
    kt1 = message.mid(k1+20,message.indexOf("\n",k1+20)-k1-21);
    kt2 = message.mid(k2+20,message.indexOf("\n",k2+20)-k2-21);


    if ( !kt1.contains(" ") || !kt2.contains(" ") ) {
        qDebug("ERROR: Widget::tcpSocketReadyRead - Sec-WebSocket keys had no spaces!");
        return;
    }


    int s1 = 0, s2 = 0;
    unsigned int n1 = 0, n2 = 0;
    for ( int i = 0; i < kt1.length(); i++ ) {
        if ( kt1.at(i).isDigit() )
            n1 = n1*10 + kt1.at(i).digitValue();
        if ( kt1.at(i).isSpace() )
            s1++;
    }
    for ( int i = 0; i < kt2.length(); i++ ) {
        if ( kt2.at(i).isDigit() )
            n2 = n2*10 + kt2.at(i).digitValue();
        if ( kt2.at(i).isSpace() )
            s2++;
    }

    n1 = n1/s1;
    n2 = n2/s2;

    char challenge[16];
    memcpy(challenge, &n1, 4);
    memcpy(challenge+4, &n2, 4);

    char t;
    t = challenge[0];
    challenge[0] = challenge[3];
    challenge[3] = t;
    t = challenge[1];
    challenge[1] = challenge[2];
    challenge[2] = t;
    t = challenge[4];
    challenge[4] = challenge[7];
    challenge[7] = t;
    t = challenge[5];
    challenge[5] = challenge[6];
    challenge[6] = t;

    QString key_3 = message.mid(message.indexOf("\r\n\r\n")+4,8);

    for ( int i = 0; i < 8; i++ )
        challenge[8+i] = key_3.at(i).unicode();

    QCryptographicHash digest(QCryptographicHash::Md5);
    digest.addData(challenge, 16);

    QByteArray location;
    location.append("ws://");
    QByteArray host;
    if ( message.contains("Host:") ) {
        int p = message.indexOf("Host: ");
        int d = message.indexOf("\r\n", p);
        host = message.mid(p+6,d-p-6);
    }
    location.append(host);
    QByteArray resource_name = message.mid(4, message.indexOf(" ",4)-4);
    location.append(resource_name);


    QByteArray responce;
    responce += tr("HTTP/1.1 101 WebSocket Protocol Handshake\r\n");
    responce += tr("Upgrade: WebSocket\r\n");
    responce += tr("Connection: Upgrade\r\n");
    responce += tr("Sec-WebSocket-Origin: ") + origin + tr("\r\n");
    responce += tr("Sec-WebSocket-Location: ") + location + tr("\r\n");
//    responce += tr("Sec-WebSocket-Protocol: \r\n");

    responce += tr("\r\n");
    responce += digest.result();

//    qDebug("Handshake responce\n");
//    qDebug(responce);
//    qDebug(responce.toHex());

    s->write(responce);

    timer = new QTimer(this);
    connect( timer, SIGNAL(timeout()), this, SLOT(handshakeTimeOut()));
    timer->start(0);
}
Exemplo n.º 11
0
Cmd5::Cmd5(unsigned char *pstr)
{
	digest(pstr);
}
Exemplo n.º 12
0
DjVuSource* DjVuSource::FromFile(const CString& strFileName)
{
	TCHAR pszName[MAX_PATH] = { 0 };
	LPTSTR pszFileName;
	GetFullPathName(strFileName, MAX_PATH, pszName, &pszFileName);

	openDocumentsLock.Lock();
	map<CString, DjVuSource*>::iterator itSource = openDocuments.find(pszName);
	if (itSource != openDocuments.end())
	{
		DjVuSource* pSource = (*itSource).second;
		pSource->AddRef();
		openDocumentsLock.Unlock();
		return pSource;
	}

	CFile file;
	if (!file.Open(pszName, CFile::modeRead | CFile::shareDenyWrite))
		return NULL;

	int nLength = static_cast<int>(min(file.GetLength(), 0x40000));
	LPBYTE pBuf = new BYTE[nLength];
	file.Read(pBuf, nLength);
	file.Close();

	MD5 digest(pBuf, nLength);
	delete[] pBuf;

	GP<DjVuDocument> pDoc = NULL;
	try
	{
		GURL url = GURL::Filename::UTF8(MakeUTF8String(CString(pszName)));
		pDoc = DjVuDocument::create(url);
		pDoc->wait_get_pages_num();
	}
	catch (GException&)
	{
		return NULL;
	}

	if (pDoc->get_pages_num() == 0)
	{
		return NULL;
	}

	map<MD5, DocSettings>::iterator it = settings.find(digest);
	bool bExisting = (it != settings.end());
	DocSettings* pSettings = &settings[digest];
	pSettings->strLastKnownLocation = pszName;

	if (!bExisting && pApplication != NULL)
	{
		pApplication->LoadDocSettings(digest.ToString(), pSettings);

		// Remove annotations for non-existing pages.
		map<int, PageSettings>::iterator it;
		for (it = pSettings->pageSettings.begin(); it != pSettings->pageSettings.end();)
		{
			int nPage = it->first;
			if (nPage < 0 || nPage >= pDoc->get_pages_num())
				pSettings->pageSettings.erase(it++);
			else
				++it;
		}
	}

	DjVuSource* pSource = new DjVuSource(pszName, pDoc, pSettings);
	openDocuments.insert(make_pair(CString(pszName), pSource));
	openDocumentsLock.Unlock();

	return pSource;
}
Exemplo n.º 13
0
 void signed_block_header::sign( const fc::ecc::private_key& signer )
 {
    witness_signature = signer.sign_compact( digest() );
 }
Exemplo n.º 14
0
 fc::ecc::public_key signed_block_header::signee()const
 {
    return fc::ecc::public_key( witness_signature, digest(), true/*enforce canonical*/ );
 }
Exemplo n.º 15
0
 bool signed_block_header::validate_signee( const fc::ecc::public_key& expected_signee, bool enforce_canonical )const
 {
    return fc::ecc::public_key( delegate_signature, digest(), enforce_canonical ) == expected_signee;
 }
Exemplo n.º 16
0
	static inline std::string digest(Name name, const std::string& buf)
	{
		return digest(name, buf.c_str(), buf.size());
	}
Exemplo n.º 17
0
 public_key_type signed_block_header::signee( bool enforce_canonical )const
 {
    return fc::ecc::public_key( delegate_signature, digest(), enforce_canonical );
 }
int Protocol::receive_message (int sd, int type)
{
        uint32_t length;
        uint32_t tmp;
        int len;
        int ret;
        int p = 0;
        int r;

        if (type == M1) {
                // log
                LOG(log, "** Receiving Message M1 **\n");

                // Receive from client:
                // M1 = C_ID, S_ID, Na

                // receive length
                len = sizeof(length);
                r = 0;
                do {
                        ret = read(sd, (void *) (&length + r), len - r);
                        if (ret == -1)
                                return ret;
                        r += ret;
                } while (r != len);
                if (length != 3 * len)
                        return -1;

                // buffer
                char *buffer = new char[length];
                r = 0;
                do {
                        ret = read(sd, (void *) &buffer[r], length - r);
                        if (ret == -1)
                                return ret;
                        r += ret;
                } while (r != length);

                // client id
                bcopy((void *) &buffer[p], (void *) &client_id, len);
                if (client_id < 0)
                        return -1;
                p += len;

                // server id
                bcopy((void *) &buffer[p], (void *) &tmp, len);
                if (tmp != server_id)
                        return -1;
                p += len;

                // client nonce
                bcopy((void *) &buffer[p], (void *) &client_nonce, len);

                // get pre-shared key with client
                get_key(shared_key, "key_server", client_id);

                // log
                LOG(log, "\tClient ID: " + utos(client_id) + "\n");
                LOG(log, "\tServer ID: " + utos(server_id) + "\n");
                LOG(log, "\tClient Nonce: " + utos(client_nonce) + "\n");
                LOG(log, "\tShared Key: " +
                    stringbyte(shared_key, EVP_MAX_KEY_LENGTH) + "\n");
                LOG(log, "** Message M1 Received **\n\n");

                // garbage collection
                delete[] buffer;
        }

        if (type == M2) {
                // log
                LOG(log, "** Receiving Message M2 **\n");

                // Receive from Server:
                // M2 = IV, {S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)}

                // receive length
                len = sizeof(length);
                r = 0;
                do {
                        ret = read(sd, (void *) (&length + r), len - r);
                        if (ret == -1)
                                return ret;
                        r += ret;
                } while (r != len);
                if (length < (EVP_MAX_IV_LENGTH + EVP_MAX_KEY_LENGTH + 3 * len
                    + md_len))
                        return -1;

                // buffers
                int td_len = 3 * sizeof(uint32_t) + EVP_MAX_KEY_LENGTH +
                              EVP_MAX_IV_LENGTH;
                int p_len;
                int c_len = length - EVP_MAX_IV_LENGTH;
                char *todigest = new char[td_len];
                char *md;
                char *r_md = new char[md_len];
                char *plaintxt;
                char *ciphertxt = new char[c_len];
                char *buffer = new char[length];

                // receive message
                r = 0;
                do {
                        ret = read(sd, (void *) &buffer[r], length - r);
                        if (ret == -1)
                                return ret;
                        r += ret;
                } while (r != length);

                // iv
                bcopy((void *) &buffer[p], (void *) iv, EVP_MAX_IV_LENGTH);
                p += EVP_MAX_IV_LENGTH;

                // ciphertext: {S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)}
                bcopy((void *) &buffer[p], (void *) ciphertxt, c_len);

                // plaintext: S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)
                dec_ctx = create_context(shared_key, iv, DEC);
                plaintxt = decrypt(dec_ctx, ciphertxt, c_len, &p_len);

                // store & check
                p = 0;
                bcopy((void *) &plaintxt[p], (void *) &tmp, len);
                if (tmp != server_id)
                        return -1;
                p += len;
                bcopy((void *) &plaintxt[p], (void *) &tmp, len);
                if (tmp != client_id)
                        return -1;
                p += len;
                bcopy((void *) &plaintxt[p], (void *) &tmp, len);
                if (tmp != client_nonce)
                        return -1;
                p += len;
                bcopy((void *) &plaintxt[p], (void *) session_key,
                      EVP_MAX_KEY_LENGTH);
                p += EVP_MAX_KEY_LENGTH;

                // received hash
                bcopy((void *) &plaintxt[p], (void *) r_md, md_len);

                // to digest: S_ID, C_ID, Na, K, IV
                p = 0;
                len = sizeof(uint32_t);
                bcopy ((void *) &server_id, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) &client_id, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) &client_nonce, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) session_key, (void *) &todigest[p],
                       EVP_MAX_KEY_LENGTH);
                p += EVP_MAX_KEY_LENGTH;
                bcopy ((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH);

                // hash
                md = digest(md_ctx, todigest, td_len);

                // check digest
                for (int i = 0; i < md_len; i++) {
                        if (md[i] != r_md[i])
                                return -1;
                }

                // log
                LOG(log, "\tLength: " + utos(length) + "\n");
                LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n");
                LOG(log, "\tServer ID: " + utos(server_id) + "\n");
                LOG(log, "\tClient ID: " + utos(client_id) + "\n");
                LOG(log, "\tClient Nonce: " + utos(client_nonce) + "\n");
                LOG(log, "\tSession Key: " + 
                    stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n");
                LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n");
                LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) +
                    "\n");
                LOG(log, "\tShared Key (decrypt): " + 
                    stringbyte(shared_key, EVP_MAX_KEY_LENGTH) + "\n");
                LOG(log, "** Message M2 Received **\n\n");

                // garbage collection
                delete[] buffer;
                delete[] ciphertxt;
                delete[] plaintxt;
                delete[] r_md;
                delete[] todigest;
                delete[] md;
        }

        if (type == M3) {
                // log
                LOG(log, "** Receiving Message M3 **\n");

                // Receive from client:
                // M3 = IV, {C_ID, S_ID, h(C_ID, S_ID, IV)}

                // receive length
                len = sizeof(length);
                r = 0;
                do {
                        ret = read(sd, (void *) (&length + r), len - r);
                        if (ret == -1)
                                return ret;
                        r += ret;
                } while (r != len);
                if (length < (EVP_MAX_IV_LENGTH + 2 * len + md_len))
                        return -1;

                // buffers
                int td_len = 2 * sizeof(uint32_t) + EVP_MAX_IV_LENGTH;
                int p_len;
                int c_len = length - EVP_MAX_IV_LENGTH;
                char *todigest = new char[td_len];
                char *md;
                char *r_md = new char[md_len];
                char *plaintxt;
                char *ciphertxt = new char[c_len];
                char *buffer = new char[length];

                // read message
                r = 0;
                do {
                        ret = read(sd, (void *) &buffer[r], length - r);
                        if (ret == -1)
                                return ret;
                        r += ret;
                } while (r != length);

                // iv
                bcopy((void *) &buffer[p], (void *) iv, EVP_MAX_IV_LENGTH);
                p += EVP_MAX_IV_LENGTH;

                // ciphertext: {C_ID, S_ID, h(C_ID, S_ID, IV)}
                bcopy((void *) &buffer[p], (void *) ciphertxt, c_len);

                // plaintext: C_ID, S_ID, h(C_ID, S_ID, IV)
                dec_ctx = create_context(session_key, iv, DEC);
                plaintxt = decrypt(dec_ctx, ciphertxt, c_len, &p_len);

                // check
                p = 0;
                len = sizeof(uint32_t);
                bcopy((void *) &plaintxt[p], (void *) &tmp, len);
                if (tmp != client_id)
                        return -1;
                p += len;
                bcopy((void *) &plaintxt[p], (void *) &tmp, len);
                if (tmp != server_id)
                        return -1;
                p += len;

                // received hash
                bcopy((void *) &plaintxt[p], (void *) r_md, md_len);

                // to digest: C_ID, S_ID, IV
                p = 0;
                bcopy ((void *) &client_id, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) &server_id, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH);

                // hash
                md = digest(md_ctx, todigest, td_len);

                // check digest
                for (int i = 0; i < md_len; i++) {
                        if (md[i] != r_md[i])
                                return -1;
                }

                // log
                LOG(log, "\tLength: " + utos(length) + "\n");
                LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n");
                LOG(log, "\tClient ID: " + utos(client_id) + "\n");
                LOG(log, "\tServer ID: " + utos(server_id) + "\n");
                LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n");
                LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) +
                    "\n");
                LOG(log, "\tSession Key (decrypt): " + 
                    stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n");
                LOG(log, "** Message M3 sent **\n\n");

                // garbage collection
                delete[] buffer;
                delete[] ciphertxt;
                delete[] plaintxt;
                delete[] r_md;
                delete[] todigest;
                delete[] md;
        }

        return 0;
}
Exemplo n.º 19
0
 public_key_type signed_block_header::signee()const
 { 
    return fc::ecc::public_key( delegate_signature, digest() );
 }
int Protocol::send_message (int sd, int type)
{
        uint32_t length;
        int len;
        int ret;
        int p = 0;

        if (type == M1) {
                // log
                LOG(log, "** Sending Message M1 **\n");

                // Send to server:
                // M1 = C_ID, S_ID, Na
                len = sizeof(uint32_t);
                length = 3 * len;
                int b_len = 4 * len;

                // message buffer
                char *buffer = new char[b_len];

                // length
                bcopy ((void *) &length, (void *) &buffer[p], len);
                p += len;

                // client_id
                bcopy ((void *) &client_id, (void *) &buffer[p], len);
                p += len;

                // server id
                bcopy ((void *) &server_id, (void *) &buffer[p], len);
                p += len;

                // client nonce
                bcopy ((void *) &client_nonce, (void *) &buffer[p], len);

                // send
                p = 0;
                do {
                        ret = write (sd, (void *) &buffer[p], b_len - p);
                        if (ret == -1)
                                return ret;
                        p += ret;
                } while (p != b_len);

                // log
                LOG(log, "\tLength: " + utos(length) + "\n");
                LOG(log, "\tClient ID: " + utos(client_id) + "\n");
                LOG(log, "\tServer ID: " + utos(server_id) + "\n");
                LOG(log, "\tClient Nonce: " + utos(client_nonce) + "\n");
                LOG(log, "** Message M1 sent **\n\n");

                // garbage collection
                delete[] buffer;
        }

        if (type == M2) {
                // log
                LOG(log, "** Sending Messagge M2 **\n");

                // buffers
                int td_len = 3 * sizeof(uint32_t) + EVP_MAX_KEY_LENGTH +
                             EVP_MAX_IV_LENGTH;
                int p_len = td_len + md_len - EVP_MAX_IV_LENGTH;
                int c_len;
                int b_len;
                char *todigest = new char[td_len];
                char *md;
                char *plaintxt = new char[p_len];
                char *ciphertxt;
                char *buffer;

                // to digest: S_ID, C_ID, Na, K, IV
                len = sizeof(uint32_t);
                bcopy ((void *) &server_id, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) &client_id, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) &client_nonce, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) session_key, (void *) &todigest[p],
                       EVP_MAX_KEY_LENGTH);
                p += EVP_MAX_KEY_LENGTH;
                select_random_iv(iv, EVP_MAX_IV_LENGTH);
                bcopy ((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH);

                // hash
                md = digest(md_ctx, todigest, td_len);

                // plaintext: S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)
                p = 0;
                bcopy ((void *) todigest, (void *) &plaintxt[p], td_len -
                       EVP_MAX_IV_LENGTH);
                p += td_len - EVP_MAX_IV_LENGTH;
                bcopy ((void *) md, (void *) &plaintxt[p], md_len);

                // ciphertext: {S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)}
                enc_ctx = create_context(shared_key, iv, ENC);
                ciphertxt = encrypt(enc_ctx, plaintxt, p_len, &c_len);

                // M2 length
                length = c_len + EVP_MAX_IV_LENGTH;

                // Send to client:
                // M2 = IV, {S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)}
                p = 0;
                b_len = length + sizeof(length);
                buffer = new char[b_len];
                bcopy ((void *) &length, (void *) &buffer[p], sizeof(length));
                p += sizeof(length);
                bcopy ((void *) iv, (void *) &buffer[p], EVP_MAX_IV_LENGTH);
                p += EVP_MAX_IV_LENGTH;
                bcopy ((void *) ciphertxt, (void *) &buffer[p], c_len);

                // send
                p = 0;
                do {
                        ret = write (sd, (void *) &buffer[p], b_len - p);
                        if (ret == -1)
                                return ret;
                        p += ret;
                } while (p != b_len);

                // log
                LOG(log, "\tLength: " + utos(length) + "\n");
                LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n");
                LOG(log, "\tServer ID: " + utos(server_id) + "\n");
                LOG(log, "\tClient ID: " + utos(client_id) + "\n");
                LOG(log, "\tClient Nonce: " + utos(client_nonce) + "\n");
                LOG(log, "\tSession Key: " + 
                    stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n");
                LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n");
                LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) +
                    "\n");
                LOG(log, "\tShared Key (encrypt): " + 
                    stringbyte(shared_key, EVP_MAX_KEY_LENGTH) + "\n");
                LOG(log, "** Message M2 sent **\n\n");

                // garbage collection
                delete[] todigest;
                delete[] md;
                delete[] plaintxt;
                delete[] ciphertxt;
                delete[] buffer;
        }

        if (type == M3) {
                // log
                LOG(log, "** Sending Message M3 **\n");

                // buffers
                int td_len = 2 * sizeof(uint32_t) + EVP_MAX_IV_LENGTH;
                int p_len = td_len + md_len - EVP_MAX_IV_LENGTH;
                int c_len;
                int b_len;
                char *todigest = new char[td_len];
                char *md;
                char *plaintxt = new char[p_len];
                char *ciphertxt;
                char *buffer;

                // to digest: C_ID, S_ID, IV
                len = sizeof(uint32_t);
                bcopy ((void *) &client_id, (void *) &todigest[p], len);
                p += len;
                bcopy ((void *) &server_id, (void *) &todigest[p], len);
                p += len;
                select_random_iv(iv, EVP_MAX_IV_LENGTH);
                bcopy ((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH);

                // hash
                md = digest(md_ctx, todigest, td_len);

                // plaintext: C_ID, S_ID, h(C_ID, S_ID, IV)
                p = 0;
                bcopy ((void *) todigest, (void *) &plaintxt[p], td_len -
                       EVP_MAX_IV_LENGTH);
                p += td_len - EVP_MAX_IV_LENGTH;
                bcopy ((void *) md, (void *) &plaintxt[p], md_len);

                // ciphertext: {C_ID, S_ID, h(C_ID, S_ID, IV)}
                enc_ctx = create_context(session_key, iv, ENC);
                ciphertxt = encrypt(enc_ctx, plaintxt, p_len, &c_len);

                // M3 length
                length = c_len + EVP_MAX_IV_LENGTH;

                // Send to server:
                // M3 = IV, {C_ID, S_ID, h(C_ID, S_ID, IV)}
                p = 0;
                b_len = length + sizeof(length);
                buffer = new char[b_len];
                bcopy ((void *) &length, (void *) &buffer[p], sizeof(length));
                p += sizeof(length);
                bcopy ((void *) iv, (void *) &buffer[p], EVP_MAX_IV_LENGTH);
                p += EVP_MAX_IV_LENGTH;
                bcopy ((void *) ciphertxt, (void *) &buffer[p], c_len);

                // send
                p = 0;
                do {
                        ret = write (sd, (void *) &buffer[p], b_len - p);
                        if (ret == -1)
                                return ret;
                        p += ret;
                } while (p != b_len);

                // log
                LOG(log, "\tLength: " + utos(length) + "\n");
                LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n");
                LOG(log, "\tClient ID: " + utos(client_id) + "\n");
                LOG(log, "\tServer ID: " + utos(server_id) + "\n");
                LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n");
                LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) +
                    "\n");
                LOG(log, "\tSession Key (encrypt): " + 
                    stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n");
                LOG(log, "** Message M3 sent **\n\n");

                // garbage collection
                delete[] todigest;
                delete[] md;
                delete[] plaintxt;
                delete[] ciphertxt;
                delete[] buffer;
        }
        return 0;
}
Exemplo n.º 21
0
void main(int argc,char **argv)
{
  char *def;
  char *local;
  const char *action = "";
  char *psz;
  const char *err;
  int fd;
  unsigned int i,j;
  int flagremote;
  int match;
  int goodexit = 0;			/* exit code for normal exit */
					/* in manager this will be set to 0 */
  unsigned long from,u,to,issue,prevmax;
  unsigned long mno = 0;
  unsigned long chunk;
  unsigned long subs = 0;
  unsigned int pos,pos1;
  unsigned int len;
  int opt;
  char outformat = 0;
  msgentry *msgtable;
  subentry *subtable;
  authentry *authtable;
  dateentry *datetable;
  struct datetime dt;
  char date[DATE822FMT];

  (void) umask(022);
  sig_pipeignore();
  when = now();
  datetime_tai(&dt,when);

  opt = getconfopt(argc,argv,options,1,0);

  initsub(0);
  if (flagformat != 0)
    if (FORMATS[str_chr(FORMATS,flagformat[0])])
      outformat = flagformat[0];
  if (outformat == 0) {
    outformat =
      (getconf_line(&line,"digformat",0)
       && FORMATS[str_chr(FORMATS,line.s[0])])
      ? line.s[0]
      : DEFAULT_FORMAT;
  }

  /* code to activate digest (-digest-code)*/
  if ((digestcode = argv[opt]) == 0) {
    if (getconf_line(&digestcodefile,"digestcode",0)
	&& digestcodefile.len > 0) {
      if (!stralloc_0(&digestcodefile)) die_nomem();
      digestcode = digestcodefile.s;
    }
  }
  /* ignore any extra args */

  if (!stralloc_copy(&subject,&outlocal)) die_nomem();	/* for subjects */
  if (!stralloc_copy(&listname,&outlocal)) die_nomem();	/* for content disp */

  local = env_get("LOCAL");
  def = env_get("DEFAULT");
  sender = get_sender();
  if (local && *local) {	/* in editor local = outlocal */
    if (!sender) strerr_die2x(100,FATAL,MSG(ERR_NOSENDER));
    if (!*sender)
      strerr_die2x(100,FATAL,MSG(ERR_BOUNCE));
    if (str_equal(sender,"#@[]"))
      strerr_die2x(100,FATAL,MSG(ERR_BOUNCE));
    if (!sender[str_chr(sender,'@')])
      strerr_die2x(100,FATAL,MSG(ERR_ANONYMOUS));
    if (def) {
      if (*def) {
	action = def;
	goodexit = 99;
      } else
	_exit(0);		/* list-@host should do -help from manager */
    } else {			/* editor */
      act = AC_DIGEST;		/* on list-@host ! */
      flageditor = 1;		/* to avoid Mailing-list error on sublists */
				/* when running out of dir/editor. */
    }
    if (case_starts(action,"dig")) {
      action += 3;
      if (action[0] == '-' || action [0] == '.') {
        action++;
	if (!digestcode)
            strerr_die2x(100,FATAL,MSG(ERR_BAD_DIGCODE));
        len = str_len(digestcode);
        if (len <= str_len(action) && case_startb(action,len,digestcode)) {
          if (FORMATS[str_chr(FORMATS,*(action+len))])
            outformat = *(action+len);
          act = AC_DIGEST;
        } else
          strerr_die2x(100,FATAL,MSG(ERR_BAD_DIGCODE));
      }
    }
  } else			/* Command line operation */
    act = AC_DIGEST;

	/* Things we deal with. If anything else just die with success!   */
	/* At the moment this is -index, -thread, and -get.               */
	/* If flagdo = 0 we only service -dig commands. This is to support*/
	/* "secret" lists that are still archived and digested. -c on     */
	/* cmd line. */

  if (act == AC_NONE) {
    if (case_equals(action,ACTION_DIGEST)) {
      act = AC_GET;		/* list-digest@ => msg since last digest */
      action = ACTION_GET;
    } else if (case_starts(action,ACTION_GET) || case_starts(action,ALT_GET))
      act = AC_GET;
    else if (case_starts(action,ACTION_INDEX) || case_starts(action,ALT_INDEX))
      act = AC_INDEX;
    else if (case_starts(action,ACTION_THREAD) ||
	 case_starts(action,ALT_THREAD))
      act = AC_THREAD;
  }
  if (act == AC_NONE)			/* not for us. Pass the buck. */
    _exit(0);
  if (act != AC_INDEX) {		/* need to do header processing */
    if(!getconf(&digheaders,"digheaders",0)) {
      if(!stralloc_copys(&digheaders,digsz)) die_nomem();
      if (!stralloc_0(&digheaders)) die_nomem();
      psz = digheaders.s;
      while (*psz) {
        if (*psz == '\\') *psz = '\0';
        ++psz;
      }
    }
    if (!constmap_init(&digheadersmap,digheaders.s,digheaders.len,0))
	die_nomem();
  }
  if (act != AC_DIGEST) {
    if (!flagdo)			/* only do digests */
      strerr_die2x(100,FATAL,MSG(ERR_NOCMD));
    if (flagpublic < 0)
      flagpublic = !getconf_isset("modgetonly") && getconf_isset("public");
    if (!flagpublic) {
		/* This all to take care of non-public lists. They should*/
		/* still do digests, but do other things only for        */
		/* moderators that have remote access. Since this is rare*/
		/* efforts have been made to keep everything that's not  */
		/* needed elsewhere in here.                   */
      getconf_line(&moddir,"modsub",0);
      flagremote = getconf_line(&line,"remote",0);
      if (!flagremote)
        strerr_die2x(100,FATAL,MSG(ERR_NOT_PUBLIC));
      if (!moddir.len) {
        if (line.len) {
          if (!stralloc_copy(&moddir,&line)) die_nomem();
        } else {
          if (!stralloc_copys(&moddir,"mod")) die_nomem();
        }
      }
      if (!stralloc_0(&moddir)) die_nomem();
      ismod = issub(moddir.s,sender,&mod);
      if (!ismod)			/* sender = moderator? */
        strerr_die2x(100,FATAL,MSG(ERR_NOT_PUBLIC));
    }
  }

  if (act == AC_DIGEST) {
    workdir = "digest";
    if (!stralloc_cats(&outlocal,"-digest")) die_nomem();
    if (getconf_line(&line,"chunk",0)) {
      if (!stralloc_0(&line)) die_nomem();
      (void) scan_ulong(line.s,&chunk);		/* same chunk as main list */
      if (chunk == 0)				/* limit range to 1-53 */
	chunk = 1L;
      else if (chunk > 52)
	chunk = 52L;
    } else {
      chunk = 0L;
    }
  } else
    workdir = ".";


  if (!flagarchived)
    strerr_die2x(100,FATAL,MSG(ERR_NOT_ARCHIVED));

  if (qmail_open(&qq) == -1)
    strerr_die2sys(111,FATAL,MSG(ERR_QMAIL_QUEUE));

  set_cpnum("");	/* default for <#n#> replacement */

  switch (act) {

  case AC_DIGEST:

/* -dig{.|-}'digestcode'[f] returns an rfc1153 digest                        */
/* of messages from the archive. Messages                                    */
/* dignum+1 through the last message received by the list are processed and  */
/* dignum is updated to the last message processed. digissue is advanced.    */

    get_num();				/* max = last successful message */
    to = max;
    lockup();			/* another digest could corrupt dignum */
				/* but will be saved only if flagdigrange==0 */
    if(getconf_line(&num,"dignum",0)) {
      if(!stralloc_0(&num)) die_nomem();
      pos = scan_ulong(num.s,&prevmax);
      if (num.s[pos] == ':') pos++;
      pos += 1 + scan_ulong(num.s+pos,&cumsize);	/* last cumsize */
      if (num.s[pos] == ':') pos++;
      scan_ulong(num.s+pos,&digwhen);			/* last reg dig */
    } else {
      prevmax = 0L;
      cumsize = 0L;
      digwhen = 0L;
    }
    mno = prevmax + 1L;
    if(!max || mno > max)	/* if a digest-list is "sending" the request, */
				/* don't make noise: errors go to postmaster!*/
      strerr_die2x(goodexit,FATAL,MSG(ERR_EMPTY_DIGEST));
    szmsgnum[fmt_ulong(szmsgnum,mno)] = '\0';
    set_cpnum(szmsgnum);	/* for copy */
				/* prepare subject to get entropy for tagmsg*/
    if (!stralloc_cats(&subject," Digest ")) die_nomem();
    if (!stralloc_catb(&subject,date,date822fmt(date,&dt)-1))
          die_nomem();		/* skip trailing in date '\n' */
    if (!stralloc_cats(&subject," Issue ")) die_nomem();
    if (getconf_line(&num,"digissue",0)) {
      if(!stralloc_0(&num)) die_nomem();
      scan_ulong(num.s,&issue);
      issue++;
    } else {
      issue = 1;
    }
    if (!stralloc_catb(&subject,strnum,fmt_ulong(strnum,issue)))
      die_nomem();
					/* use the subject as entropy */
    if (!stralloc_copy(&line,&subject)) die_nomem();
    if (!stralloc_0(&line)) die_nomem();

    if (!stralloc_ready(&seed,HASHLEN+1)) die_nomem();
    seed.len = HASHLEN + 1;
    seed.s[HASHLEN] = '\0';
    makehash(line.s,line.len,seed.s);
    if (chunk) {			/* only if slaves are used */
      qmail_puts(&qq,"Ezauth: ");
      qmail_put(&qq,seed.s,HASHLEN);
      qmail_puts(&qq,"\n");
    }

    doheaders();
    qmail_puts(&qq,"To: ");
    if (!quote(&quoted,&listname)) die_nomem();
    qmail_put(&qq,quoted.s,quoted.len);
    qmail_puts(&qq,"@");
    qmail_put(&qq,outhost.s,outhost.len);
    qmail_puts(&qq,"\n");
    if (flagindexed && (outformat != NATIVE))
      idx_mkthreads(&msgtable,&subtable,&authtable,&datetable,
	mno,to,max,flaglocked);
    else
      idx_mklist(&msgtable,&subtable,&authtable,mno,to);
    digest(msgtable,subtable,authtable,mno,to,&subject,AC_DIGEST,outformat);

    write_ulong(issue,0L,0L,"digissue","digissuen");
    write_ulong(max,cumsizen, (unsigned long) when,"dignum","dignumn");
    break;

  case AC_GET:

/* -get[-|\.][[num].num2] copies archive num-num2. num & num2 are adjusted   */
/* to be > 0 and <= last message, to num2 >= num and to num2-num <= MAXGET.  */

    zapnonsub(ACTION_GET);		/* restrict to subs if requested */
    tosender();
				/* for rfc1153 */
    if (!stralloc_cats(&subject," Digest of: ")) die_nomem();
    if (!stralloc_cats(&subject,action)) die_nomem();

    to = 0;
    pos = str_len(ACTION_GET);
    if (!case_starts(action,ACTION_GET))
      pos = str_len(ALT_GET);
    if (FORMATS[str_chr(FORMATS,action[pos])]) {
       outformat = action[pos];
       ++pos;
    }
					/* optional - or . after '-get' */
    if (action[pos] == '-' || action[pos] == '.') pos++;
    get_num();				/* max = last successful message */
					/* accept any separator. It may be  */
					/* the terminal '\n', but then      */
					/* scan will = 0 on the \0 so should*/
					/* be safe                          */
    if (!max)
      strerr_die2x(100,FATAL,MSG(ERR_EMPTY_LIST));
    szmsgnum[fmt_ulong(szmsgnum,max)] = '\0';
    set_cpnum(szmsgnum);	/* for copy this is the latest message arch'd*/
    doheaders();
    if(action[pos += scan_ulong(action + pos,&u)])
      scan_ulong(action + pos + 1, &to);
    if (u == 0 && to == 0) {		/* default: messages since last */
					/* digest, or last MAXGET if too many */
      to= max;
      u = dignum();
      if (u == 0) {		/* no digest => last up to HISTGET msgs */
	to = max;
	if (max > HISTGET) u = max - HISTGET; else u = 1;
      }
      if (to - u >= MAXGET) u = to - MAXGET + 1;	/* max MAXGET */
    } else if (u > max) {
      if (to) {			/* -get.999999_x returns 30 and msg since last*/
	to = max;		/* digest 30*/
        u = dignum();
	if (u > HISTGET) u -= HISTGET; else u = 1;
        if (to - u >= MAXGET) u = to - MAXGET + 1;
      } else
	u = max;
    }
    if (u == 0) u = 1;			/* -get.5 => 1-5 */
    if (to < u) to = u;			/* -get23_2 => 23 */
    if (to >= u + MAXGET) to = u + MAXGET - 1;
					/* no more than MAXGET at a time */
    if (to > max) to = max;
    if (flagindexed && (outformat != NATIVE))	/* fake out threading */
      idx_mkthreads(&msgtable,&subtable,&authtable,&datetable,
	u,to,max,0);
    else
      idx_mklist(&msgtable,&subtable,&authtable,u,to);
    digest(msgtable,subtable,authtable,u,to,&subject,AC_GET,outformat);
    break;

  case AC_INDEX:

/* -index[f][#|-|\.][[num][.num2] Show subject index for messages num-num2 in*/
/* sets of 100.                                                              */
/* Default last 2 sets. num and num2 are made reasonable as for get. num2 is */
/* limited to num+MAXINDEX to limit the amount of data sent.                 */

    if (!flagindexed)
      strerr_die2x(100,FATAL,MSG(ERR_NOT_INDEXED));
    zapnonsub(ACTION_INDEX);	/* restrict to subs if requested */
    to = 0;
    pos = str_len(ACTION_INDEX);
    if (!case_starts(action,ACTION_INDEX))
      pos = str_len(ALT_INDEX);
    if (FORMATS[str_chr(FORMATS,action[pos])]) {
       outformat = action[pos];		/* ignored, but be nice ... */
       ++pos;
    }
    get_num();				/* max = last successful message */
    if (!max)
      strerr_die2x(100,FATAL,MSG(ERR_EMPTY_LIST));
    szmsgnum[fmt_ulong(szmsgnum,max)] = '\0';
    set_cpnum(szmsgnum);	/* for copy this is the latest message arch'd*/

    doheaders();
    tosender();
    if (!stralloc_cats(&subject," Result of: ")) die_nomem();
    if (!stralloc_cats(&subject,action)) die_nomem();
    presub(1,1,&subject,AC_INDEX,outformat);

    if (action[pos] == '-' || action[pos] == '.') pos++;
    if(action[pos += scan_ulong(action + pos,&u)])
      scan_ulong(action + pos + 1, &to);

    if (u == 0 && to == 0) { to = max; u = max - 100; }
    if (u <= 0) u = 1;
    if (u > max) u = max;
    if (to < u) to = u;
    if (to > u + MAXINDEX) to = u+MAXINDEX;	/* max MAXINDEX index files */
    if (to > max) to = max;
    u /= 100;
    to /= 100;
    while (u <= to) {
      if (!stralloc_copys(&fn,"archive/")) die_nomem();
      if (!stralloc_catb(&fn,strnum,fmt_ulong(strnum,u))) die_nomem();
      if (!stralloc_cats(&fn,"/index")) die_nomem();
      if (!stralloc_0(&fn)) die_nomem();

      if (u == max/100)	/* lock if last index file in archive */
        lockup();

      fd = open_read(fn.s);
      if (fd == -1)
        if (errno != error_noent)
          strerr_die2sys(111,FATAL,MSG1(ERR_OPEN,fn.s));
        else
          code_qputs(MSG(TXT_NOINDEX));
      else {
        substdio_fdbuf(&sstext,read,fd,textbuf,sizeof(textbuf));
        for (;;) {
          if (getln(&sstext,&line,&match,'\n') == -1)
            strerr_die2sys(111,FATAL,MSG1(ERR_READ,fn.s));
          if (match) {
            if (line.s[0] != '\t') {	/* subject line */
              pos = byte_chr(line.s,line.len,' ');
	      pos1 = 0;
	      if (pos && pos != line.len && line.s[pos - 1] == ':')
                pos1 = pos + HASHLEN + 1;	/* after hash */
              if (pos1 >= line.len) {	/* bad! */
                pos = 0;
                pos1 = 0;		/* output as is */
              }
              if (!stralloc_copyb(&line2,line.s,pos)) die_nomem();
              if (!stralloc_catb(&line2,line.s+pos1,line.len-pos1)) die_nomem();
            } else {
	      pos = byte_chr(line.s,line.len,';');
	      if (pos + HASHLEN + 1 < line.len && pos > 15 &&
				line.s[pos + 1] != ' ') {
		  if (!stralloc_copyb(&line2,line.s,pos - 15)) die_nomem();
		  pos++;
		  if (!stralloc_catb(&line2,line.s + pos + HASHLEN,
			line.len - pos - HASHLEN)) die_nomem();
	      } else			/* old format - no author hash */
                if (!stralloc_copyb(&line2,line.s,line.len)) die_nomem();
	    }
            code_qput(line2.s,line2.len);
          } else
            break;
        }
        close(fd);
      }

      if (u == max/100)	/* unlock if last index in archive file */
        unlock();

      u++;
    }
    normal_bottom(outformat);
    postmsg(outformat);
    break;

  case AC_THREAD:

/* -thread[f][-|.]num returns messages with subject matching message        */
/* 'num' in the subject index. If 'num' is not in[1..last_message] an error */
/* message is returned.                                                     */

    if (!flagindexed)
      strerr_die2x(100,FATAL,MSG(ERR_NOT_INDEXED));

    zapnonsub(ACTION_THREAD);		/* restrict to subs if requested*/

    get_num();				/* max = last successful message */
    if (!max)
      strerr_die2x(100,FATAL,MSG(ERR_EMPTY_LIST));
    szmsgnum[fmt_ulong(szmsgnum,max)] = '\0';
    set_cpnum(szmsgnum);	/* for copy this is the latest message arch'd*/

    doheaders();
    tosender();
				/* for rfc1153 */
    if (!stralloc_cats(&subject," Digest of: ")) die_nomem();
    if (!stralloc_cats(&subject,action)) die_nomem();

    to = 0;
    pos = str_len(ACTION_THREAD);
    if (!case_starts(action,ACTION_THREAD))
      pos = str_len(ALT_THREAD);
    if (FORMATS[str_chr(FORMATS,action[pos])]) {
       outformat = action[pos];
       ++pos;
    }
    if (action[pos] == '-' || action[pos] == '.') pos++;
    if(action[pos += scan_ulong(action + pos,&u)])
      scan_ulong(action + pos + 1, &to);

    if(u == 0 || u > max) {
      hdr_add2("Subject: ",subject.s,subject.len);
      qmail_puts(&qq,"\n");
      copy(&qq,"text/get-bad",flagcd);
    } else {	/* limit range to at most u-THREAD_BEFORE to u+THREAD_AFTER */
      if (u > THREAD_BEFORE)
        from = u-THREAD_BEFORE;
      else
        from = 1L;
      if (u + THREAD_AFTER > max) {
        idx_mkthread(&msgtable,&subtable,&authtable,from,max,u,max,0);
        digest(msgtable,subtable,authtable,from,max,&subject,
		AC_THREAD,outformat);
      } else {
        idx_mkthread(&msgtable,&subtable,&authtable,
		from,u+THREAD_AFTER,u,max,0);
        digest(msgtable,subtable,authtable,from,u+THREAD_AFTER,
			&subject,AC_THREAD,outformat);
      }
    }
    break;

  default:
	/* This happens if the initial check at the beginning of 'main'    */
	/* matches something that isn't matched here. Conversely, just     */
	/* adding an action here is not enough - it has to be added to the */
	/* initial check as well.                                          */

    strerr_die2x(100,FATAL,
		 "Program error: I'm supposed to deal with this but I didn't");
  }

  if (!stralloc_copy(&line,&outlocal)) die_nomem();
  if (act == AC_DIGEST) {
    if (chunk) {
      if (!stralloc_cats(&line,"-return-g-")) die_nomem();
    } else
      if (!stralloc_cats(&line,"-return-")) die_nomem();
    strnum[fmt_ulong(strnum,mno)] = '\0';
    if (!stralloc_cats(&line,strnum)) die_nomem();
    if (!stralloc_cats(&line,"-@")) die_nomem();

    if (!stralloc_cat(&line,&outhost)) die_nomem();
    if (!stralloc_cats(&line,"-@[]")) die_nomem();
  } else {
    if (!stralloc_cats(&line,"-return-@")) die_nomem();
    if (!stralloc_cat(&line,&outhost)) die_nomem();
  }
  if (!stralloc_0(&line)) die_nomem();

  qmail_from(&qq,line.s);
  if (act == AC_DIGEST) {	 /* Do recipients */
    tagmsg(mno,seed.s,"d",hashout,qq.msgbytes,chunk);
    if (chunk) {
      if (!stralloc_copys(&line,"T")) die_nomem();
      if (!stralloc_cat(&line,&outlocal)) die_nomem();
      if (!stralloc_cats(&line,"-s-d-")) die_nomem();
      if (!stralloc_catb(&line,hashout,COOKIE)) die_nomem();
      if (!stralloc_cats(&line,"-")) die_nomem();
      if (!stralloc_cats(&line,strnum)) die_nomem();
      if (!stralloc_cats(&line,"-")) die_nomem();
      if (!stralloc_copys(&line2,"@")) die_nomem();
      if (!stralloc_cat(&line2,&outhost)) die_nomem();
      if (!stralloc_0(&line2)) die_nomem();
      j = 0;
      for (i = 0; i <= 52; i += chunk) {		/* To slaves */
        qmail_put(&qq,line.s,line.len);
        schar[0] = '0' + i / 10;
        schar[1] = '0' + (i % 10);
        qmail_put(&qq,schar,3);
        j += (chunk - 1);
        if (j > 52) j = 52;
        schar[0] = '0' + j / 10;
        schar[1] = '0' + (j % 10);
        qmail_put(&qq,schar,2);
        qmail_put(&qq,line2.s,line2.len);
      }
    } else
      subs = putsubs(workdir,0L,52L,&subto);
  } else {			/* if local is set, sender is checked */
    if (ismod)
      qmail_to(&qq,mod.s);
    else
      qmail_to(&qq,sender);
  }

  if (*(err = qmail_close(&qq)) == '\0') {	/* Done. Skip rest. */
    if (act == AC_DIGEST) {
      if (chunk)
	(void) logmsg(mno,0L,0L,2);
      else
        (void) logmsg(mno,0L,subs,4);
    }
    closesub();			/* close db connection */
    unlock();			/* NOP if nothing locked */
    strnum[fmt_ulong(strnum,qmail_qp(&qq))] = 0;
    strerr_die2x(goodexit,"ezmlm-get: info: qp ",strnum);
  } else {			/* failed. Reset last msg & issue for digest */
    if(act == AC_DIGEST) {
      issue--;
      write_ulong(issue,0L,0L,"digissue","digissuen");
      write_ulong(prevmax,cumsize,(unsigned long) digwhen,"dignum","dignumn");
    }
    unlock();			/* NOP if nothing locked */
    strerr_die4x(111,FATAL,MSG(ERR_TMP_QMAIL_QUEUE),": ",err + 1);
  }
}
int Protocol::send_data (int sd, char *buf, int len)
{
        // log
        LOG(log, "** Sending Data **\n");

        int n = sizeof(uint32_t);
        int p = 0;
        uint32_t length;

        // buffers
        int td_len = 2 * n + len + EVP_MAX_IV_LENGTH;
        int p_len = td_len + md_len - EVP_MAX_IV_LENGTH;
        int c_len;
        int b_len;
        char *todigest = new char[td_len];
        char *md;
        char *plaintxt = new char[p_len];
        char *ciphertxt;
        char *buffer;

        // to digest: C_ID, S_ID, buf, IV
        bcopy((void *) &client_id, (void *) &todigest[p], n);
        p += n;
        bcopy((void *) &server_id, (void *) &todigest[p], n);
        p += n;
        bcopy((void *) buf, (void *) &todigest[p], len);
        p += len;
        select_random_iv(iv, EVP_MAX_IV_LENGTH);
        bcopy((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH);

        // hash
        md = digest(md_ctx, todigest, td_len);

        // plaintext: C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)
        p = 0;
        bcopy((void *) todigest, (void *) &plaintxt[p], p_len - md_len);
        p += p_len - md_len;
        bcopy((void *) md, (void *) &plaintxt[p], md_len);

        // ciphertext: {C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)}
        enc_ctx = create_context(session_key, iv, ENC);
        ciphertxt = encrypt(enc_ctx, plaintxt, p_len, &c_len);
        EVP_CIPHER_CTX_cleanup(enc_ctx);

        // Message length
        length = c_len + EVP_MAX_IV_LENGTH;

        // Send:
        // M = IV, {C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)}
        p = 0;
        b_len = length + n;
        buffer = new char[b_len];
        bcopy((void *) &length, (void *) &buffer[p], n);
        p += n;
        bcopy((void *) iv, (void *) &buffer[p], EVP_MAX_IV_LENGTH);
        p += EVP_MAX_IV_LENGTH;
        bcopy((void *) ciphertxt, (void *) &buffer[p], c_len);

        // send
        p = 0;
        int ret;
        do {
                ret = write (sd, (void *) &buffer[p], b_len - p);
                if (ret == -1)
                        return ret;
                p += ret;
        } while (p != b_len);

        // log
        LOG(log, "\tLength: " + utos(length) + "\n");
        LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n");
        LOG(log, "\tClient ID: " + utos(client_id) + "\n");
        LOG(log, "\tServer ID: " + utos(server_id) + "\n");
        LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n");
        LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) + "\n");
        LOG(log, "\tData: " + stringbyte(buf, len) + "\n");
        LOG(log, "\tSession Key (encrypt): " + 
            stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n");
        LOG(log, "** Data Sent **\n\n");

        // garbage collection
        delete[] todigest;
        delete[] md;
        delete[] plaintxt;
        delete[] ciphertxt;
        delete[] buffer;

        return 0;
}
Exemplo n.º 23
0
string vkmobDigestable::getDigestX() {
  string digest("");
  return digest;
}
int Protocol::receive_data (int sd, char *&buf, int *len)
{
        // log
        LOG(log, "** Receiving Data **\n");

        int n = sizeof(uint32_t);
        int p = 0;
        uint32_t length;

        // Receive:
        // M = IV, {C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)}

        // receive length
        int ret, r = 0;
        do {
                ret = read(sd, (void *) (&length + r), n - r);
                if (ret == -1)
                        return ret;
                r += ret;
        } while (r != n);
        if (length <= (EVP_MAX_IV_LENGTH + 2 * n + md_len))
                return -1;

        // buffers
        int td_len;
        int p_len;
        int c_len = length - EVP_MAX_IV_LENGTH;
        char *todigest;
        char *md;
        char *r_md = new char[md_len];
        char *plaintxt;
        char *ciphertxt = new char[c_len];
        char *buffer = new char[length];

        // read message
        r = 0;
        do {
                ret = read(sd, (void *) &buffer[r], length - r);
                if (ret == -1)
                        return ret;
                r += ret;
        } while (r != length);

        // iv
        bcopy((void *) &buffer[p], (void *) iv, EVP_MAX_IV_LENGTH);
        p += EVP_MAX_IV_LENGTH;

        // ciphertext:  {C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)}
        bcopy((void *) &buffer[p], (void *) ciphertxt, c_len);

        // plaintext: C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)
        dec_ctx = create_context(session_key, iv, DEC);
        plaintxt = decrypt(dec_ctx, ciphertxt, c_len, &p_len);
        EVP_CIPHER_CTX_cleanup(dec_ctx);

        // check
        uint32_t tmp;
        p = 0;
        bcopy((void *) &plaintxt[p], (void *) &tmp, n);
        if (tmp != client_id) {
                printf("esco qui\n");
                return -1;
        }
        p += n;
        bcopy((void *) &plaintxt[p], (void *) &tmp, n);
        if (tmp != server_id)
                return -1;
        p += n;

        // data
        *len = p_len - (2 * n + md_len);
        buf = new char[*len];
        bcopy((void *) &plaintxt[p], (void *) buf, *len);
        p += *len;

        // received hash
        bcopy((void *) &plaintxt[p], (void *) r_md, md_len);

        // todigest: C_ID, S_ID, buf, IV
        p = 0;
        td_len = 2 * n + *len + EVP_MAX_IV_LENGTH;
        todigest = new char[td_len];
        bcopy((void *) &client_id, (void *) &todigest[p], n);
        p += n;
        bcopy((void *) &server_id, (void *) &todigest[p], n);
        p += n;
        bcopy((void *) buf, (void *) &todigest[p], *len);
        p += *len;
        bcopy((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH);

        // hash
        md = digest(md_ctx, todigest, td_len);

        // check hash
        for (int i = 0; i < md_len; i++) {
                if (md[i] != r_md[i])
                        return -1;
        }

        // log
        LOG(log, "\tLength: " + utos(length) + "\n");
        LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n");
        LOG(log, "\tClient ID: " + utos(client_id) + "\n");
        LOG(log, "\tServer ID: " + utos(server_id) + "\n");
        LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n");
        LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) + "\n");
        LOG(log, "\tData: " + stringbyte(buf, *len) + "\n");
        LOG(log, "\tSession Key (decrypt): " + 
            stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n");
        LOG(log, "** Data Received **\n\n");

        // garbage collection
        delete[] todigest;
        delete[] md;
        delete[] r_md;
        delete[] plaintxt;
        delete[] ciphertxt;
        delete[] buffer;

        return 0;
}
Exemplo n.º 25
0
 void                         subscribe_message::sign( const fc::ecc::private_key& k )
 {
    sig = k.sign_compact( digest() );
 }
Exemplo n.º 26
0
 void signed_transaction::sign( const fc::ecc::private_key& signer )
 {
    signatures.push_back( signer.sign_compact( digest() ) );
 }
Exemplo n.º 27
0
 void signed_transaction::sign( const fc::ecc::private_key& signer, const digest_type& chain_id )
 {
    signatures.push_back( signer.sign_compact( digest( chain_id ) ) );
 }
Exemplo n.º 28
0
Arquivo: hash.c Projeto: EarlGray/ling
static int hash_set_internal(hash_t *ht, const void *key, int klen, void *val, alloc_func_t alloc_func)
{
	assert(ht != 0);
	assert(key != 0);
	assert(klen > 0);

	uint32_t hash = digest(key, klen);

	int index = hash & (HASH_BUCKETS-1);
	hash_entry_t *entry = ht->buckets[index];
	hash_entry_t **ref = &ht->buckets[index];
	while (entry != 0)
	{
		if (entry->hash == hash &&
			entry->klen == klen && memcmp(key, entry->key, klen) == 0)
		{
			//key exists - update (or delete)
			if (val == 0)
			{
				//delete
				*ref = entry->next;

				entry->next = ht->free;
				ht->free = entry;
			}
			else
			{
				//update
				entry->val = val;
			}
			return 0;
		}
		ref = &entry->next;
		entry = entry->next;
	}

	if (ht->free == 0)
	{
		//no more free entries - allocate a new node
		memnode_t *node = alloc_func(HASH_NODE_SIZE - sizeof(memnode_t));
		if (node == 0)
			return -NO_MEMORY;

		node->next = ht->nodes;
		ht->nodes = node;

		entry = (hash_entry_t *)node->starts;
		while ((void *)node->ends - (void *)entry >= sizeof(*entry))
		{
			entry->next = ht->free;
			ht->free = entry;
			entry++;
		}
	}

	entry = ht->free;
	ht->free = entry->next;

	entry->hash = hash;
	entry->key = key;
	entry->klen = klen;
	entry->val = val;

	entry->next = ht->buckets[index];
	ht->buckets[index] = entry;

	ht->count++;
	return 0;	//success
}
Exemplo n.º 29
0
	std::string digest(const std::string& buf)
	{
		return digest(buf.c_str(), buf.size());
	}
Exemplo n.º 30
0
result_t hash_base::sha512(Buffer_base *data, obj_ptr<Digest_base> &retVal)
{
    return digest(hash_base::_SHA512, data, retVal);
}