-
Notifications
You must be signed in to change notification settings - Fork 142
/
net.go
325 lines (278 loc) · 7.44 KB
/
net.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package coldfire
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strconv"
"strings"
"syscall"
"time"
portscanner "github.com/anvie/port-scanner"
"github.com/jackpal/gateway"
"golang.org/x/crypto/ssh"
)
// GetGlobalIp is used to return the global Ip address of the machine.
func GetGlobalIP() string {
ip := ""
resolvers := []string{
"https://api.ipify.org?format=text",
"http://myexternalip.com/raw",
"http://ident.me",
"https://ifconfig.me",
"https://bot.whatismyipaddress.com/",
"https://ifconfig.co",
}
for {
url := RandomSelectStr(resolvers)
resp, err := http.Get(url)
if err != nil {
log.Printf("%v\n", err)
}
defer resp.Body.Close()
i, _ := ioutil.ReadAll(resp.Body)
ip = string(i)
if resp.StatusCode == 200 {
break
}
}
return ip
}
// GetLocalIp is used to get the local Ip address of the machine.
func GetLocalIP() string {
conn, _ := net.Dial("udp", "8.8.8.8:80")
defer conn.Close()
ip := conn.LocalAddr().(*net.UDPAddr).IP
return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
}
// GetGatewayIP returns the Ip address of the gateway in the network where the machine resides.
func GetGatewayIP() string {
ip, err := gateway.DiscoverGateway()
ExitOnError(err)
return ip.String()
}
// Returns an IP address of a given interface
func IfaceIP(ifname string) string {
niface, err := net.InterfaceByName(ifname)
addrs, err := niface.Addrs()
ExitOnError(err)
return addrs[0].(*net.IPNet).IP.String()
}
// Iface returns the currently used wireless interface and its MAC address.
func Iface() (string, string) {
current_iface := ""
interfaces, err := net.Interfaces()
ExitOnError(err)
for _, interf := range interfaces {
if addrs, err := interf.Addrs(); err == nil {
for _, addr := range addrs {
if strings.Contains(addr.String(), GetLocalIP()) {
current_iface = interf.Name
}
}
}
}
netInterface, err := net.InterfaceByName(current_iface)
ExitOnError(err)
name := netInterface.Name
macAddress := netInterface.HardwareAddr
hwAddr, err := net.ParseMAC(macAddress.String())
ExitOnError(err)
return name, hwAddr.String()
}
// Ifaces returns the names of all local interfaces.
func Ifaces() []string {
ifs := []string{}
interfaces, _ := net.Interfaces()
for _, interf := range interfaces {
ifs = append(ifs, interf.Name)
}
return ifs
}
// SendDataTCP sends data to a given host:port using the TCP protocol.
func SendDataTCP(host string, port int, data string) error {
addr := host + ":" + strconv.Itoa(port)
conn, err := net.Dial("tcp", addr)
if err != nil {
return err
}
_, err = io.WriteString(conn, data+"\n")
if err != nil {
return err
}
defer conn.Close()
return nil
}
// SendDataUDP sends data to a given host:port using the UDP protocol.
func SendDataUDP(host string, port int, data string) error {
addr := host + ":" + strconv.Itoa(port)
conn, err := net.Dial("udp", addr)
if err != nil {
return err
}
_, err = io.WriteString(conn, data+"\n")
if err != nil {
return err
}
defer conn.Close()
return nil
}
// Download downloads a file from a url.
func Download(url string) error {
splitted := strings.Split(url, "/")
filename := splitted[len(splitted)-1]
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
response, err := http.Get(url)
if err != nil {
return err
}
defer response.Body.Close()
_, err = io.Copy(f, response.Body)
if err != nil {
return err
}
return nil
}
// Networks returns a list of nearby wireless networks.
func Networks() ([]string, error) {
return networks()
}
// ExpandCidr returns a list of Ip addresses within a given CIDR.
func ExpandCidr(cidr string) ([]string, error) {
ip, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return nil, err
}
var ips []string
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); IpIncrement(ip) {
ips = append(ips, ip.String())
}
lenIPs := len(ips)
switch {
case lenIPs < 2:
return ips, nil
default:
return ips[1 : len(ips)-1], nil
}
}
// DnsLookup returns the list of Ip adddress associated with the given hostname.
func DnsLookup(hostname string) ([]string, error) {
i := []string{}
ips, err := net.LookupIP(hostname)
if err != nil {
return nil, err
}
for _, ip := range ips {
i = append(i, ip.String())
}
return i, nil
}
// RdnsLookup returns the list of hostnames associated with the given Ip address.
func RdnsLookup(ip string) ([]string, error) {
ips, err := net.LookupAddr(ip)
if err != nil {
return nil, err
}
return ips, nil
}
// Portscan checks for open ports in a given target.
func Portscan(target string, timeout, threads int) (pr []int) {
ps := portscanner.NewPortScanner(target, time.Duration(timeout)*time.Second, threads)
opened_ports := ps.GetOpenedPort(0, 65535)
for p := range opened_ports {
port := opened_ports[p]
pr = append(pr, port)
}
return
}
// PortscanSingle checks if a specific port is open in a given target.
func PortscanSingle(target string, port int) bool {
ps := portscanner.NewPortScanner(target, time.Duration(10)*time.Second, 3)
opened_ports := ps.GetOpenedPort(port-1, port+1)
return len(opened_ports) != 0
}
// PortscanSingleTimeout checks if a specific port is open in a given target.
// Connection timeout as well as no. of threads can be adjusted
func PortscanSingleTimeout(target string, port, timeout, threads int) bool {
ps := portscanner.NewPortScanner(target, time.Duration(timeout)*time.Second, threads)
opened_ports := ps.GetOpenedPort(port-1, port+1)
return len(opened_ports) != 0
}
// Returns true if host is alive
func Ping(target string) bool {
open_counter := 0
ports_to_check := []int{80, 443, 21, 22}
ps := portscanner.NewPortScanner(target, 2*time.Second, 5)
for _, port := range ports_to_check {
if ps.IsOpen(port) {
open_counter += 1
}
}
return true
}
// Removes hosts from slice that did not respond to a ping request
func RemoveInactive(targets []string) {
for i, t := range targets {
if !Ping(t) {
targets[i] = ""
}
}
}
// Returns a random free port
func PortFree(port int) int {
var a *net.TCPAddr
a, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0
}
var l *net.TCPListener
l, _ = net.ListenTCP("tcp", a)
defer l.Close()
return l.Addr().(*net.TCPAddr).Port
}
func PortReuse(network string, address string, conn syscall.RawConn) error {
return portReuse(network, address, conn)
}
// Gracefully closes an instance of net.Listener
func CloseListener(lst net.Listener) {
if lst != nil {
lst.Close()
lst = nil
}
}
// Returns a slice with lines of file from URL
func Url2Lines(url string) []string {
resp, err := http.Get(url)
Check(err)
defer resp.Body.Close()
var lns []string
scn := bufio.NewScanner(resp.Body)
for scn.Scan() {
lns = append(lns, scn.Text())
}
return lns
}
// Checks if an SSH client connection has a root context
func CheckRootSSH(client ssh.Client) bool {
uid0_session := false
session, err := client.NewSession()
defer session.Close()
Check(err)
var user_id bytes.Buffer
session.Stdout = &user_id
if session.Run("id") != nil {
if ContainsAny(user_id.String(), []string{"uid=0", "gid=0", "root"}) {
uid0_session = true
}
}
return uid0_session
}