Skip to content

Commit

Permalink
Added a few default values to variables.
Browse files Browse the repository at this point in the history
Updated Telemetry to QueueBackgroundWorkItem to improve user experience.
Telemetry sends additional info, sends as json instead of CSV, but still anonymous data.
  • Loading branch information
markdomansky committed May 21, 2018
1 parent 7e0c2d4 commit 508c6fa
Show file tree
Hide file tree
Showing 11 changed files with 193 additions and 53 deletions.
8 changes: 5 additions & 3 deletions WebJEA/Config.vb
Original file line number Diff line number Diff line change
Expand Up @@ -146,16 +146,18 @@

Public Function GetCommand(uinfo As UserInfo, ID As String) As PSCmd

Dim foundCmd As PSCmd
Dim foundCmd As PSCmd = Nothing

For Each Command As PSCmd In Commands
If Command.ID = ID Then
foundCmd = Command
End If
Next

If (IsGlobalUser(uinfo) Or foundCmd.IsCommandAvailable(uinfo)) Then
Return foundCmd
If (foundCmd IsNot Nothing) Then
If (IsGlobalUser(uinfo) Or foundCmd.IsCommandAvailable(uinfo)) Then
Return foundCmd
End If
End If

'no match
Expand Down
3 changes: 3 additions & 0 deletions WebJEA/Global.asax.vb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ Public Class Global_asax

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session is started
Session("init") = 0 'forces session to start, so session id is maintained.
Session("sessionid") = Session.SessionID

End Sub

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Expand Down
3 changes: 2 additions & 1 deletion WebJEA/Global.vb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Public grpfinder As New GroupFinder
Public uinfo As UserInfo
Public cfg As WebJEA.Config
Public objTelemetry As New Telemetry

Public Enum globalKeys
aws_enabled
Expand All @@ -17,7 +18,7 @@
{globalKeys.aws_key, "AKIAJ6X6FWQ3UWAOQL7Q"},
{globalKeys.aws_keysec, "o2xPU115uqFZA6OotH9IWfWXGATU17wtm7vQRev6"},
{globalKeys.aws_serviceUrl, "https://sqs.us-west-2.amazonaws.com"},
{globalKeys.aws_queueUrl, "https://sqs.us-west-2.amazonaws.com/777088161147/webjea-usage"}}
{globalKeys.aws_queueUrl, "https://sqs.us-west-2.amazonaws.com/777088161147/webjea-telemetry"}}


End Module
2 changes: 1 addition & 1 deletion WebJEA/GroupFinder.vb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Public Class GroupFinder
'#End If

'create a context for the domain/machine in the group
Dim pc As PrincipalContext
Dim pc As PrincipalContext = Nothing
If prvPC.ContainsKey(groupcontext) Then 'sid already found in cache
dlog.Trace("GroupFinder: GetSID: Found cached Context: " & groupcontext)
pc = prvPC(groupcontext)
Expand Down
46 changes: 7 additions & 39 deletions WebJEA/Helpers.vb
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
Module Helpers
Imports Microsoft.VisualBasic
Imports Microsoft.VisualBasic.Devices


Module Helpers
Public Function CoalesceString(ByVal ParamArray arguments As String()) As String
Dim argument As String
For Each argument In arguments
Expand Down Expand Up @@ -27,44 +31,7 @@

End Function

Public Sub SendUsage(DomainSid As String, DomainDNSRoot As String, ScriptID As String, UserID As String, ParamCount As Integer, isOnload As Boolean, SecondsRuntime As Single)
If globalSettings(globalKeys.aws_enabled) = False Then Return 'disable in code

