How to create a TCP port scanner using the SYN (TCP SYN) method?

Asked

Viewed 1,483 times

-3

#####################################
# Portscan TCP         #
# #
#####################################
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import socket

ip = input("Digite o IP ou endereco: ")

ports = []
count = 0

while count < 10:
    ports.append(int(input("Digite a porta: ")))
    count += 1


for port in ports:
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.settimeout(0.05)
    code = client.connect_ex((ip, port)) #conecta e traz a msg de erro
#Like connect(address), but return an error indicator instead of raising an exception for errors
    if code == 0: #0 = Success
        print (str(port) + " -> Porta aberta")
    else:
        print (str(port) + " -> Porta fechada")

print ("Scan Finalizado")

The code above is a TCP Scanning. How can I turn it into a TCP SYN Scanning?

  • 2

    See help: https://gist.github.com/fffaraz/57144833c6ef8bd9d453

  • I’m still trying to!

  • 2

    Did you? Paul sincerely think he should learn to program in this area gradually, starting in simpler things (ex: http://answall.com/questions/143321/criando-um-bot-de-vota%C3%A7%C3%a3o-em-python/143334#143334, http://answall.com/questions/145883/como-pega-as-manchetes-das-olimp%C3%adadas-no-site-da-cnn-com-python-usando-beautifu/145887#145887, http://en.stackoverflow.com/questions/142790/login-no-facebook-com-python) I think you will find interesting these links, are from this area and are things that can scale and do more complex things

  • I haven’t been able to!

  • Did you take a look at the links? Did you run the code? Do you know how to move the discussion to chat?

  • I guess I don’t have a reputation for it yet!

Show 2 more comments

1 answer

2


Paul, a TCP SYN (Synchronize) package needs a process called a three-part handshake (Handshaking). They are they:

1) Sending an initial package (SYN) from the client to the server

2) Sending a synchronization recognition package from the server to the client (SYN-ACK - Synchronize Acknowledge)

3) The end of the three-part handshake sent by the client to the server or acknowledgement message (ACK - Acknowledge).

As the TCP protocol has several sub-protocols as for example HTTP this handshake varies a lot and to implement this it is necessary not only programming knowledge, but knowledge of the protocol to which the handshake is being made.

So I suggest you study more about exchanging SYN packets and the protocols you want to sync (or establish connection - or check ports).

Edited: As promised follows an example of communication with authentication in 3 parts implementing only the idea, but no specific protocol.

With regard to the protocol, I shall abstain from the example because there are many possibilities and probably no example will serve the author of the question, as he has not specified any.

Follow server and client code. To test run on the same machine first the server and soon after a client instance.

Server Code: #! /usr/bin/python

import socket
import thread

class ServidorTcp:

    def __init__(self, host, porta):
        self.TAMANHO_BUFFER = 1024
        self.socket_servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket_servidor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket_servidor.bind((host, porta))

    def escutar(self):
        self.socket_servidor.listen(5)
        print("Aguardando conexoes")

        while 1:
            (cliente, endereco) = self.socket_servidor.accept()
            print("Cliente conectado: " + endereco[0])

            thread_cliente = thread.start_new_thread(self.sincronizar, (cliente, endereco))

    def sincronizar(self, cliente, endereco):
        retorno = cliente.recv(self.TAMANHO_BUFFER)

        if(retorno == "SYN"):
            cliente.send("SYN-ACK")

            retorno = cliente.recv(self.TAMANHO_BUFFER)

            if(retorno == "ACK"):
                print("Sincronizado com o cliente remoto.")

        cliente.close()

#executar o server.
servidor = ServidorTcp('localhost', 7171)
servidor.escutar()

Client code:

    #!/usr/bin/python

import socket

class ClienteTcp:

    def __init__(self):
        self.TAMANHO_BUFFER = 1024
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def conectar(self, host, porta):
        print("Conectando a " + host + ":" + str(porta) + "...")
        self.socket.connect((host, porta))

    def sincronizar(self):
        self.socket.send("SYN")
        retorno = self.socket.recv(self.TAMANHO_BUFFER)

        autenticado = False

        if retorno == "SYN-ACK":
            self.socket.send("ACK")

            #Conexao efetuada com sucesso.
            autenticado = True

        return autenticado

    def enviar(self, mensagem):
        self.socket.send(mensagem)

    def fechar(self):
        self.socket.close()

#executar o cliente.
cliente = ClienteTcp()
cliente.conectar('localhost', 7171)

if cliente.sincronizar():
    #Agora sei com quem estou me comunicando e a conversa pode iniciar entre as pontas.
    print("Sincronizado com o servidor remoto.")
else:
    print("Nao foi possivel estabelecer o sincronismo com o servidor remoto.")

I hope my answer was helpful.

  • could you show a simple example in python? I’d like to learn. You can only do "normal" TCP@Bruno Bermann

  • Paul, I’m not a Python expert specifically. I’ll have the time to give you this answer more fully tonight.

  • @ Bruno Bermann, thanks for your help!

  • @Bruno Bermann, could show a simple python implementation?

  • Paul Sigonoso and @Ed-S, as promised, follow my example in Python. Sorry about anything, but it’s not a language I’ve mastered.

  • @Bruno Bermann, thank you very much. I’m trying to learn how to program. Your code has been very useful.

  • @Brunobermann, excuse my ignorance. I did not understand: "As for the protocol I will abstain from the example because there are many possibilities and probably no example will serve the author of the question, since it did not specify any."

  • @Eds, the protocols are message exchange standards established between the tips (client and server) which indicate how the communication should be. For example, they define which criteria should be followed to authenticate as a valid client or even for example the HTTP protocol (widely used on the web, along with the HTTPS) establishes a message header and several parameters for this header for which server and client if "understand" when talking to each other. For more details, please read: https://nandovieira.com.br/understandndo-um-pouco-mais-sobre-o-protocolo-http

  • 1

    @Bruno Bermann, thank you very much!

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.