Get the App
SLTechnology News&Howtos  ›  Network Security  › 

How to realize online Port scanning function in PHP

Shulou Source: shulou.com Published: 2022-06-01 00:43:36 09月20日 Update

In this issue, Xiaobian will bring you about how to implement online port scanning function in PHP. The article is rich in content and analyzes and narrates from a professional perspective. After reading this article, I hope you can gain something.

PHP4/5/7 provides the fsockopen method, which is used to open a network connection or a Unix socket connection, and can also be used for open port scanning.

Using the fsockopen() method we can design the following ideas to implement open port detection:

1. Get the target IP address and list of ports to scan.

2. Use the For loop to traverse the scanned port array, concatenating the destination IP address with the port.

3. Use fsockopen() function to detect: judge by Timeout parameter: if there is no response for more than 1s, it is considered that the port is not open.

4. Considering the particularity of port scanning function, SSRF vulnerability may exist, so SSRF vulnerability needs to be protected.

The code implemented by Open Port Scan is as follows:

function getOpenPort($ip,$port){ $msg = array('Ftp','Telnet','Smtp','Finger','Http','Pop3','Location Service','Netbios-NS','Netbios-DGM','Netbios-SSN','IMAP','Https','Microsoft-DS','MSSQL','MYSQL'); foreach ($port as $key => $value){ echo $value. '&nbsp&nbsp'; echo $msg[$key]. '&nbsp&nbsp'; $fp = @fsockopen($ip,$value,$errno,$errstr,0.5); $result = $fp ? '

' : '

'; echo $result;

For SSRF vulnerability protection, our solution is to create IP blacklist, shield intranet IP, and prevent scanning intranet IP addresses.

For the above scenario, we wrote the following protection code:

$blackHostlist = array("172. ", "10. ", "localhost", "127. ", "192. ");foreach($blackHostlist as $blackHost){ if(strpos($ip, $blackHost) === 0){ echo 'alert("Do not scan intranet addresses! ");'; die(); }}

Also design a front-end form to accept user-passed parameters:

#index.html Target IP - IP Address:

Scan Ports- Ports:

Start scanning- Start:

The final PHP backend code is as follows:

Tags: Port address open function code method vulnerability target protection online content front end parameter scheme analysis design special professional small and medium rich in content Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei OPPO Reno Apple MariaDB Shulou Tech Info