Como as portas de origem são determinadas e como posso forçá-lo a usar uma porta específica

21

Quando me conecto ao link , isso muda para 216.58.198.228:443. Então uma conexão para mim será aberta em [My IP Address]: 63998.

Minha pergunta é como é 63998 porta escolhida e existe uma maneira de forçá-lo a ser 63999.

    
por TheGathron 29.08.2016 / 12:01

2 respostas

31

Como as portas locais são determinadas

O número da porta é escolhido pelo software de implementação TCP de um intervalo de números de portas chamado Portas efêmeras .

O mecanismo exato para escolher o número da porta e o intervalo a ser usado depende do sistema operacional.

Existe uma maneira de forçá-lo a ser 63999?

Isso pode ser feito alterando a configuração do software de implementação do TCP.

As instruções sobre como configurar a gama de Portas efêmeras para uma variedade de sistemas operacionais diferentes podem ser encontradas em Alterar o intervalo de portas efêmeras .

  • As instruções para Linux e Windows estão incluídas nesta resposta abaixo para referência.

No entanto, não é uma boa ideia restringir o intervalo a uma única porta, por exemplo, 63999 .

  • Na verdade, no Windows isso não é possível como:

    The minimum range of ports that can be set is 255.

O intervalo de portas efêmeras

A TCP/IPv4 connection consists of two endpoints, and each endpoint consists of an IP address and a port number. Therefore, when a client user connects to a server computer, an established connection can be thought of as the 4-tuple of (server IP, server port, client IP, client port).

Usually three of the four are readily known -- client machine uses its own IP address and when connecting to a remote service, the server machine's IP address and service port number are required.

What is not immediately evident is that when a connection is established that the client side of the connection uses a port number. Unless a client program explicitly requests a specific port number, the port number used is an ephemeral port number.

Ephemeral ports are temporary ports assigned by a machine's IP stack, and are assigned from a designated range of ports for this purpose. When the connection terminates, the ephemeral port is available for reuse, although most IP stacks won't reuse that port number until the entire pool of ephemeral ports have been used.

So, if the client program reconnects, it will be assigned a different ephemeral port number for its side of the new connection.

Fonte O intervalo de portas efêmeras

Alterando o intervalo de portas efêmeras

Linux:

Linux allows you to view and change the ephemeral port range by simply using the file /proc/sys/net/ipv4/ip_local_port_range. For example, this shows the default configuration on a kernel 2.2 system:

$ cat /proc/sys/net/ipv4/ip_local_port_range 
1024 4999

To change this to the preferred range, you could do (as superuser):

# echo "49152 65535" > /proc/sys/net/ipv4/ip_local_port_range 

Note that you would need to do this each time the system boots, so be sure to add a line to a system startup script such as /etc/rc.local so your range is always used.

Also note that the Linux 2.4 kernel will default the range of 32768 through 61000 if adequate kernel memory is available, so changing the range may not be necessary on newer Linux systems.

Finally, also note that you may be able to use the sysctl interface to change the settings rather than using the /proc filesystem. The name of the sysctl parameter is "net.ipv4.ip_local_port_range". Edit the /etc/sysctl.conf file if you have it, or have a startup script run the sysctl command manually if you want to change this parameter using sysctl.

Windows Vista / Windows Server 2008 e mais recentes:

As of Windows Vista and Windows Server 2008, Windows now uses a large range (49152-65535) by default, according to Microsoft Knowledgebase Article 929851. That same article also shows how you can change the range if desired, but the default range is now sufficient for most servers.

Fonte Mudando o intervalo de portas efêmeras

You can view the dynamic port range on a computer that is running Windows Vista or Windows Server 2008 computer by using the following netsh commands:

netsh int ipv4 show dynamicport tcp
netsh int ipv4 show dynamicport udp
netsh int ipv6 show dynamicport tcp
netsh int ipv6 show dynamicport udp 

Notes:

  • The range is set separately for each transport and for each version of IP.
  • The port range is now truly a range with a starting point and with an endpoint.
  • Microsoft customers who deploy servers that are running Windows Server 2008 may have problems with RPC communication between servers if firewalls are used on the internal network.
  • In these cases, we recommend that you reconfigure the firewalls to allow for traffic between servers in the dynamic port range of 49152 through 65535.
  • This range is in addition to well-known ports that are used by services and by applications.
  • Or, the port range that is used by the servers can be modified on each server.

