aboutsummaryrefslogtreecommitdiff
path: root/internal/exec/wmi/exec.go
blob: b61bf5ced490760e34abfef19ef617a3f6f3693b (plain)
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
package wmiexec

import (
  "context"
  "encoding/json"
  "errors"
  "fmt"
  "github.com/FalconOpsLLC/goexec/internal/client/dce"
  "github.com/FalconOpsLLC/goexec/internal/exec"
  "github.com/RedTeamPentesting/adauth"
  "github.com/RedTeamPentesting/adauth/dcerpcauth"
  "github.com/oiweiwei/go-msrpc/dcerpc"
  "github.com/oiweiwei/go-msrpc/msrpc/dcom"
  "github.com/oiweiwei/go-msrpc/msrpc/dcom/iactivation/v0"
  "github.com/oiweiwei/go-msrpc/msrpc/dcom/wmi"
  "github.com/oiweiwei/go-msrpc/msrpc/dcom/wmi/iwbemlevel1login/v0"
  "github.com/oiweiwei/go-msrpc/msrpc/dcom/wmi/iwbemservices/v0"
  "github.com/oiweiwei/go-msrpc/ssp/gssapi"
  "github.com/rs/zerolog"
)

const (
  ProtocolSequenceRPC uint16 = 7
  ProtocolSequenceNP  uint16 = 15
  DefaultWmiEndpoint  string = "ncacn_ip_tcp:[135]"
)

var (
  ComVersion = &dcom.COMVersion{
    MajorVersion: 5,
    MinorVersion: 7,
  }
  ORPCThis = &dcom.ORPCThis{Version: ComVersion}
)

func (mod *Module) Cleanup(ctx context.Context, _ *exec.CleanupConfig) (err error) {

  log := zerolog.Ctx(ctx).With().
    Str("module", "tsch").
    Str("func", "Cleanup").Logger()

  if err = mod.dce.Close(ctx); err != nil {
    log.Warn().Err(err).Msg("Failed to close DCERPC connection")
  }
  mod.sc = nil
  mod.dce = nil
  return
}

func (mod *Module) Connect(ctx context.Context, creds *adauth.Credential, target *adauth.Target, ccfg *exec.ConnectionConfig) (err error) {

  log := zerolog.Ctx(ctx).With().
    Str("method", ccfg.ConnectionMethod).
    Str("func", "Connect").Logger()

  if cfg, ok := ccfg.ConnectionMethodConfig.(dce.ConnectionMethodDCEConfig); !ok {
    return errors.New("invalid configuration for DCE connection method")
  } else {
    var dceOpts []dcerpc.Option

    // Create DCE connection
    if mod.dce, err = cfg.GetDce(ctx, creds, target, DefaultWmiEndpoint, "", dceOpts...); err != nil {
      log.Error().Err(err).Msg("Failed to initialize DCE dialer")
      return fmt.Errorf("create DCE dialer: %w", err)
    }
    ia, err := iactivation.NewActivationClient(ctx, mod.dce)
    if err != nil {
      log.Error().Err(err).Msg("Failed to create activation client")
      return fmt.Errorf("create activation client: %w", err)
    }
    act, err := ia.RemoteActivation(ctx, &iactivation.RemoteActivationRequest{
      ORPCThis:                   ORPCThis,
      ClassID:                    wmi.Level1LoginClassID.GUID(),
      IIDs:                       []*dcom.IID{iwbemlevel1login.Level1LoginIID},
      RequestedProtocolSequences: []uint16{ProtocolSequenceRPC, ProtocolSequenceNP}, // TODO: dynamic
    })
    if err != nil {
      return fmt.Errorf("request remote activation: %w", err)
    }
    if act.HResult != 0 {
      return fmt.Errorf("remote activation failed with code %d", act.HResult)
    }
    retBinds := act.OXIDBindings.GetStringBindings()
    if len(act.InterfaceData) < 1 || len(retBinds) < 1 {
      return errors.New("remote activation failed")
    }
    ipid := act.InterfaceData[0].GetStandardObjectReference().Std.IPID
    for _, sb := range retBinds {
      //sb.NetworkAddr = target.AddressWithoutPort() // TODO: check if sb.NetworkAddr contains the port
      dceOpts = append(dceOpts, dcerpc.WithEndpoint(sb.String()))
    }

    if mod.dce, err = cfg.GetDce(ctx, creds, target, DefaultWmiEndpoint, "", dceOpts...); err != nil {
      log.Error().Err(err).Msg("Failed to initialize secondary DCE dialer")
    }
    loginClient, err := iwbemlevel1login.NewLevel1LoginClient(ctx, mod.dce, dcom.WithIPID(ipid))
    if err != nil {
      return fmt.Errorf("initialize wbem login client: %w", err)
    }
    login, err := loginClient.NTLMLogin(ctx, &iwbemlevel1login.NTLMLoginRequest{
      This:            ORPCThis,
      NetworkResource: "//./root/cimv2", // TODO: make this dynamic
    })
    if err != nil {
      return fmt.Errorf("ntlm login: %w", err)
    }

    mod.sc, err = iwbemservices.NewServicesClient(ctx, mod.dce, dcom.WithIPID(login.Namespace.InterfacePointer().IPID()))
    if err != nil {
      return fmt.Errorf("iwbemservices.NewServicesClient: %w", err)
    }
  }

  return
}

