-
Notifications
You must be signed in to change notification settings - Fork 0
/
bankServer_connection.cs
342 lines (296 loc) · 12.8 KB
/
bankServer_connection.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
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
338
339
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Net.Json;
using System.Net.Security;
using System.Security.Authentication;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using BankServer;
// new changes
namespace BankServer
{
public class HttpProcessor {
public TcpClient socket;
public HttpServer srv;
public X509Certificate serverCert;
public SslStream sslStream;
public String http_method;
public String http_url;
public String http_protocol_versionstring;
public Hashtable httpHeaders = new Hashtable();
private static int MAX_POST_SIZE = 10 * 1024 * 1024; // 10MB
public HttpProcessor(TcpClient s, HttpServer srv, X509Certificate serverCertificate) {
this.socket = s;
this.srv = srv;
this.serverCert = serverCertificate;
}
private string streamReadLine(SslStream inputStream) {
int next_char;
string data = "";
while (true) {
next_char = inputStream.ReadByte();
if (next_char == '\n') { break; }
if (next_char == '\r') { continue; }
if (next_char == -1) { Thread.Sleep(1); continue; };
data += Convert.ToChar(next_char);
}
return data;
}
public void process() {
// A client has connected. Create the
// sslStream using the client's network stream.
sslStream = new SslStream(socket.GetStream(), false);
// Authenticate the server but don't require the client to authenticate.
try
{
sslStream.AuthenticateAsServer(serverCert,
false, SslProtocols.Tls, true);
// Display the properties and settings for the authenticated stream.
DisplaySecurityLevel(sslStream);
DisplaySecurityServices(sslStream);
DisplayCertificateInformation(sslStream);
DisplayStreamProperties(sslStream);
// Set timeouts for the read and write to 5 seconds.
sslStream.ReadTimeout = 5000;
sslStream.WriteTimeout = 5000;
Console.WriteLine("Read timeout: " + sslStream.ReadTimeout);
Console.WriteLine("Write timeout: " + sslStream.WriteTimeout);
// Write status message to the client.
byte[] message = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\n");
Console.WriteLine("Sending status message.");
sslStream.Write(message);
try
{
parseRequest();
readHeaders();
if (http_method.Equals("GET"))
{
Console.WriteLine("http_method: " + http_method);
handleGETRequest();
}
else if (http_method.Equals("POST"))
{
Console.WriteLine("http_method: " + http_method);
handlePOSTRequest();
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
writeFailure();
return;
}
}
catch (AuthenticationException e)
{
Console.WriteLine("Exception: {0}", e.Message);
if (e.InnerException != null)
{
Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
}
Console.WriteLine("Authentication failed - closing the connection.");
sslStream.Close();
socket.Close();
return;
}
finally
{
// The client stream will be closed with the sslStream
// because we specified this behavior when creating
// the sslStream.
sslStream.Close();
socket.Close();
}
}
public void parseRequest() {
String request = streamReadLine(sslStream);
string[] tokens = request.Split(' ');
if (tokens.Length != 3) {
throw new Exception("invalid http request line");
}
http_method = tokens[0].ToUpper();
http_url = tokens[1];
http_protocol_versionstring = tokens[2];
Console.WriteLine("starting: " + request);
}
public void readHeaders() {
Console.WriteLine("readHeaders()");
String line;
while ((line = streamReadLine(sslStream)) != null) {
if (line.Equals("")) {
Console.WriteLine("got headers");
return;
}
int separator = line.IndexOf(':');
if (separator == -1) {
throw new Exception("invalid http header line: " + line);
}
String name = line.Substring(0, separator);
int pos = separator + 1;
while ((pos < line.Length) && (line[pos] == ' ')) {
pos++; // strip any spaces
}
string value = line.Substring(pos, line.Length - pos);
Console.WriteLine("header: {0}:{1}",name,value);
httpHeaders[name] = value;
}
}
public void handleGETRequest() {
srv.handleGETRequest(this);
}
private const int BUF_SIZE = 4096;
public void handlePOSTRequest() {
// this post data processing just reads everything into a memory stream.
// this is fine for smallish things, but for large stuff we should really
// hand an input stream to the request processor. However, the input stream
// we hand him needs to let him see the "end of the stream" at this content
// length, because otherwise he won't know when he's seen it all!
Console.WriteLine("get post data start");
int content_len = 0;
MemoryStream ms = new MemoryStream();
if (this.httpHeaders.ContainsKey("Content-Length")) {
content_len = Convert.ToInt32(this.httpHeaders["Content-Length"]);
if (content_len > MAX_POST_SIZE) {
throw new Exception(
String.Format("POST Content-Length({0}) too big for this simple server",
content_len));
}
byte[] buf = new byte[BUF_SIZE];
int to_read = content_len;
while (to_read > 0) {
Console.WriteLine("starting Read, to_read={0}",to_read);
int numread = this.sslStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read));
Console.WriteLine("read finished, numread={0}", numread);
if (numread == 0) {
if (to_read == 0) {
break;
} else {
throw new Exception("client disconnected during post");
}
}
to_read -= numread;
ms.Write(buf, 0, numread);
}
ms.Seek(0, SeekOrigin.Begin);
}
Console.WriteLine("get post data end");
srv.handlePOSTRequest(this, new StreamReader(ms));
}
public void writeFailure() {
string text = "HTTP/1.1 404 File not found\n"+"Connection: close\n";
byte[] message = Encoding.UTF8.GetBytes(text);
sslStream.Write(message);
}
static void DisplaySecurityLevel(SslStream stream)
{
Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
Console.WriteLine("Protocol: {0}", stream.SslProtocol);
}
static void DisplaySecurityServices(SslStream stream)
{
Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
Console.WriteLine("IsSigned: {0}", stream.IsSigned);
Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
}
static void DisplayStreamProperties(SslStream stream)
{
Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
}
static void DisplayCertificateInformation(SslStream stream)
{
Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);
X509Certificate localCertificate = stream.LocalCertificate;
if (stream.LocalCertificate != null)
{
Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
localCertificate.Subject,
localCertificate.GetEffectiveDateString(),
localCertificate.GetExpirationDateString());
}
else
{
Console.WriteLine("Local certificate is null.");
}
// Display the properties of the client's certificate.
X509Certificate remoteCertificate = stream.RemoteCertificate;
if (stream.RemoteCertificate != null)
{
Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
remoteCertificate.Subject,
remoteCertificate.GetEffectiveDateString(),
remoteCertificate.GetExpirationDateString());
}
else
{
Console.WriteLine("Remote certificate is null.");
}
}
}
public abstract class HttpServer {
protected int port;
TcpListener listener;
bool is_active = true;
public Hashtable respStatus;
string certificate = null;
static X509Certificate serverCertificate = null;
public HttpServer(int port, string cert) {
this.port = port;
this.certificate = cert;
}
// The certificate parameter specifies the name of the file
// containing the machine certificate.
public void listen() {
serverCertificate = X509Certificate.CreateFromCertFile(certificate);
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
Console.WriteLine("Listening On: " + port.ToString());
while (is_active) {
Console.WriteLine("Waiting for connection...\n");
TcpClient s = listener.AcceptTcpClient();
HttpProcessor processor = new HttpProcessor(s, this, serverCertificate);
Thread thread = new Thread(new ThreadStart(processor.process));
thread.Start();
Thread.Sleep(1);
}
}
public abstract void handleGETRequest(HttpProcessor p);
public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);
}
public class MyHttpServer : HttpServer {
public MyHttpServer(int port, string cert)
: base(port, cert) {
}
public override void handleGETRequest (HttpProcessor p)
{
bankServer_requestHandler.handleRequest(p, null, "GET");
}
public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData) {
bankServer_requestHandler.handleRequest(p, inputData, "POST");
}
}
public class TestMain {
public static int Main(String[] args) {
HttpServer httpServer;
string certificate = null;
if (args.GetLength(0) > 0) {
certificate = args[1];
httpServer = new MyHttpServer(Convert.ToInt16(args[0]), certificate);
} else {
certificate = "TempCert.cer";
httpServer = new MyHttpServer(443, certificate);
}
Thread thread = new Thread(new ThreadStart(httpServer.listen));
thread.Start();
return 0;
}
}
}