public override async Task Invoke(IOwinContext context) { var request = Create(context.Request); var body = context.Response.Body; var memoryStream = new MemoryStream(); context.Response.Body = memoryStream; await Next.Invoke(context); var response = new HttpResponse() { StatusCode = context.Response.StatusCode }; memoryStream.Position = 0; var streamReader = new StreamReader(memoryStream); var resposeResult = streamReader.ReadToEnd(); response.Result = Regex.Replace(resposeResult, "\"access_token\":\".{36}\"", "\"access_token\":\"******************\""); memoryStream.Position = 0; memoryStream.CopyTo(body); context.Response.Body = body; streamReader.Dispose(); memoryStream.Dispose(); HttpLogger.Write(request, response); }
// Token: 0x060000BB RID: 187 RVA: 0x00005390 File Offset: 0x00003590 private void OnAuthenticateRequest(object sender, EventArgs eventArgs) { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[BuildUserTokenModule.OnAuthenticate] Enter."); HttpApplication httpApplication = (HttpApplication)sender; HttpContext context = httpApplication.Context; if (context.User == null) { ExTraceGlobals.HttpModuleTracer.TraceError((long)this.GetHashCode(), "[BuildUserTokenModule.OnAuthenticate] Request is Unauthorized."); HttpLogger.SafeAppendGenericError("BuildUerTokenModule", "context.User is NULL", false); context.Response.StatusCode = 401; httpApplication.CompleteRequest(); return; } UserToken userToken = this.BuildCurrentUserToken(); if (userToken == null) { ExTraceGlobals.HttpModuleTracer.TraceError((long)this.GetHashCode(), "[BuildUserTokenModule.OnAuthenticate] Request is Unauthorized."); HttpLogger.SafeAppendGenericError("BuildUerTokenModule", "userToken is NULL", true); context.Response.StatusCode = 401; httpApplication.CompleteRequest(); return; } context.Items["X-EX-UserToken"] = userToken; ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[BuildUserTokenModule.OnAuthenticate] Leave."); }
// Token: 0x060000C1 RID: 193 RVA: 0x000059B8 File Offset: 0x00003BB8 private PartitionId GetPartitionId(CommonAccessToken commonAccessToken, IIdentity identity) { string text = null; if (commonAccessToken != null && commonAccessToken.ExtensionData.ContainsKey("Partition")) { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[BuildUserTokenModule::GetPartitionId] From CAT."); text = commonAccessToken.ExtensionData["Partition"]; } else { GenericSidIdentity genericSidIdentity = identity as GenericSidIdentity; if (genericSidIdentity != null) { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[BuildUserTokenModule::GetPartitionId] From Generic Sid Identity."); text = genericSidIdentity.PartitionId; } } if (text != null) { PartitionId result; if (PartitionId.TryParse(text, out result)) { return(result); } ExTraceGlobals.HttpModuleTracer.TraceError <string>((long)this.GetHashCode(), "[BuildUserTokenModule::GetPartitionId] Invalid partition id {0}.", text); HttpLogger.SafeAppendGenericError("BuildUserTokenModule.GetPartition", "Invalid partition id " + text, false); } return(null); }
private void ReviseAction(string funcName) { ExTraceGlobals.HttpModuleTracer.TraceFunction <string>((long)this.GetHashCode(), "[PingDetectionModule::{0}] Enter", funcName); HttpContext httpContext = HttpContext.Current; HttpResponse response = httpContext.Response; if (response == null) { return; } if (httpContext.Items["ActionHasBeenRevised"] != null) { return; } httpContext.Items["ActionHasBeenRevised"] = "Y"; WinRMInfo winRMInfoFromHttpHeaders = WinRMInfo.GetWinRMInfoFromHttpHeaders(httpContext.Request.Headers); string text; if (WinRMRequestTracker.TryReviseAction(winRMInfoFromHttpHeaders, response.StatusCode, response.SubStatusCode, out text)) { HttpLogger.SafeSetLogger(RpsHttpMetadata.Action, text); string headerValue = "Ping".Equals(text) ? "Ping" : "Non-Ping"; this.SafeSetResponseHeader(response, "X-RemotePS-Ping", headerValue); this.SafeSetResponseHeader(response, "X-RemotePS-RevisedAction", text); } ExTraceGlobals.HttpModuleTracer.TraceFunction <string>((long)this.GetHashCode(), "[PingDetectionModule::{0}] Exit.", funcName); }
private void OnPostAuthenticateRequest(object sender, EventArgs e) { ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[LoggingEndModule::OnPostAuthenticateRequest] Enter"); HttpContext httpContext = HttpContext.Current; if (!httpContext.Request.IsAuthenticated) { ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[LoggingEndModule::OnPostAuthenticateRequest] Exit IsAuthenticated = false."); return; } UserToken userToken = httpContext.CurrentUserToken(); if (userToken != null) { httpContext.Items["AuthType"] = userToken.AuthenticationType; } if (userToken != null && !string.IsNullOrWhiteSpace(userToken.UserName)) { httpContext.Items["AuthenticatedUser"] = userToken.UserName; } if (userToken != null) { string friendlyName = userToken.Organization.GetFriendlyName(); if (!string.IsNullOrWhiteSpace(friendlyName)) { HttpLogger.SafeSetLogger(ActivityStandardMetadata.TenantId, friendlyName); } } ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[LoggingEndModule::OnPostAuthenticateRequest] Exit."); }
private void OnAuthenticateRequest(object source, EventArgs e) { HttpContext httpContext = HttpContext.Current; if (!(httpContext.User.Identity is WindowsIdentity)) { return; } WindowsIdentity windowsIdentity = (WindowsIdentity)httpContext.User.Identity; if (windowsIdentity.User == null) { string value = string.Format("UnExpected: WindowsIdentity.User = null, AuthNType = {0}, Name = {1}", windowsIdentity.AuthenticationType, windowsIdentity.Name); HttpLogger.SafeAppendGenericError("WindowsIdentityToGenericIdentityModule", value, true); HttpApplication httpApplication = (HttpApplication)source; httpContext.Response.StatusCode = 401; httpApplication.CompleteRequest(); return; } ExAssert.RetailAssert(httpContext.User != null && httpContext.User.Identity != null && httpContext.User.Identity.Name != null, "HttpContext.User.Identity.Name should not be null."); GenericIdentity identity = new GenericIdentity(httpContext.User.Identity.Name.ToLower(), "Converted-" + httpContext.User.Identity.AuthenticationType); httpContext.User = new GenericPrincipal(identity, new string[0]); using (WinRMDataSender winRMDataSender = new WinRMDataSender(httpContext, null)) { WinRMInfo winRMInfo = httpContext.Items["X-RemotePS-WinRMInfo"] as WinRMInfo; if (winRMInfo != null) { winRMDataSender.SessionId = winRMInfo.FomattedSessionId; } winRMDataSender.RequestId = HttpLogger.ActivityScope.ActivityId.ToString(); winRMDataSender.UserToken = new UserToken(AuthenticationType.Kerberos, null, null, windowsIdentity.Name, windowsIdentity.User, null, OrganizationId.ForestWideOrgId, null, false, new CommonAccessToken(windowsIdentity)); winRMDataSender.Send(); } }
// Token: 0x0600143B RID: 5179 RVA: 0x0004A334 File Offset: 0x00048534 private static void SendAuthenticationDataToWinRM(HttpContext httpContext, UserToken userToken) { WinRMInfo winRMInfo = httpContext.Items["X-RemotePS-WinRMInfo"] as WinRMInfo; if (ProxySecurityContextModule.NeedSendDataToWinRM(winRMInfo)) { userToken.UniformCommonAccessToken(); if (winRMInfo != null && "New-PSSession".Equals(winRMInfo.Action, StringComparison.OrdinalIgnoreCase)) { HttpLogger.SafeAppendGenericInfo("WinRMCAT", userToken.GetReadableCommonAccessToken()); } LatencyTracker latencyTracker = HttpContext.Current.Items["Logging-HttpRequest-Latency"] as LatencyTracker; using (WinRMDataSender winRMDataSender = new WinRMDataSender(httpContext, latencyTracker)) { winRMDataSender.SessionId = winRMInfo.FomattedSessionId; if (HttpLogger.ActivityScope != null) { Guid activityId = HttpLogger.ActivityScope.ActivityId; winRMDataSender.RequestId = HttpLogger.ActivityScope.ActivityId.ToString(); } winRMDataSender.UserToken = userToken; winRMDataSender.Send(); } } }
internal static ADUser ResolveCertificate(X509Identifier certificate, string orgName) { Logger.EnterFunction(ExTraceGlobals.CertAuthTracer, "ResolveCertificate"); ADSessionSettings sessionSettings = null; if (string.IsNullOrEmpty(orgName)) { sessionSettings = ADSessionSettings.FromRootOrgScopeSet(); } else { try { sessionSettings = ADSessionSettings.FromTenantAcceptedDomain(orgName); } catch (CannotResolveTenantNameException ex) { Logger.LogError(string.Format("Can not resolve the organization based on org name {0} provided in requesting url.", orgName), ex); Logger.LogEvent(CertificateAuthenticationModule.eventLogger, TaskEventLogConstants.Tuple_CertAuth_OrganizationNotFound, null, new object[] { ex, orgName }); Logger.ExitFunction(ExTraceGlobals.CertAuthTracer, "ResolveCertificate"); HttpLogger.SafeAppendGenericError("ResolveCertificate", ex.ToString(), false); return(null); } } IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(ConsistencyMode.IgnoreInvalid, sessionSettings, 193, "ResolveCertificate", "f:\\15.00.1497\\sources\\dev\\Configuration\\src\\CertificateAuthentication\\CertificateAuthenticationModule.cs"); ADUser result = (ADUser)tenantOrRootOrgRecipientSession.FindByCertificate(certificate); Logger.ExitFunction(ExTraceGlobals.CertAuthTracer, "ResolveCertificate"); return(result); }
internal ILogger CreateLogger() { Level = GetLevel(); Target = GetTarget(); switch (Target) { case Target.CONSOLE: ConsoleLogger logger = new ConsoleLogger(); logger.SetLevel(Level); return(logger); case Target.FILE: FileLogger fileLogger = new FileLogger(Configuration.Configuration.FilePath); fileLogger.SetLevel(Level); return(fileLogger); case Target.HTTP: HttpLogger httpLogger = new HttpLogger(Configuration.Configuration.HttpUrl); httpLogger.SetLevel(Level); return(httpLogger); case Target.DATABASE: DatabaseLogger databaseLogger = new DatabaseLogger(); databaseLogger.SetLevel(Level); return(databaseLogger); default: ConsoleLogger consoleLogger = new ConsoleLogger(); consoleLogger.SetLevel(Level); return(consoleLogger); } }
// Token: 0x06000090 RID: 144 RVA: 0x00004994 File Offset: 0x00002B94 internal static void Log() { if (TickDiffer.Elapsed(CPUMemoryLogger.lastLogTime).TotalMinutes > (double)AppSettings.Current.LogCPUMemoryIntervalInMinutes) { CPUMemoryLogger.lastLogTime = Environment.TickCount; HttpLogger.SafeSetLogger(ConfigurationCoreMetadata.CPU, (long)CPUMemoryLogger.ProcessCpuPerfCounter.GetValue() + "% * " + CPUMemoryLogger.ProcessorCount); HttpLogger.SafeSetLogger(ConfigurationCoreMetadata.Memory, CPUMemoryLogger.GetMemory()); } }
private void TriggerFailFast(string wlID) { int hashCode = this.GetHashCode(); ExTraceGlobals.HttpModuleTracer.TraceFunction((long)hashCode, "[RemotePowerShellAuthModule::TriggerFailFast] Enter."); FailFastUserCache.Instance.AddUserToCache(wlID, BlockedType.NewRequest, TimeSpan.Zero); HttpLogger.SafeAppendGenericInfo("TriggerFailFast", wlID); ExTraceGlobals.HttpModuleTracer.TraceFunction((long)hashCode, "[RemotePowerShellAuthModule::TriggerFailFast] Exit."); }
public override async Task <bool> Run() { this.Info($"Host:{Arguments.Host} Start rollBack from version:" + Arguments.DeployFolderName); HttpRequestClient httpRequestClient = new HttpRequestClient(); httpRequestClient.SetFieldValue("publishType", "windowservice_rollback"); httpRequestClient.SetFieldValue("id", Arguments.LoggerId); httpRequestClient.SetFieldValue("serviceName", Arguments.ServiceName); httpRequestClient.SetFieldValue("deployFolderName", Arguments.DeployFolderName); httpRequestClient.SetFieldValue("Token", Arguments.Token); HttpLogger HttpLogger = new HttpLogger { Key = Arguments.LoggerId, Url = $"http://{Arguments.Host}/logger?key=" + Arguments.LoggerId }; var isSuccess = true; WebSocketClient webSocket = new WebSocketClient(this.Log, HttpLogger); try { var hostKey = await webSocket.Connect($"ws://{Arguments.Host}/socket"); httpRequestClient.SetFieldValue("wsKey", hostKey); var uploadResult = await httpRequestClient.Upload($"http://{Arguments.Host}/rollback", null, GetProxy()); webSocket.ReceiveHttpAction(true); if (webSocket.HasError) { isSuccess = false; this.Error($"Host:{Arguments.Host},Rollback Fail,Skip to Next"); } else { if (uploadResult.Item1) { this.Info($"【rollback success】Host:{Arguments.Host},Response:{uploadResult.Item2}"); } else { isSuccess = false; this.Error($"Host:{Arguments.Host},Response:{uploadResult.Item2},Skip to Next"); } } } catch (Exception ex) { isSuccess = false; this.Error($"Fail Rollback,Host:{Arguments.Host},Response:{ex.Message},Skip to Next"); } finally { await webSocket?.Dispose(); } return(await Task.FromResult(isSuccess)); }
// Token: 0x060000C9 RID: 201 RVA: 0x00005CC8 File Offset: 0x00003EC8 internal static void EndPowerShellRequestWithFriendlyError(HttpContext context, FailureCategory failureCategory, string failureName, string errorMessage, string className, bool isCriticalError) { context.Response.StatusCode = 400; string text = string.Format("[FailureCategory={0}] ", failureCategory + "-" + failureName) + errorMessage; HttpLogger.SafeAppendGenericError(className, text, isCriticalError); ExTraceGlobals.HttpModuleTracer.TraceError <string>(0L, className + " Get error. {0}", text); context.Response.Write(text); context.Response.End(); }
private void CheckRemotePSEnabledFlag() { int hashCode = this.GetHashCode(); ExTraceGlobals.HttpModuleTracer.TraceFunction((long)hashCode, "[RemotePowerShellAuthModule::CheckRemotePSEnabledFlag] Enter."); IPrincipal user = HttpContext.Current.User; if (user != null) { PartitionId partitionId = null; string text; SecurityIdentifier userSid = this.GetUserSid(user, out partitionId, out text); if (userSid != null) { bool rpsEnabledFlag; if (!RemotePowerShellAuthZModule.rpsEnableCache.TryGetValue(userSid, out rpsEnabledFlag)) { string text2 = null; rpsEnabledFlag = this.GetRpsEnabledFlag(userSid, partitionId, out text2); RemotePowerShellAuthZModule.rpsEnableCache.InsertAbsolute(userSid, rpsEnabledFlag, RemotePowerShellAuthZModule.timeSpanForRpsEnableFlag, null); if (text2 != null) { HttpLogger.SafeAppendGenericError("CheckRemotePSEnabledFlag", text2, false); ExTraceGlobals.HttpModuleTracer.TraceError((long)hashCode, string.Format("[RemotePowerShellAuthModule::CheckRemotePSEnabledFlag] Got an error '{0}' During Find ADRawEntry.", text2)); } else { HttpLogger.SafeAppendGenericInfo("RpsEnabled", rpsEnabledFlag.ToString()); } } else { HttpLogger.SafeAppendGenericInfo("RpsEnabled", "HitCache"); } if (!rpsEnabledFlag) { if (!string.IsNullOrEmpty(text)) { this.TriggerFailFast(text); } this.AccessDenied(); } } else { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)hashCode, "Identity in the context is not valid. It should be either LiveIDIdentity or WindowsIdentity."); } } else { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)hashCode, "Current user is null."); } ExTraceGlobals.HttpModuleTracer.TraceFunction((long)hashCode, "[RemotePowerShellAuthModule::CheckRemotePSEnabledFlag] Exit."); }
// Token: 0x06001439 RID: 5177 RVA: 0x0004A0D8 File Offset: 0x000482D8 private void OnAuthenticateRequest(object source, EventArgs e) { ExTraceGlobals.AccessCheckTracer.TraceDebug(0L, "Start OnAuthenticateRequest"); HttpApplication httpApplication = (HttpApplication)source; HttpContext context = httpApplication.Context; UserToken userToken = context.CurrentUserToken(); if (this.IsDelegatedAuth(context)) { ExTraceGlobals.AccessCheckTracer.TraceDebug(0L, "Delegated auth, let delegated auth module handle the request"); } else { if (context.Request.IsAuthenticated && userToken.HasCommonAccessToken) { try { if (userToken.HasCommonAccessToken && ProxySecurityContextModule.AuthenticationTypes.ContainsKey(userToken.AuthenticationType)) { string text = ProxySecurityContextModule.AuthenticationTypes[userToken.AuthenticationType]; if (context.User != null && context.User.Identity != null) { context.Items["AuthType"] = context.User.Identity.AuthenticationType; if (!context.Items.Contains("AuthenticatedUser")) { context.Items["AuthenticatedUser"] = context.User.Identity.Name; } else { HttpLogger.SafeAppendGenericInfo("User.Identity", context.User.Identity.Name); } } ExTraceGlobals.AccessCheckTracer.TraceDebug <AuthenticationType, string>(0L, "Token Type = {0}, AuthenticationType = {1}.", userToken.AuthenticationType, text); ExAssert.RetailAssert(context.User != null && context.User.Identity != null && context.User.Identity.Name != null, "HttpContext.User.Identity.Name should not be null."); GenericIdentity identity = new GenericIdentity(context.User.Identity.Name.ToLower(), text); context.User = new GenericPrincipal(identity, new string[0]); ProxySecurityContextModule.SendAuthenticationDataToWinRM(context, userToken); } goto IL_201; } catch (Exception ex) { HttpModuleHelper.EndPowerShellRequestWithFriendlyError(context, FailureCategory.ProxySecurityContext, "Exception", ex.ToString(), "ProxySecurityContextModule", KnownException.IsUnhandledException(ex)); goto IL_201; } } ExTraceGlobals.AccessCheckTracer.TraceDebug(0L, "Request is Unauthorized."); WinRMInfo.SetFailureCategoryInfo(context.Response.Headers, FailureCategory.ProxySecurityContext, "Unauthorized"); context.Response.StatusCode = 401; httpApplication.CompleteRequest(); } IL_201: ExTraceGlobals.AccessCheckTracer.TraceDebug(0L, "Exit OnAuthenticateRequest"); }
// Token: 0x060000C0 RID: 192 RVA: 0x000057CC File Offset: 0x000039CC private SecurityIdentifier GetUserSid(CommonAccessToken commonAccessToken, IIdentity identity) { if (!(HttpContext.Current.User is DelegatedPrincipal)) { try { SecurityIdentifier securityIdentifier = identity.GetSecurityIdentifier(); ExTraceGlobals.HttpModuleTracer.TraceDebug <string>((long)this.GetHashCode(), "[BuildUserTokenModule::GetUserSid] Get user sid from HttpContext.Current.User. sid = {0}", securityIdentifier.ToString()); return(securityIdentifier); } catch (Exception ex) { Exception ex3; ExTraceGlobals.HttpModuleTracer.TraceError <Exception>((long)this.GetHashCode(), "[BuildUserTokenModule::GetUserSid] Exception {0}", ex3); HttpLogger.SafeAppendGenericError("BuildUserTokenModule.GetUserSid", ex3, (Exception ex) => false); } } HttpContext httpContext = HttpContext.Current; string text = null; if (commonAccessToken != null && commonAccessToken.ExtensionData.ContainsKey("UserSid")) { text = commonAccessToken.ExtensionData["UserSid"]; ExTraceGlobals.HttpModuleTracer.TraceDebug <string>((long)this.GetHashCode(), "[BuildUserTokenModule::GetUserSid] Get user sid from CAT. sid = {0}", text); } else if (!string.IsNullOrWhiteSpace((string)httpContext.Items["X-EX-UserSid"])) { text = (string)httpContext.Items["X-EX-UserSid"]; ExTraceGlobals.HttpModuleTracer.TraceDebug <string>((long)this.GetHashCode(), "[BuildUserTokenModule::GetUserSid] Get user sid from HttpContext. sid = {0}", text); } else if (commonAccessToken != null && "Windows".Equals(commonAccessToken.TokenType) && commonAccessToken.WindowsAccessToken != null) { text = commonAccessToken.WindowsAccessToken.UserSid; ExTraceGlobals.HttpModuleTracer.TraceDebug <string>((long)this.GetHashCode(), "[BuildUserTokenModule::GetUserSid] Get user sid from CAT for Kerberos. sid = {0}", text); } if (string.IsNullOrWhiteSpace(text)) { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[BuildUserTokenModule::GetUserSid] Get user sid from HttpContext. sid = null"); return(null); } SecurityIdentifier result; try { result = new SecurityIdentifier(text); } catch (Exception ex2) { HttpLogger.SafeAppendGenericError("BuildUserTokenModule.GetUserSid", ex2, new Func <Exception, bool>(KnownException.IsUnhandledException)); ExTraceGlobals.HttpModuleTracer.TraceError <Exception>((long)this.GetHashCode(), "[BuildUserTokenModule::GetUserSid] Exception {0}", ex2); result = null; } return(result); }
private void SafeSetResponseHeader(HttpResponse response, string header, string headerValue) { try { response.Headers[header] = headerValue; } catch (Exception ex) { HttpLogger.SafeAppendGenericError("PingDetctionModule.SafeSetResponseHeader", ex.ToString(), false); } }
// Token: 0x060000E3 RID: 227 RVA: 0x00006628 File Offset: 0x00004828 private void OnBeginRequest(object sender, EventArgs e) { ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[ProbePingModule::OnBeginRequest] Enter"); HttpContext httpContext = HttpContext.Current; HttpRequest request = httpContext.Request; if (LoggerHelper.IsProbePingRequest(request)) { HttpLogger.SafeSetLogger(RpsHttpMetadata.Action, "ProbePing"); HttpContext.Current.ApplicationInstance.CompleteRequest(); } ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[ProbePingModule::OnBeginRequest] Exit."); }
public static void Main() { var fileLogger = new FileLogger("c:\\path"); var httpLogger = new HttpLogger(new Uri("www.idnes.cz/logs")); var outputLogger = new OutputLogger(); var multiLogger = new CompositeLogger(fileLogger, httpLogger, outputLogger) { MessageBuffer = 50 }; multiLogger.Log("LOG FOR MULTIPLE LOGGERS"); }
// Token: 0x060012CF RID: 4815 RVA: 0x0003D0D4 File Offset: 0x0003B2D4 private static bool TestWhetherUriNeedsModification(Uri requestUri, NameValueCollection httpHeaders, out string modifiedPath, out string queryString, out string organization, out string delegatedOrg) { bool flag = false; modifiedPath = null; queryString = null; delegatedOrg = null; UriBuilder uriBuilder = new UriBuilder(requestUri); NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(uriBuilder.Query); organization = nameValueCollection["organization"]; if (!string.IsNullOrWhiteSpace(organization)) { string value = httpHeaders["X-Psws-KeepOrgInUrl"]; bool flag2; if (bool.TryParse(value, out flag2) && flag2) { ExTraceGlobals.AccessCheckTracer.TraceDebug(0L, "[PswsUrlRewriteModule.TestWhetherUriNeedsModification] X-Psws-KeepOrgInUrl exists in header and organization is kept in the URL."); } else { flag = true; nameValueCollection.Remove("organization"); uriBuilder.Query = nameValueCollection.ToString(); HttpLogger.SafeAppendGenericInfo("UrlRewrite", "Organization:" + organization + " removed"); } } delegatedOrg = nameValueCollection["DelegatedOrg"]; if (!string.IsNullOrEmpty(delegatedOrg)) { flag = true; nameValueCollection.Remove("DelegatedOrg"); uriBuilder.Query = nameValueCollection.ToString(); HttpLogger.SafeAppendGenericInfo("UrlRewrite", "DelegatedOrg:" + delegatedOrg + " removed"); } if (uriBuilder.Path.EndsWith(".svc", StringComparison.OrdinalIgnoreCase) && string.IsNullOrWhiteSpace(uriBuilder.Query)) { flag = true; uriBuilder.Path += '/'; } if (flag) { modifiedPath = uriBuilder.Path; queryString = uriBuilder.Query; if (!string.IsNullOrWhiteSpace(queryString) && queryString.StartsWith("?")) { queryString = queryString.Substring(1); } } return(flag); }
private void AccessDenied() { int hashCode = this.GetHashCode(); ExTraceGlobals.HttpModuleTracer.TraceFunction((long)hashCode, "[RemotePowerShellAuthModule::AccessDenied] Enter."); HttpContext httpContext = HttpContext.Current; httpContext.Response.StatusCode = 400; HttpLogger.SafeAppendGenericError("RemotePowerShellAuthModule", "RemotePowerShell not enabled user.", false); ExTraceGlobals.HttpModuleTracer.TraceError <string>((long)hashCode, "[ProxySecurityContextModule::AccessDenied] RpsEnabled is false.", "RemotePowerShell not enabled user."); httpContext.Response.Write(string.Format("[FailureCategory={0}] ", FailureCategory.AuthZ + "-RpsNotEnabled") + Strings.ErrorRpsNotEnabled); httpContext.Response.End(); ExTraceGlobals.HttpModuleTracer.TraceFunction((long)hashCode, "[RemotePowerShellAuthModule::AccessDenied] Exit."); }
private static void ApplicationPreSendRequestHeaders(object sender, EventArgs e) { if (!FailFastUserCache.FailFastEnabled) { return; } Logger.EnterFunction(ExTraceGlobals.FailureThrottlingTracer, "PowerShellFailureThrottlingModule.ApplicationPreSendRequestContent"); HttpApplication httpApplication = (HttpApplication)sender; HttpContext context = httpApplication.Context; if (context == null || context.Request == null || context.Response == null) { Logger.TraceDebug(ExTraceGlobals.FailureThrottlingTracer, "context == null || context.Request == null || context.Response == null", new object[0]); Logger.ExitFunction(ExTraceGlobals.FailureThrottlingTracer, "PowerShellFailureThrottlingModule.ApplicationPreSendRequestContent"); return; } string text = context.Response.Headers[FailFastModule.HeaderKeyToStoreUserToken]; Logger.TraceDebug(ExTraceGlobals.FailureThrottlingTracer, "Current UserToken is {0}.", new object[] { text }); context.Response.Headers.Remove(FailFastModule.HeaderKeyToStoreUserToken); Logger.TraceDebug(ExTraceGlobals.FailureThrottlingTracer, "Remove {0} from header.", new object[] { FailFastModule.HeaderKeyToStoreUserToken }); if (!PowerShellFailureThrottlingModule.failureThrottlingEnabled) { Logger.TraceDebug(ExTraceGlobals.FailureThrottlingTracer, "Failure throttling is disabled.", new object[0]); Logger.ExitFunction(ExTraceGlobals.FailureThrottlingTracer, "PowerShellFailureThrottlingModule.ApplicationPreSendRequestContent"); return; } if (!context.Request.IsAuthenticated) { Logger.TraceDebug(ExTraceGlobals.FailureThrottlingTracer, "Un-authenticated request.", new object[0]); Logger.ExitFunction(ExTraceGlobals.FailureThrottlingTracer, "PowerShellFailureThrottlingModule.ApplicationPreSendRequestContent"); return; } if (!string.IsNullOrEmpty(text) && FailureThrottling.CountBasedOnStatusCode(text, context.Response.StatusCode)) { HttpLogger.SafeAppendColumn(RpsCommonMetadata.ContributeToFailFast, "FailureThrottling", LoggerHelper.GetContributeToFailFastValue("User", text, "NewRequest", -1.0)); Logger.TraceDebug(ExTraceGlobals.FailureThrottlingTracer, "Add user {0} to fail-fast user cache.", new object[] { text }); FailFastUserCache.Instance.AddUserToCache(text, BlockedType.NewRequest, TimeSpan.Zero); } Logger.ExitFunction(ExTraceGlobals.FailureThrottlingTracer, "PowerShellFailureThrottlingModule.ApplicationPreSendRequestContent"); }
private void OnEndRequest(object sender, EventArgs e) { ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[LoggingEndModule::OnEndRequest] Enter"); if (HttpLogger.LoggerNotDisposed) { try { HttpContext httpContext = HttpContext.Current; HttpResponse response = httpContext.Response; HttpLogger.SafeSetLogger(ConfigurationCoreMetadata.SubStatus, response.SubStatusCode); CPUMemoryLogger.Log(); LatencyTracker latencyTracker = HttpContext.Current.Items["Logging-HttpRequest-Latency"] as LatencyTracker; if (latencyTracker != null) { long num = latencyTracker.Stop(); HttpLogger.SafeSetLogger(ConfigurationCoreMetadata.TotalTime, num); latencyTracker.PushLatencyDetailsToLog(null, null, delegate(string funcName, string totalLatency) { HttpLogger.SafeAppendColumn(RpsCommonMetadata.GenericLatency, funcName, totalLatency); }); if (Constants.IsPowerShellWebService) { PswsPerfCounter.UpdatePerfCounter(num); } else { RPSPerfCounter.UpdateAverageRTCounter(num); } } else { HttpLogger.SafeAppendColumn(RpsCommonMetadata.GenericLatency, "LatencyMissed", "httpRequestLatencyTracker is null"); } HttpLogger.SafeAppendGenericInfo("OnEndRequest.End.ContentType", response.ContentType); } finally { if (HttpLogger.ActivityScope != null) { RequestMonitor.Instance.UnRegisterRequest(HttpLogger.ActivityScope.ActivityId); } HttpLogger.AsyncCommit(false); } } ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[LoggingEndModule::OnEndRequest] Exit"); }
// Token: 0x060000BD RID: 189 RVA: 0x000054FC File Offset: 0x000036FC private AuthenticationType GetAuthenticationType(CommonAccessToken commonAccessToken, IIdentity identity, out AccessTokenType accessTokenType) { AuthenticationType result = AuthenticationType.Unknown; accessTokenType = AccessTokenType.Anonymous; if (commonAccessToken != null) { if (!Enum.TryParse <AccessTokenType>(commonAccessToken.TokenType, true, out accessTokenType)) { HttpLogger.SafeAppendGenericError("Invalid-CAT-Type", accessTokenType.ToString(), false); ExTraceGlobals.UserTokenTracer.TraceError <string>((long)this.GetHashCode(), "[BuildUserTokenModule::GetAuthenticationType] Invalid token type {0}", commonAccessToken.TokenType); throw new ArgumentException(string.Format("The token type {0} is unexpected.", commonAccessToken.TokenType)); } ExTraceGlobals.UserTokenTracer.TraceDebug <AccessTokenType>((long)this.GetHashCode(), "[BuildUserTokenModule::GetAuthenticationType] Access token type {0}", accessTokenType); switch (accessTokenType) { case AccessTokenType.Windows: return(AuthenticationType.Kerberos); case AccessTokenType.LiveIdBasic: return(AuthenticationType.LiveIdBasic); case AccessTokenType.LiveIdNego2: return(AuthenticationType.LiveIdNego2); case AccessTokenType.OAuth: return(AuthenticationType.OAuth); case AccessTokenType.CertificateSid: return(AuthenticationType.Certificate); case AccessTokenType.RemotePowerShellDelegated: return(AuthenticationType.RemotePowerShellDelegated); } HttpLogger.SafeAppendGenericError("NotSupported-CAT-Type", accessTokenType.ToString(), false); ExTraceGlobals.UserTokenTracer.TraceError <AccessTokenType>((long)this.GetHashCode(), "[BuildUserTokenModule::GetAuthenticationType] Not supported token type {0}", accessTokenType); throw new NotSupportedException(string.Format("Unknown token type {0}", accessTokenType)); } else if (identity is SidOAuthIdentity) { result = AuthenticationType.OAuth; } return(result); }
// Token: 0x06000003 RID: 3 RVA: 0x000020E8 File Offset: 0x000002E8 private static void OnBeginRequest(object source, EventArgs args) { Logger.EnterFunction(ExTraceGlobals.ClientDiagnosticsModuleTracer, "ClientDiagnosticsModule.OnBeginRequest"); HttpContext httpContext = HttpContext.Current; string text = httpContext.Request.Headers[ClientDiagnosticsModule.MsExchProxyUri]; if (string.IsNullOrEmpty(text)) { ClientDiagnosticsModule.LogVerbose("Get orginal url directly since it is not come from CAFE. Request url: {0}", new object[] { httpContext.Request.Url }); text = httpContext.Request.Url.ToString(); } NameValueCollection urlProperties = DiagnosticsHelper.GetUrlProperties(new Uri(text)); if (ClientDiagnosticsModule.NeedAddDiagnostics(urlProperties)) { string value = urlProperties["BEServer"]; if (ClientDiagnosticsModule.AddBEServerInformationIfNeeded(ref value)) { UriBuilder uriBuilder = new UriBuilder(text); urlProperties["BEServer"] = value; uriBuilder.Query = urlProperties.ToString().Replace("&", ";").Trim(); string text2 = uriBuilder.ToString(); HttpLogger.SafeAppendGenericInfo("DiagRedirect", text + " TO " + text2); ClientDiagnosticsModule.LogVerbose("Add diagnositcs information to request: Orginal url is {0}, Redirect url is {1}.", new object[] { text, text2 }); Logger.LogEvent(ClientDiagnosticsModule.eventLogger, TaskEventLogConstants.Tuple_ClientDiagnostics_RedirectWithDiagnosticsInformation, null, new object[] { text, httpContext.Server.UrlDecode(text2) }); httpContext.Response.Redirect(text2); } } Logger.ExitFunction(ExTraceGlobals.ClientDiagnosticsModuleTracer, "ClientDiagnosticsModule.OnBeginRequest"); }
// Token: 0x060012C4 RID: 4804 RVA: 0x0003CB88 File Offset: 0x0003AD88 internal static void SendErrorToClient(PswsErrorCode errorCode, Exception exception, string additionalInfo) { ExTraceGlobals.PublicPluginAPITracer.TraceDebug <PswsErrorCode, Exception, string>(0L, "[PswsErrorHandling.SendErrorToClient] Error Code = {0}, Exception = \"{1}\", additionalInfo = \"{2}\".", errorCode, exception, additionalInfo); try { HttpContext httpContext = HttpContext.Current; if (httpContext != null) { HttpResponse response = httpContext.Response; if (response != null) { if (response.Headers["X-Psws-ErrorCode"] == null) { response.AddHeader("X-Psws-ErrorCode", ((int)PswsErrorHandling.TranslateErrorCode(errorCode, exception, additionalInfo)).ToString()); HttpLogger.SafeSetLogger(ServiceCommonMetadata.ErrorCode, errorCode); if (exception != null) { string text = exception.GetType() + "," + exception.Message; if (text.Length > 500) { text = text.Substring(0, 500 - "...(truncated)".Length); text += "...(truncated)"; } response.AddHeader("X-Psws-Exception", text); HttpLogger.SafeAppendGenericInfo("PswsExceptionInfo", text); } if (!string.IsNullOrWhiteSpace(additionalInfo)) { response.AddHeader("X-Psws-ErrorInfo", additionalInfo); HttpLogger.SafeAppendGenericInfo("PswsErrorAdditionalInfo", additionalInfo); } } } } } catch (Exception ex) { ExTraceGlobals.PublicPluginAPITracer.TraceDebug <Exception>(0L, "[PswsErrorHandling.SendErrorToClient] Exception {0}.", ex); HttpLogger.SafeAppendGenericError("SendErrorToClientError", ex, new Func <Exception, bool>(KnownException.IsUnhandledException)); } }
private void AuthenticateRequest(object sender, EventArgs e) { ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[RemotePowerShellAuthModule::AuthenticateRequest] Enter."); HttpContext httpContext = HttpContext.Current; if (!httpContext.Request.IsAuthenticated || httpContext.User == null) { ExTraceGlobals.HttpModuleTracer.TraceDebug((long)this.GetHashCode(), "[RemotePowerShellAuthModule::AuthenticateRequest] Request is not authenticated."); return; } try { this.CheckRemotePSEnabledFlag(); } catch (Exception ex) { ExTraceGlobals.HttpModuleTracer.TraceError((long)this.GetHashCode(), string.Format("[RemotePowerShellAuthModule::AuthenticateRequest] Got an error '{0}' During CheckRemotePSEnabledFlag.", ex.Message)); HttpLogger.SafeAppendGenericError("AuthenticateRequest", ex.Message, false); } ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[RemotePowerShellAuthModule::AuthenticateRequest] Exit."); }
private void OnPostAuthenticateRequest(object sender, EventArgs e) { HttpContextBase context = new HttpContextWrapper(((HttpApplication)sender).Context); WinRMInfo winRMInfoFromHttpHeaders = WinRMInfo.GetWinRMInfoFromHttpHeaders(context.Request.Headers); if (winRMInfoFromHttpHeaders != null) { string sessionUniqueId = winRMInfoFromHttpHeaders.SessionUniqueId; int num = 0; if (!string.IsNullOrEmpty(sessionUniqueId) && RpsHttpDatabaseValidationModule.ActiveSessionCache.TryGetValue(sessionUniqueId, out num)) { HttpLogger.SafeAppendGenericInfo("CachedSessionId", sessionUniqueId); return; } } using (new MonitoredScope("RpsHttpDatabaseValidationModule", "RpsHttpDatabaseValidationModule", HttpModuleHelper.HttpPerfMonitors)) { HttpDatabaseValidationHelper.ValidateHttpDatabaseHeader(context, delegate { }, delegate(string routingError) { if (context.Request.Headers[WellKnownHeader.XCafeLastRetryHeaderKey] != null) { HttpLogger.SafeAppendGenericInfo("IgnoreRoutingError", "Cafe last retry"); return; } HttpLogger.SafeAppendGenericError("ServerRoutingError", routingError, false); WinRMInfo.SetFailureCategoryInfo(context.Response.Headers, FailureCategory.DatabaseValidation, "ServerRoutingError"); this.SendErrorResponse(context, 555, 0, routingError, delegate(HttpResponseBase response) { response.Headers[WellKnownHeader.BEServerRoutingError] = routingError; }, false); }, delegate { HttpLogger.SafeAppendGenericError("InvalidMailboxDatabaseGuid", "Cannot Parse MailboxDatabaseGuid From Header", false); WinRMInfo.SetFailureCategoryInfo(context.Response.Headers, FailureCategory.DatabaseValidation, "InvalidDatabaseGuid"); this.SendErrorResponse(context, 400, 0, "Invalid database guid", null, false); }); } }
public Startup(DirectoryInfo baseDataDir, Uri proxyUri, Uri[] targetUris, Uri controlUri, Uri uiUri = null) { var baseDir = baseDataDir; var logger = new HttpLogger(baseDir); apps = new List <HttpAppBase>(); var proxy = new HttpProxy(proxyUri, targetUris); { proxy.AnalyserEngine.Register(new RequestStore(baseDir, logger)); proxy.AnalyserEngine.Register(logger); proxy.AnalyserEngine.Register(new TextIndexer(baseDir, logger)); //proxy.AnalyserEngine.Register(new RequestFeatureMap(baseDir, logger)); proxy.ApplicationHost.StatusChanged += (s, v) => { Console.WriteLine("Proxy status = {0}", v.Value); }; var control = new HttpController(controlUri, proxy); Console.WriteLine("Binding to {0}", proxyUri); Console.WriteLine("Control via {0}", controlUri); if (uiUri != null) { var app = new WebPortal(uiUri); control.AllowOrigin(uiUri); apps.Add(app); Console.WriteLine("Admin portal via {0}", uiUri); } apps.Add(proxy); apps.Add(control); } }
private static ADUser ResolveCertificateFromCacheOrAD(HttpClientCertificate certificate, string orgName) { Logger.EnterFunction(ExTraceGlobals.CertAuthTracer, "ResolveCertificateFromCacheOrAD"); X509Identifier x509Identifier = CertificateAuthenticationModule.CreateCertificateIdentity(certificate); ADUser aduser = CertificateAuthenticationModule.GetUserFromCache(x509Identifier); if (aduser == null) { aduser = CertificateAuthenticationModule.ResolveCertificate(x509Identifier, orgName); if (aduser != null) { CertificateAuthenticationModule.AddUserToCache(x509Identifier, aduser); } } else { HttpLogger.SafeAppendGenericInfo("ResolveCertificateFromCacheOrAD", "Cache"); } if (aduser == null) { Logger.LogEvent(CertificateAuthenticationModule.eventLogger, TaskEventLogConstants.Tuple_CertAuth_UserNotFound, certificate.Subject, new object[] { certificate.Subject }); Logger.LogVerbose("Found no user by certificate {0}", new object[] { certificate.Subject }); } else { Logger.LogVerbose("Found user {0} by certificate {1}", new object[] { aduser.Name, certificate.Subject }); } Logger.ExitFunction(ExTraceGlobals.CertAuthTracer, "ResolveCertificateFromCacheOrAD"); return(aduser); }
private static void Main() { try { var logger = new HttpLogger(); logger.AddHost(null); using (var host = new HttpDebuggerHost()) { var subCtx = host.Subscribe(ReceiveMessage); try { host.Start(); Console.WriteLine("started"); for (var i = 0; i < 1000; i++) { logger.Log("test" + i, tag: "yeah!"); } Console.ReadLine(); } finally { subCtx.Unsubscribe(); } } } catch (Exception ex) { Console.WriteLine("[ERROR]: {0}", ex.GetBaseException()); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("===== ENTER ====="); Console.ReadLine(); }