func (mod *Module) _Connect(ctx context.Context, creds *adauth.Credential, target *adauth.Target, _ *exec.ConnectionConfig) (err error) {

  var baseOpts, authOpts []dcerpc.Option
  var ipid *dcom.IPID // This will store the IPID of the remote instance
  var bind2Opts []dcerpc.Option

  ctx = gssapi.NewSecurityContext(ctx)
  log := zerolog.Ctx(ctx).With().
    Str("module", "tsch").
    Str("func", "Connect").Logger()

  // Assemble DCERPC options
  {
    baseOpts = []dcerpc.Option{
      dcerpc.WithLogger(log),
      dcerpc.WithSign(), // Enforce signing
      dcerpc.WithSeal(), // Enforce packet stub encryption
    }
    // Add target name option if possible
    if tn, err := target.Hostname(ctx); err == nil {
      baseOpts = append(baseOpts, dcerpc.WithTargetName(tn))
    } else {
      log.Debug().Err(err).Msg("Failed to get target hostname")
    }
    // Parse target and credentials
    if authOpts, err = dcerpcauth.AuthenticationOptions(ctx, creds, target, &dcerpcauth.Options{}); err != nil {
      return fmt.Errorf("parse authentication options: %w", err)
    }
  }

  // Establish first connection (REMACT)
  {
    // Connection options
    rp := "ncacn_ip_tcp"                 // Underlying protocol
    ro := 135                            // RPC port
    rb := fmt.Sprintf("%s:[%d]", rp, ro) // RPC binding

    // Create DCERPC dialer
    mod.dce, err = dcerpc.Dial(ctx, target.AddressWithoutPort(), append(baseOpts, append(authOpts, dcerpc.WithEndpoint(rb))...)...)
    if err != nil {
      return fmt.Errorf("create DCERPC dialer: %w", err)
    }
    // Create remote activation client
    ia, err := iactivation.NewActivationClient(ctx, mod.dce, append(baseOpts, dcerpc.WithEndpoint(rb))...)
    if err != nil {
      return fmt.Errorf("create activation client: %w", err)
    }
    // Send remote activation request
    act, err := ia.RemoteActivation(ctx, &iactivation.RemoteActivationRequest{
      ORPCThis:                   ORPCThis,
      ClassID:                    wmi.Level1LoginClassID.GUID(),
      IIDs:                       []*dcom.IID{iwbemlevel1login.Level1LoginIID},
      RequestedProtocolSequences: []uint16{ProtocolSequenceRPC, ProtocolSequenceNP}, // TODO: dynamic
    })
    if err != nil {
      return fmt.Errorf("request remote activation: %w", err)
    }
    if act.HResult != 0 {
      return fmt.Errorf("remote activation failed with code %d", act.HResult)
    }
    retBinds := act.OXIDBindings.GetStringBindings()
    if len(act.InterfaceData) < 1 || len(retBinds) < 1 {
      return errors.New("remote activation failed")
    }
    ipid = act.InterfaceData[0].GetStandardObjectReference().Std.IPID

    // This ensures that the original target address/hostname is used in the string binding
    origBind := retBinds[0].String()
    if bind, err := dcerpc.ParseStringBinding(origBind); err != nil {
      log.Warn().Str("binding", origBind).Err(err).Msg("Failed to parse binding string returned by server")
      bind2Opts = act.OXIDBindings.EndpointsByProtocol(rp) // Try using the server supplied string binding
    } else {
      bind.NetworkAddress = target.AddressWithoutPort() // Replace address/hostname in new string binding
      bs := bind.String()
      log.Info().Str("binding", bs).Msg("found binding")
      bind2Opts = append(bind2Opts, dcerpc.WithEndpoint(bs)) // Use the new string binding
    }
  }

  // Establish second connection (WMI)
  {
    bind2Opts = append(bind2Opts, authOpts...)
    mod.dce, err = dcerpc.Dial(ctx, target.AddressWithoutPort(), append(baseOpts, bind2Opts...)...)
    if err != nil {
      return fmt.Errorf("dial WMI: %w", err)
    }
    // Create login client
    loginClient, err := iwbemlevel1login.NewLevel1LoginClient(ctx, mod.dce, append(baseOpts, dcom.WithIPID(ipid))...)
    if err != nil {
      return fmt.Errorf("initialize wbem login client: %w", err)
    }
    login, err := loginClient.NTLMLogin(ctx, &iwbemlevel1login.NTLMLoginRequest{ // TODO: Other login opts/methods?
      This:            ORPCThis,
      NetworkResource: "//./root/cimv2", // TODO: make this dynamic
    })
    if err != nil {
      return fmt.Errorf("ntlm login: %w", err)
    }

    mod.sc, err = iwbemservices.NewServicesClient(ctx, mod.dce, dcom.WithIPID(login.Namespace.InterfacePointer().IPID()))
    if err != nil {
      return fmt.Errorf("iwbemservices.NewServicesClient: %w", err)
    }
  }
  return nil
}

