File size: 11,016 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Eventing;
using System.Diagnostics.Eventing.Reader;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Resources;
using System.Xml;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// Class that implements the New-WinEvent cmdlet.
    /// This cmdlet writes a new Etw event using the provider specified in parameter.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "WinEvent", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096808")]
    public sealed class NewWinEventCommand : PSCmdlet
    {
        private ProviderMetadata _providerMetadata;
        private EventDescriptor? _eventDescriptor;

        private const string TemplateTag = "template";
        private const string DataTag = "data";

        private readonly ResourceManager _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager();

        /// <summary>
        /// ProviderName.
        /// </summary>
        [Parameter(
            Position = 0,
            Mandatory = true,
            ParameterSetName = ParameterAttribute.AllParameterSets)]
        public string ProviderName { get; set; }

        /// <summary>
        /// Id (EventId defined in manifest file)
        /// </summary>
        [Parameter(
            Position = 1,
            Mandatory = true,
            ParameterSetName = ParameterAttribute.AllParameterSets)]
        public int Id
        {
            get
            {
                return _id;
            }

            set
            {
                _id = value;
                _idSpecified = true;
            }
        }

        private int _id;
        private bool _idSpecified = false;

        /// <summary>
        /// Version (event version)
        /// </summary>
        [Parameter(
            Mandatory = false,
            ParameterSetName = ParameterAttribute.AllParameterSets)]
        public byte Version
        {
            get
            {
                return _version;
            }

            set
            {
                _version = value;
                _versionSpecified = true;
            }
        }

        private byte _version;
        private bool _versionSpecified = false;

        /// <summary>
        /// Event Payload.
        /// </summary>
        [Parameter(
            Position = 2,
            Mandatory = false,
            ParameterSetName = ParameterAttribute.AllParameterSets),
        AllowEmptyCollection,
        SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
            Target = "Microsoft.PowerShell.Commands",
            Justification = "A string[] is required here because that is the type Powershell supports")]
        public object[] Payload { get; set; }

        /// <summary>
        /// BeginProcessing.
        /// </summary>
        protected override void BeginProcessing()
        {
            LoadProvider();
            LoadEventDescriptor();

            base.BeginProcessing();
        }

        private void LoadProvider()
        {
            if (string.IsNullOrEmpty(ProviderName))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderNotSpecified")), "ProviderName");
            }

            using (EventLogSession session = new())
            {
                foreach (string providerName in session.GetProviderNames())
                {
                    if (string.Equals(providerName, ProviderName, StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            _providerMetadata = new ProviderMetadata(providerName);
                        }
                        catch (EventLogException exc)
                        {
                            string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderMetadataUnavailable"), providerName, exc.Message);
                            throw new Exception(msg, exc);
                        }

                        break;
                    }
                }
            }

            if (_providerMetadata == null)
            {
                string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), ProviderName);
                throw new ArgumentException(msg);
            }
        }

        private void LoadEventDescriptor()
        {
            if (_idSpecified)
            {
                List<EventMetadata> matchedEvents = new();
                foreach (EventMetadata emd in _providerMetadata.Events)
                {
                    if (emd.Id == _id)
                    {
                        matchedEvents.Add(emd);
                    }
                }

                if (matchedEvents.Count == 0)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture,
                        _resourceMgr.GetString("IncorrectEventId"),
                        _id,
                        ProviderName);
                    throw new EventWriteException(msg);
                }

                EventMetadata matchedEvent = null;
                if (!_versionSpecified && matchedEvents.Count == 1)
                {
                    matchedEvent = matchedEvents[0];
                }
                else
                {
                    if (_versionSpecified)
                    {
                        foreach (EventMetadata emd in matchedEvents)
                        {
                            if (emd.Version == _version)
                            {
                                matchedEvent = emd;
                                break;
                            }
                        }

                        if (matchedEvent == null)
                        {
                            string msg = string.Format(CultureInfo.InvariantCulture,
                                _resourceMgr.GetString("IncorrectEventVersion"),
                                _version,
                                _id,
                                ProviderName);

                            throw new EventWriteException(msg);
                        }
                    }
                    else
                    {
                        string msg = string.Format(CultureInfo.InvariantCulture,
                            _resourceMgr.GetString("VersionNotSpecified"),
                            _id,
                            ProviderName);

                        throw new EventWriteException(msg);
                    }
                }

                VerifyTemplate(matchedEvent);
                _eventDescriptor = CreateEventDescriptor(_providerMetadata, matchedEvent);
            }
            else
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("EventIdNotSpecified")), "Id");
            }
        }

        private bool VerifyTemplate(EventMetadata emd)
        {
            if (emd.Template != null)
            {
                XmlReaderSettings readerSettings = new()
                {
                    CheckCharacters = false,
                    IgnoreComments = true,
                    IgnoreProcessingInstructions = true,
                    MaxCharactersInDocument = 0, // no limit
                    ConformanceLevel = ConformanceLevel.Fragment,
                    XmlResolver = null
                };

                int definedParameterCount = 0;
                using (XmlReader reader = XmlReader.Create(new StringReader(emd.Template), readerSettings))
                {
                    if (reader.ReadToFollowing(TemplateTag))
                    {
                        bool found = reader.ReadToDescendant(DataTag);
                        while (found)
                        {
                            definedParameterCount++;
                            found = reader.ReadToFollowing(DataTag);
                        }
                    }
                }

                if ((Payload == null && definedParameterCount != 0)
                    || ((Payload != null) && Payload.Length != definedParameterCount))
                {
                    string warning = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("PayloadMismatch"), _id, emd.Template);
                    WriteWarning(warning);

                    return false;
                }
            }

            return true;
        }

        private static EventDescriptor CreateEventDescriptor(ProviderMetadata providerMetaData, EventMetadata emd)
        {
            long keywords = 0;
            foreach (EventKeyword keyword in emd.Keywords)
            {
                keywords |= keyword.Value;
            }

            byte channel = 0;
            foreach (EventLogLink logLink in providerMetaData.LogLinks)
            {
                if (string.Equals(logLink.LogName, emd.LogLink.LogName, StringComparison.OrdinalIgnoreCase))
                    break;
                channel++;
            }

            return new EventDescriptor(
                (int)emd.Id,
                emd.Version,
                channel,
                (byte)emd.Level.Value,
                (byte)emd.Opcode.Value,
                emd.Task.Value,
                keywords);
        }

        /// <summary>
        /// ProcessRecord.
        /// </summary>
        protected override void ProcessRecord()
        {
            using (EventProvider provider = new(_providerMetadata.Id))
            {
                EventDescriptor ed = _eventDescriptor.Value;

                if (Payload != null && Payload.Length > 0)
                {
                    for (int i = 0; i < Payload.Length; i++)
                    {
                        if (Payload[i] == null)
                        {
                            Payload[i] = string.Empty;
                        }
                    }

                    provider.WriteEvent(in ed, Payload);
                }
                else
                {
                    provider.WriteEvent(in ed);
                }
            }

            base.ProcessRecord();
        }

        /// <summary>
        /// EndProcessing.
        /// </summary>
        protected override void EndProcessing()
        {
            _providerMetadata?.Dispose();

            base.EndProcessing();
        }
    }

    internal sealed class EventWriteException : Exception
    {
        internal EventWriteException(string msg, Exception innerException)
            : base(msg, innerException)
        { }

        internal EventWriteException(string msg)
            : base(msg)
        { }
    }
}