-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.aspx.cs
249 lines (220 loc) · 6.75 KB
/
response.aspx.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Net;
using System.Configuration;
namespace LetsEncryptProxy
{
public partial class response : System.Web.UI.Page
{
List<string> WhiteListedHosts = new List<string>();
static string LetsEncryptDirectories = "/.well-known/acme-challenge/";
static bool EnableLogging = false;
protected void Page_Load(object sender, EventArgs e)
{
// Get the list of whitelisted host names from web.config
WhiteListedHosts = ConfigurationManager.AppSettings["DnsHostWhiteList"].Split(';').ToList();
// Get from web.config if logging is enabled. If true, you might consider change the logging directory (see notes in WriteLog())
bool.TryParse(ConfigurationManager.AppSettings["EnableLogging"].ToString(), out EnableLogging);
string userHost = string.Empty;
string rawUrl = string.Empty;
string dnsSafeHost = string.Empty;
bool isLetsEncrypt = false;
if (Request.Url != null)
{
if (!string.IsNullOrEmpty(Request.Url.DnsSafeHost))
{
dnsSafeHost = Request.Url.DnsSafeHost;
}
if (!string.IsNullOrEmpty(Request.RawUrl))
{
rawUrl = Request.RawUrl;
}
if(!string.IsNullOrEmpty(Request.UserHostAddress))
{
userHost = Request.UserHostAddress;
}
// check if rawurl begins with /.well-known/acme-challenge/
isLetsEncrypt = rawUrl.ToLower().StartsWith(LetsEncryptDirectories);
}
string ResponseString = "";
// check if dnsSafeHost is whitelisted
bool hostNameIsEnabled = HostNameIsEnabled(dnsSafeHost);
if (isLetsEncrypt && hostNameIsEnabled)
{
if (rawUrl.IndexOf('/') > -1)
{
string token = rawUrl.Substring(rawUrl.LastIndexOf('/'));
if (!string.IsNullOrEmpty(token))
{
token = token.Replace("/", "").Trim();
//check if url token length is 43
if (token.Length == 43)
{
// reads the Key from the token file on client
ResponseString = GetKey(dnsSafeHost, token);
}
else
{
WriteLog("Token has wrong length (" + token.Length + ", should be 43): " + token, true);
}
}
else
{
WriteLog("Token is null or empty", true);
}
}
else
{
WriteLog("rawurl is has no /", true);
}
}
else if(!hostNameIsEnabled)
{
WriteLog("Host " + dnsSafeHost + " is not whitelisted in web.config", true);
}
LogVisit(dnsSafeHost, rawUrl, userHost, isLetsEncrypt, ResponseString);
if(isLetsEncrypt)
{
Response.Write(ResponseString);
Response.End();
}
}
/// <summary>
/// Checks if hostname is whitelisted (in WhiteListedHosts from web.config)
/// </summary>
/// <param name="hostName">host name to check (case ignored)</param>
/// <returns></returns>
bool HostNameIsEnabled(string hostName)
{
if (!string.IsNullOrEmpty(hostName))
{
hostName = hostName.ToLower();
foreach (string host in WhiteListedHosts)
{
if (host=="*")
{
return true;
}
if(hostName==host.ToLower())
{
return true;
}
}
}
return false;
}
/// <summary>
/// Gets the token file content from the client
/// </summary>
/// <param name="host">Host name</param>
/// <param name="token">Token (file name)</param>
/// <returns></returns>
string GetKey(string host, string token)
{
string key = string.Empty;
// the LAN internal path to the token file on the client
string url = "http://" + host + LetsEncryptDirectories + token;
using (System.Net.WebClient wc = new System.Net.WebClient())
{
try
{
// try to fetch the token file content from the client via HTTP
key = wc.DownloadString(url);
}
catch (Exception e)
{
WriteLog(e.ToString() +" "+ url, true);
}
// Some web server configurations only allow HTTPS connections. So if HTTP doesn't work, it will try HTTPS.
if(string.IsNullOrEmpty(key))
{
url = url.Replace("http://", "https://");
try
{
// try to fetch the token file content from the client via HTTPS
key = wc.DownloadString(url);
}
catch (Exception e)
{
WriteLog(e.ToString() + " " + url, true);
}
}
//check if key has a length other than 87 (which means it would be invalid)
if (string.IsNullOrEmpty(key) || key.Length != 87)
{
key = string.Empty;
WriteLog("Key has wrong length (" + key.Length + ", should be 87): " + key, true);
}
}
return key;
}
/// <summary>
/// Logs a request
/// </summary>
/// <param name="DnsSafeHost">Host name</param>
/// <param name="RawUrl">Raw URL</param>
/// <param name="UserHost">User host</param>
/// <param name="IsLetsEncrypt"></param>
/// <param name="ResponseString"></param>
void LogVisit(string DnsSafeHost, string RawUrl, string UserHost, bool IsLetsEncrypt, string ResponseString = "")
{
StringBuilder sb = new StringBuilder();
sb.Append(DnsSafeHost);
sb.Append("\t");
sb.Append(RawUrl);
sb.Append("\t");
sb.Append(UserHost);
if(!string.IsNullOrEmpty(ResponseString))
{
sb.Append("\t");
sb.Append(ResponseString);
}
string toLog = sb.ToString();
if(!string.IsNullOrEmpty(toLog))
{
WriteLog(toLog, IsLetsEncrypt);
}
}
static object loglock = new object();
/// <summary>
/// Writes an entry to a log file. One log file per day, one for all requests, one for letsencrypt requests only
/// </summary>
/// <param name="s">String to write</param>
/// <param name="IsLetsEncrypt">Determines if requests is a challenge response request</param>
void WriteLog(string s, bool IsLetsEncrypt)
{
if (EnableLogging)
{
string prefix = string.Empty;
if (IsLetsEncrypt)
{
prefix = "letsencrypt_";
}
// For security reasons you should not use a public log file path. Change it to a non relative. The Application of course needs write access to that directory.
string dirPath = Server.MapPath("~/Logs/");
// Static path example:
//string dirPath = @"C:\inetpub\logs\letsencryptproxy\";
string fileName = prefix + "log_" + DateTime.Now.ToString("ddMMyyyy") + ".txt";
string fullPath = Path.Combine(dirPath, fileName);
if (!string.IsNullOrEmpty(s))
{
lock (loglock)
{
using (System.IO.TextWriter writeFile = new StreamWriter(fullPath, true))
{
writeFile.WriteLine(DateTime.Now.ToString() + "\t" + s);
writeFile.Flush();
writeFile.Close();
}
}
}
}
}
}
}