func (mod *Module) Exec(ctx context.Context, ecfg *exec.ExecutionConfig) (err error) {
  log := zerolog.Ctx(ctx).With().
    Str("module", "tsch").
    Str("method", ecfg.ExecutionMethod).Logger()

  if ecfg.ExecutionMethod == MethodCall {
    if cfg, ok := ecfg.ExecutionMethodConfig.(MethodCallConfig); !ok {
      return errors.New("invalid execution configuration")

    } else {
      out, err := mod.query(ctx, cfg.Class, cfg.Method, cfg.Arguments)
      if err != nil {
        return fmt.Errorf("query: %w", err)
      }
      if outJson, err := json.Marshal(out); err != nil {
        log.Error().Err(err).Msg("failed to marshal call output")
      } else {
        fmt.Println(string(outJson))
      }
    }
  } else if ecfg.ExecutionMethod == MethodProcess {
    if cfg, ok := ecfg.ExecutionMethodConfig.(MethodProcessConfig); !ok {
      return errors.New("invalid execution configuration")
    } else {
      out, err := mod.query(ctx, "Win32_Process", "Create", map[string]any{
        "CommandLine": cfg.Command,
        "WorkingDir":  cfg.WorkingDirectory,
      })
      if err != nil {
        return fmt.Errorf("query: %w", err)
      }
      if pid, ok := out["ProcessId"]; ok && pid != nil {
        log.Info().
          Any("PID", pid).
          Any("return", out["ReturnValue"]).
          Msg("Process created")
      } else {
        log.Error().
          Any("return", out["ReturnValue"]).
          Msg("Process creation failed")
        return errors.New("failed to create process")
      }
    }
  } else {
    return errors.New("unsupported execution method")
  }
  return nil
}