fscan/Plugins/portscan.go

88 lines
1.8 KiB
Go
Raw Normal View History

2020-12-29 01:17:10 -08:00
package Plugins
import (
"fmt"
"github.com/shadow1ng/fscan/common"
"net"
"strconv"
"sync"
"time"
)
2021-03-07 18:00:56 -08:00
type Addr struct {
ip string
port int
2020-12-29 01:17:10 -08:00
}
2021-03-07 18:00:56 -08:00
func PortScan(hostslist []string, ports string, timeout int64) []string {
var AliveAddress []string
probePorts := common.ParsePort(ports)
2021-05-05 20:37:29 -07:00
noPorts := common.ParsePort(common.NoPorts)
if len(noPorts) > 0 {
tmp := make(map[int]struct{})
var tmpPorts []int
for _, port := range probePorts {
for _, noport := range noPorts {
if port != noport {
if _, ok := tmp[port]; !ok {
tmp[port] = struct{}{}
tmpPorts = append(tmpPorts, port)
}
}
}
}
probePorts = tmpPorts
}
2021-03-07 18:00:56 -08:00
workers := common.Threads
2021-05-29 00:55:05 -07:00
Addrs := make(chan Addr, len(hostslist)*len(probePorts))
results := make(chan string, len(hostslist)*len(probePorts))
2021-03-07 18:00:56 -08:00
var wg sync.WaitGroup
2020-12-29 01:17:10 -08:00
2021-03-07 18:00:56 -08:00
//接收结果
go func() {
for found := range results {
AliveAddress = append(AliveAddress, found)
2021-04-21 21:06:03 -07:00
wg.Done()
2020-12-29 01:17:10 -08:00
}
2021-03-07 18:00:56 -08:00
}()
2020-12-29 01:17:10 -08:00
2021-03-07 18:00:56 -08:00
//多线程扫描
for i := 0; i < workers; i++ {
go func() {
for addr := range Addrs {
2021-04-21 21:06:03 -07:00
PortConnect(addr, results, timeout, &wg)
2021-03-07 18:00:56 -08:00
wg.Done()
}
}()
2020-12-29 01:17:10 -08:00
}
2021-03-07 18:00:56 -08:00
//添加扫描目标
2021-03-07 18:16:21 -08:00
for _, port := range probePorts {
for _, host := range hostslist {
2021-03-07 18:00:56 -08:00
wg.Add(1)
2021-04-21 21:06:03 -07:00
Addrs <- Addr{host, port}
2021-03-07 18:00:56 -08:00
}
2020-12-29 01:17:10 -08:00
}
wg.Wait()
2021-03-07 18:00:56 -08:00
close(Addrs)
close(results)
2020-12-29 01:17:10 -08:00
return AliveAddress
}
2021-03-07 18:00:56 -08:00
2021-04-21 21:06:03 -07:00
func PortConnect(addr Addr, respondingHosts chan<- string, adjustedTimeout int64, wg *sync.WaitGroup) {
2021-03-07 18:00:56 -08:00
host, port := addr.ip, addr.port
2021-09-10 05:32:51 -07:00
conn, err := net.DialTimeout("tcp4", fmt.Sprintf("%s:%v", host, port), time.Duration(adjustedTimeout)*time.Second)
defer func() {
if conn != nil{
conn.Close()
}
}()
2021-03-07 18:00:56 -08:00
if err == nil {
address := host + ":" + strconv.Itoa(port)
result := fmt.Sprintf("%s open", address)
common.LogSuccess(result)
2021-04-21 21:06:03 -07:00
wg.Add(1)
2021-09-10 05:32:51 -07:00
respondingHosts <- address
2021-03-07 18:00:56 -08:00
}
}