Dim wints As DateTime = DateTime.UtcNow
Dim ts As Integer = (wints - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds
Dim version As String = "1" 'version of string format
Dim oid As String = UsageHash(DomainSid & ";" & DomainDNSRoot.ToUpper())
Dim sid As String = UsageHash(oid & ";" & ScriptID.ToUpper())
Dim uid As String = UsageHash(oid & ";" & UserID.ToUpper())
Dim isOnloadInt As Integer = Math.Abs(Convert.ToInt16(isOnload)) '0=false, 1=true
Dim secondsRuntimeStr As String = (Math.Ceiling(SecondsRuntime * 10D) / 10D).ToString()
Dim msg As String = wints.ToString("yyyy-MM-dd hh:mm:ss") & "," & ts & "," & version & "," & oid & "," & sid & "," & uid & "," & ParamCount & "," & isOnloadInt & "," & secondsRuntimeStr


Try
'Dim cred As Amazon.Runtime.AWSCredentials = New Amazon.Runtime.AnonymousAWSCredentials
Dim cred As Amazon.Runtime.AWSCredentials = New Amazon.Runtime.BasicAWSCredentials(globalSettings(globalKeys.aws_key), globalSettings(globalKeys.aws_keysec))

Dim conf As New Amazon.SQS.AmazonSQSConfig
conf.Timeout = New TimeSpan(0, 0, 5)
conf.ServiceURL = globalSettings(globalKeys.aws_serviceUrl)

Dim client As New Amazon.SQS.AmazonSQSClient(cred, conf)

Dim req As New Amazon.SQS.Model.SendMessageRequest
req.QueueUrl = globalSettings(globalKeys.aws_queueUrl)
req.MessageBody = msg

Dim resp As Amazon.SQS.Model.SendMessageResponse = client.SendMessage(req)
Catch
'if it errors, do nothing
End Try



End Sub

Public Function UsageHash(strin As String) As String
Public Function StringHash256(strin As String) As String

'Const rounds As Integer = 5

Expand All @@ -84,6 +51,7 @@
Return ByteArrayToHexString(hash)

End Function

Private Function ByteArrayToHexString(ByVal bytes_Input As Byte()) As String
Dim strTemp As New StringBuilder(bytes_Input.Length * 2)
For Each b As Byte In bytes_Input
Expand Down
4 changes: 2 additions & 2 deletions WebJEA/My Project/AssemblyInfo.vb
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ Imports System.Runtime.InteropServices
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>

<Assembly: AssemblyVersion("0.9.125.18132")>
<Assembly: AssemblyFileVersion("0.9.120.18132")>
<Assembly: AssemblyVersion("0.9.131.18141")>
<Assembly: AssemblyFileVersion("0.9.126.18141")>
127 changes: 127 additions & 0 deletions WebJEA/Telemetry.vb
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
Imports System.Web.Hosting
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Web.Script.Serialization

Class Telemetry

Private Metrics As New Dictionary(Of String, Object)

Public Sub Add(key As String, value As Object)
If Metrics.Keys.Contains(key) Then
Metrics(key) = value 'update
Else
Metrics.Add(key, value) 'add
End If

End Sub

Public Sub Clear(key As String)
Metrics.Clear()
End Sub
Public Sub Remove(key As String)
If Metrics.Keys.Contains(key) Then
Metrics.Remove(key)
End If
End Sub
Public Sub SendTelemetry()
dlog.Trace("SendTelemetry")
'sends whatever telemetry we have
Dim cts As New CancellationTokenSource
HostingEnvironment.QueueBackgroundWorkItem(Sub() AddMetricsAndSendTelemetry())

End Sub

Public Sub AddIDs(DomainSid As String, DomainDNSRoot As String, ScriptID As String, UserID As String, Optional Permitted As Boolean = True)

Dim oid As String = StringHash256(DomainSid & ";" & DomainDNSRoot.ToUpper())
Add("orgid", oid)
Add("scriptid", StringHash256(oid & ";" & ScriptID.ToUpper()))
Add("userid", StringHash256(oid & ";" & UserID.ToUpper()))
Add("permitted", Permitted)

End Sub

Public Sub AddRuntime(SecondsRuntime As Single, Optional isOnload As Boolean = False)

Dim RuntimeName = "runtimesec"
If isOnload Then RuntimeName = "runtimesecOnload"
Add(RuntimeName, (Math.Ceiling(SecondsRuntime * 10D) / 10D).ToString()) 'round up to 1 decimal

End Sub

Private Sub AddMetricsAndSendTelemetry()
AddSystemMetrics()
AddTimeMetrics()
SubmitToAWSQueue(Metrics)

End Sub

Private Sub SubmitToAWSQueue(dictobj As Dictionary(Of String, Object))
Dim msg As String = ToJSON(dictobj)

SubmitToAWSQueue(msg)
End Sub

Private Sub SubmitToAWSQueue(msg As String)
If globalSettings(globalKeys.aws_enabled) = False Then Return 'disable in code

Try
'Dim cred As Amazon.Runtime.AWSCredentials = New Amazon.Runtime.AnonymousAWSCredentials
dlog.Info("Sending Telemetry: " + msg)
Dim cred As Amazon.Runtime.AWSCredentials = New Amazon.Runtime.BasicAWSCredentials(globalSettings(globalKeys.aws_key), globalSettings(globalKeys.aws_keysec))

Dim conf As New Amazon.SQS.AmazonSQSConfig
conf.Timeout = New TimeSpan(0, 0, 5)
conf.ServiceURL = globalSettings(globalKeys.aws_serviceUrl)

Dim client As New Amazon.SQS.AmazonSQSClient(cred, conf)

Dim req As New Amazon.SQS.Model.SendMessageRequest
req.QueueUrl = globalSettings(globalKeys.aws_queueUrl)
req.MessageBody = msg

Dim resp As Amazon.SQS.Model.SendMessageResponse = client.SendMessage(req)
Catch
'if it errors, do nothing
End Try



End Sub

Private Function ToJSON(obj As Object) As String

Dim serializer As New JavaScriptSerializer()
serializer.RecursionLimit = 2
Return serializer.Serialize(obj)

End Function

Private Sub AddTimeMetrics()

Dim wints As DateTime = DateTime.UtcNow
Dim ts As Integer = (wints - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds
Dim version As String = "2" 'version of string format

Add("wints", wints.ToString("yyyy-MM-dd hh:mm:ss"))
Add("unixts", ts)
Add("version", version)

End Sub


Private Sub AddSystemMetrics()

Add("CPUCount", Environment.ProcessorCount) 'cpu count
Dim mgmtobjs As System.Management.ManagementObjectCollection = New System.Management.ManagementObjectSearcher("Select MaxClockSpeed from Win32_Processor").Get()
For Each mgmtobj In mgmtobjs
Add("CPUMhz", mgmtobj("maxclockspeed"))
Next
Add("OS", My.Computer.Info.OSFullName) 'os details
Add("RAM", Math.Round(My.Computer.Info.TotalPhysicalMemory / 1024 / 1024 / 1024, 1)) 'GB ram


End Sub

End Class
2 changes: 1 addition & 1 deletion WebJEA/UserInfo.vb
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Public Class UserInfo

Try
Dim regpath As String = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography"
Dim readValue = My.Computer.Registry.GetValue(regpath, "MachineGuid", "-")
Dim readValue = My.Computer.Registry.GetValue(regpath, "MachineGuid", "-") 'i think this always fails for permissions
prvDomainSID = readValue
prvDomainDNSRoot = Environment.MachineName
Catch
Expand Down
3 changes: 3 additions & 0 deletions WebJEA/Web.config
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
<customErrors mode="RemoteOnly" defaultRedirect="error.aspx"/>
<httpRuntime/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
<sessionState
regenerateExpiredSessionId="true"
timeout="30" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
Expand Down
18 changes: 17 additions & 1 deletion WebJEA/WebJEA.vbproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
<AssemblyVersion>0.9.125.18132</AssemblyVersion>
<TypeScriptToolsVersion>2.7</TypeScriptToolsVersion>
<TypeScriptToolsVersion>2.8</TypeScriptToolsVersion>
<Use64BitIISExpress />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
Expand All @@ -45,6 +46,19 @@
<FilesToIncludeForPublish>AllFilesInTheProject</FilesToIncludeForPublish>
<PublishDatabases>false</PublishDatabases>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<TypeScriptTarget>ES2017</TypeScriptTarget>
<TypeScriptJSXEmit>None</TypeScriptJSXEmit>
<TypeScriptModuleKind>AMD</TypeScriptModuleKind>
<TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
<TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
<TypeScriptRemoveComments>False</TypeScriptRemoveComments>
<TypeScriptOutFile />
<TypeScriptOutDir />
<TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
<TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
<TypeScriptSourceMap>True</TypeScriptSourceMap>
<TypeScriptMapRoot />
<TypeScriptSourceRoot />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
Expand Down Expand Up @@ -88,6 +102,7 @@
<Reference Include="System.DirectoryServices" />
<Reference Include="System.DirectoryServices.AccountManagement" />
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll</HintPath>
Expand Down Expand Up @@ -344,6 +359,7 @@
<Compile Include="PSCmdParam.vb" />
<Compile Include="PSCmdParamVal.vb" />
<Compile Include="PSWebHelper.vb" />
<Compile Include="Telemetry.vb" />
<Compile Include="UserInfo.vb" />
</ItemGroup>
<ItemGroup>
Expand Down
Loading

0 comments on commit 508c6fa

Please sign in to comment.