Repository navigation
Expand file tree
/
Copy pathScriptInjectionMiddleware.cs
More file actions
150 lines (124 loc) · 5.69 KB
/
Copy pathScriptInjectionMiddleware.cs
File metadata and controls
150 lines (124 loc) · 5.69 KB
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
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace JellyRate;
public class ScriptInjectionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ScriptInjectionMiddleware> _logger;
public ScriptInjectionMiddleware(RequestDelegate next, ILogger<ScriptInjectionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var path = context.Request.Path.Value ?? string.Empty;
if (!IsIndexHtmlRequest(path))
{
await _next(context).ConfigureAwait(false);
return;
}
_logger.LogDebug("JellyRate: Intercepting request - Path={Path}, PathBase={PathBase}",
path, context.Request.PathBase.Value);
// Remove Accept-Encoding to prevent compressed response
context.Request.Headers.Remove("Accept-Encoding");
var originalBodyStream = context.Response.Body;
try
{
using var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;
await _next(context).ConfigureAwait(false);
if (context.Response.StatusCode != 200)
{
await WriteOriginalResponse(memoryStream, originalBodyStream).ConfigureAwait(false);
return;
}
var contentEncoding = context.Response.Headers.ContentEncoding.ToString();
if (!string.IsNullOrEmpty(contentEncoding))
{
await WriteOriginalResponse(memoryStream, originalBodyStream).ConfigureAwait(false);
return;
}
var contentType = context.Response.ContentType ?? string.Empty;
if (!contentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase))
{
await WriteOriginalResponse(memoryStream, originalBodyStream).ConfigureAwait(false);
return;
}
memoryStream.Position = 0;
string responseBody;
using (var reader = new StreamReader(memoryStream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
{
responseBody = await reader.ReadToEndAsync().ConfigureAwait(false);
}
if (string.IsNullOrEmpty(responseBody))
{
await WriteOriginalResponse(memoryStream, originalBodyStream).ConfigureAwait(false);
return;
}
// The on-disk block may be stale (older token or tag): always swap in the current one
responseBody = ScriptInjector.BlockRegex.Replace(responseBody, string.Empty);
var basePath = context.Request.PathBase.Value?.TrimEnd('/') ?? string.Empty;
if (string.IsNullOrEmpty(basePath))
{
var webIndex = path.IndexOf("/web/", StringComparison.OrdinalIgnoreCase);
if (webIndex < 0 && path.EndsWith("/web", StringComparison.OrdinalIgnoreCase))
{
webIndex = path.Length - 4;
}
if (webIndex > 0)
{
basePath = path.Substring(0, webIndex);
}
}
var safeBasePath = System.Net.WebUtility.HtmlEncode(basePath);
var injectionBlock = ScriptInjector.BuildBlock(safeBasePath);
var bodyCloseIndex = responseBody.LastIndexOf("</body>", StringComparison.OrdinalIgnoreCase);
if (bodyCloseIndex == -1)
{
_logger.LogWarning("JellyRate: No </body> tag found in response");
await WriteOriginalResponse(memoryStream, originalBodyStream).ConfigureAwait(false);
return;
}
var modifiedBody = responseBody.Insert(bodyCloseIndex, injectionBlock);
var modifiedBytes = Encoding.UTF8.GetBytes(modifiedBody);
context.Response.Headers.Remove("Content-Length");
context.Response.ContentLength = modifiedBytes.Length;
await originalBodyStream.WriteAsync(modifiedBytes, 0, modifiedBytes.Length).ConfigureAwait(false);
_logger.LogInformation("JellyRate: Successfully injected script tag via middleware");
}
catch (Exception ex)
{
_logger.LogDebug(ex, "JellyRate: Script injection failed, passing through original response");
try
{
await WriteOriginalResponse(context.Response.Body as MemoryStream ?? new MemoryStream(), originalBodyStream).ConfigureAwait(false);
}
catch { /* last resort */ }
}
finally
{
context.Response.Body = originalBodyStream;
}
}
private static async Task WriteOriginalResponse(MemoryStream memoryStream, Stream originalBodyStream)
{
if (memoryStream.Length > 0)
{
memoryStream.Position = 0;
await memoryStream.CopyToAsync(originalBodyStream).ConfigureAwait(false);
}
}
private static bool IsIndexHtmlRequest(string path)
{
return path.Equals("/", StringComparison.OrdinalIgnoreCase)
|| path.Equals("/index.html", StringComparison.OrdinalIgnoreCase)
|| path.Equals("/web", StringComparison.OrdinalIgnoreCase)
|| path.Equals("/web/", StringComparison.OrdinalIgnoreCase)
|| path.Equals("/web/index.html", StringComparison.OrdinalIgnoreCase)
|| path.EndsWith("/web", StringComparison.OrdinalIgnoreCase)
|| path.EndsWith("/web/", StringComparison.OrdinalIgnoreCase)
|| path.EndsWith("/web/index.html", StringComparison.OrdinalIgnoreCase);
}
}