fscan/Plugins/portscan.go

84 lines
1.7 KiB
Go
Raw Normal View History

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