github.com/iDigitalFlame/xmt@v0.5.4/c2/listener.go (about)

     1  //go:build !implant
     2  // +build !implant
     3  
     4  // Copyright (C) 2020 - 2023 iDigitalFlame
     5  //
     6  // This program is free software: you can redistribute it and/or modify
     7  // it under the terms of the GNU General Public License as published by
     8  // the Free Software Foundation, either version 3 of the License, or
     9  // any later version.
    10  //
    11  // This program is distributed in the hope that it will be useful,
    12  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  // GNU General Public License for more details.
    15  //
    16  // You should have received a copy of the GNU General Public License
    17  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    18  //
    19  
    20  package c2
    21  
    22  import (
    23  	"context"
    24  	"io"
    25  	"net"
    26  	"time"
    27  
    28  	"github.com/iDigitalFlame/xmt/c2/cfg"
    29  	"github.com/iDigitalFlame/xmt/c2/cout"
    30  	"github.com/iDigitalFlame/xmt/com"
    31  	"github.com/iDigitalFlame/xmt/data"
    32  	"github.com/iDigitalFlame/xmt/util/bugtrack"
    33  	"github.com/iDigitalFlame/xmt/util/xerr"
    34  )
    35  
    36  var _ connServer = (*Listener)(nil)
    37  
    38  // Listener is a struct that is passed back when a C2 Listener is added to the
    39  // Server.
    40  //
    41  // The Listener struct allows for controlling the Listener and setting callback
    42  // functions to be used when a client connects, registers or disconnects.
    43  type Listener struct {
    44  	listener net.Listener
    45  	connection
    46  
    47  	ch     chan struct{}
    48  	cancel context.CancelFunc
    49  	name   string
    50  	state  state
    51  }
    52  
    53  // Wait will block until the current socket associated with this Listener is
    54  // closed and shutdown.
    55  func (l *Listener) Wait() {
    56  	<-l.ch
    57  }
    58  func (l *Listener) listen() {
    59  	if bugtrack.Enabled {
    60  		defer bugtrack.Recover("c2.Listener.listen()")
    61  	}
    62  	if cout.Enabled {
    63  		l.log.Info(`[%s] Starting Listener "%s"..`, l.name, l.listener)
    64  	}
    65  	for {
    66  		select {
    67  		case <-l.ctx.Done():
    68  			l.state.Set(stateClosing)
    69  		default:
    70  		}
    71  		if l.state.Closing() {
    72  			break
    73  		}
    74  		if l.listener == nil && l.state.Replacing() {
    75  			time.Sleep(time.Millisecond * 30) // Prevent CPU buring loops.
    76  			continue
    77  		}
    78  		c, err := l.listener.Accept()
    79  		if err != nil {
    80  			if l.state.Replacing() {
    81  				continue
    82  			}
    83  			if l.state.Closing() {
    84  				break
    85  			}
    86  			if isClosedError(err) {
    87  				// NOTE(dij): Catch the socket being replaced, this should
    88  				//            only happen when replacement occurs, if we ARE
    89  				//            closing or the ctx was canceled, continue and
    90  				//            that /should/ be hit at the top of the loop.
    91  				continue
    92  			}
    93  			e, ok := err.(net.Error)
    94  			if ok && e.Timeout() {
    95  				continue
    96  			}
    97  			if cout.Enabled {
    98  				l.log.Error("[%s] Error during Listener accept: %s!", l.name, err.Error())
    99  			}
   100  			if ok && !e.Timeout() {
   101  				break
   102  			}
   103  			continue
   104  		}
   105  		if c == nil {
   106  			continue
   107  		}
   108  		if cout.Enabled {
   109  			l.log.Trace(`[%s] Received a connection from "%s"..`, l.name, c.RemoteAddr().String())
   110  		}
   111  		go handle(l.log, c, l, c.RemoteAddr().String())
   112  	}
   113  	if cout.Enabled {
   114  		l.log.Debug("[%s] Stopping Listener.", l.name)
   115  	}
   116  	if l.cancel(); !l.state.WakeClosed() {
   117  		l.state.Set(stateWakeClose)
   118  	}
   119  	if l.listener != nil {
   120  		l.listener.Close()
   121  	}
   122  	l.s.delListener <- l.name
   123  	l.state.Set(stateClosed)
   124  	close(l.ch)
   125  }
   126  func (l *Listener) clientLock() {
   127  	l.s.lock.RLock()
   128  }
   129  
   130  // Close stops the operation of the Listener and any Sessions that may be
   131  // connected.
   132  //
   133  // Resources used with this Listener will be freed up for reuse. This function
   134  // blocks until the listener socket is closed.
   135  func (l *Listener) Close() error {
   136  	if l.state.Closed() {
   137  		return nil
   138  	}
   139  	l.state.Set(stateClosing)
   140  	l.cancel()
   141  	var err error
   142  	if !l.state.Replacing() {
   143  		err = l.listener.Close()
   144  	}
   145  	<-l.ch
   146  	return err
   147  }
   148  func (l *Listener) clientUnlock() {
   149  	l.s.lock.RUnlock()
   150  }
   151  
   152  // IsActive returns true if the Listener is still able to send and receive
   153  // Packets.
   154  func (l *Listener) IsActive() bool {
   155  	return !l.state.Closing()
   156  }
   157  func (l *Listener) prefix() string {
   158  	return l.name
   159  }
   160  
   161  // String returns the Name of this Listener.
   162  func (l *Listener) String() string {
   163  	return l.name
   164  }
   165  
   166  // Address returns the string representation of the address the Listener is
   167  // bound to.
   168  func (l *Listener) Address() string {
   169  	if l.listener == nil {
   170  		return ""
   171  	}
   172  	return l.listener.Addr().String()
   173  }
   174  func (l *Listener) wrapper() cfg.Wrapper {
   175  	return l.w
   176  }
   177  func (l *Listener) clientClear(i uint32) {
   178  	v, ok := l.s.sessions[i]
   179  	if !ok {
   180  		return
   181  	}
   182  	v.chn = nil
   183  	v.state.Unset(stateChannelProxy)
   184  }
   185  
   186  // Done returns a channel that's closed when this Listener is closed.
   187  //
   188  // This can be used to monitor a Listener's status using a select statement.
   189  func (l *Listener) Done() <-chan struct{} {
   190  	return l.ch
   191  }
   192  func (l *Listener) keyValue() data.KeyPair {
   193  	return l.s.Keys
   194  }
   195  func (l *Listener) transform() cfg.Transform {
   196  	return l.t
   197  }
   198  func (l *Listener) clientGet(i uint32) (connHost, bool) {
   199  	s, ok := l.s.sessions[i]
   200  	return s, ok
   201  }
   202  func (l *Listener) clientSet(i uint32, c chan *com.Packet) {
   203  	v, ok := l.s.sessions[i]
   204  	if !ok {
   205  		return
   206  	}
   207  	if v.chn != nil {
   208  		return
   209  	}
   210  	v.state.Set(stateChannelProxy)
   211  	for v.chn = c; len(v.send) > 0; {
   212  		select {
   213  		case c <- <-v.send:
   214  		default:
   215  		}
   216  	}
   217  }
   218  func (l *Listener) notify(h connHost, n *com.Packet) error {
   219  	if h == nil {
   220  		return receive(nil, l, n)
   221  	}
   222  	s, ok := h.(*Session)
   223  	if !ok {
   224  		return nil
   225  	}
   226  	// KeyCrypt: Process new Packet here instead.
   227  	//           Fire if key is set in here for exchange.
   228  	s.keyCryptAndUpdate(l.name, n, false)
   229  	return receive(s, l, n)
   230  }
   231  
   232  // Replace allows for rebinding this Listener to another address or using
   233  // another Profile without closing the Listener.
   234  //
   235  // If the provided Profile is nil, the Listener will not change its profile.
   236  //
   237  // The listening socket will be closed and the Listener will be paused and
   238  // cannot accept any more connections before being reopened.
   239  //
   240  // If the replacement fails, the Listener will be closed.
   241  func (l *Listener) Replace(addr string, p cfg.Profile) error {
   242  	if p == nil {
   243  		p = l.p
   244  	}
   245  	h, w, t := p.Next()
   246  	if len(addr) > 0 {
   247  		h = addr
   248  	}
   249  	if len(h) == 0 {
   250  		return ErrNoHost
   251  	}
   252  	l.state.Set(stateReplacing)
   253  	l.listener.Close()
   254  	l.listener = nil
   255  	v, err := p.Listen(l.ctx, h)
   256  	if err != nil {
   257  		l.Close()
   258  		return xerr.Wrap("unable to listen", err)
   259  	} else if v == nil {
   260  		l.Close()
   261  		return xerr.Sub("unable to listen", 0x49)
   262  	}
   263  	l.listener, l.w, l.t, l.p = v, w, t, p
   264  	if l.state.Unset(stateReplacing); cout.Enabled {
   265  		l.log.Info(`[%s] Replaced listener socket, now bound to "%s"!`, l.name, h)
   266  	}
   267  	return nil
   268  }
   269  func (l *Listener) talk(a string, n *com.Packet) (*conn, bool, error) {
   270  	if n.Device.Empty() || l.state.Closing() {
   271  		return nil, false, io.ErrClosedPipe
   272  	}
   273  	if cout.Enabled {
   274  		l.log.Trace(`[%s:%s] %s: Received a Packet "%s"..`, l.name, n.Device, a, n)
   275  	}
   276  	l.s.lock.RLock()
   277  	var (
   278  		i     = n.Device.Hash()
   279  		s, ok = l.s.sessions[i]
   280  	)
   281  	if l.s.lock.RUnlock(); !ok {
   282  		if n.Empty() && n.ID == SvHello {
   283  			if cout.Enabled {
   284  				l.log.Error("[%s:%s] %s: Received an empty hello Packet!", l.name, n.Device, a)
   285  			}
   286  			return nil, false, ErrMalformedPacket
   287  		}
   288  		if n.ID != SvHello {
   289  			if cout.Enabled {
   290  				l.log.Warning("[%s:%s] %s: Received a non-hello Packet from a unregistered client!", l.name, n.Device, a)
   291  			}
   292  			var f com.Flag
   293  			if n.Flags&com.FlagFrag != 0 {
   294  				f.SetPosition(0)
   295  				f.SetLen(n.Flags.Len())
   296  				f.SetGroup(n.Flags.Group())
   297  			}
   298  			return &conn{next: &com.Packet{ID: SvRegister, Flags: f, Device: n.Device}}, false, nil
   299  		}
   300  		s = &Session{
   301  			ch:         make(chan struct{}),
   302  			ID:         n.Device,
   303  			jobs:       make(map[uint16]*Job),
   304  			send:       make(chan *com.Packet, 128),
   305  			wake:       make(chan struct{}, 1),
   306  			frags:      make(map[uint16]*cluster),
   307  			parent:     l,
   308  			Created:    time.Now(),
   309  			connection: connection{s: l.s, m: l.m, log: l.log, ctx: l.ctx},
   310  		}
   311  		if l.state.CanRecv() {
   312  			s.recv = make(chan *com.Packet, 128)
   313  		}
   314  		var err error
   315  		if s.proxies, err = s.readDeviceInfo(infoHello, n); err != nil {
   316  			if cout.Enabled {
   317  				l.log.Error("[%s:%s] %s: Error reading data from client: %s!", l.name, s.ID, a, err.Error())
   318  			}
   319  			return nil, false, err
   320  		}
   321  		// KeyCrypt: If client has indicated that they have a Key, generate
   322  		//           the set from the key data passed.
   323  		if s.keyListenerInit(l.s.Keys.Private, l.name, n); cout.Enabled {
   324  			l.log.Debug("[%s:%s] %s: Received client device info: (OS: %s, %s).", l.name, s.ID, a, s.Device.OS(), s.Device.Version)
   325  		}
   326  		l.s.lock.Lock()
   327  		l.s.sessions[i] = s
   328  		if l.s.lock.Unlock(); cout.Enabled {
   329  			l.log.Info(`[%s:%s] %s: New client registered as "%s" (0x%X).`, l.name, s.ID, a, s.ID, i)
   330  		}
   331  	}
   332  	if s.host.Set(a); ok && s.parent != l {
   333  		s.parent = l
   334  	}
   335  	if s.Last = time.Now(); !ok {
   336  		if n.Flags&com.FlagProxy == 0 {
   337  			s.write(true, keyHostSync(l, n))
   338  		}
   339  		if l.s.New != nil {
   340  			l.m.queue(event{s: s, sf: l.s.New})
   341  		}
   342  	}
   343  	c, err := l.resolve(s, a, n.Tags)
   344  	if err != nil {
   345  		return nil, false, err
   346  	}
   347  	// KeyCrypt: Decrypt Incoming Packet (only if non-new)
   348  	if ok {
   349  		s.keyCryptAndUpdate(l.name, n, true)
   350  	}
   351  	if err = c.process(l.log, l, a, n, false); err != nil {
   352  		return nil, false, err
   353  	}
   354  	return c, ok, nil
   355  }
   356  func (l *Listener) resolve(s *Session, a string, t []uint32) (*conn, error) {
   357  	if len(t) == 0 {
   358  		return &conn{host: s, keys: s.keys}, nil
   359  	}
   360  	c := &conn{
   361  		add:  make([]*com.Packet, 0, len(t)),
   362  		subs: make(map[uint32]bool, len(t)),
   363  		host: s,
   364  		keys: s.keys,
   365  	}
   366  	return c, c.resolve(l.log, s, l, a, t, false)
   367  }
   368  func (l *Listener) talkSub(a string, n *com.Packet, o bool) (connHost, uint32, *com.Packet, error) {
   369  	if n.Device.Empty() || l.state.Closing() {
   370  		return nil, 0, nil, io.ErrShortBuffer
   371  	}
   372  	if cout.Enabled {
   373  		l.log.Trace(`[%s:%s/M] %s: Received a Packet "%s"..`, l.name, n.Device, a, n)
   374  	}
   375  	l.s.lock.RLock()
   376  	var (
   377  		i     = n.Device.Hash()
   378  		s, ok = l.s.sessions[i]
   379  	)
   380  	if l.s.lock.RUnlock(); !ok {
   381  		if n.ID != SvHello {
   382  			if cout.Enabled {
   383  				l.log.Warning("[%s:%s/M] %s: Received a non-hello Packet from a unregistered client!", l.name, n.Device, a)
   384  			}
   385  			var f com.Flag
   386  			if n.Flags&com.FlagFrag != 0 {
   387  				f.SetPosition(0)
   388  				f.SetLen(n.Flags.Len())
   389  				f.SetGroup(n.Flags.Group())
   390  			}
   391  			return nil, 0, &com.Packet{ID: SvRegister, Flags: f, Device: n.Device}, nil
   392  		}
   393  		s = &Session{
   394  			ch:         make(chan struct{}),
   395  			ID:         n.Device,
   396  			jobs:       make(map[uint16]*Job),
   397  			send:       make(chan *com.Packet, 128),
   398  			wake:       make(chan struct{}, 1),
   399  			frags:      make(map[uint16]*cluster),
   400  			parent:     l,
   401  			Created:    time.Now(),
   402  			connection: connection{s: l.s, m: l.m, log: l.log, ctx: l.ctx},
   403  		}
   404  		if l.state.CanRecv() {
   405  			s.recv = make(chan *com.Packet, 128)
   406  		}
   407  		var err error
   408  		if s.proxies, err = s.readDeviceInfo(infoHello, n); err != nil {
   409  			if cout.Enabled {
   410  				l.log.Error("[%s:%s/M] %s: Error reading data from client: %s!", l.name, s.ID, a, err.Error())
   411  			}
   412  			return nil, 0, nil, err
   413  		}
   414  		// KeyCrypt: If client has indicated that they have a Key, generate
   415  		//           the set from the key data passed.
   416  		if s.keyListenerInit(l.s.Keys.Private, l.name, n); cout.Enabled {
   417  			l.log.Debug("[%s:%s/M] %s: Received client device info: (OS: %s, %s).", l.name, s.ID, a, s.Device.OS(), s.Device.Version)
   418  		}
   419  		l.s.lock.Lock()
   420  		l.s.sessions[i] = s
   421  		if l.s.lock.Unlock(); cout.Enabled {
   422  			l.log.Info(`[%s:%s/M] %s: New client registered as "%s" (0x%X).`, l.name, s.ID, a, s.ID, i)
   423  		}
   424  	}
   425  	s.host.Set(a)
   426  	if s.Last = time.Now(); !ok {
   427  		if n.Flags&com.FlagProxy == 0 {
   428  			s.write(true, keyHostSync(l, n))
   429  		}
   430  		if l.s.New != nil {
   431  			l.m.queue(event{s: s, sf: l.s.New})
   432  		}
   433  	}
   434  	// KeyCrypt: Decrypt Incoming Packet (only if non-new)
   435  	if ok {
   436  		s.keyCryptAndUpdate(l.name, n, true)
   437  	}
   438  	if err := receive(s, l, n); err != nil {
   439  		if cout.Enabled {
   440  			l.log.Error("[%s:%s/M] %s: Error processing Packet: %s!", l.name, s.ID, a, err.Error())
   441  		}
   442  		return nil, 0, nil, err
   443  	}
   444  	if o {
   445  		return s, i, nil, nil
   446  	}
   447  	z := s.next(true)
   448  	if z != nil {
   449  		// KeyCrypt: Encrypt this new Packet and check for key changes.
   450  		z.KeyCrypt(s.keys)
   451  		s.keyCheckSync()
   452  	}
   453  	return s, i, z, nil
   454  }