libdkim-1.0.21.orig/0000755000175000017500000000000011331376040013511 5ustar magnusmagnuslibdkim-1.0.21.orig/CVS/0000777000175000017500000000000011321057746014160 5ustar magnusmagnuslibdkim-1.0.21.orig/src/0000777000175000017500000000000010613420036014301 5ustar magnusmagnuslibdkim-1.0.21.orig/src/CVS/0000777000175000017500000000000011321057750014742 5ustar magnusmagnuslibdkim-1.0.21.orig/src/Makefile0000666000175000017500000000130410772175532015755 0ustar magnusmagnus# libdkim makefile for UNIX # #ifdef LINUX CFLAGS = -c LFLAGS = LIBS = -lcrypto -lresolv #else CFLAGS = -c LFLAGS = LIBS = -lcrypto #endif INCL = -I /usr/include/openssl/ SRCS = dkim.cpp dns.cpp dkimbase.cpp dkimsign.cpp dkimverify.cpp OBJS = $(SRCS:.cpp=.o) HDRS = dkim.h dns.h dkimbase.h dkimsign.h dkimverify.h all: libdkim.a libdkimtest libdkim.a: $(OBJS) rm -f libdkim.a ar cr libdkim.a $(OBJS) ranlib libdkim.a libdkimtest : libdkim.a libdkimtest.o g++ -olibdkimtest $(LFLAGS) \ -L . libdkimtest.o $(LIBS) -ldkim libdkimtest.o: libdkimtest.cpp $(HDRS) .cpp.o: g++ $(CFLAGS) -c $< clean: rm *.o libdkim.lib libdkimtest libdkim-1.0.21.orig/src/libdkim.def0000666000175000017500000000034410772175532016413 0ustar magnusmagnus EXPORTS DKIMSignInit DKIMSignProcess DKIMSignGetSig DKIMSignFree DKIMVerifyInit DKIMVerifyProcess DKIMVerifyResults DKIMVerifyGetDetails DKIMVerifyFree DKIMVersion DKIMGetErrorString DKIMSignGetSig2 libdkim-1.0.21.orig/src/libdkim.dsp0000666000175000017500000000720310270202614016425 0ustar magnusmagnus# Microsoft Developer Studio Project File - Name="libdkim" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) External Target" 0x0106 CFG=libdkim - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "libdkim.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "libdkim.mak" CFG="libdkim - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "libdkim - Win32 Release" (based on "Win32 (x86) External Target") !MESSAGE "libdkim - Win32 Debug" (based on "Win32 (x86) External Target") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" !IF "$(CFG)" == "libdkim - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Cmd_Line "NMAKE /f libdkim.mak" # PROP BASE Rebuild_Opt "/a" # PROP BASE Target_File "libdkim.exe" # PROP BASE Bsc_Name "libdkim.bsc" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Cmd_Line "nmake /f "makefile.vc"" # PROP Rebuild_Opt "/a" # PROP Target_File "Release\libdkim.dll" # PROP Bsc_Name "" # PROP Target_Dir "" !ELSEIF "$(CFG)" == "libdkim - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Cmd_Line "NMAKE /f libdkim.mak" # PROP BASE Rebuild_Opt "/a" # PROP BASE Target_File "libdkim.exe" # PROP BASE Bsc_Name "libdkim.bsc" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Cmd_Line "nmake /f "makefile.vc" DEBUG=1" # PROP Rebuild_Opt "/a" # PROP Target_File "Debug\libdkim.dll" # PROP Bsc_Name "" # PROP Target_Dir "" !ENDIF # Begin Target # Name "libdkim - Win32 Release" # Name "libdkim - Win32 Debug" !IF "$(CFG)" == "libdkim - Win32 Release" !ELSEIF "$(CFG)" == "libdkim - Win32 Debug" !ENDIF # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\dkim.cpp # End Source File # Begin Source File SOURCE=.\dkimbase.cpp # End Source File # Begin Source File SOURCE=.\dkimsign.cpp # End Source File # Begin Source File SOURCE=.\dkimverify.cpp # End Source File # Begin Source File SOURCE=.\dns.cpp # End Source File # Begin Source File SOURCE=.\dnsresolv.cpp # End Source File # Begin Source File SOURCE=.\libdkimtest.cpp # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE=.\dkim.h # End Source File # Begin Source File SOURCE=.\dkimbase.h # End Source File # Begin Source File SOURCE=.\dkimsign.h # End Source File # Begin Source File SOURCE=.\dkimverify.h # End Source File # Begin Source File SOURCE=.\dns.h # End Source File # Begin Source File SOURCE=.\dnsresolv.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # Begin Source File SOURCE=.\libdkim.def # End Source File # Begin Source File SOURCE=.\Makefile.vc # End Source File # End Target # End Project libdkim-1.0.21.orig/src/dkimbase.cpp0000666000175000017500000002071411012004330016555 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifdef WIN32 #include #pragma warning( disable: 4786 ) #else #endif #include #include "dkim.h" #include "dkimbase.h" #include CDKIMBase::CDKIMBase() { m_From = NULL; m_Sender = NULL; m_hTag = NULL; m_hTagSize = 0; m_hTagPos = 0; m_Line = NULL; m_LineSize = 0; m_LinePos = 0; m_InHeaders = true; } CDKIMBase::~CDKIMBase() { Free( m_Line ); Free( m_From ); Free( m_Sender ); Free( m_hTag ); } int CDKIMBase::Init(void) { return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // Alloc - allocate buffer // //////////////////////////////////////////////////////////////////////////////// int CDKIMBase::Alloc( char*& szBuffer, int nRequiredSize ) { szBuffer = new char[nRequiredSize]; return (szBuffer == NULL) ? DKIM_OUT_OF_MEMORY : DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // ReAlloc - extend buffer if necessary, leaving room for future expansion // //////////////////////////////////////////////////////////////////////////////// int CDKIMBase::ReAlloc( char*& szBuffer, int& nBufferSize, int nRequiredSize ) { if( nRequiredSize > nBufferSize ) { char* newp; int nNewSize = nRequiredSize + BUFFER_ALLOC_INCREMENT; if( Alloc( newp, nNewSize ) == DKIM_SUCCESS ) { if( szBuffer != NULL && nBufferSize > 0 ) { memcpy( newp, szBuffer, nBufferSize ); delete[] szBuffer; } szBuffer = newp; nBufferSize = nNewSize; } else { return DKIM_OUT_OF_MEMORY; // memory alloc error! } } return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // Process - split buffers into lines without any CRs or LFs at the end. // //////////////////////////////////////////////////////////////////////////////// void CDKIMBase::Free( char* szBuffer ) { if( szBuffer ) delete[] szBuffer; } //////////////////////////////////////////////////////////////////////////////// // // Process - split buffers into lines without any CRs or LFs at the end. // //////////////////////////////////////////////////////////////////////////////// int CDKIMBase::Process( char* szBuffer, int nBufLength, bool bEOF ) { char* p = szBuffer; char* e = szBuffer + nBufLength; while( p < e ) { if( *p != '\n' || m_LinePos == 0 || m_Line[m_LinePos-1] != '\r' ) { // add char to line if (m_LinePos >= m_LineSize) { int nRet = ReAlloc( m_Line, m_LineSize, m_LinePos+1 ); if (nRet != DKIM_SUCCESS) return nRet; } m_Line[m_LinePos++] = *p; } else { // back up past the CR m_LinePos--; if (m_InHeaders) { // process header line if (m_LinePos == 0) { m_InHeaders = false; int Result = ProcessHeaders(); if (Result != DKIM_SUCCESS) return Result; } else { // append the header to the headers list if ( m_Line[0] != ' ' && m_Line[0] != '\t' ) { HeaderList.push_back( string( m_Line, m_LinePos ) ); } else { if ( !HeaderList.empty() ) { HeaderList.back().append( "\r\n", 2 ).append( m_Line, m_LinePos ); } else { // no header to append to... } } } } else { // process body line int Result = ProcessBody(m_Line, m_LinePos, bEOF); if (Result != DKIM_SUCCESS) { m_LinePos = 0; return Result; } } m_LinePos = 0; } p++; } return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // ProcessFinal - process leftovers if stopping before the body or mid-line // //////////////////////////////////////////////////////////////////////////////// int CDKIMBase::ProcessFinal(void) { if ( m_LinePos > 0 ) { Process( "\r\n", 2, true ); } if( m_InHeaders ) { m_InHeaders = false; ProcessHeaders(); ProcessBody("", 0, true); } return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // ProcessHeaders - process the headers (to be implemented by derived class) // //////////////////////////////////////////////////////////////////////////////// int CDKIMBase::ProcessHeaders() { return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // ProcessBody - process body line (to be implemented by derived class) // //////////////////////////////////////////////////////////////////////////////// int CDKIMBase::ProcessBody( char* szBuffer, int nBufLength, bool bEOF ) { return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // RemoveSWSP - remove streaming white space from buffer/string inline // //////////////////////////////////////////////////////////////////////////////// struct isswsp { bool operator()( char ch ) { return( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' ); } }; void CDKIMBase::RemoveSWSP( char* szBuffer ) { *remove_if( szBuffer, szBuffer+strlen(szBuffer), isswsp() ) = '\0'; } void CDKIMBase::RemoveSWSP( char* pBuffer, int& nBufLength ) { nBufLength = remove_if( pBuffer, pBuffer+nBufLength, isswsp() ) - pBuffer; } void CDKIMBase::RemoveSWSP( string& sBuffer ) { sBuffer.erase( remove_if( sBuffer.begin(), sBuffer.end(), isswsp() ), sBuffer.end() ); } ////////////////////////////////////////////////////////////////////////////////////////// // // CompressSWSP - compress streaming white space into single spaces from buffer/string inline // ////////////////////////////////////////////////////////////////////////////////////////// void CDKIMBase::CompressSWSP( char* pBuffer, int& nBufLength ) { char* pSrc = pBuffer; char* pDst = pBuffer; char* pEnd = pBuffer+nBufLength; while (pSrc != pEnd) { if (isswsp()(*pSrc)) { do { ++pSrc; } while (pSrc != pEnd && isswsp()(*pSrc)); if (pSrc == pEnd) break; *pDst++ = ' '; } *pDst++ = *pSrc++; } nBufLength = pDst - pBuffer; } void CDKIMBase::CompressSWSP( string& sBuffer ) { string::iterator iSrc = sBuffer.begin(); string::iterator iDst = sBuffer.begin(); string::iterator iEnd = sBuffer.end(); while (iSrc != iEnd) { if (isswsp()(*iSrc)) { do { ++iSrc; } while (iSrc != iEnd && isswsp()(*iSrc)); if (iSrc == iEnd) break; *iDst++ = ' '; } *iDst++ = *iSrc++; } sBuffer.erase(iDst, iEnd); } ////////////////////////////////////////////////////////////////////////////////////////// // // RelaxHeader - relax a header field (lower case the name, remove swsp before and after :) // // modified 4/21/06 STB to remove white space before colon // ////////////////////////////////////////////////////////////////////////////////////////// string CDKIMBase::RelaxHeader( const string& sHeader ) { string sTemp = sHeader; CompressSWSP(sTemp); unsigned cpos = sTemp.find(':'); if (cpos == -1) { // no colon?! } else { // lower case the header field name for (unsigned i=0; i= 'A' && sTemp[i] <= 'Z') sTemp[i] += 'a'-'A'; } // remove the space after the : if (cpos+1 < sTemp.length() && sTemp[cpos+1] == ' ') sTemp.erase(cpos+1, 1); // remove the space before the : if (cpos > 0 && sTemp[cpos-1] == ' ') sTemp.erase(cpos-1, 1); } return sTemp; } libdkim-1.0.21.orig/src/resource.h0000666000175000017500000000206211063377410016310 0ustar magnusmagnus//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by libdkim.rc // #define VER_MAJOR 1 #define VER_MINOR 0 #define VER_REV 21 #define VER_BUILD 0 #define VERSION_STRING "1.0.21" #define IDS_PROJNAME 100 #define IDR_WMDMLOGGER 101 #define IDS_LOG_SEV_INFO 201 #define IDS_LOG_SEV_WARN 202 #define IDS_LOG_SEV_ERROR 203 #define IDS_LOG_DATETIME 204 #define IDS_LOG_SRCNAME 205 #define IDS_DEF_LOGFILE 301 #define IDS_DEF_MAXSIZE 302 #define IDS_DEF_SHRINKTOSIZE 303 #define IDS_DEF_LOGENABLED 304 #define IDS_MUTEX_TIMEOUT 401 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 201 #define _APS_NEXT_COMMAND_VALUE 32768 #define _APS_NEXT_CONTROL_VALUE 201 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif libdkim-1.0.21.orig/src/dns.h0000666000175000017500000000351511012004416015234 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ // This file is an intermediary which chooses the correct resolver // to use based on the platform // // Windows 2k+ -> Dynamically load dnsapi.dll and use DnsQuery() // Win9x/NT -> Use dnsresolv.cpp // UNIX -> Use res_query from libresolv // // These DNS resolution routines are encapsulated by the API below // return values for DNS functions: #define MAX_DOMAIN 254 #define DNSRESP_SUCCESS 0 // DNS lookup returned sought after records #define DNSRESP_TEMP_FAIL 1 // No response from DNS server #define DNSRESP_PERM_FAIL 2 // DNS server returned error or no records #define DNSRESP_DOMAIN_NAME_TOO_LONG 3 // Domain name too long #define DNSRESP_NXDOMAIN 4 // DNS server returned Name Error #define DNSRESP_EMPTY 5 // DNS server returned successful response but no records // Pass in the FQDN to get the TXT record int DNSGetTXT( const char *szFQDN, char* Buffer, int nBufLen ); libdkim-1.0.21.orig/src/dns.cpp0000666000175000017500000001717311012004406015573 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifdef WIN32 #include #include "windns.h" #else #include #include #include #include #include #include #endif #include #include #include "dkim.h" #include "dns.h" #ifdef WIN32 #include "dnsresolv.h" #endif #ifdef WIN32 #ifndef DNS_ERROR_RCODE_SERVER_FAILURE #define DNS_ERROR_RCODE_SERVER_FAILURE 9002L #endif typedef DNS_STATUS (WINAPI *DNSQUERYFUNC)( LPCSTR lpstrName, WORD wType, DWORD fOptions, PIP4_ARRAY aipServers, PDNS_RECORD *ppQueryResultsSet, PVOID *pReserved ); typedef void (WINAPI *DNSRECORDLISTFREE)(PDNS_RECORD, DNS_FREE_TYPE); static HMODULE s_hDNSAPI = NULL; // handle to dnsapi.dll static bool s_bDNSAPIAvailable = true; // set to false if DLL can't be loaded static DNSQUERYFUNC s_DnsQuery = NULL; // DnsQuery function address static DNSRECORDLISTFREE s_DnsRecordListFree = NULL; //////////////////////////////////////////////////////////////////////////////// // // CheckForDNSAPI - Attempt to load dnsapi.dll once // //////////////////////////////////////////////////////////////////////////////// bool CheckForDNSAPI(void) { if( s_bDNSAPIAvailable ) { if( s_hDNSAPI == NULL ) { s_hDNSAPI = LoadLibrary( "dnsapi.dll" ); if( s_hDNSAPI == NULL ) { s_bDNSAPIAvailable = false; } else { s_DnsQuery = (DNSQUERYFUNC)GetProcAddress( s_hDNSAPI, "DnsQuery_A" ); s_DnsRecordListFree = (DNSRECORDLISTFREE)GetProcAddress( s_hDNSAPI, "DnsRecordListFree" ); if( s_DnsQuery == NULL || s_DnsRecordListFree == NULL ) { FreeLibrary( s_hDNSAPI ); s_hDNSAPI = NULL; s_bDNSAPIAvailable = false; } } } } return s_bDNSAPIAvailable; } //////////////////////////////////////////////////////////////////////////////// // // _DNSGetTXT2k - for Win2k+ // //////////////////////////////////////////////////////////////////////////////// int _DNSGetTXT2k( const char* szSubDomain, char* Buffer, int nBufLen ) { PDNS_RECORD answer; DNS_STATUS res = s_DnsQuery( szSubDomain, DNS_TYPE_TEXT, DNS_QUERY_TREAT_AS_FQDN, NULL, &answer, NULL ); if (res) { if( res == DNS_ERROR_RCODE_SERVER_FAILURE) return DNSRESP_TEMP_FAIL; else if (res == DNS_ERROR_RCODE_NAME_ERROR) return DNSRESP_NXDOMAIN; else return DNSRESP_PERM_FAIL; } bool bFoundRecord = false; int nRet = DNSRESP_EMPTY; PDNS_RECORD prr = answer; while( prr ) { if( prr->wType == DNS_TYPE_TEXT && prr->Data.Txt.dwStringCount > 0 ) { if( bFoundRecord ) { // multiple records are allowed but we only use the first one } else { char* BufPtr = Buffer; int BufLeft = nBufLen-1; // -1 to save room for null terminator bool Truncated = false; for( unsigned int i = 0; i < prr->Data.Txt.dwStringCount && !Truncated; i++ ) { int Len = strlen( prr->Data.Txt.pStringArray[i] ); if( Len > BufLeft ) { Len = BufLeft; Truncated = true; } memcpy( BufPtr, prr->Data.Txt.pStringArray[i], Len ); BufPtr += Len; BufLeft -= Len; } *BufPtr = '\0'; // TODO: verify that the record follows the DKIM tag-value syntax bFoundRecord = true; // TODO: use a different return code if the result was truncated? nRet = DNSRESP_SUCCESS; } } prr = prr->pNext; } s_DnsRecordListFree( answer, DnsFreeRecordList ); return nRet; } #define PACKETSZ 1024 #define C_IN 1 #define T_TXT 16 #define HFIXEDSZ 12 /* #/bytes of fixed data in header */ #define MAXDNAME 1025 /* maximum domain name */ #define QFIXEDSZ 4 #define RRFIXEDSZ 10 /* #/bytes of fixed data in r record */ #define NS_CMPRSFLGS 0xc0 /* Flag bits indicating name compression. */ #define NS_MAXCDNAME 255 /* maximum compressed domain name */ #define MAXCDNAME NS_MAXCDNAME #endif // defined WIN32 static inline unsigned short getshort(unsigned char *cp) { return (cp[0] << 8) | cp[1]; } //////////////////////////////////////////////////////////////////////////////// // // _DNSGetTXT for UNIX and win2k- // //////////////////////////////////////////////////////////////////////////////// int _DNSGetTXT( const char* szSubDomain, char* Buffer, int nBufLen ) { u_char answer[2*PACKETSZ+1]; int answerlen; int ancount, qdcount; /* answer count and query count */ u_char *eom, *cp; u_short type, rdlength; /* fields of records returned */ int rc; char* bufptr; answerlen = res_query( szSubDomain, C_IN, T_TXT, answer, sizeof(answer)); if( answerlen < 0 ) { if( h_errno == TRY_AGAIN ) return DNSRESP_TEMP_FAIL; else return DNSRESP_PERM_FAIL; } unsigned char rcode = answer[3] & 15; if (rcode != 0) { if (rcode == 3) return DNSRESP_NXDOMAIN; else return DNSRESP_PERM_FAIL; } qdcount = getshort( answer + 4); /* http://crynwr.com/rfc1035/rfc1035.html#4.1.1. */ ancount = getshort( answer + 6); eom = answer + answerlen; cp = answer + HFIXEDSZ; while( qdcount-- > 0 && cp < eom ) { rc = dn_expand( answer, eom, cp, Buffer, nBufLen ); if( rc < 0 ) { return DNSRESP_PERM_FAIL; } cp += rc + QFIXEDSZ; } while( ancount-- > 0 && cp < eom ) { rc = dn_expand( answer, eom, cp, Buffer, nBufLen ); if( rc < 0 ) { return DNSRESP_PERM_FAIL; } cp += rc; if (cp + RRFIXEDSZ >= eom) return DNSRESP_PERM_FAIL; type = getshort(cp + 0); /* http://crynwr.com/rfc1035/rfc1035.html#4.1.3. */ rdlength = getshort(cp + 8); cp += RRFIXEDSZ; if( type != T_TXT ) { cp += rdlength; continue; } bufptr = Buffer; while (rdlength && cp < eom) { int cnt; cnt = *cp++; /* http://crynwr.com/rfc1035/rfc1035.html#3.3.14. */ if( bufptr-Buffer + cnt + 1 >= nBufLen ) return DNSRESP_PERM_FAIL; if (cp + cnt > eom) return DNSRESP_PERM_FAIL; memcpy( bufptr, cp, cnt); rdlength -= cnt + 1; bufptr += cnt; cp += cnt; *bufptr = '\0'; } return DNSRESP_SUCCESS; } return DNSRESP_EMPTY; } //////////////////////////////////////////////////////////////////////////////// // // DNSGetTXT // // Pass in the FQDN to get the TXT record // //////////////////////////////////////////////////////////////////////////////// int DNSGetTXT( const char* szFQDN, char* Buffer, int nBufLen ) { if (strlen(szFQDN) > MAX_DOMAIN) return DNSRESP_DOMAIN_NAME_TOO_LONG; // Initialize out parameter Buffer[0] = '\0'; #ifdef WIN32 if( CheckForDNSAPI() == true ) { return _DNSGetTXT2k( szFQDN, Buffer, nBufLen ); } #endif return _DNSGetTXT( szFQDN, Buffer, nBufLen ); } libdkim-1.0.21.orig/src/dnsresolv.cpp0000666000175000017500000003250711012004426017026 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifdef WIN32 #include #include #include #include #include #pragma warning( disable: 4786 ) #pragma warning( disable: 4503 ) #include #include using namespace std; #include "dnsresolv.h" #pragma pack( push, DNSPacketDef ) #pragma pack( 1 ) struct DNSPacket { unsigned int nMsgLength; unsigned short Hdr[DNSMSG_HDR_SIZE]; unsigned char Data[DNSMSG_MAX_DATA_SIZE]; }; struct SocketInfo { SOCKET s; SOCKADDR_IN sockaddr; list DNSServers; }; #pragma pack( pop, DNSPacketDef ) int dn_expand( const u_char *msg, const u_char *eom, const u_char *src, char *dst, int dstsiz) { char* d = dst; u_char* p = (u_char*)src; int n = 0; int len = -1; //OutputDebugString( "dn_expand\n" ); while( p < eom && *p != 0) { if ((*p & DNSMSG_COMPRESS_FLAG) == DNSMSG_COMPRESS_FLAG ) { p++; if( len == -1 ) len = p - src + 1; p = (u_char*)(msg + (((p[-1] & 0x3f) << 8) | (*p & 0xff))); if( p < msg || p > eom ) { return -1; } } else if ((*p & DNSMSG_COMPRESS_FLAG) != 0 ) { return -1; } n = *p++; while( p < eom && n > 0 ) { if( *p == 0x22 || *p == 0x2E || *p == 0x3B || *p == 0x5C || *p == 0x40 || *p == 0x24 ) { *d++ = '\\'; *d++ = *p; } else if( *p > 0x20 && *p < 0x7f ) { *d++ = *p; } else { *d++ = '\\'; *d++ = '0' + *p / 100; *d++ = '0' + *p % 100; *d++ = '0' + *p % 10; } p++; n--; } *d++ = '.'; } if( d[-1] == '.' ) d[-1] = '\0'; else *d = 0; if( len == -1 ) len = p - src + 1; return (len); } void SwapHeader( struct DNSPacket* pkt ) { #if BYTE_ORDER == LITTLE_ENDIAN int i; for( i = 0; i < DNSMSG_HDR_SIZE; i++ ) { unsigned char* p = (unsigned char*)(&pkt->Hdr[i]); unsigned char b = p[0]; p[0] = p[1]; p[1] = b; } #endif } void AddShort( char** ptr, unsigned short s ) { unsigned char* p = (unsigned char*)&s; #if BYTE_ORDER == LITTLE_ENDIAN *(*ptr) = p[1]; (*ptr)++; *(*ptr) = p[0]; (*ptr)++; #else *(*ptr) = p[0]; (*ptr)++; *(*ptr) = p[1]; (*ptr)++; #endif } int InitDNSPacket( struct DNSPacket* pkt, const char* name, int iclass, int itype ) { char szLabel[DNSMSG_MAX_LABEL]; char* n = (char*)name; char* lastdot = NULL; char* s = szLabel; char* p; char backslash = 0; int nLabelLen = 0; ZeroMemory( pkt, sizeof(struct DNSPacket) ); pkt->Hdr[DNSMSG_HDR_ID] = 0; pkt->Hdr[DNSMSG_HDR_CODES] = 0x100; pkt->Hdr[DNSMSG_HDR_QDCOUNT] = 1; pkt->Hdr[DNSMSG_HDR_ANCOUNT] = 0; pkt->Hdr[DNSMSG_HDR_NSCOUNT] = 0; pkt->Hdr[DNSMSG_HDR_ARCOUNT] = 0; SwapHeader( pkt ); p = (char*)pkt->Data; pkt->nMsgLength = 0; while( *n ) { if( backslash ) { int nChar; if( *n >= '0' && *n <= '9' ) { nChar = 100 * (int)(*n - '0'); n++; if( *n < '0' || *n > '9' ) { return EMSGSIZE; //invalid escape code } nChar += 10 * (int)(*n - '0'); n++; if( *n < '0' || *n > '9' ) { return EMSGSIZE; //invalid escape code } nChar += (int)(*n - '0'); if( (s - szLabel + 1) < DNSMSG_MAX_LABEL ) { *s = (char) nChar; s++; } else { return EMSGSIZE; } } else { if( (s - szLabel + 1) < DNSMSG_MAX_LABEL ) { *s = (char) *n; s++; } else { return EMSGSIZE; } } backslash = 0; } else if( *n == '\\' ) { // enter escape mode backslash = 1; } else if( *n == '.' ) { nLabelLen = (s - szLabel); //*s = 0; *p++ = nLabelLen; memcpy( p, szLabel, nLabelLen); p += nLabelLen; s = szLabel; if( n[1] == '\0' ) { *p++ = 0; // Type *p++ = 0; *p++ = T_TXT; // Class *p++ = 0; *p++ = C_IN; pkt->nMsgLength = (u_char*)p - pkt->Data + DNSMSG_HDR_SIZE * 2; return 0; } } else { // normal char if( (s - szLabel + 1) < DNSMSG_MAX_LABEL ) { *s = *n; s++; } else { return EMSGSIZE; } } n++; } nLabelLen = (s - szLabel); if( nLabelLen > 0 ) { *p++ = nLabelLen; memcpy( p, szLabel, nLabelLen); p += nLabelLen; } *p++ = 0; // Type AddShort( &p, T_TXT ); // Class AddShort( &p, C_IN ); pkt->nMsgLength = (u_char*)p - pkt->Data + DNSMSG_HDR_SIZE * 2; return 0; } void SaveDNSServer( struct SocketInfo* skt, char* szIPAddress ) { skt->DNSServers.push_back( szIPAddress ); } bool GetInternalDNSServer( struct SocketInfo* skt ) { char IP[256]; char buffer[256]; buffer[0] = '\0'; int IPSize = sizeof(IP); typedef DWORD (WINAPI *LPGETNETWORKPARAMS)(PFIXED_INFO pFixedInfo, PULONG pOutBufLen); static LPGETNETWORKPARAMS pGetNetworkParams = (LPGETNETWORKPARAMS)-1; static HMODULE hIpHelperDll = NULL; if (pGetNetworkParams == (LPGETNETWORKPARAMS)-1) { hIpHelperDll = LoadLibrary("iphlpapi.dll"); if (hIpHelperDll != NULL) pGetNetworkParams = (LPGETNETWORKPARAMS)GetProcAddress(hIpHelperDll, "GetNetworkParams"); else pGetNetworkParams = NULL; // keep the DLL loaded } if (pGetNetworkParams != NULL) { char fibuffer[2048]; FIXED_INFO &fi = *(FIXED_INFO*)fibuffer; ULONG size = sizeof(fibuffer); DWORD dwResult = pGetNetworkParams(&fi, &size); if (dwResult == ERROR_SUCCESS) { IP_ADDR_STRING *ip = &fi.DnsServerList; while (ip != NULL) { if (ip->IpAddress.String[0] != '\0') { strcat(buffer, ip->IpAddress.String); strcat(buffer, " "); } ip = ip->Next; } } } // if that didn't work, try reading from the registry if (buffer[0] == '\0') { HKEY hRegKey = NULL; if (GetVersion() & 0x80000000) RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\VxD\\MSTCP", 0, KEY_QUERY_VALUE, &hRegKey); else RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\TCPIP\\Parameters", 0, KEY_QUERY_VALUE, &hRegKey); if (hRegKey != NULL) { ULONG size = sizeof(buffer); RegQueryValueEx(hRegKey, "NameServer", NULL, NULL, (BYTE*)buffer, &size); if (buffer[0] == '\0') { size = sizeof(buffer); RegQueryValueEx(hRegKey, "DhcpNameServer", NULL, NULL, (BYTE*)buffer, &size); } RegCloseKey(hRegKey); } // look for encoded DNS servers on Win95 if (buffer[0] == '\0' && RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\VxD\\DHCP\\DHCPInfo00", 0, KEY_QUERY_VALUE, &hRegKey) == ERROR_SUCCESS) { unsigned char binbuffer[1024]; ULONG size = sizeof(binbuffer); if (RegQueryValueEx(hRegKey, "OptionInfo", NULL, NULL, binbuffer, &size) == ERROR_SUCCESS) { unsigned char *ptr = binbuffer; while (ptr <= binbuffer+size-2) { unsigned type = ptr[0]; unsigned len = ptr[1]; ptr += 2; if (type == 6) { while (len >= 4) { sprintf(buffer+strlen(buffer), "%d.%d.%d.%d ", ptr[0], ptr[1], ptr[2], ptr[3]); ptr += 4; len -= 4; } break; } ptr += len; } } RegCloseKey(hRegKey); } } int i = 0; char *ptr = buffer; for (;;) { while (*ptr == ' ' || *ptr == ',' || *ptr == ';') ptr++; if (*ptr == '\0') break; char *start = ptr; for (;;) { ptr++; if (*ptr == '\0') { break; } else if (*ptr == ' ' || *ptr == ',' || *ptr == ';') { *ptr++ = '\0'; break; } } strncpy(IP, start, IPSize-1); IP[IPSize-1] = '\0'; SaveDNSServer( skt, IP ); } return (skt->DNSServers.size() > 0); } int InitWinsock( struct SocketInfo* skt ) { WSADATA wsaData; WORD wVersionRequested = MAKEWORD(1, 1); int nResult; nResult = WSAStartup( wVersionRequested, &wsaData ); if( nResult != 0 ) { return -1; } if( !GetInternalDNSServer( skt ) ) { return -2; } ZeroMemory( &skt->sockaddr, sizeof(SOCKADDR_IN) ); skt->sockaddr.sin_family = AF_INET; skt->sockaddr.sin_port = htons(53); skt->sockaddr.sin_addr.s_addr = 0xff000001; skt->s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); return 0; } int SendPacket( struct DNSPacket* pkt, struct SocketInfo* skt ) { int nRet; nRet = sendto( skt->s, (const char*)pkt->Hdr, pkt->nMsgLength, 0, (SOCKADDR*)&skt->sockaddr, sizeof(SOCKADDR_IN) ); if( nRet > 0 ) return 0; return -1; } int ReceivePacket( u_char* answer, int anslen, struct SocketInfo* skt ) { int nRet; fd_set fdread; struct timeval tTimeout; FD_ZERO(&fdread); // zero out set first FD_SET( skt->s, &fdread); // add socket to set tTimeout.tv_sec = 3; // 10 seconds tTimeout.tv_usec = 0; // 0 milliseconds // check socket for readability nRet = select( skt->s, &fdread, NULL, NULL, &tTimeout); if ( nRet < 1 ) { // Retry? return -1; } nRet = recvfrom( skt->s, (char*)answer, anslen, 0, NULL, NULL); if( nRet > 0 ) { //char szMsg[80]; //sprintf( szMsg, "received %d bytes\n", nRet ); //OutputDebugString( szMsg ); /* { FILE* fp = fopen( "out.bin", "wb" ); if( fp ) { fwrite( answer, 1, anslen, fp ); fclose(fp ); } }*/ return nRet; } return -1; } void Cleanup( struct SocketInfo* skt ) { closesocket( skt->s ); WSACleanup(); } int UDPQuery( struct DNSPacket* pkt, struct SocketInfo* skt, u_char* answer, int anslen ) { list::iterator DnsIter; int nRet = -1; for( DnsIter = skt->DNSServers.begin(); DnsIter != skt->DNSServers.end(); DnsIter++ ) { unsigned long nIPAddr = inet_addr( DnsIter->c_str() ); if( nIPAddr == INADDR_NONE ) { nRet = -1; } else { skt->sockaddr.sin_addr.s_addr = nIPAddr; nRet = SendPacket( pkt, skt ); if( nRet != 0 ) { // Error sending packet return -1; } nRet = ReceivePacket( answer, anslen, skt ); if( nRet > 0 ) { break; } } } return nRet; } int TCPQuery( struct DNSPacket* pkt, struct SocketInfo* skt, u_char* answer, int anslen ) { list::iterator DnsIter; int nRet = -1; for( DnsIter = skt->DNSServers.begin(); DnsIter != skt->DNSServers.end(); DnsIter++ ) { unsigned long nIPAddr = inet_addr( DnsIter->c_str() ); if( nIPAddr == INADDR_NONE ) { nRet = -1; } else { skt->sockaddr.sin_addr.s_addr = nIPAddr; closesocket( skt->s ); skt->s = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); nRet = connect( skt->s, (sockaddr*)&skt->sockaddr, sizeof(struct sockaddr_in) ); if( nRet == 0 ) { unsigned char nPktLen[2]; nPktLen[1] = pkt->nMsgLength & 0xff; nPktLen[0] = (pkt->nMsgLength & 0xff00) >> 8; // send the message length nRet = send( skt->s, (const char*) &nPktLen, 2, 0 ); nRet = send( skt->s, (const char*) pkt->Hdr, pkt->nMsgLength, 0 ); if( nRet > 0 ) { fd_set fdread; struct timeval tTimeout; FD_ZERO(&fdread); // zero out set first FD_SET( skt->s, &fdread); // add socket to set tTimeout.tv_sec = 3; // 10 seconds tTimeout.tv_usec = 0; // 0 milliseconds // check socket for readability nRet = select( skt->s, &fdread, NULL, NULL, &tTimeout); if ( nRet == 1 ) { nRet = recv( skt->s, (char*)nPktLen, 2, 0 ); if( nRet == 2 ) { unsigned short nResponseLen = nPktLen[0] * 256 + nPktLen[1]; if( nResponseLen < anslen ) { nRet = recv( skt->s, (char*)answer, anslen, 0 ); } } else { nRet = -1; } } } else { nRet = -1; } } if( nRet > 0 ) break; } } return nRet; } int res_query( const char* name, int iclass, int itype, u_char* answer, int anslen) { struct DNSPacket pkt; struct SocketInfo skt; int nRet; if( iclass != C_IN || itype != T_TXT ) { return -1; } nRet = InitDNSPacket( &pkt, name, iclass, itype ); if( nRet != 0 ) { // Error with name return -1; } nRet = InitWinsock( &skt ); if( nRet != 0 ) { // Error in winsock return -1; } nRet = UDPQuery( &pkt, &skt, answer, anslen ); if( ((nRet > 0) && ((answer[2] & 0x02) != 0)) // Check for TrunCation bit || ( nRet == -1 ) ) { nRet = TCPQuery( &pkt, &skt, answer, anslen ); } Cleanup( &skt ); return nRet; } #endiflibdkim-1.0.21.orig/src/dkimbase.h0000666000175000017500000000413111012004314016217 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifndef DKIMBASE_H #define DKIMBASE_H #include #include #include #define BUFFER_ALLOC_INCREMENT 256 #include #include using namespace std; class CDKIMBase { public: CDKIMBase(); ~CDKIMBase(); int Init(void); int Process( char* szBuffer, int nBufLength, bool bEOF ); int ProcessFinal(void); int Alloc( char*& szBuffer, int nRequiredSize ); int ReAlloc( char*& szBuffer, int& nBufferLength, int nRequiredSize ); void Free( char* szBuffer ); static void RemoveSWSP( char* szBuffer ); static void RemoveSWSP( char* pBuffer, int& nBufLength ); static void RemoveSWSP( string& sBuffer ); static void CompressSWSP( char* pBuffer, int& nBufLength ); static void CompressSWSP( string& sBuffer ); static string RelaxHeader( const string& sHeader ); virtual int ProcessHeaders(void); virtual int ProcessBody( char* szBuffer, int nBufLength, bool bEOF ); protected: char* m_From; char* m_Sender; char* m_hTag; int m_hTagSize; int m_hTagPos; char* m_Line; int m_LineSize; int m_LinePos; bool m_InHeaders; list HeaderList; }; #endif // DKIMBASE_H libdkim-1.0.21.orig/src/dkimsign.cpp0000666000175000017500000006164011012004342016611 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifdef WIN32 #include #pragma warning( disable: 4786 ) #pragma warning( disable: 4503 ) #else #define _strnicmp strncasecmp #define _stricmp strcasecmp #define LOWORD(l) ((unsigned)(l) & 0xffff) #define HIWORD(l) ((unsigned)(l) >> 16) #endif #include #include #include "dkim.h" #include "dkimsign.h" CDKIMSign::CDKIMSign() { m_EmptyLineCount = 0; m_pfnHdrCallback = NULL; EVP_SignInit( &m_allman_sha1ctx, EVP_sha1() ); EVP_SignInit( &m_Hdr_ietf_sha1ctx, EVP_sha1() ); EVP_SignInit( &m_Hdr_ietf_sha256ctx, EVP_sha256() ); EVP_DigestInit( &m_Bdy_ietf_sha1ctx, EVP_sha1() ); EVP_DigestInit( &m_Bdy_ietf_sha256ctx, EVP_sha256() ); } CDKIMSign::~CDKIMSign() { EVP_MD_CTX_cleanup( &m_allman_sha1ctx ); EVP_MD_CTX_cleanup( &m_Hdr_ietf_sha1ctx ); EVP_MD_CTX_cleanup( &m_Hdr_ietf_sha256ctx ); EVP_MD_CTX_cleanup( &m_Bdy_ietf_sha1ctx ); EVP_MD_CTX_cleanup( &m_Bdy_ietf_sha256ctx ); } //////////////////////////////////////////////////////////////////////////////// // // Init - save the options // //////////////////////////////////////////////////////////////////////////////// int CDKIMSign::Init( DKIMSignOptions* pOptions ) { int nRet = CDKIMBase::Init(); m_Canon = pOptions->nCanon; // as of draft 01, these are the only allowed signing types: if( (m_Canon != DKIM_SIGN_SIMPLE_RELAXED) && (m_Canon != DKIM_SIGN_RELAXED) && (m_Canon != DKIM_SIGN_RELAXED_SIMPLE) ) { m_Canon = DKIM_SIGN_SIMPLE; } sSelector.assign( pOptions->szSelector ); m_pfnHdrCallback = pOptions->pfnHeaderCallback; sDomain.assign( pOptions->szDomain ); m_IncludeBodyLengthTag = ( pOptions->nIncludeBodyLengthTag != 0 ); m_nBodyLength = 0; m_ExpireTime = pOptions->expireTime; sIdentity.assign( pOptions->szIdentity ); m_nIncludeTimeStamp = pOptions->nIncludeTimeStamp; m_nIncludeQueryMethod = pOptions->nIncludeQueryMethod; m_nIncludeCopiedHeaders = pOptions->nIncludeCopiedHeaders; m_nIncludeBodyHash = pOptions->nIncludeBodyHash; // NOTE: the following line is not backwards compatible with MD 8.0.3 // because the szRequiredHeaders member was added after the release //sRequiredHeaders.assign( pOptions->szRequiredHeaders ); //make sure there is a colon after the last header in the list if( (sRequiredHeaders.size() > 0) && sRequiredHeaders.at(sRequiredHeaders.size()-1) != ':' ) { sRequiredHeaders.append( ":" ); } m_nHash = pOptions->nHash; m_bReturnedSigAssembled = false; m_sCopiedHeaders.erase(); return nRet; } //FILE* fpdebug = NULL; //////////////////////////////////////////////////////////////////////////////// // // Hash - update the hash // //////////////////////////////////////////////////////////////////////////////// void CDKIMSign::Hash( const char* szBuffer, int nBufLength, bool bHdr, bool bAllmanOnly ) { /** START DEBUG CODE ** if( nBufLength == 2 && szBuffer[0] == '\r' && szBuffer[1] == '\n' ) { printf( "[CRLF]\n" ); } else { char* szDbg = new char[nBufLength+1]; strncpy( szDbg, szBuffer, nBufLength ); szDbg[nBufLength] = '\0'; printf( "[%s]\n", szDbg ); } *** if( fpdebug == NULL ) { fpdebug = fopen( "canon.msg", "wb" ); } fwrite( szBuffer, 1, nBufLength, fpdebug ); /** END DEBUG CODE **/ if( bAllmanOnly ) { if( m_nIncludeBodyHash & DKIM_BODYHASH_ALLMAN_1 ) { EVP_SignUpdate( &m_allman_sha1ctx, szBuffer, nBufLength ); } } else { if( m_nIncludeBodyHash < DKIM_BODYHASH_IETF_1 ) { EVP_SignUpdate( &m_allman_sha1ctx, szBuffer, nBufLength ); } else if( m_nIncludeBodyHash & DKIM_BODYHASH_IETF_1 ) { if( m_nIncludeBodyHash & DKIM_BODYHASH_ALLMAN_1 ) { EVP_SignUpdate( &m_allman_sha1ctx, szBuffer, nBufLength ); } if( m_nHash & DKIM_HASH_SHA256 ) { if( bHdr ) EVP_SignUpdate( &m_Hdr_ietf_sha256ctx, szBuffer, nBufLength ); else EVP_DigestUpdate( &m_Bdy_ietf_sha256ctx, szBuffer, nBufLength ); } if( m_nHash != DKIM_HASH_SHA256 ) { if( bHdr ) EVP_SignUpdate( &m_Hdr_ietf_sha1ctx, szBuffer, nBufLength ); else EVP_DigestUpdate( &m_Bdy_ietf_sha1ctx, szBuffer, nBufLength ); } } } } //////////////////////////////////////////////////////////////////////////////// // // SignThisTag - return boolean whether or not to sign this tag // //////////////////////////////////////////////////////////////////////////////// bool CDKIMSign::SignThisTag( const string& sTag ) { bool bRet = true; if( _strnicmp( sTag.c_str(), "X-", 2 ) == 0 || _stricmp( sTag.c_str(), "Authentication-Results:" ) == 0 || _stricmp( sTag.c_str(), "Return-Path:" ) == 0 ) { bRet = false; } return bRet; } bool ConvertHeaderToQuotedPrintable(const char *source, char* dest) { bool bConvert = false; // do quoted printable static unsigned char hexchars[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; unsigned char *d = (unsigned char*)dest; for (const unsigned char *s = (const unsigned char *)source; *s != '\0'; s++) { if (*s >= 33 && *s <= 126 && *s != '=' && *s != ':' && *s != ';' && *s != '|') { *d++ = *s; } else { bConvert = true; *d++ = '='; *d++ = hexchars[*s >> 4]; *d++ = hexchars[*s & 15]; } } *d = '\0'; return bConvert; } //////////////////////////////////////////////////////////////////////////////// // // GetHeaderParams - Extract any needed header parameters // //////////////////////////////////////////////////////////////////////////////// void CDKIMSign::GetHeaderParams( const string& sHdr ) { if ( _strnicmp( sHdr.c_str(), "X", 1) == 0) return; if( _strnicmp( sHdr.c_str(), "From:", 5 ) == 0 ) { sFrom.assign( sHdr.c_str() + 5 ); } if( _strnicmp( sHdr.c_str(), "Sender:", 7 ) == 0 ) { sSender.assign( sHdr.c_str() + 7 ); } if( m_nIncludeCopiedHeaders ) { string::size_type pos = sHdr.find( ':' ); if( pos != string::npos ) { string sTag, sValue; char* workBuffer = new char[sHdr.size() * 3 + 1]; sTag.assign( sHdr.substr( 0, pos ) ); sValue.assign( sHdr.substr( pos+1, string::npos ) ); ConvertHeaderToQuotedPrintable( sTag.c_str(), workBuffer ); if( !m_sCopiedHeaders.empty() ) { m_sCopiedHeaders.append( "|" ); } m_sCopiedHeaders.append( workBuffer ); m_sCopiedHeaders.append( ":" ); ConvertHeaderToQuotedPrintable( sValue.c_str(), workBuffer ); m_sCopiedHeaders.append( workBuffer ); delete[] workBuffer; } } } //////////////////////////////////////////////////////////////////////////////// // // ProcessHeaders - sign headers and save needed parameters // //////////////////////////////////////////////////////////////////////////////// int CDKIMSign::ProcessHeaders(void) { map::reverse_iterator> IterMap; map::reverse_iterator>::iterator IterMapIter; list::reverse_iterator riter; list::iterator iter; string sTag; bool bFromHeaderFound = false; // walk the header list for( iter = HeaderList.begin(); iter != HeaderList.end(); iter++ ) { sTag.assign( *iter ); // look for a colon string::size_type pos = sTag.find( ':' ); if (pos != string::npos) { int nSignThisTag = 1; // hack off anything past the colon sTag.erase( pos + 1, string::npos ); // is this the From: header? if( _stricmp( sTag.c_str(), "From:" ) == 0 ) { bFromHeaderFound = true; nSignThisTag = 1; IsRequiredHeader( sTag ); // remove from required header list } // is this in the list of headers that must be signed? else if( IsRequiredHeader( sTag ) ) { nSignThisTag = 1; } else { if( m_pfnHdrCallback ) { nSignThisTag = m_pfnHdrCallback( iter->c_str() ); } else { nSignThisTag = SignThisTag( sTag ) ? 1 : 0; } } // save header parameters GetHeaderParams( *iter ); if( nSignThisTag > 0 ) { // add this tag to h= hParam.append( sTag ); IterMapIter = IterMap.find( sTag ); riter = ( IterMapIter == IterMap.end() ) ? HeaderList.rbegin() : IterMapIter->second; // walk the list in reverse looking for the last instance of this header while ( riter != HeaderList.rend() ) { if( _strnicmp( riter->c_str(), sTag.c_str(), sTag.size() ) == 0 ) { ProcessHeader( *riter ); // save the reverse iterator position for this tag riter++; IterMap[sTag] = riter; break; } riter++; } } } } Hash( "\r\n", 2, true, true ); // only for Allman sig if( !bFromHeaderFound ) { string sFrom( "From:" ); hParam.append( sFrom ); IsRequiredHeader( sFrom ); // remove from required header list // Hash( "\r\n", 2 ); } hParam.append( sRequiredHeaders ); // string::size_type end = sRequiredHeaders.find( ':' ); // while (end != string::npos) // { // Hash( "\r\n", 2 ); // end = sRequiredHeaders.find( ':', end+1 ); // } // remove the last colon from h= if( hParam.at( hParam.size() - 1 ) == ':' ) hParam.erase( hParam.size() - 1, string::npos ); return DKIM_SUCCESS; } void CDKIMSign::ProcessHeader( const string& sHdr ) { switch( HIWORD( m_Canon ) ) { case DKIM_CANON_SIMPLE: Hash( sHdr.c_str(), sHdr.size(), true ); Hash( "\r\n", 2, true ); break; case DKIM_CANON_NOWSP: { string sTemp = sHdr; RemoveSWSP( sTemp ); // convert characters before ':' to lower case for( char* s = (char*)sTemp.c_str(); *s != '\0' && *s != ':'; s++ ) { if( *s >= 'A' && *s <= 'Z' ) *s += 'a'-'A'; } Hash( sTemp.c_str(), sTemp.size(), true ); Hash( "\r\n", 2, true ); } break; case DKIM_CANON_RELAXED: { string sTemp = RelaxHeader( sHdr ); Hash( sTemp.c_str(), sTemp.length(), true ); Hash( "\r\n", 2, true ); } break; } } int CDKIMSign::ProcessBody( char* szBuffer, int nBufLength, bool bEOF ) { switch( LOWORD( m_Canon ) ) { case DKIM_CANON_SIMPLE: if( nBufLength > 0 ) { while( m_EmptyLineCount > 0 ) { Hash( "\r\n", 2, false ); m_nBodyLength += 2; m_EmptyLineCount--; } Hash( szBuffer, nBufLength, false ); Hash( "\r\n", 2, false ); m_nBodyLength += nBufLength + 2; } else { m_EmptyLineCount++; if( bEOF ) { Hash( "\r\n", 2, false ); m_nBodyLength += 2; } } break; case DKIM_CANON_NOWSP: RemoveSWSP( szBuffer, nBufLength ); if( nBufLength > 0 ) { Hash( szBuffer, nBufLength, false ); m_nBodyLength += nBufLength; } break; case DKIM_CANON_RELAXED: CompressSWSP( szBuffer, nBufLength ); if( nBufLength > 0 ) { while( m_EmptyLineCount > 0 ) { Hash( "\r\n", 2, false ); m_nBodyLength += 2; m_EmptyLineCount--; } Hash( szBuffer, nBufLength, false ); m_nBodyLength += nBufLength; if ( !bEOF ) { Hash( "\r\n", 2, false ); m_nBodyLength += 2; } } else m_EmptyLineCount++; break; } return DKIM_SUCCESS; } bool CDKIMSign::ParseFromAddress( void ) { string::size_type pos; string sAddress; if( !sFrom.empty() ) { sAddress.assign( sFrom ); } else if( !sSender.empty() ) { sAddress.assign( sSender ); } else { return false; } // simple for now, beef it up later // remove '<' and anything before it pos = sAddress.find( '<' ); if( pos != string::npos ) sAddress.erase( 0, pos ); // remove '>' and anything after it pos = sAddress.find( '>' ); if( pos != string::npos ) sAddress.erase( pos, string::npos ); // look for '@' symbol pos = sAddress.find( '@' ); if( pos == string::npos ) return false; if( sDomain.empty() ) { sDomain.assign( sAddress.c_str() + pos + 1 ); RemoveSWSP( sDomain ); } return true; } //////////////////////////////////////////////////////////////////////////////// // // InitSig - initialize signature folding algorithm // //////////////////////////////////////////////////////////////////////////////// void CDKIMSign::InitSig(void) { m_sSig.reserve( 1024 ); m_sSig.assign( "DKIM-Signature:" ); m_nSigPos = m_sSig.size(); } //////////////////////////////////////////////////////////////////////////////// // // AddTagToSig - add tag and value to signature folding if necessary // if bFold, fold at cbrk char // //////////////////////////////////////////////////////////////////////////////// void CDKIMSign::AddTagToSig( char* Tag, const string &sValue, char cbrk, bool bFold ) { int nTagLen = strlen(Tag); AddInterTagSpace( (!bFold) ? sValue.size() + nTagLen + 2 : nTagLen + 2 ); m_sSig.append( Tag ); m_sSig.append( "=" ); m_nSigPos += 1 + nTagLen; if( !bFold ) { m_sSig.append( sValue ); m_nSigPos += sValue.size(); } else { AddFoldedValueToSig( sValue, cbrk ); } m_sSig.append( ";" ); m_nSigPos++; } //////////////////////////////////////////////////////////////////////////////// // // AddTagToSig - add tag and numeric value to signature folding if necessary // //////////////////////////////////////////////////////////////////////////////// void CDKIMSign::AddTagToSig( char* Tag, unsigned long nValue ) { char szValue[64]; sprintf( szValue, "%u", nValue ); AddTagToSig( Tag, szValue, 0, false ); } //////////////////////////////////////////////////////////////////////////////// // // AddInterTagSpace - add space or fold here // //////////////////////////////////////////////////////////////////////////////// void CDKIMSign::AddInterTagSpace( int nSizeOfNextTag ) { if( m_nSigPos + nSizeOfNextTag + 1 > OptimalHeaderLineLength ) { m_sSig.append( "\r\n\t" ); m_nSigPos = 1; } else { m_sSig.append( " " ); m_nSigPos++; } } //////////////////////////////////////////////////////////////////////////////// // // AddTagToSig - add value to signature folding if necessary // if cbrk == 0 fold anywhere, otherwise fold only at cbrk // //////////////////////////////////////////////////////////////////////////////// void CDKIMSign::AddFoldedValueToSig( const string &sValue, char cbrk ) { string::size_type pos = 0; if( cbrk == 0 ) { // fold anywhere while( pos < sValue.size() ) { string::size_type len = OptimalHeaderLineLength - m_nSigPos; if( len > sValue.size() - pos ) len = sValue.size() - pos; m_sSig.append( sValue.substr( pos, len ) ); m_nSigPos += len; pos += len; if( pos < sValue.size() ) { m_sSig.append( "\r\n\t" ); m_nSigPos = 1; } } } else { // fold only at cbrk while( pos < sValue.size() ) { string::size_type len = OptimalHeaderLineLength - m_nSigPos; string::size_type brkpos; if( sValue.size() - pos < len ) { brkpos = sValue.size() - 1; } else { brkpos = sValue.rfind( cbrk, pos + len ); } if( brkpos == string::npos || brkpos < pos ) { brkpos = sValue.find( cbrk, pos ); if( brkpos == string::npos ) { brkpos = sValue.size(); } } len = brkpos - pos + 1; m_sSig.append( sValue.substr( pos, len ) ); m_nSigPos += len; pos += len; if( pos < sValue.size() ) { m_sSig.append( "\r\n\t" ); m_nSigPos = 1; } } } } //////////////////////////////////////////////////////////////////////////////// // // GetSig - compute hash and return signature header in szSignature // //////////////////////////////////////////////////////////////////////////////// int CDKIMSign::GetSig( char* szPrivKey, char* szSignature, int nSigLength ) { if( szPrivKey == NULL ) { return DKIM_BAD_PRIVATE_KEY; } if( szSignature == NULL ) { return DKIM_BUFFER_TOO_SMALL; } int nRet = AssembleReturnedSig( szPrivKey ); if( nRet != DKIM_SUCCESS ) return nRet; if( m_sReturnedSig.size() + 1 < nSigLength ) { strcpy( szSignature, m_sReturnedSig.c_str() ); } else { return DKIM_BUFFER_TOO_SMALL; } return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // GetSig - compute hash and return signature header in szSignature // //////////////////////////////////////////////////////////////////////////////// int CDKIMSign::GetSig2( char* szPrivKey, char** pszSignature ) { if( szPrivKey == NULL ) { return DKIM_BAD_PRIVATE_KEY; } if( pszSignature == NULL ) { return DKIM_BUFFER_TOO_SMALL; } int nRet = AssembleReturnedSig( szPrivKey ); if( nRet != DKIM_SUCCESS ) return nRet; *pszSignature = (char*)m_sReturnedSig.c_str(); return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // IsRequiredHeader - Check if header in required list. If so, delete // header from list. // //////////////////////////////////////////////////////////////////////////////// bool CDKIMSign::IsRequiredHeader( const string& sTag ) { string::size_type start = 0; string::size_type end = sRequiredHeaders.find( ':' ); while (end != string::npos) { // check for a zero-length header if( start == end ) { sRequiredHeaders.erase( start, 1 ); } else { if( _stricmp( sTag.c_str(), sRequiredHeaders.substr( start, end - start + 1 ).c_str() ) == 0 ) { sRequiredHeaders.erase( start, end - start + 1 ); return true; } else { start = end + 1; } } end = sRequiredHeaders.find( ':', start ); } return false; } int CDKIMSign::ConstructSignature( char* szPrivKey, bool bUseIetfBodyHash, bool bUseSha256 ) { string sSignedSig; unsigned char* sig; EVP_PKEY *pkey; BIO *bio, *b64; unsigned int siglen; int size; int len; char* buf; int pos = 0; // construct the DKIM-Signature: header and add to hash InitSig(); if( bUseIetfBodyHash ) { AddTagToSig( "v", "1", 0, false ); } AddTagToSig( "a", bUseSha256 ? "rsa-sha256" : "rsa-sha1", 0, false ); switch( m_Canon ) { case DKIM_SIGN_SIMPLE: AddTagToSig( "c", "simple", 0, false ); break; case DKIM_SIGN_SIMPLE_RELAXED: AddTagToSig( "c", "simple/relaxed", 0, false ); break; case DKIM_SIGN_RELAXED: AddTagToSig( "c", "relaxed/relaxed", 0, false ); break; case DKIM_SIGN_RELAXED_SIMPLE: AddTagToSig( "c", "relaxed", 0, false ); break; } AddTagToSig( "d", sDomain, 0, false ); AddTagToSig( "s", sSelector, 0, false ); if( m_IncludeBodyLengthTag ) { AddTagToSig( "l", m_nBodyLength ); } if( m_nIncludeTimeStamp != 0 ) { time_t t; time( &t ); AddTagToSig( "t", t ); } if( m_ExpireTime != 0 ) { AddTagToSig( "x", m_ExpireTime ); } if( !sIdentity.empty() ) { AddTagToSig( "i", sIdentity, 0, false ); } if( m_nIncludeQueryMethod ) { AddTagToSig( "q", bUseIetfBodyHash ? "dns/txt" : "dns" , 0, false ); } AddTagToSig( "h", hParam, ':', true ); if( m_nIncludeCopiedHeaders ) { AddTagToSig( "z", m_sCopiedHeaders, 0, true ); } if( bUseIetfBodyHash ) { unsigned char Hash[EVP_MAX_MD_SIZE]; unsigned int nHashLen = 0; EVP_DigestFinal( bUseSha256 ? &m_Bdy_ietf_sha256ctx : &m_Bdy_ietf_sha1ctx, Hash, &nHashLen ); bio = BIO_new(BIO_s_mem()); if (!bio) { return DKIM_OUT_OF_MEMORY; } b64 = BIO_new(BIO_f_base64()); if (!b64) { BIO_free(bio); return DKIM_OUT_OF_MEMORY; } BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); BIO_push(b64, bio); if (BIO_write(b64, Hash, nHashLen) < nHashLen) { BIO_free_all(b64); return DKIM_OUT_OF_MEMORY; } BIO_flush(b64); len = nHashLen * 2; buf = new char[len]; if( buf == NULL ) { BIO_free_all(b64); return DKIM_OUT_OF_MEMORY; } size = BIO_read(bio, buf, len); BIO_free_all(b64); // this should never happen if (size >= len) { delete[] buf; return DKIM_OUT_OF_MEMORY; } buf[size] = '\0'; AddTagToSig( "bh", buf, 0, true ); delete[] buf; } AddInterTagSpace( 3 ); m_sSig.append( "b=" ); m_nSigPos += 2; // Force a full copy - no reference copies please sSignedSig.assign( m_sSig.c_str() ); // note that since we're not calling hash here, need to dump this // to the debug file if you want the full canonical form string sTemp; if( HIWORD(m_Canon) == DKIM_CANON_RELAXED ) { sTemp = RelaxHeader( sSignedSig ); } else { sTemp = sSignedSig.c_str(); } if( bUseIetfBodyHash ) { EVP_SignUpdate( bUseSha256 ? &m_Hdr_ietf_sha256ctx : &m_Hdr_ietf_sha1ctx, sTemp.c_str(), sTemp.size() ); } else { EVP_SignUpdate( &m_allman_sha1ctx, sTemp.c_str(), sTemp.size() ); } bio = BIO_new_mem_buf(szPrivKey, -1); if( bio == NULL ) return DKIM_OUT_OF_MEMORY; pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL); BIO_free(bio); if (!pkey) { return DKIM_BAD_PRIVATE_KEY; } siglen = EVP_PKEY_size(pkey); int nSignRet; sig = (unsigned char*) OPENSSL_malloc(siglen); if( sig == NULL ) { EVP_PKEY_free(pkey); return DKIM_OUT_OF_MEMORY; } if( bUseIetfBodyHash ) { nSignRet = EVP_SignFinal( bUseSha256 ? &m_Hdr_ietf_sha256ctx : &m_Hdr_ietf_sha1ctx, sig, &siglen, pkey); } else { nSignRet = EVP_SignFinal( &m_allman_sha1ctx, sig, &siglen, pkey); } EVP_PKEY_free(pkey); if( !nSignRet ) { OPENSSL_free(sig); return DKIM_BAD_PRIVATE_KEY; // key too small } bio = BIO_new(BIO_s_mem()); if (!bio) { return DKIM_OUT_OF_MEMORY; } b64 = BIO_new(BIO_f_base64()); if (!b64) { BIO_free(bio); return DKIM_OUT_OF_MEMORY; } BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); BIO_push(b64, bio); if (BIO_write(b64, sig, siglen) < siglen) { OPENSSL_free(sig); BIO_free_all(b64); return DKIM_OUT_OF_MEMORY; } BIO_flush(b64); OPENSSL_free(sig); len = siglen * 2; buf = new char[len]; if( buf == NULL ) { BIO_free_all(b64); return DKIM_OUT_OF_MEMORY; } size = BIO_read(bio, buf, len); BIO_free_all(b64); // this should never happen if (size >= len) { delete[] buf; return DKIM_OUT_OF_MEMORY; } buf[size] = '\0'; AddFoldedValueToSig( buf, 0 ); delete[] buf; return DKIM_SUCCESS; } int CDKIMSign::AssembleReturnedSig( char* szPrivKey ) { int nRet; if( m_bReturnedSigAssembled ) return DKIM_SUCCESS; ProcessFinal(); if( ParseFromAddress() == false ) { //return DKIM_NO_SENDER; } Hash( "\r\n", 2, true, true ); // only for Allman sig string allmansha1sig, ietfsha256Sig, ietfsha1Sig; if( m_nIncludeBodyHash < DKIM_BODYHASH_IETF_1 ) { nRet = ConstructSignature( szPrivKey, false, false ); if( nRet == DKIM_SUCCESS ) { allmansha1sig.assign( m_sSig ); } else { return nRet; } } else if( m_nIncludeBodyHash & DKIM_BODYHASH_IETF_1 ) { if( m_nIncludeBodyHash & DKIM_BODYHASH_ALLMAN_1 ) { nRet = ConstructSignature( szPrivKey, false, false ); if( nRet == DKIM_SUCCESS ) { allmansha1sig.assign( m_sSig ); } else { return nRet; } } if( m_nHash & DKIM_HASH_SHA256 ) { nRet = ConstructSignature( szPrivKey, true, true ); if( nRet == DKIM_SUCCESS ) { ietfsha256Sig.assign( m_sSig ); } else { return nRet; } } if( m_nHash != DKIM_HASH_SHA256 ) { nRet = ConstructSignature( szPrivKey, true, false ); if( nRet == DKIM_SUCCESS ) { ietfsha1Sig.assign( m_sSig ); } else { return nRet; } } } // fclose( fpdebug ); // fpdebug = NULL; m_sReturnedSig.assign( allmansha1sig ); if( !ietfsha1Sig.empty() ) { if( !m_sReturnedSig.empty() ) { m_sReturnedSig.append( "\r\n" ); } m_sReturnedSig.append( ietfsha1Sig ); } if( !ietfsha256Sig.empty() ) { if( !m_sReturnedSig.empty() ) { m_sReturnedSig.append( "\r\n" ); } m_sReturnedSig.append( ietfsha256Sig ); } m_bReturnedSigAssembled = true; return DKIM_SUCCESS; } libdkim-1.0.21.orig/src/dkim.cpp0000666000175000017500000001404011063377406015744 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifdef WIN32 #include #pragma warning( disable: 4786 ) #else #endif #include "dkim.h" #include "dkimsign.h" #include "dkimverify.h" #include "resource.h" #include #define DKIMID ('D' | 'K'<<8 | 'I'<<16 | 'M'<<24) #ifdef WIN32 ////////////////////////////////////////////////////////////////////// // DllMain ////////////////////////////////////////////////////////////////////// BOOL APIENTRY DllMain( HANDLE hModule, DWORD dwReason, LPVOID lpReserved ) { switch (dwReason) { case DLL_PROCESS_ATTACH: //g_Instance = (HINSTANCE)hModule; break; case DLL_PROCESS_DETACH: break; } return TRUE; } #endif // #ifdef WIN32 static void InitContext( DKIMContext* pContext, bool bSign, void* pObject ) { pContext->reserved1 = DKIMID; pContext->reserved2 = bSign ? 1 : 0; pContext->reserved3 = pObject; } static void* ValidateContext( DKIMContext* pContext, bool bSign ) { if( pContext->reserved1 != DKIMID ) return NULL; if( pContext->reserved2 != (unsigned int)(bSign ? 1 : 0) ) return NULL; return pContext->reserved3; } int DKIM_CALL DKIMSignInit( DKIMContext* pSignContext, DKIMSignOptions* pOptions ) { int nRet = DKIM_OUT_OF_MEMORY; CDKIMSign* pSign = new CDKIMSign; if( pSign ) { nRet = pSign->Init( pOptions ); if( nRet != DKIM_SUCCESS ) delete pSign; } if( nRet == DKIM_SUCCESS ) { InitContext( pSignContext, true, pSign ); } return nRet; } int DKIM_CALL DKIMSignProcess( DKIMContext* pSignContext, char* szBuffer, int nBufLength ) { CDKIMSign* pSign = (CDKIMSign*)ValidateContext( pSignContext, true ); if( pSign ) { return pSign->Process( szBuffer, nBufLength, false ); } return DKIM_INVALID_CONTEXT; } int DKIM_CALL DKIMSignGetSig( DKIMContext* pSignContext, char* szPrivKey, char* szSignature, int nSigLength ) { CDKIMSign* pSign = (CDKIMSign*)ValidateContext( pSignContext, true ); if( pSign ) { return pSign->GetSig( szPrivKey, szSignature, nSigLength ); } return DKIM_INVALID_CONTEXT; } int DKIM_CALL DKIMSignGetSig2( DKIMContext* pSignContext, char* szPrivKey, char** pszSignature ) { CDKIMSign* pSign = (CDKIMSign*)ValidateContext( pSignContext, true ); if( pSign ) { return pSign->GetSig2( szPrivKey, pszSignature ); } return DKIM_INVALID_CONTEXT; } void DKIM_CALL DKIMSignFree( DKIMContext* pSignContext ) { CDKIMSign* pSign = (CDKIMSign*)ValidateContext( pSignContext, true ); if( pSign ) { delete pSign; pSignContext->reserved3 = NULL; } } int DKIM_CALL DKIMVerifyInit( DKIMContext* pVerifyContext, DKIMVerifyOptions* pOptions ) { int nRet = DKIM_OUT_OF_MEMORY; CDKIMVerify* pVerify = new CDKIMVerify; if( pVerify ) { nRet = pVerify->Init( pOptions ); if( nRet != DKIM_SUCCESS ) delete pVerify; } if( nRet == DKIM_SUCCESS ) { InitContext( pVerifyContext, false, pVerify ); } return nRet; } int DKIM_CALL DKIMVerifyProcess( DKIMContext* pVerifyContext, char* szBuffer, int nBufLength ) { CDKIMVerify* pVerify = (CDKIMVerify*)ValidateContext( pVerifyContext, false ); if( pVerify ) { return pVerify->Process( szBuffer, nBufLength, false ); } return DKIM_INVALID_CONTEXT; } int DKIM_CALL DKIMVerifyResults( DKIMContext* pVerifyContext ) { CDKIMVerify* pVerify = (CDKIMVerify*)ValidateContext( pVerifyContext, false ); if( pVerify ) { return pVerify->GetResults(); } return DKIM_INVALID_CONTEXT; } int DKIM_CALL DKIMVerifyGetDetails( DKIMContext* pVerifyContext, int* nSigCount, DKIMVerifyDetails** pDetails, char* szPractices ) { szPractices[0] = '\0'; CDKIMVerify* pVerify = (CDKIMVerify*)ValidateContext( pVerifyContext, false ); if( pVerify ) { strcpy(szPractices, pVerify->GetPractices()); return pVerify->GetDetails(nSigCount, pDetails); } return DKIM_INVALID_CONTEXT; } void DKIM_CALL DKIMVerifyFree( DKIMContext* pVerifyContext ) { CDKIMVerify* pVerify = (CDKIMVerify*)ValidateContext( pVerifyContext, false ); if( pVerify ) { delete pVerify; pVerifyContext->reserved3 = NULL; } } char* DKIM_CALL DKIMVersion() { return VERSION_STRING; } static char* DKIMErrorStrings[-1-DKIM_MAX_ERROR] = { "DKIM_FAIL", "DKIM_BAD_SYNTAX", "DKIM_SIGNATURE_BAD", "DKIM_SIGNATURE_BAD_BUT_TESTING", "DKIM_SIGNATURE_EXPIRED", "DKIM_SELECTOR_INVALID", "DKIM_SELECTOR_GRANULARITY_MISMATCH", "DKIM_SELECTOR_KEY_REVOKED", "DKIM_SELECTOR_DOMAIN_NAME_TOO_LONG", "DKIM_SELECTOR_DNS_TEMP_FAILURE", "DKIM_SELECTOR_DNS_PERM_FAILURE", "DKIM_SELECTOR_PUBLIC_KEY_INVALID", "DKIM_NO_SIGNATURES", "DKIM_NO_VALID_SIGNATURES", "DKIM_BODY_HASH_MISMATCH", "DKIM_SELECTOR_ALGORITHM_MISMATCH", "DKIM_STAT_INCOMPAT", "DKIM_UNSIGNED_FROM", "DKIM_OUT_OF_MEMORY", "DKIM_INVALID_CONTEXT", "DKIM_NO_SENDER", "DKIM_BAD_PRIVATE_KEY", "DKIM_BUFFER_TOO_SMALL", }; char* DKIM_CALL DKIMGetErrorString( int ErrorCode ) { if (ErrorCode >= 0 || ErrorCode <= DKIM_MAX_ERROR) return "Unknown"; else return DKIMErrorStrings[-1-ErrorCode]; } libdkim-1.0.21.orig/src/dkim.h0000666000175000017500000002012411063377410015404 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifdef WIN32 #define DKIM_CALL WINAPI #else #define DKIM_CALL #define MAKELONG(a,b) ((long)(((unsigned)(a) & 0xffff) | (((unsigned)(b) & 0xffff) << 16))) #endif #ifdef __cplusplus extern "C" { #endif // DKIM Body hash versions #define DKIM_BODYHASH_ALLMAN_1 1 #define DKIM_BODYHASH_IETF_1 2 #define DKIM_BODYHASH_BOTH DKIM_BODYHASH_ALLMAN_1 | DKIM_BODYHASH_IETF_1 // DKIM hash algorithms #define DKIM_HASH_SHA1 1 #define DKIM_HASH_SHA256 2 #define DKIM_HASH_SHA1_AND_256 DKIM_HASH_SHA1 | DKIM_HASH_SHA256 // DKIM canonicalization methods #define DKIM_CANON_SIMPLE 1 #define DKIM_CANON_NOWSP 2 #define DKIM_CANON_RELAXED 3 #define DKIM_SIGN_SIMPLE MAKELONG(DKIM_CANON_SIMPLE,DKIM_CANON_SIMPLE) #define DKIM_SIGN_SIMPLE_RELAXED MAKELONG(DKIM_CANON_RELAXED,DKIM_CANON_SIMPLE) #define DKIM_SIGN_RELAXED MAKELONG(DKIM_CANON_RELAXED,DKIM_CANON_RELAXED) #define DKIM_SIGN_RELAXED_SIMPLE MAKELONG(DKIM_CANON_SIMPLE,DKIM_CANON_RELAXED) // DKIM Error codes #define DKIM_SUCCESS 0 // operation successful #define DKIM_FAIL -1 // verify error: message is suspicious #define DKIM_BAD_SYNTAX -2 // signature error: DKIM-Signature could not parse or has bad tags/values #define DKIM_SIGNATURE_BAD -3 // signature error: RSA verify failed #define DKIM_SIGNATURE_BAD_BUT_TESTING -4 // signature error: RSA verify failed but testing #define DKIM_SIGNATURE_EXPIRED -5 // signature error: x= is old #define DKIM_SELECTOR_INVALID -6 // signature error: selector doesn't parse or contains invalid values #define DKIM_SELECTOR_GRANULARITY_MISMATCH -7 // signature error: selector g= doesn't match i= #define DKIM_SELECTOR_KEY_REVOKED -8 // signature error: selector p= empty #define DKIM_SELECTOR_DOMAIN_NAME_TOO_LONG -9 // signature error: selector domain name too long to request #define DKIM_SELECTOR_DNS_TEMP_FAILURE -10 // signature error: temporary dns failure requesting selector #define DKIM_SELECTOR_DNS_PERM_FAILURE -11 // signature error: permanent dns failure requesting selector #define DKIM_SELECTOR_PUBLIC_KEY_INVALID -12 // signature error: selector p= value invalid or wrong format #define DKIM_NO_SIGNATURES -13 // process error, no sigs #define DKIM_NO_VALID_SIGNATURES -14 // process error, no valid sigs #define DKIM_BODY_HASH_MISMATCH -15 // sigature verify error: message body does not hash to bh value #define DKIM_SELECTOR_ALGORITHM_MISMATCH -16 // signature error: selector h= doesn't match signature a= #define DKIM_STAT_INCOMPAT -17 // signature error: incompatible v= #define DKIM_UNSIGNED_FROM -18 // signature error: not all message's From headers in signature #define DKIM_OUT_OF_MEMORY -20 // memory allocation failed #define DKIM_INVALID_CONTEXT -21 // DKIMContext structure invalid for this operation #define DKIM_NO_SENDER -22 // signing error: Could not find From: or Sender: header in message #define DKIM_BAD_PRIVATE_KEY -23 // signing error: Could not parse private key #define DKIM_BUFFER_TOO_SMALL -24 // signing error: Buffer passed in is not large enough #define DKIM_MAX_ERROR -25 // set this to 1 greater than the highest error code (but negative) // DKIM_SUCCESS // verify result: all signatures verified // signature result: signature verified #define DKIM_FINISHED_BODY 1 // process result: no more message body is needed #define DKIM_PARTIAL_SUCCESS 2 // verify result: at least one but not all signatures verified #define DKIM_NEUTRAL 3 // verify result: no signatures verified but message is not suspicous #define DKIM_SUCCESS_BUT_EXTRA 4 // signature result: signature verified but it did not include all of the body // This function is called once for each header in the message // return 1 to include this header in the signature and 0 to exclude. typedef int (DKIM_CALL *DKIMHEADERCALLBACK)(const char* szHeader); // This function is called to retrieve a TXT record from DNS typedef int (DKIM_CALL *DKIMDNSCALLBACK)(const char* szFQDN, char* szBuffer, int nBufLen ); #ifdef _WIN32 #include #endif typedef struct DKIMContext_t { unsigned int reserved1; unsigned int reserved2; void* reserved3; } DKIMContext; typedef struct DKIMSignOptions_t { int nCanon; // canonization int nIncludeBodyLengthTag; // 0 = don't include l= tag, 1 = include l= tag int nIncludeTimeStamp; // 0 = don't include t= tag, 1 = include t= tag int nIncludeQueryMethod; // 0 = don't include q= tag, 1 = include q= tag char szSelector[80]; // selector - required char szDomain[256]; // domain - optional - if empty, domain is computed from sender char szIdentity[256]; // for i= tag, if empty tag will not be included in sig unsigned long expireTime; // for x= tag, if 0 tag will not be included in sig DKIMHEADERCALLBACK pfnHeaderCallback; // header callback char szRequiredHeaders[256]; // colon-separated list of headers that must be signed int nHash; // use one of the DKIM_HASH_xx constants here // even if not present in the message int nIncludeCopiedHeaders; // 0 = don't include z= tag, 1 = include z= tag int nIncludeBodyHash; // use one of the DKIM_BODYHASH_xx constants here } DKIMSignOptions; typedef struct DKIMVerifyOptions_t { DKIMDNSCALLBACK pfnSelectorCallback; // selector record callback DKIMDNSCALLBACK pfnPracticesCallback; // ADSP record callback int nHonorBodyLengthTag; // 0 = ignore l= tag, 1 = use l= tag to limit the amount of body verified int nCheckPractices; // 0 = use default (unknown) practices, 1 = request and use author domain signing practices int nSubjectRequired; // 0 = subject is required to be signed, 1 = not required int nSaveCanonicalizedData; // 0 = canonicalized data is not saved, 1 = canonicalized data is saved int nAllowUnsignedFromHeaders; // 0 = From headers not included in the signature are not allowed, 1 = allowed } DKIMVerifyOptions; typedef struct DKIMVerifyDetails_t { char *szSignature; char *szSignatureDomain; char *szIdentityDomain; char *szCanonicalizedData; int nResult; } DKIMVerifyDetails; #ifdef _WIN32 #include #endif int DKIM_CALL DKIMSignInit( DKIMContext* pSignContext, DKIMSignOptions* pOptions ); int DKIM_CALL DKIMSignProcess( DKIMContext* pSignContext, char* szBuffer, int nBufLength ); int DKIM_CALL DKIMSignGetSig( DKIMContext* pSignContext, char* szPrivKey, char* szSignature, int nSigLength ); int DKIM_CALL DKIMSignGetSig2( DKIMContext* pSignContext, char* szPrivKey, char** pszSignature ); void DKIM_CALL DKIMSignFree( DKIMContext* pSignContext ); int DKIM_CALL DKIMVerifyInit( DKIMContext* pVerifyContext, DKIMVerifyOptions* pOptions ); int DKIM_CALL DKIMVerifyProcess( DKIMContext* pVerifyContext, char* szBuffer, int nBufLength ); int DKIM_CALL DKIMVerifyResults( DKIMContext* pVerifyContext ); int DKIM_CALL DKIMVerifyGetDetails( DKIMContext* pVerifyContext, int* nSigCount, DKIMVerifyDetails** pDetails, char* szPractices ); void DKIM_CALL DKIMVerifyFree( DKIMContext* pVerifyContext ); char *DKIM_CALL DKIMVersion(); char *DKIM_CALL DKIMGetErrorString( int ErrorCode ); #ifdef __cplusplus } #endif libdkim-1.0.21.orig/src/Makefile.vc0000666000175000017500000000437310772175532016375 0ustar magnusmagnus# libdkim makefile for VC6 # # Note: The INCLUDE environment variable must contain the Platform SDK include # directory and the OpenSSL inc32 directory. The LIB environment variable must # contain the Platform SDK lib directory and the OpenSSL out32dll directory. # # To build: # nmake /f makefile.vc # CC = cl /nologo AR = lib /nologo LD = link /nologo OPENSSL_INC = ../OpenSSL/inc32 OPENSSL_LIB = ../OpenSSL !IFDEF DEBUG OUTDIR = Debug CFLAGS = /MTd /W3 /GX /Zi /Od /I"$(OPENSSL_INC)" /D "WIN32" /D "DEBUG" /D "_WINDOWS" /c /Fo"$(OUTDIR)/" LFLAGS = /debug LIBS = LIBCMTD.LIB $(OPENSSL_LIB)/libeay32.lib ws2_32.lib Advapi32.lib !ELSE OUTDIR = Release CFLAGS = /MT /W3 /GX /O2 /I"$(OPENSSL_INC)" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /c /Fo"$(OUTDIR)/" LFLAGS = LIBS = LIBCMT.LIB $(OPENSSL_LIB)/libeay32.lib ws2_32.lib Advapi32.lib !ENDIF LIBOBJS = $(OUTDIR)/dkim.obj $(OUTDIR)/dns.obj $(OUTDIR)/dnsresolv.obj \ $(OUTDIR)/dkimbase.obj $(OUTDIR)/dkimsign.obj $(OUTDIR)/dkimverify.obj HDRS = dkim.h dns.h dnsresolv.h dkimbase.h dkimsign.h dkimverify.h all: $(OUTDIR) $(OUTDIR)/libdkim.dll $(OUTDIR)/libdkim.lib $(OUTDIR)/libdkimtest.exe $(OUTDIR): mkdir $(OUTDIR) $(OUTDIR)/dkim.obj: dkim.cpp $(HDRS) $(CC) $(CFLAGS) dkim.cpp $(OUTDIR)/dns.obj: dns.cpp $(HDRS) $(CC) $(CFLAGS) dns.cpp $(OUTDIR)/dnsresolv.obj: dnsresolv.cpp $(HDRS) $(CC) $(CFLAGS) dnsresolv.cpp $(OUTDIR)/dkimbase.obj: dkimbase.cpp $(HDRS) $(CC) $(CFLAGS) dkimbase.cpp $(OUTDIR)/dkimsign.obj: dkimsign.cpp $(HDRS) $(CC) $(CFLAGS) dkimsign.cpp $(OUTDIR)/dkimverify.obj: dkimverify.cpp $(HDRS) $(CC) $(CFLAGS) dkimverify.cpp $(OUTDIR)/libdkim.lib: $(LIBOBJS) $(AR) /out:$(OUTDIR)/libdkim.lib $(LIBOBJS) $(OUTDIR)/libdkim.dll: $(LIBOBJS) libdkim.res $(LD) /dll /def:libdkim.def /out:$(OUTDIR)/libdkim.dll $(LFLAGS) \ /implib:$(OUTDIR)/libdkim.dll.lib $(LIBOBJS) libdkim.res $(LIBS) $(OUTDIR)/libdkimtest.exe : $(OUTDIR)/libdkim.lib $(OUTDIR)/libdkimtest.obj $(LD) /out:$(OUTDIR)/libdkimtest.exe $(LFLAGS) \ $(OUTDIR)/libdkim.lib $(OUTDIR)/libdkimtest.obj $(LIBS) $(OUTDIR)/libdkimtest.obj: libdkimtest.cpp $(HDRS) $(CC) $(CFLAGS) libdkimtest.cpp clean: rmdir /s /q $(OUTDIR) libdkim-1.0.21.orig/src/libdkim.vcproj0000666000175000017500000002265711063377410017164 0ustar magnusmagnus libdkim-1.0.21.orig/src/dkimverify.cpp0000666000175000017500000011341411063377406017176 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifdef WIN32 #include #pragma warning( disable: 4786 ) #else #define _strnicmp strncasecmp #define _stricmp strcasecmp #endif #include "dkim.h" #include "dkimverify.h" #include "dns.h" #include #include #include #include #include #define MAX_SIGNATURES 10 // maximum number of DKIM signatures to process in a message SignatureInfo::SignatureInfo(bool s) { VerifiedBodyCount = 0; UnverifiedBodyCount = 0; EVP_MD_CTX_init( &m_Hdr_ctx ); EVP_MD_CTX_init( &m_Bdy_ctx ); m_pSelector = NULL; Status = DKIM_SUCCESS; m_nHash = 0; EmptyLineCount = 0; m_SaveCanonicalizedData = s; } SignatureInfo::~SignatureInfo() { EVP_MD_CTX_cleanup( &m_Hdr_ctx ); EVP_MD_CTX_cleanup( &m_Bdy_ctx ); } inline bool isswsp(char ch) { return( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' ); } //////////////////////////////////////////////////////////////////////////////// // // Parse a DKIM tag-list. Returns true for success // //////////////////////////////////////////////////////////////////////////////// bool ParseTagValueList(char *tagvaluelist, const char *wanted[], char *values[]) { char *s = tagvaluelist; for (;;) { // skip whitespace while (isswsp(*s)) s++; // if at the end of the string, return success. note: this allows a list with no entries if (*s == '\0') return true; // get tag name if (!isalpha(*s)) return false; char *tag = s; do { s++; } while (isalnum(*s) || *s == '-'); char *endtag = s; // skip whitespace before equals while (isswsp(*s)) s++; // next character must be equals if (*s != '=') return false; s++; // null-terminate tag name *endtag = '\0'; // skip whitespace after equals while (isswsp(*s)) s++; // get tag value char *value = s; while (*s != ';' && ((*s == '\t' || *s == '\r' || *s == '\n') || (*s >= ' ' && *s <= '~'))) s++; char *e = s; // make sure the next character is the null terminator (which means we're done) or a semicolon (not done) bool done = false; if (*s == '\0') done = true; else { if (*s != ';') return false; s++; } // skip backwards past any trailing whitespace while (e > value && isswsp(e[-1])) e--; // null-terminate tag value *e = '\0'; // check to see if we want this tag for (unsigned i=0; wanted[i] != NULL; i++) { if (strcmp(wanted[i], tag) == 0) { // return failure if we already have a value for this tag (duplicates not allowed) if (values[i] != NULL) return false; values[i] = value; break; } } if (done) return true; } } //////////////////////////////////////////////////////////////////////////////// // // Convert hex char to value (0-15) // //////////////////////////////////////////////////////////////////////////////// char tohex(char ch) { if (ch >= '0' && ch <= '9') return (ch-'0'); else if (ch >= 'A' && ch <= 'F') return (ch-'A'+10); else if (ch >= 'a' && ch <= 'f') return (ch-'a'+10); else { assert(0); return 0; } } //////////////////////////////////////////////////////////////////////////////// // // Decode quoted printable string in-place // //////////////////////////////////////////////////////////////////////////////// void DecodeQuotedPrintable(char *ptr) { char *s = ptr; while (*s != '\0' && *s != '=') s++; if (*s == '\0') return; char *d = s; do { if (*s == '=' && isxdigit(s[1]) && isxdigit(s[2])) { *d++ = (tohex(s[1]) << 4) | tohex(s[2]); s += 3; } else { *d++ = *s++; } } while (*s != '\0'); *d = '\0'; } //////////////////////////////////////////////////////////////////////////////// // // Decode base64 string in-place, returns number of bytes output // //////////////////////////////////////////////////////////////////////////////// unsigned DecodeBase64(char *ptr) { static const unsigned char base64_table[256] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; unsigned char *s = (unsigned char *)ptr; unsigned char *d = (unsigned char *)ptr; unsigned b64accum=0; unsigned char b64shift=0; while (*s != '\0') { unsigned char value = base64_table[*s++]; if ( (signed char)value >= 0 ) { b64accum = (b64accum << 6) | value; b64shift += 6; if (b64shift >= 8) { b64shift -= 8; *d++ = (b64accum >> b64shift); } } } return (char*)d-ptr; } //////////////////////////////////////////////////////////////////////////////// // // Match a string with a pattern (used for g= value) // Supports a single, optional "*" wildcard character. // //////////////////////////////////////////////////////////////////////////////// bool WildcardMatch( const char *p, const char *s ) { // special case: An empty "g=" value never matches any addresses if (*p == '\0') return false; const char *wildcard = strchr(p, '*'); if (wildcard == NULL) { return strcmp(s, p) == 0; } else { unsigned beforewildcardlen = wildcard-p; unsigned afterwildcardlen = strlen(wildcard+1); unsigned slen = strlen(s); return (slen >= beforewildcardlen+afterwildcardlen) && (strncmp(s, p, beforewildcardlen) == 0) && strcmp(s+slen-afterwildcardlen, wildcard+1) == 0; } } //////////////////////////////////////////////////////////////////////////////// // // Parse addresses from a string. Returns true if at least one address found // //////////////////////////////////////////////////////////////////////////////// bool ParseAddresses( string str, vector &Addresses ) { char *s = (char*) str.c_str(); while (*s != '\0') { char *start = s; char *from = s; char *to = s; char *lt = NULL; // pointer to less than character (<) which starts the address if found while (*from != '\0') { if (*from == '(') { // skip over comment from++; for (int depth=1; depth != 0; from++) { if (*from == '\0') break; else if (*from == '(') depth++; else if (*from == ')') depth--; else if (*from == '\\' && from[1] != '\0') from++; } } else if (*from == ')') { // ignore closing parenthesis outside of comment from++; } else if (*from == ',' || *from == ';') { // comma/selicolon ends the address from++; break; } else if (*from == ' ' || *from == '\t' || *from == '\r' || *from == '\n') { // ignore whitespace from++; } else if (*from == '"') { // copy the contents of a quoted string from++; while (*from != '\0') { if (*from == '"') { from++; break; } else if (*from == '\\' && from[1] != '\0') *to++ = *from++; *to++ = *from++; } } else if (*from == '\\' && from[1] != '\0') { // copy quoted-pair *to++ = *from++; *to++ = *from++; } else { // copy any other char *to = *from++; // save pointer to '<' for later... if (*to == '<') lt = to; to++; } } *to = '\0'; // if there's < > get what's inside if (lt != NULL) { start = lt+1; char *gt = strchr(start, '>'); if (gt != NULL) *gt = '\0'; } else { // look for and strip group name char *colon = strchr(start, ':'); if (colon != NULL) { char *at = strchr(start, '@'); if (at == NULL || colon < at) start = colon+1; } } if (*start != '\0' && strchr(start, '@') != NULL) { Addresses.push_back(start); } s = from; } return !Addresses.empty(); } //////////////////////////////////////////////////////////////////////////////// CDKIMVerify::CDKIMVerify() { m_pfnSelectorCallback = NULL; m_pfnPracticesCallback = NULL; m_HonorBodyLengthTag = false; m_CheckPractices = false; m_SubjectIsRequired = true; m_SaveCanonicalizedData = false; m_AllowUnsignedFromHeaders = false; } CDKIMVerify::~CDKIMVerify() { } //////////////////////////////////////////////////////////////////////////////// // // Init - save the options // //////////////////////////////////////////////////////////////////////////////// int CDKIMVerify::Init( DKIMVerifyOptions* pOptions ) { int nRet = CDKIMBase::Init(); m_pfnSelectorCallback = pOptions->pfnSelectorCallback; m_pfnPracticesCallback = pOptions->pfnPracticesCallback; #ifdef WIN32 if (m_pfnSelectorCallback) assert(!IsBadCodePtr( (FARPROC) m_pfnSelectorCallback )); if (m_pfnPracticesCallback) assert(!IsBadCodePtr( (FARPROC) m_pfnPracticesCallback )); #endif m_HonorBodyLengthTag = pOptions->nHonorBodyLengthTag != 0; m_CheckPractices = pOptions->nCheckPractices != 0; m_SubjectIsRequired = pOptions->nSubjectRequired == 0; m_SaveCanonicalizedData = pOptions->nSaveCanonicalizedData != 0; m_AllowUnsignedFromHeaders = pOptions->nAllowUnsignedFromHeaders != 0; return nRet; } //////////////////////////////////////////////////////////////////////////////// // // GetResults - return the pass/fail/neutral verification result // //////////////////////////////////////////////////////////////////////////////// int CDKIMVerify::GetResults(void) { ProcessFinal(); int SuccessCount=0; int TestingFailures=0; int RealFailures=0; list SuccessfulDomains; // can contain duplicates for (list::iterator i = Signatures.begin(); i != Signatures.end(); ++i) { if (i->Status == DKIM_SUCCESS) { if (!i->BodyHashData.empty()) { // check the body hash unsigned char md[EVP_MAX_MD_SIZE]; unsigned len = 0; int res = EVP_DigestFinal( &i->m_Bdy_ctx, md, &len); if (!res || len != i->BodyHashData.length() || memcmp(i->BodyHashData.data(), md, len) != 0) { // body hash mismatch // if the selector is in testing mode... if (i->m_pSelector->Testing) { i->Status = DKIM_SIGNATURE_BAD_BUT_TESTING; // todo: make a new error code for this? TestingFailures++; } else { i->Status = DKIM_BODY_HASH_MISMATCH; RealFailures++; } continue; } } else { // hash CRLF separating the body from the signature i->Hash( "\r\n", 2 ); } // check the header hash string sSignedSig = i->Header; string sSigValue = sSignedSig.substr( sSignedSig.find(':')+1 ); static const char *tags[] = {"b",NULL}; char *values[sizeof(tags)/sizeof(tags[0])] = {NULL}; char *pSigValue = (char *) sSigValue.c_str(); if (ParseTagValueList(pSigValue, tags, values) && values[0] != NULL) { sSignedSig.erase( 15+values[0]-pSigValue, strlen(values[0]) ); } if ( i->HeaderCanonicalization == DKIM_CANON_RELAXED ) { sSignedSig = RelaxHeader( sSignedSig ); } else if ( i->HeaderCanonicalization == DKIM_CANON_NOWSP ) { RemoveSWSP( sSignedSig ); // convert "DKIM-Signature" to lower case sSignedSig.replace( 0, 14, "dkim-signature", 14 ); } i->Hash( sSignedSig.c_str(), sSignedSig.length() ); assert( i->m_pSelector != NULL ); int res = EVP_VerifyFinal( &i->m_Hdr_ctx, (unsigned char *) i->SignatureData.data(), i->SignatureData.length(), i->m_pSelector->PublicKey); if (res == 1) { if (i->UnverifiedBodyCount == 0) i->Status = DKIM_SUCCESS; else i->Status = DKIM_SUCCESS_BUT_EXTRA; SuccessCount++; SuccessfulDomains.push_back( i->Domain ); } else { // if the selector is in testing mode... if (i->m_pSelector->Testing) { i->Status = DKIM_SIGNATURE_BAD_BUT_TESTING; TestingFailures++; } else { i->Status = DKIM_SIGNATURE_BAD; RealFailures++; } } } else if (i->Status == DKIM_SELECTOR_GRANULARITY_MISMATCH || i->Status == DKIM_SELECTOR_ALGORITHM_MISMATCH || i->Status == DKIM_SELECTOR_KEY_REVOKED) { // treat these as failures // todo: maybe see if the selector is in testing mode? RealFailures++; } } // get the From address's domain if we might need it string sFromDomain; if (SuccessCount > 0 || m_CheckPractices) { for (list::iterator i = HeaderList.begin(); i != HeaderList.end(); ++i) { if (_strnicmp(i->c_str(), "From", 4) == 0) { // skip over whitespace between the header name and : const char *s = i->c_str()+4; while (*s == ' ' || *s == '\t') s++; if (*s == ':') { vector Addresses; if (ParseAddresses(s+1, Addresses)) { unsigned atpos = Addresses[0].find('@'); sFromDomain = Addresses[0].substr(atpos+1); break; } } } } } // if a signature from the From domain verified successfully, return success now // without checking the author domain signing practices if (SuccessCount > 0 && !sFromDomain.empty()) { for (list::iterator i = SuccessfulDomains.begin(); i != SuccessfulDomains.end(); ++i) { // see if the successful domain is the same as or a parent of the From domain if (i->length() > sFromDomain.length()) continue; if (_stricmp(i->c_str(), sFromDomain.c_str()+sFromDomain.length()-i->length()) != 0) continue; if (i->length() == sFromDomain.length() || sFromDomain.c_str()[sFromDomain.length()-i->length()-1] == '.') { return SuccessCount == Signatures.size() ? DKIM_SUCCESS : DKIM_PARTIAL_SUCCESS; } } } // get the author domain signing practices int iPractices = DKIM_ADSP_UNKNOWN; if (m_CheckPractices && !sFromDomain.empty()) { int ADSPStatus = GetADSP(sFromDomain, iPractices); if (ADSPStatus != DKIM_SUCCESS) { // could not get practices, leave values at the defaults } } // if there was a successful signature and policy is not discardable, return success if (SuccessCount > 0 && (iPractices == DKIM_ADSP_UNKNOWN || iPractices == DKIM_ADSP_ALL)) { return SuccessCount == Signatures.size() ? DKIM_SUCCESS : DKIM_PARTIAL_SUCCESS; } // if the message should be signed, return fail if (iPractices == DKIM_ADSP_ALL || iPractices == DKIM_ADSP_DISCARDABLE) return DKIM_FAIL; // return neutral for everything else return DKIM_NEUTRAL; } //////////////////////////////////////////////////////////////////////////////// // // Hash - update the hash // //////////////////////////////////////////////////////////////////////////////// void SignatureInfo::Hash( const char* szBuffer, unsigned nBufLength, bool IsBody ) { #if 0 /** START DEBUG CODE **/ if( nBufLength == 2 && szBuffer[0] == '\r' && szBuffer[1] == '\n' ) { printf( "[CRLF]\n" ); } else { char* szDbg = new char[nBufLength+1]; strncpy( szDbg, szBuffer, nBufLength ); szDbg[nBufLength] = '\0'; printf( "[%s]\n", szDbg ); } /** END DEBUG CODE **/ #endif if (IsBody && BodyLength != -1) { VerifiedBodyCount += nBufLength; if (VerifiedBodyCount > BodyLength) { nBufLength = BodyLength - (VerifiedBodyCount - nBufLength); UnverifiedBodyCount += VerifiedBodyCount - BodyLength; VerifiedBodyCount = BodyLength; if (nBufLength == 0) return; } } if (IsBody && !BodyHashData.empty()) { EVP_DigestUpdate( &m_Bdy_ctx, szBuffer, nBufLength ); } else { EVP_VerifyUpdate( &m_Hdr_ctx, szBuffer, nBufLength ); } if (m_SaveCanonicalizedData) { CanonicalizedData.append( szBuffer, nBufLength ); } } //////////////////////////////////////////////////////////////////////////////// // // ProcessHeaders - Look for DKIM-Signatures and start processing them // //////////////////////////////////////////////////////////////////////////////// int CDKIMVerify::ProcessHeaders(void) { // look for DKIM-Signature header(s) for( list::iterator i = HeaderList.begin(); i != HeaderList.end(); ++i ) { if( _strnicmp(i->c_str(), "DKIM-Signature", 14 ) == 0 ) { // skip over whitespace between the header name and : const char *s = i->c_str()+14; while (*s == ' ' || *s == '\t') s++; if (*s == ':') { // found SignatureInfo sig(m_SaveCanonicalizedData); sig.Status = ParseDKIMSignature( *i, sig ); Signatures.push_back( sig ); if (Signatures.size() >= MAX_SIGNATURES) break; } } } if ( Signatures.empty() ) return DKIM_NO_SIGNATURES; bool ValidSigFound = false; for ( list::iterator s = Signatures.begin(); s != Signatures.end(); ++s ) { SignatureInfo &sig = *s; if ( sig.Status != DKIM_SUCCESS) continue; SelectorInfo &sel = GetSelector(sig.Selector, sig.Domain); sig.m_pSelector = &sel; if (sel.Status != DKIM_SUCCESS) { sig.Status = sel.Status; } else { // check the granularity if (!WildcardMatch(sel.Granularity.c_str(), sig.IdentityLocalPart.c_str())) sig.Status = DKIM_SELECTOR_GRANULARITY_MISMATCH; // this error causes the signature to fail // check the hash algorithm if ( (sig.m_nHash == DKIM_HASH_SHA1 && !sel.AllowSHA1) || (sig.m_nHash == DKIM_HASH_SHA256 && !sel.AllowSHA256) ) sig.Status = DKIM_SELECTOR_ALGORITHM_MISMATCH; // causes signature to fail // check for same domain if (sel.SameDomain && _stricmp(sig.Domain.c_str(), sig.IdentityDomain.c_str()) != 0) sig.Status = DKIM_BAD_SYNTAX; } if (sig.Status != DKIM_SUCCESS) continue; // initialize the hashes if (sig.m_nHash == DKIM_HASH_SHA256) { EVP_VerifyInit( &sig.m_Hdr_ctx, EVP_sha256() ); EVP_DigestInit( &sig.m_Bdy_ctx, EVP_sha256() ); } else { EVP_VerifyInit( &sig.m_Hdr_ctx, EVP_sha1() ); EVP_DigestInit( &sig.m_Bdy_ctx, EVP_sha1() ); } // compute the hash of the header vector::reverse_iterator> used; for (vector::iterator x = sig.SignedHeaders.begin(); x != sig.SignedHeaders.end(); ++x) { list::reverse_iterator i; for( i = HeaderList.rbegin(); i != HeaderList.rend(); ++i ) { if (_strnicmp(i->c_str(), x->c_str(), x->length()) == 0) { // skip over whitespace between the header name and : const char *s = i->c_str()+x->length(); while (*s == ' ' || *s == '\t') s++; if (*s == ':' && find(used.begin(), used.end(), i) == used.end()) break; } } if (i != HeaderList.rend()) { used.push_back(i); // hash this header if (sig.HeaderCanonicalization == DKIM_CANON_SIMPLE) { sig.Hash( i->c_str(), i->length() ); } else if (sig.HeaderCanonicalization == DKIM_CANON_RELAXED) { string sTemp = RelaxHeader( *i ); sig.Hash( sTemp.c_str(), sTemp.length() ); } else if (sig.HeaderCanonicalization == DKIM_CANON_NOWSP) { string sTemp = *i; RemoveSWSP( sTemp ); // convert characters before ':' to lower case for( char* s = (char*)sTemp.c_str(); *s != '\0' && *s != ':'; s++ ) { if( *s >= 'A' && *s <= 'Z' ) *s += 'a'-'A'; } sig.Hash( sTemp.c_str(), sTemp.length() ); } sig.Hash( "\r\n", 2 ); } } if (sig.BodyHashData.empty()) { // hash CRLF separating headers from body sig.Hash( "\r\n", 2 ); } if (!m_AllowUnsignedFromHeaders) { // make sure the message has no unsigned From headers list::reverse_iterator i; for( i = HeaderList.rbegin(); i != HeaderList.rend(); ++i ) { if( _strnicmp(i->c_str(), "From", 4 ) == 0 ) { // skip over whitespace between the header name and : const char *s = i->c_str()+4; while (*s == ' ' || *s == '\t') s++; if (*s == ':') { if (find(used.begin(), used.end(), i) == used.end()) { // this From header was not signed break; } } } } if (i != HeaderList.rend()) { // treat signature as invalid sig.Status = DKIM_UNSIGNED_FROM; continue; } } ValidSigFound = true; } if ( !ValidSigFound ) return DKIM_NO_VALID_SIGNATURES; return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // Strictly parse an unsigned integer. Don't allow spaces, negative sign, // 0x prefix, etc. Values greater than 2^32-1 are capped at 2^32-1 // //////////////////////////////////////////////////////////////////////////////// bool ParseUnsigned(const char *s, unsigned *result) { unsigned temp=0, last=0; bool overflowed = false; do { if (*s < '0' || *s > '9') return false; // returns false for an initial '\0' temp = temp * 10 + (*s - '0'); if (temp < last) overflowed = true; last = temp; s++; } while (*s != '\0'); *result = overflowed ? -1 : temp; return true; } //////////////////////////////////////////////////////////////////////////////// // // ParseDKIMSignature - Parse a DKIM-Signature header field // //////////////////////////////////////////////////////////////////////////////// int CDKIMVerify::ParseDKIMSignature( const string& sHeader, SignatureInfo &sig ) { // save header for later sig.Header = sHeader; string sValue = sHeader.substr( sHeader.find(':')+1 ); static const char *tags[] = {"v","a","b","d","h","s","c","i","l","q","t","x","bh",NULL}; char *values[sizeof(tags)/sizeof(tags[0])] = {NULL}; if (!ParseTagValueList( (char*) sValue.c_str(), tags, values)) return DKIM_BAD_SYNTAX; // check signature version if (values[0] != NULL) { if (strcmp(values[0], "1") == 0 || strcmp(values[0], "0.5") == 0 || strcmp(values[0], "0.4") == 0 || strcmp(values[0], "0.3") == 0 || strcmp(values[0], "0.2") == 0) { sig.Version = DKIM_SIG_VERSION_02_PLUS; } else { // unknown version return DKIM_STAT_INCOMPAT; } } else { // Note: DKIM Interop 1 pointed out that v= is now required, but we do // not enforce that in order to verify signatures made by older drafts. // prior to 0.2, there MUST NOT have been a v= // (optionally) support these signatures, for backwards compatibility if (true) { sig.Version = DKIM_SIG_VERSION_PRE_02; } else { return DKIM_BAD_SYNTAX; } } // signature MUST have a=, b=, d=, h=, s= if (values[1] == NULL || values[2] == NULL || values[3] == NULL || values[4] == NULL || values[5] == NULL) return DKIM_BAD_SYNTAX; // algorithm can be "rsa-sha1" or "rsa-sha256" if (strcmp(values[1], "rsa-sha1") == 0) { sig.m_nHash = DKIM_HASH_SHA1; } else if (strcmp(values[1], "rsa-sha256") == 0) { sig.m_nHash = DKIM_HASH_SHA256; } else { return DKIM_BAD_SYNTAX; // todo: maybe create a new error code for unknown algorithm } // make sure the signature data is not empty unsigned SigDataLen = DecodeBase64(values[2]); if (SigDataLen == 0) return DKIM_BAD_SYNTAX; sig.SignatureData.assign(values[2], SigDataLen); // check for body hash if (values[12] == NULL) { // use the old single hash way for backwards compatibility if (sig.Version != DKIM_SIG_VERSION_PRE_02) return DKIM_BAD_SYNTAX; } else { unsigned BodyHashLen = DecodeBase64(values[12]); if (BodyHashLen == 0) return DKIM_BAD_SYNTAX; sig.BodyHashData.assign(values[12], BodyHashLen); } // domain must not be empty if (*values[3] == '\0') return DKIM_BAD_SYNTAX; sig.Domain = values[3]; // signed headers must not be empty (more verification is done later) if (*values[4] == '\0') return DKIM_BAD_SYNTAX; // selector must not be empty if (*values[5] == '\0') return DKIM_BAD_SYNTAX; sig.Selector = values[5]; // canonicalization if (values[6] == NULL) { sig.HeaderCanonicalization = sig.BodyCanonicalization = DKIM_CANON_SIMPLE; } else if (sig.Version == DKIM_SIG_VERSION_PRE_02 && strcmp(values[6], "nowsp") == 0) { // for backwards compatibility sig.HeaderCanonicalization = sig.BodyCanonicalization = DKIM_CANON_NOWSP; } else { char *slash = strchr(values[6], '/'); if (slash != NULL) *slash = '\0'; if (strcmp(values[6], "simple") == 0) sig.HeaderCanonicalization = DKIM_CANON_SIMPLE; else if (strcmp(values[6], "relaxed") == 0) sig.HeaderCanonicalization = DKIM_CANON_RELAXED; else return DKIM_BAD_SYNTAX; if (slash == NULL || strcmp(slash+1, "simple") == 0) sig.BodyCanonicalization = DKIM_CANON_SIMPLE; else if (strcmp(slash+1, "relaxed") == 0) sig.BodyCanonicalization = DKIM_CANON_RELAXED; else return DKIM_BAD_SYNTAX; } // identity if (values[7] == NULL) { sig.IdentityLocalPart.erase(); sig.IdentityDomain = sig.Domain; } else { // quoted-printable decode the value DecodeQuotedPrintable(values[7]); // must have a '@' separating the local part from the domain char *at = strchr(values[7], '@'); if (at == NULL) return DKIM_BAD_SYNTAX; *at = '\0'; char *ilocalpart = values[7]; char *idomain = at+1; // i= domain must be the same as or a subdomain of the d= domain int idomainlen = strlen(idomain); int ddomainlen = strlen(values[3]); // todo: maybe create a new error code for invalid identity domain if (idomainlen < ddomainlen) return DKIM_BAD_SYNTAX; if (_stricmp(idomain+idomainlen-ddomainlen, values[3]) != 0) return DKIM_BAD_SYNTAX; if (idomainlen > ddomainlen && idomain[idomainlen-ddomainlen-1] != '.') return DKIM_BAD_SYNTAX; sig.IdentityLocalPart = ilocalpart; sig.IdentityDomain = idomain; } // body count if (values[8] == NULL || !m_HonorBodyLengthTag) { sig.BodyLength = -1; } else { if (!ParseUnsigned(values[8], &sig.BodyLength)) return DKIM_BAD_SYNTAX; } // query methods if (values[9] != NULL) { // make sure "dns" is in the list bool HasDNS = false; char *s = strtok(values[9], ":"); while (s != NULL) { if (strncmp(s, "dns", 3) == 0 && (s[3] == '\0' || s[3] == '/')) { HasDNS = true; break; } s = strtok(NULL, ": \t"); } if (!HasDNS) return DKIM_BAD_SYNTAX; // todo: maybe create a new error code for unknown query method } // signature time unsigned SignedTime = -1; if (values[10] != NULL) { if (!ParseUnsigned(values[10], &SignedTime)) return DKIM_BAD_SYNTAX; } // expiration time if (values[11] == NULL) { sig.ExpireTime = -1; } else { if (!ParseUnsigned(values[11], &sig.ExpireTime)) return DKIM_BAD_SYNTAX; if (sig.ExpireTime != -1) { // the value of x= MUST be greater than the value of t= if both are present if (SignedTime != -1 && sig.ExpireTime <= SignedTime) return DKIM_BAD_SYNTAX; // todo: if possible, use the received date/time instead of the current time unsigned curtime = time(NULL); if (curtime > sig.ExpireTime) return DKIM_SIGNATURE_EXPIRED; } } // parse the signed headers list bool HasFrom = false, HasSubject = false; RemoveSWSP(values[4]); // header names shouldn't have spaces in them so this should be ok... char *s = strtok(values[4], ":"); while (s != NULL) { if (_stricmp(s, "From") == 0) HasFrom = true; else if (_stricmp(s, "Subject") == 0) HasSubject = true; sig.SignedHeaders.push_back(s); s = strtok(NULL, ":"); } if (!HasFrom) return DKIM_BAD_SYNTAX; // todo: maybe create a new error code for h= missing From if (m_SubjectIsRequired && !HasSubject) return DKIM_BAD_SYNTAX; // todo: maybe create a new error code for h= missing Subject return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // ProcessBody - Process message body data // //////////////////////////////////////////////////////////////////////////////// int CDKIMVerify::ProcessBody( char* szBuffer, int nBufLength, bool bEOF ) { bool MoreBodyNeeded = false; for ( list::iterator i = Signatures.begin(); i != Signatures.end(); ++i ) { if ( i->Status == DKIM_SUCCESS ) { if ( i->BodyCanonicalization == DKIM_CANON_SIMPLE ) { if (nBufLength > 0) { while (i->EmptyLineCount > 0) { i->Hash( "\r\n", 2, true ); i->EmptyLineCount--; } i->Hash( szBuffer, nBufLength, true ); i->Hash( "\r\n", 2, true ); } else { i->EmptyLineCount++; if (bEOF) i->Hash( "\r\n", 2, true); } } else if ( i->BodyCanonicalization == DKIM_CANON_RELAXED ) { CompressSWSP( szBuffer, nBufLength ); if (nBufLength > 0) { while (i->EmptyLineCount > 0) { i->Hash( "\r\n", 2, true ); i->EmptyLineCount--; } i->Hash( szBuffer, nBufLength, true ); if ( !bEOF ) i->Hash( "\r\n", 2, true); } else i->EmptyLineCount++; } else if ( i->BodyCanonicalization == DKIM_CANON_NOWSP ) { RemoveSWSP( szBuffer, nBufLength ); i->Hash( szBuffer, nBufLength, true ); } if ( i->UnverifiedBodyCount == 0 ) MoreBodyNeeded = true; } } if ( !MoreBodyNeeded ) return DKIM_FINISHED_BODY; return DKIM_SUCCESS; } SelectorInfo::SelectorInfo(const string &sSelector, const string &sDomain) : Selector(sSelector), Domain(sDomain) { AllowSHA1 = true; AllowSHA256 = true; PublicKey = NULL; Testing = false; SameDomain = false; Status = DKIM_SUCCESS; } SelectorInfo::~SelectorInfo() { if (PublicKey != NULL) { EVP_PKEY_free(PublicKey); } } //////////////////////////////////////////////////////////////////////////////// // // Parse - Parse a DKIM selector // //////////////////////////////////////////////////////////////////////////////// int SelectorInfo::Parse( char* Buffer ) { static const char *tags[] = {"v","g","h","k","p","s","t","n",NULL}; char *values[sizeof(tags)/sizeof(tags[0])] = {NULL}; if (!ParseTagValueList(Buffer, tags, values)) return DKIM_SELECTOR_INVALID; if (values[0] != NULL) { // make sure the version is "DKIM1" if (strcmp(values[0], "DKIM1") != 0) return DKIM_SELECTOR_INVALID; // todo: maybe create a new error code for unsupported selector version // make sure v= is the first tag in the response // todo: maybe don't enforce this, it seems unnecessary for (int j=1; jtype == EVP_PKEY_RSA || pkey->type == EVP_PKEY_RSA2) { PublicKey = pkey; } else { EVP_PKEY_free(pkey); return DKIM_SELECTOR_PUBLIC_KEY_INVALID; } } return DKIM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // // GetSelector - Get a DKIM selector for a domain // //////////////////////////////////////////////////////////////////////////////// SelectorInfo &CDKIMVerify::GetSelector( const string &sSelector, const string &sDomain ) { // see if we already have this selector for ( list::iterator i = Selectors.begin(); i != Selectors.end(); ++i ) { if ( _stricmp(i->Selector.c_str(), sSelector.c_str()) == 0 && _stricmp(i->Domain.c_str(), sDomain.c_str()) == 0) { return *i; } } Selectors.push_back( SelectorInfo(sSelector, sDomain) ); SelectorInfo &sel = Selectors.back(); string sFQDN = sSelector; sFQDN += "._domainkey."; sFQDN += sDomain; char Buffer[1024]; int BufLen = 1024; int DNSResult; if ( m_pfnSelectorCallback ) DNSResult = m_pfnSelectorCallback( sFQDN.c_str(), Buffer, BufLen ); else DNSResult = DNSGetTXT( sFQDN.c_str(), Buffer, BufLen ); switch (DNSResult) { case DNSRESP_SUCCESS: sel.Status = sel.Parse( Buffer ); break; case DNSRESP_TEMP_FAIL: sel.Status = DKIM_SELECTOR_DNS_TEMP_FAILURE; break; case DNSRESP_PERM_FAIL: default: sel.Status = DKIM_SELECTOR_DNS_PERM_FAILURE; break; case DNSRESP_DOMAIN_NAME_TOO_LONG: sel.Status = DKIM_SELECTOR_DOMAIN_NAME_TOO_LONG; break; } return sel; } //////////////////////////////////////////////////////////////////////////////// // // GetADSP - Get DKIM Author Domain Signing Practices for a domain // //////////////////////////////////////////////////////////////////////////////// int CDKIMVerify::GetADSP( const string &sDomain, int &iADSP ) { string sFQDN = "_adsp._domainkey."; sFQDN += sDomain; char Buffer[1024]; int BufLen = 1024; int DNSResult; if ( m_pfnPracticesCallback ) DNSResult = m_pfnPracticesCallback( sFQDN.c_str(), Buffer, BufLen ); else { DNSResult = DNSGetTXT( sFQDN.c_str(), Buffer, BufLen ); if (DNSResult != DNSRESP_SUCCESS) { int DomainDNSResult = DNSGetTXT( sDomain.c_str(), Buffer, BufLen ); if (DomainDNSResult == DNSRESP_NXDOMAIN) { return DKIM_POLICY_DNS_PERM_FAILURE; // TODO: new error indicating domain is out of scope? } } } switch (DNSResult) { case DNSRESP_SUCCESS: { Practices = Buffer; static const char *tags[] = {"dkim",NULL}; char *values[sizeof(tags)/sizeof(tags[0])] = {NULL}; if (!ParseTagValueList(Buffer, tags, values)) return DKIM_POLICY_INVALID; // practices iADSP = DKIM_ADSP_UNKNOWN; if (values[0] != NULL) { if (strcmp(values[0], "all") == 0) iADSP = DKIM_ADSP_ALL; else if (strcmp(values[0], "discardable") == 0) iADSP = DKIM_ADSP_DISCARDABLE; } } return DKIM_SUCCESS; case DNSRESP_TEMP_FAIL: return DKIM_POLICY_DNS_TEMP_FAILURE; case DNSRESP_PERM_FAIL: default: return DKIM_POLICY_DNS_PERM_FAILURE; case DNSRESP_DOMAIN_NAME_TOO_LONG: return DKIM_POLICY_DOMAIN_NAME_TOO_LONG; } } //////////////////////////////////////////////////////////////////////////////// // // GetDetails - Get DKIM verification details (per signature) // //////////////////////////////////////////////////////////////////////////////// int CDKIMVerify::GetDetails( int* nSigCount, DKIMVerifyDetails** pDetails ) { Details.clear(); for (list::iterator i = Signatures.begin(); i != Signatures.end(); ++i) { DKIMVerifyDetails d; d.szSignature = (char*)i->Header.c_str(); d.szSignatureDomain = (char*)i->Domain.c_str(); d.szIdentityDomain = (char*)i->IdentityDomain.c_str(); d.szCanonicalizedData = (char*)i->CanonicalizedData.c_str(); d.nResult = i->Status; Details.push_back(d); } *nSigCount = Details.size(); *pDetails = (*nSigCount != 0) ? &Details[0] : NULL; return DKIM_SUCCESS; } libdkim-1.0.21.orig/src/dkimsign.h0000666000175000017500000000664111012004356016263 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifndef DKIMSIGN_H #define DKIMSIGN_H #include "dkimbase.h" class CDKIMSign : public CDKIMBase { public: CDKIMSign(); ~CDKIMSign(); int Init( DKIMSignOptions* pOptions ); int GetSig( char* szPrivKey, char* szSignature, int nSigLength ); int GetSig2( char* szPrivKey, char** pszSignature ); virtual int ProcessHeaders(void); virtual int ProcessBody( char* szBuffer, int nBufLength, bool bEOF ); enum CKDKIMConstants { OptimalHeaderLineLength = 65 }; protected: void Hash( const char* szBuffer, int nBufLength, bool bHdr, bool bAllmanOnly = false ); bool SignThisTag( const string& sTag ); void GetHeaderParams( const string& sHdr ); void ProcessHeader( const string& sHdr ); bool ParseFromAddress( void ); void InitSig(void); void AddTagToSig( char* Tag, const string &sValue, char cbrk, bool bFold ); void AddTagToSig( char* Tag, unsigned long nValue ); void AddInterTagSpace( int nSizeOfNextTag ); void AddFoldedValueToSig( const string &sValue, char cbrk ); bool IsRequiredHeader( const string& sTag ); int ConstructSignature( char* szPrivKey, bool bUseIetfBodyHash, bool bUseSha256 ); int AssembleReturnedSig( char* szPrivKey ); EVP_MD_CTX m_Hdr_ietf_sha1ctx; /* the header hash for ietf sha1 */ EVP_MD_CTX m_Hdr_ietf_sha256ctx; /* the header hash for ietf sha256 */ EVP_MD_CTX m_Bdy_ietf_sha1ctx; /* the body hash for ietf sha1 */ EVP_MD_CTX m_Bdy_ietf_sha256ctx; /* the body hash for ietf sha256 */ EVP_MD_CTX m_allman_sha1ctx; /* the hash for allman sha1 */ int m_Canon; // canonization method int m_EmptyLineCount; string hParam; string sFrom; string sSender; string sSelector; string sDomain; string sIdentity; // for i= tag, if empty tag will not be included in sig string sRequiredHeaders; bool m_IncludeBodyLengthTag; int m_nBodyLength; time_t m_ExpireTime; int m_nIncludeTimeStamp; // 0 = don't include t= tag, 1 = include t= tag int m_nIncludeQueryMethod; // 0 = don't include q= tag, 1 = include q= tag int m_nHash; // use one of the DKIM_HASH_xx constants here int m_nIncludeCopiedHeaders; // 0 = don't include z= tag, 1 = include z= tag int m_nIncludeBodyHash; // 0 = calculate sig using draft 0, 1 = include bh= tag and // use new signature computation algorithm DKIMHEADERCALLBACK m_pfnHdrCallback; string m_sSig; int m_nSigPos; string m_sReturnedSig; bool m_bReturnedSigAssembled; string m_sCopiedHeaders; }; #endif // DKIMSIGN_H libdkim-1.0.21.orig/src/dkimverify.h0000666000175000017500000000712211063377410016634 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifndef DKIMVERIFY_H #define DKIMVERIFY_H #include "dkimbase.h" #include #define DKIM_ADSP_UNKNOWN 1 #define DKIM_ADSP_ALL 2 #define DKIM_ADSP_DISCARDABLE 3 #define DKIM_POLICY_DOMAIN_NAME_TOO_LONG -50 // internal error #define DKIM_POLICY_DNS_TEMP_FAILURE -51 // internal error #define DKIM_POLICY_DNS_PERM_FAILURE -52 // internal error #define DKIM_POLICY_INVALID -53 // internal error #define DKIM_SIG_VERSION_PRE_02 0 #define DKIM_SIG_VERSION_02_PLUS 1 class SelectorInfo { public: SelectorInfo(const string &sSelector, const string &sDomain); ~SelectorInfo(); string Domain; string Selector; string Granularity; bool AllowSHA1; bool AllowSHA256; EVP_PKEY *PublicKey; /* the public key */ bool Testing; bool SameDomain; int Status; int Parse( char* Buffer ); }; class SignatureInfo { public: SignatureInfo(bool SaveCanonicalizedData); ~SignatureInfo(); void Hash( const char* szBuffer, unsigned nBufLength, bool IsBody=false ); string Header; unsigned Version; string Domain; string Selector; string SignatureData; string BodyHashData; string IdentityLocalPart; string IdentityDomain; string CanonicalizedData; vector SignedHeaders; unsigned BodyLength; unsigned HeaderCanonicalization; unsigned BodyCanonicalization; unsigned ExpireTime; unsigned VerifiedBodyCount; unsigned UnverifiedBodyCount; EVP_MD_CTX m_Hdr_ctx; EVP_MD_CTX m_Bdy_ctx; SelectorInfo *m_pSelector; int Status; int m_nHash; // use one of the DKIM_HASH_xxx constants here unsigned EmptyLineCount; bool m_SaveCanonicalizedData; }; class CDKIMVerify : public CDKIMBase { public: CDKIMVerify(); ~CDKIMVerify(); int Init( DKIMVerifyOptions* pOptions ); int GetResults(void); int GetDetails( int* nSigCount, DKIMVerifyDetails** pDetails ); virtual int ProcessHeaders(void); virtual int ProcessBody( char* szBuffer, int nBufLength, bool bEOF ); const char* GetPractices() { return Practices.c_str(); } protected: int ParseDKIMSignature( const string& sHeader, SignatureInfo &sig ); SelectorInfo& GetSelector( const string &sSelector, const string &sDomain ); int GetADSP( const string &sDomain, int &iADSP ); list Signatures; list Selectors; DKIMDNSCALLBACK m_pfnSelectorCallback; // selector record callback DKIMDNSCALLBACK m_pfnPracticesCallback; // ADSP record callback bool m_HonorBodyLengthTag; bool m_CheckPractices; bool m_SubjectIsRequired; bool m_SaveCanonicalizedData; bool m_AllowUnsignedFromHeaders; vector Details; string Practices; }; #endif //DKIMVERIFY_H libdkim-1.0.21.orig/src/libdkimtest.cpp0000666000175000017500000001465211012004446017325 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ #ifdef WIN32 #include #else #define strnicmp strncasecmp #endif #include #include #include #include #include "dkim.h" #include "dns.h" // change these to your selector name, domain name, etc #define MYSELECTOR "MDaemon" #define MYDOMAIN "bardenhagen.com" #define MYIDENTITY "dkimtest@bardenhagen.com" int DKIM_CALL SignThisHeader(const char* szHeader) { if( strnicmp( szHeader, "X-", 2 ) == 0 ) { return 0; } return 1; } int DKIM_CALL SelectorCallback(const char* szFQDN, char* szBuffer, int nBufLen ) { return 0; } int main(int argc, char* argv[]) { int n; char* PrivKeyFile = "test.pem"; char* MsgFile = "test.msg"; char* OutFile = "signed.msg"; int nPrivKeyLen; char PrivKey[2048]; char Buffer[1024]; int BufLen; char szSignature[10024]; time_t t; DKIMContext ctxt; DKIMSignOptions opts = {0}; opts.nHash = DKIM_HASH_SHA1_AND_256; time(&t); opts.nCanon = DKIM_SIGN_RELAXED; opts.nIncludeBodyLengthTag = 1; opts.nIncludeQueryMethod = 0; opts.nIncludeTimeStamp = 0; opts.expireTime = t + 604800; // expires in 1 week strcpy( opts.szSelector, MYSELECTOR ); strcpy( opts.szDomain, MYDOMAIN ); strcpy( opts.szIdentity, MYIDENTITY ); opts.pfnHeaderCallback = SignThisHeader; strcpy( opts.szRequiredHeaders, "NonExistant" ); opts.nIncludeCopiedHeaders = 0; opts.nIncludeBodyHash = DKIM_BODYHASH_BOTH; int nArgParseState = 0; bool bSign = true; for( n = 1; n < argc; n++ ) { if( argv[n][0] == '-' && strlen(argv[n]) > 1 ) { switch( argv[n][1] ) { case 'b': // allman or ietf draft 1 or both opts.nIncludeBodyHash = atoi( &argv[n][2] ); break; case 'c': // canonicalization if( argv[n][2] == 'r' ) { opts.nCanon = DKIM_SIGN_RELAXED; } else if( argv[n][2] == 's' ) { opts.nCanon = DKIM_SIGN_SIMPLE; } else if( argv[n][2] == 't' ) { opts.nCanon = DKIM_SIGN_RELAXED_SIMPLE; } else if( argv[n][2] == 'u' ) { opts.nCanon = DKIM_SIGN_SIMPLE_RELAXED; } break; case 'l': // body length tag opts.nIncludeBodyLengthTag = 1; break; case 'h': printf( "usage: \n" ); return 0; case 'i': // identity if( argv[n][2] == '-' ) { opts.szIdentity[0] = '\0'; } else { strcpy( opts.szIdentity, argv[n] + 2 ); } break; case 'q': // query method tag opts.nIncludeQueryMethod = 1; break; case 's': // sign bSign = true; break; case 't': // timestamp tag opts.nIncludeTimeStamp = 1; break; case 'v': // verify bSign = false; break; case 'x': // expire time if( argv[n][2] == '-' ) { opts.expireTime = 0; } else { opts.expireTime = t + atoi( argv[n] + 2 ); } break; case 'z': // sign w/ sha1, sha256 or both opts.nHash = atoi( &argv[n][2] ); break; } } else { switch( nArgParseState ) { case 0: MsgFile = argv[n]; break; case 1: PrivKeyFile = argv[n]; break; case 2: OutFile = argv[n]; break; } nArgParseState++; } } if( bSign ) { FILE* PrivKeyFP = fopen( PrivKeyFile, "r" ); if ( PrivKeyFP == NULL ) { printf( "dkimlibtest: can't open private key file %s\n", PrivKeyFile ); exit(1); } nPrivKeyLen = fread( PrivKey, 1, sizeof(PrivKey), PrivKeyFP ); if (nPrivKeyLen == sizeof(PrivKey)) { /* TC9 */ printf( "dkimlibtest: private key buffer isn't big enough, use a smaller private key or recompile.\n"); exit(1); } PrivKey[nPrivKeyLen] = '\0'; fclose(PrivKeyFP); FILE* MsgFP = fopen( MsgFile, "rb" ); if ( MsgFP == NULL ) { printf( "dkimlibtest: can't open msg file %s\n", MsgFile ); exit(1); } n = DKIMSignInit( &ctxt, &opts ); while (1) { BufLen = fread( Buffer, 1, sizeof(Buffer), MsgFP ); if( BufLen > 0 ) { DKIMSignProcess( &ctxt, Buffer, BufLen ); } else { break; } } fclose( MsgFP ); //n = DKIMSignGetSig( &ctxt, PrivKey, szSignature, sizeof(szSignature) ); char* pSig = NULL; n = DKIMSignGetSig2( &ctxt, PrivKey, &pSig ); strcpy( szSignature, pSig ); DKIMSignFree( &ctxt ); FILE* in = fopen( MsgFile, "rb" ); FILE* out = fopen( OutFile, "wb+" ); fwrite( szSignature, 1, strlen(szSignature), out ); fwrite( "\r\n", 1, 2, out ); while (1) { BufLen = fread( Buffer, 1, sizeof(Buffer), in ); if( BufLen > 0 ) { fwrite( Buffer, 1, BufLen, out ); } else { break; } } fclose( in ); } else { FILE* in = fopen( MsgFile, "rb" ); DKIMVerifyOptions vopts = {0}; vopts.pfnSelectorCallback = NULL; //SelectorCallback; n = DKIMVerifyInit( &ctxt, &vopts ); while (1) { BufLen = fread( Buffer, 1, sizeof(Buffer), in ); if( BufLen > 0 ) { DKIMVerifyProcess( &ctxt, Buffer, BufLen ); } else { break; } } n = DKIMVerifyResults( &ctxt ); int nSigCount = 0; DKIMVerifyDetails* pDetails; char szPolicy[512]; n = DKIMVerifyGetDetails(&ctxt, &nSigCount, &pDetails, szPolicy ); for ( int i = 0; i < nSigCount; i++) { printf( "Signature #%d: ", i + 1 ); if( pDetails[i].nResult >= 0 ) printf( "Success\n" ); else printf( "Failure\n" ); } DKIMVerifyFree( &ctxt ); } return 0; } libdkim-1.0.21.orig/src/libdkim.rc0000666000175000017500000000523010772175532016260 0ustar magnusmagnus//Microsoft Developer Studio generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE DISCARDABLE BEGIN "resource.h\0" END 2 TEXTINCLUDE DISCARDABLE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE DISCARDABLE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #ifndef _MAC ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION VER_MAJOR,VER_MINOR,VER_REV,VER_BUILD PRODUCTVERSION VER_MAJOR,VER_MINOR,VER_REV,VER_BUILD FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "Comments", "DomainKeys Identified Mail\0" VALUE "CompanyName", "Alt-N Technologies, Ltd.\0" VALUE "FileDescription", "DKIM Library\0" VALUE "FileVersion", VERSION_STRING "\0" VALUE "InternalName", "LIBDKIM\0" VALUE "LegalCopyright", "Copyright © 1996-2008 Alt-N Technologies, Ltd.\0" VALUE "LegalTrademarks", "\0" VALUE "OriginalFilename", "LibDKIM.dll\0" VALUE "PrivateBuild", "\0" VALUE "ProductName", "DKIM Library\0" VALUE "ProductVersion", VERSION_STRING "\0" VALUE "SpecialBuild", "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif // !_MAC #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED libdkim-1.0.21.orig/src/dnsresolv.h0000666000175000017500000000323611012004436016471 0ustar magnusmagnus/***************************************************************************** * Copyright 2005 Alt-N Technologies, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This code incorporates intellectual property owned by Yahoo! and licensed * pursuant to the Yahoo! DomainKeys Patent License Agreement. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ // DNS query routines #ifndef DNSRESOLV_H #define DNSRESOLV_H #define DNSMSG_HDR_ID 0 #define DNSMSG_HDR_CODES 1 #define DNSMSG_HDR_QDCOUNT 2 #define DNSMSG_HDR_ANCOUNT 3 #define DNSMSG_HDR_NSCOUNT 4 #define DNSMSG_HDR_ARCOUNT 5 #define DNSMSG_HDR_SIZE 6 #define DNSMSG_MAX_LABEL 64 #define DNSMSG_MAX_UDP_SIZE 512 #define DNSMSG_MAX_DATA_SIZE (DNSMSG_MAX_UDP_SIZE - (DNSMSG_HDR_SIZE*2)) #define DNSMSG_COMPRESS_FLAG 0xc0 #define C_IN 1 #define T_TXT 16 #define EMSGSIZE 1 #define ENOENT 2 typedef unsigned char u_char; typedef unsigned int u_int; int res_query(const char *, int, int, u_char *, int); int dn_expand(const u_char *, const u_char *, const u_char *, char *, int); #endif // DNSRESOLV_Hlibdkim-1.0.21.orig/LICENSE0000666000175000017500000002644610270202614014532 0ustar magnusmagnus Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. libdkim-1.0.21.orig/README0000666000175000017500000001031011063377410014374 0ustar magnusmagnusAlt-N DKIM Open Source Project Copyright 2008 Alt-N Technologies, Ltd. This code incorporates intellectual property owned by Yahoo! and licensed pursuant to the Yahoo! DomainKeys Patent License Agreement. By making, using, selling, offering for sale, importing, and/or sublicensing Implementations as permitted, you agree to the terms and conditions of the Yahoo! DomainKeys Patent License Agreement or other agreement contained herein. ---------------------- 1.0.21 ---------------------- o updated verifier to latest draft of DKIM ADSP o fixed some error codes overlapping success codes o added signature and identity domain information to DKIMVerifyDetails structure ------------------- 1.0.20 Aug 26, 2008 ------------------- o verifier by default requires all From headers in the message to be signed ------------------- 1.0.19 May 12, 2008 ------------------- o fix to trailing lines of whitespace not being ignored with relaxed body canonicalization ---------------------- 1.0.18 January 9, 2008 ---------------------- o fix to incorrect body hashes for empty bodies o fix to verification error for signatures with whitespace around the b= value o more fixes to verification errors with whitespace between the header name and : ----------------------- 1.0.17 October 29, 2007 ----------------------- o verifier fully supports g= value wildcard matching o fix to verifier not canonicalizing message headers that had whitespace between the header name and : o fix to verifier not validating t= value or comparing it to the x= value o fix to verifier accepting blank values for l= and x= ---------------------- 1.0.16 August 22, 2007 ---------------------- o supports SSP (Sender Signing Practices) draft 00 o added verifier option to save canonicalized message data ------------------- 1.0.15 May 30, 2007 ------------------- o fix to DKIM_FAIL being returned for messages with invalid signatures --------------------- 1.0.14 April 24, 2007 --------------------- o updated to final publication of DKIM (version 1) o fix to buffer overflow parsing malformed From headers ------------------------ 1.0.13 February 22, 2007 ------------------------ o by default, verifier requires subject header to be signed o added visual studio 2005 project files o changed q=dns to q=dns/txt in signer o fixed hash for empty body ---------------------- 1.0.12 August 31, 2006 ---------------------- o added verification option to not check the sender's policy (the default is to not check) -------------------- 1.0.11 July 25, 2006 -------------------- o updated to 04 draft ------------------------ 1.0.10 February 21, 2006 ------------------------ o added sha-256 hashing capability. Can sign with either sha-1, sha-256, or both. Either type can be verified. This version requires OpenSSL 0.9.8a ----------------------- 1.0.9 November 22, 2005 ----------------------- o update to 01 draft ------------------- 1.0.8 July 28, 2005 ------------------- o fix to verifier requesting policy records from the wrong location o the policy is no longer checked if the From domain is a subdomain of any of the successful signing domains ------------------- 1.0.7 July 21, 2005 ------------------- o added option to honor/ignore body length tags when verifying default is to ignore ------------------- 1.0.6 July 14, 2005 ------------------- o initial release This library implements DKIM (DomainKeys Identified Mail). The internet drafts are available here: http://www.ietf.org/internet-drafts/draft-allman-dkim-base-01.txt http://www.ietf.org/internet-drafts/draft-allman-dkim-ssp-01.txt http://www.ietf.org/internet-drafts/draft-fenton-dkim-threats-01.txt Build Instructions ------------------ You must have OpenSSL installed and built. http://www.openssl.org/ For Win32, - Edit the make file Makefile.vc and set the OpenSSL include and lib paths (OPENSSL_INC and OPENSSL_LIB) - Run "nmake /f Makefile.vc" For Unix, - Run "make" Usage ------- See libdkimtest.cpp for an example of how to call the library. libdkim-1.0.21.orig/Yahoo! DomainKeys Patent License Agreement v1_0.txt0000666000175000017500000002144111321056220024613 0ustar magnusmagnus***************************************************************************** Copyrights ***************************************************************************** DomainKeys is a registered trademark of Yahoo! MDaemon and all parts thereof are copyright (c) 1996-2009 Alt-N Technologies, Ltd and may not be used, copied or distributed except as expressly authorized by the MDaemon EULA (see the \MDaemon\Docs\ directory). MDaemon is a registered trademark of Alt-N Technologies, Ltd. ***************************************************************************** Yahoo! DomainKeys Patent License Agreement v1.0 ***************************************************************************** Yahoo! DomainKeys Patent License Agreement v1.0 (this "Agreement") Copyright (c) 2004, Yahoo! Inc. All rights reserved. You agree to be bound by all the terms and conditions set forth below and, subject to those terms and conditions, You may use the intellectual property described below. 1. LICENSE GRANT. 1.1. Subject to the terms and conditions of this Agreement, DomainKeys Developer hereby grants You, a royalty-free, worldwide, sub-licensable, non-exclusive license under its rights to the Yahoo! Patent Claims to make, use, sell, offer for sale, and/or import Implementations. 2. DEFINITIONS. 2.1. "DomainKeys Developer" means Yahoo! Inc. ("Yahoo!") or any licensee or sublicensee (direct or indirect) of the Yahoo! Patent Claims. 2.2. "Implementations" means the specific portions of a hardware or software implementation expressly required to be compliant with the Specifications for the sole purpose of a sender verification solution in connection with e-mail. 2.3. "Specifications" means the specification having submission ID "draft-delany-domainkeys-base-01.txt" dated Aug 2004 published through the IETF (Internet Engineering Task Force). The Specifications may be found at the following link: http://antispam.yahoo.com/domainkeys/draft-delany-domainkeys-base-01.txt 2.4. "Yahoo! Patent Claims" shall mean those claims of all Yahoo! foreign and domestic patents and patent applications that base their priority on U.S. Provisional Patent Application Ser. Nos. 60/497,794, filed Aug. 26, 2003, or 60/553,300, filed Mar. 15, 2004, or Patent Application Ser. Nos. 10/671,319, filed Sep. 24, 2003, or 10/805,181, filed Mar. 19, 2004. 2.5. "You" or "Your" means an individual, company, or other legal entity exercising rights under this Agreement. Any individual exercising rights under this Agreement on behalf of a company or other legal entity represents and warrants that the individual has the authority to enter into this Agreement on behalf of the company or other legal entity. 3. TERMS. 3.1. You agree not to assert against Yahoo!, or any other DomainKeys Developer, a patent infringement claim against any Implementation ("Implementation IP Claim"). 3.2. To indicate your assent to the terms and conditions of this Agreement and in order to obtain a license to make, use, sell, offer for sale, and/or import Implementations, You must include or preserve the following prominently displayed statement in the source code and object code of any such Implementations : "This code incorporates intellectual property owned by Yahoo! and licensed pursuant to the Yahoo! DomainKeys Patent License Agreement.". 3.3. You will not use the name of Yahoo! to endorse or promote any products or Implementations without specific prior written permission of Yahoo!. "DomainKeys" is a trademark of Yahoo!. However, You may state Your Implementation is "DomainKeys compliant", "supports DomainKeys", or is "DomainKeys-enabled", without citation to Yahoo!, but You should create Your own product names or trademarks for Your specific Implementations and the term "DomainKeys" shall not be used by You in or as part of a name for Your specific Implementations. 3.4. You may choose to distribute Implementations under this Agreement or a separate agreement, including without limitation a sublicense agreement, provided that: (a) such agreement complies with the terms and conditions of this Agreement; (b) a copy of this Agreement or the separate agreement is included with each copy of the Implementations along with the following prominently displayed statement: "By making, using, selling, offering for sale, and/or importing this product, you agree to the terms and conditions of the Yahoo! DomainKeys Patent License Agreement or other separate agreement contained herein."; and (c) if distributed under a separate agreement, such separate agreement must contain terms no less protective of DomainKeys Developers than the terms and conditions of this Agreement, including, without limitation, Sections 3.1, 3.4, 3.7, 4.1, 4.2, and 4.3. 3.5. You acknowledge that implementations of the Specifications may be subject to U.S. export jurisdiction and other applicable national and international laws. You agree to comply with all export, re-export, or import restrictions, laws, or regulations. 3.6. Yahoo!, and only Yahoo!, may, from time to time, update or modify the terms of this Agreement. If Yahoo! makes such a modification, You may continue under the terms and conditions of this Agreement or agree to the updated or modified terms and conditions. For the most recent version of this Agreement please contact Yahoo!. 3.7. The term of this Agreement is perpetual unless terminated as set forth below. This Agreement and the rights hereunder will terminate: (a) automatically without notice from Yahoo!, if You at any time during the term of this Agreement assert any Implementation IP Claim against Yahoo!; (b) upon written notice from Yahoo!, if You at any time during the term of this Agreement assert any Implementation IP Claim against any DomainKeys Developer other than Yahoo!; or (c) where (a) or (b) do not apply, automatically without notice from Yahoo!, if You fail to comply with any term(s) of this Agreement and fail to cure such breach within 30 days of You becoming aware of such breach. 3.8. This Agreement constitutes the entire agreement between the parties with respect to the subject matter hereof. This Agreement shall be governed by and construed under the laws of the United States and the State of California without giving effect to California conflict of law provisions or to construction provisions favoring either party. All actions arising out of or relating to this Agreement will be adjudicated exclusively by the Superior Court of the State of California for the County of Santa Clara or the United States District Court for the Northern District of California. 4. LEGAL DISCLAIMERS. 4.1. THE YAHOO! PATENT CLAIMS, THIS AGREEMENT, THE DOMAINKEYS TRADEMARK, AND SPECIFICATIONS ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT REPRESENTATIONS, WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of exercising any rights under this Agreement and using the Specifications and the DomainKeys trademark and assume all risks associated in connection therewith, including, but not limited to, the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 4.2. You expressly acknowledge and agree that no assurances are provided by any DomainKeys Developer with respect to the validity of the Yahoo! Patent Claims or that the Specifications, the DomainKeys trademark or any implementations related to the Specifications or the DomainKeys trademark do not infringe or misappropriate the patent or other intellectual property rights of any other entity. All DomainKeys Developers disclaim any liability to You for claims brought by any other person or entity based on infringement or misappropriation of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, You hereby assume sole responsibility to secure any other intellectual property rights needed, if any. 4.3. DOMAINKEYS DEVELOPER SHALL NOT HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE EXERCISE OF ANY RIGHTS UNDER THIS AGREEMENT, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.