You adjust this range by using the netsh command, as follows:

netsh int <ipv4|ipv6> set dynamic <tcp|udp> start=number num=range

This command sets the dynamic port range for TCP. The start port is number, and the total number of ports is range. The following are sample commands:

netsh int ipv4 set dynamicport tcp start=10000 num=1000
netsh int ipv4 set dynamicport udp start=10000 num=1000
netsh int ipv6 set dynamicport tcp start=10000 num=1000
netsh int ipv6 set dynamicport udp start=10000 num=1000

These sample commands set the dynamic port range to start at port 10000 and to end at port 10999 (1000 ports).

Notes:

  • The minimum range of ports that can be set is 255.
  • The minimum starting port that can be set is 1025.
  • The maximum end port (based on the range being configured) cannot exceed 65535.
  • To duplicate the default behavior of Windows Server 2003, use 1025 as the start port, and then use 3976 as the range for both TCP and UDP. This results in a start port of 1025 and an end port of 5000.

Artigo da Base de Dados de Conhecimento da Microsoft 929851 :

Windows XP e mais antigo:

For older Windows operating systems (Windows XP and older), Windows uses the traditional BSD range of 1024 through 4999 for its ephemeral port range. Unfortunately it appears that you can only set the upper bound of the ephemeral port range. Here is information excerpted from Microsoft Knowledgebase Article 196271:

  • Start Registry Editor (Regedt32.exe).
  • Locate the following key in the registry:

    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

  • On the "Edit" menu, click "Add Value", and then add the following registry value:

    Value Name: MaxUserPort Data Type: REG_DWORD Value: 65534 (for example)

    Valid Range: 5000-65534 (decimal) Default: 0x1388 (5000 decimal)

    Description: This parameter controls the maximum port number used when an application requests any available user port from the system. Normally, ephemeral (that is, short-lived) ports are allocated between the values of 1024 and 5000 inclusive.

  • Quit Registry Editor.

Note: There is another relevant KB article (812873) which claims to allow you to set an exclusion range, which could mean that you could exclude ports 1024-9999 (for example) to have the ephemeral port range be 10000-65534. However, we have not been able to get this to work (as of October 2004).

Fonte Mudando o intervalo de portas efêmeras

    
por 29.08.2016 / 12:29
8

A resposta de David Postill está perfeitamente certa. Eu gostaria apenas de acrescentar, ressaltando que mudar o intervalo de portas efêmeras em Linux é tão simples, que o OP tem uma resposta afirmativa.

Você altera o EPR da seguinte forma:

echo "40000 60000" > /proc/sys/net/ipv4/ip_local_port_range 

e você pode selecionar a porta 50000 (como um exemplo) com o seguinte script:

OLD_RANGE=$(cat /proc/sys/net/ipv4/ip_local_port_range)
MY_PORT=50000
echo "$MY_PORT $MY_PORT" > /proc/sys/net/ipv4/ip_local_port_range
sudo -u SomeUser SomeApplication  & 
echo $OLD_RANGE" > /proc/sys/net/ipv4/ip_local_port_range 

Uma ressalva aqui: como há uma única porta no intervalo, outro aplicativo pode tirá-la de você entre a execução da terceira e da quarta linhas acima; Além disso, mesmo se não houver nenhuma condição de corrida, você irá paralisar todos os outros aplicativos até que você restaure um EPR grande, razão pela qual eu restaurei o intervalo original o mais rápido possível.

Assim, se o sistema operacional dos OPs fosse Linux, a resposta seria que isso poderia ser feito facilmente.

Surpreendentemente, isso não é tão simples em BSDs, alguns dos quais nem sequer têm uma configuração de kernel de tempo de execução para o EPR. MacOS X, FreeBSD e OpenBSD requerem modificar o arquivo /etc/sysctl.conf , mas eles têm escolhas diferentes para o EPR.

Independentemente do acima e do sistema operacional, o fato de que algo pode ser feito não significa que deve ser feito: por que diabos você precisa disso? Não consigo pensar em um único caso de uso.

    
por 29.08.2016 / 13:19