|
| 1 | +package simulator |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "math/rand" |
| 6 | + "net" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +// generateRandomData genereates n random bytes. |
| 11 | +// TODO: this method should be moved to utils along with all the other use cases of generating random data |
| 12 | +func generateRandomData(n int) []byte { |
| 13 | + src := rand.NewSource(time.Now().Unix()) |
| 14 | + r := rand.New(src) |
| 15 | + buffer := make([]byte, n) |
| 16 | + _, _ = r.Read(buffer) |
| 17 | + return buffer |
| 18 | +} |
| 19 | + |
| 20 | +// CleartextProtocolSimulator simulates cleartext protocol traffic |
| 21 | +type CleartextProtocolSimulator struct { |
| 22 | + bind BindAddr |
| 23 | + data []byte |
| 24 | +} |
| 25 | + |
| 26 | +// NewCleartextProtocolSimulator creates new instance of CleartextProtocolSimulator |
| 27 | +func NewCleartextProtocolSimulator() *CleartextProtocolSimulator { |
| 28 | + return &CleartextProtocolSimulator{} |
| 29 | +} |
| 30 | + |
| 31 | +func (cps *CleartextProtocolSimulator) Init(bind BindAddr) error { |
| 32 | + cps.bind = bind |
| 33 | + |
| 34 | + // random bytes are generated in Init because it's not necessary |
| 35 | + // to generate them everytime Simulate method is run |
| 36 | + data := generateRandomData(1000) |
| 37 | + |
| 38 | + cps.data = data |
| 39 | + |
| 40 | + return nil |
| 41 | +} |
| 42 | + |
| 43 | +func (CleartextProtocolSimulator) Cleanup() { |
| 44 | + |
| 45 | +} |
| 46 | + |
| 47 | +// Simulate cleartext protocol traffic |
| 48 | +func (cps *CleartextProtocolSimulator) Simulate(ctx context.Context, dst string) error { |
| 49 | + d := &net.Dialer{LocalAddr: &net.TCPAddr{IP: cps.bind.Addr}} |
| 50 | + conn, err := d.DialContext(ctx, "tcp", dst) |
| 51 | + |
| 52 | + if err != nil { |
| 53 | + return err |
| 54 | + } |
| 55 | + defer conn.Close() |
| 56 | + |
| 57 | + if _, err = conn.Write(cps.data); err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + if _, err = conn.Read(nil); err != nil { |
| 62 | + return err |
| 63 | + } |
| 64 | + |
| 65 | + return nil |
| 66 | +} |
| 67 | + |
| 68 | +// Hosts returns IP:port pairs used to connect to AlphaSOC sandbox |
| 69 | +func (cps *CleartextProtocolSimulator) Hosts(scope string, size int) ([]string, error) { |
| 70 | + var hosts []string |
| 71 | + |
| 72 | + ports := []string{"21", "23", "110", "143", "873"} |
| 73 | + |
| 74 | + ips, err := net.LookupIP("cleartext.sandbox-services.alphasoc.xyz") |
| 75 | + |
| 76 | + if err != nil { |
| 77 | + return nil, err |
| 78 | + } |
| 79 | + |
| 80 | + // take the first IP address returned by LookupIP |
| 81 | + targetIP := ips[0].String() |
| 82 | + |
| 83 | + for i := 0; i < len(ports) && i < size; i++ { |
| 84 | + hosts = append(hosts, net.JoinHostPort(targetIP, ports[i])) |
| 85 | + } |
| 86 | + |
| 87 | + return hosts, nil |
| 88 | +} |
0 commit comments