Guest User

Untitled

a guest
Jan 21st, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.41 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Security.Cryptography;
  7. using System.Net.Sockets;
  8. using System.Net;
  9. using System.Collections;
  10. using System.Threading;
  11.  
  12. namespace sockerv4
  13. {
  14.  
  15.  
  16. class Program
  17. {
  18. private static byte[] _buffer = new byte[2048];
  19. private static IDictionary<string, Socket> clients = new Dictionary<string, Socket>();
  20.  
  21. private static IList socket_list = new ArrayList();
  22.  
  23. static void Main()
  24. {
  25. Console.WriteLine("Program Start");
  26.  
  27. Socket socket = open_main_socket();
  28.  
  29.  
  30. Console.ReadKey();
  31. }
  32.  
  33. private static Socket open_main_socket()
  34. {
  35.  
  36. try
  37. {
  38.  
  39. IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("192.168.0.7"), 100);
  40. Console.WriteLine("Opening Main Socket...");
  41. Socket main_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  42. main_socket.Bind(endpoint);
  43. listen_new(main_socket);
  44. clients.Add("main_socket", main_socket);
  45. return main_socket;
  46. }
  47. catch (SocketException e)
  48. {
  49. Console.WriteLine("Socket Error Occured (Main Socket):" + e.Message);
  50. return null;
  51. }
  52.  
  53. }
  54. private static void listen_new(Socket sock)
  55. {
  56.  
  57. try
  58. {
  59. Console.WriteLine("Listening Incoming Connnection...");
  60. sock.Listen(5);
  61. sock.BeginAccept(new AsyncCallback(start_accept_new), sock);
  62. }
  63. catch (SocketException e)
  64. {
  65. Console.WriteLine("Socket Error Occured (Listen New):" + e.Message);
  66. }
  67. }
  68. private static void start_accept_new(IAsyncResult AR)
  69. {
  70. try {
  71. Console.WriteLine("Accepting New Connection....");
  72. Socket sock = ((Socket)AR.AsyncState).EndAccept(AR);
  73. listen_new((Socket)AR.AsyncState);
  74. sock.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(begin_handshake), sock);
  75. } catch (SocketException e)
  76. {
  77. Console.WriteLine("Socket Error Occured(Start Accept New):" + e.Message);
  78. }
  79.  
  80. }
  81. private static void begin_handshake(IAsyncResult AR)
  82. {
  83. Console.WriteLine("Shaking Hands");
  84. Socket sock = ((Socket)AR.AsyncState);
  85. int Data = sock.EndReceive(AR);
  86. byte[] databyte = new byte[Data];
  87. Array.Copy(_buffer, databyte, Data);
  88.  
  89. String text = Encoding.ASCII.GetString(databyte);
  90. List<string> headers = retriveheaders(text);
  91. acceptuser(headers, sock);
  92.  
  93. }
  94. private static void acceptuser(List<string> headers, Socket sock) {
  95.  
  96. ICollection<string> keys = (clients.Keys);
  97. IList user_list = new ArrayList();
  98. user_list = keys.ToList();
  99.  
  100. if (user_list.Contains(headers[0])) {
  101.  
  102. Console.Write("User Already Connectedn");
  103. Socket currentsock;
  104. bool check = clients.TryGetValue(headers[0], out currentsock);
  105.  
  106.  
  107. close_frame(currentsock);
  108. clients.Remove(headers[0]);
  109.  
  110.  
  111. string handshake;
  112. string Key = headers[4].Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  113. SHA1 sha = new SHA1CryptoServiceProvider();
  114. clients.Add(headers[0], sock);
  115. byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(Key));
  116. handshake = Convert.ToBase64String(hash);
  117. string AcceptKey = "HTTP/1.1 101 Switching ProtocolsrnUpgrade: websocketrnConnection: UpgradernSec-WebSocket-Protocol: " + headers[5].Trim() + "rnSec-WebSocket-Accept: " + handshake.Trim() + "rnrn";
  118. send_handshake(AcceptKey, sock);
  119. message_listener(sock);
  120.  
  121. }
  122. else
  123. {
  124.  
  125. string handshake;
  126. string Key = headers[4].Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  127. SHA1 sha = new SHA1CryptoServiceProvider();
  128. clients.Add(headers[0], sock);
  129. byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(Key));
  130. handshake = Convert.ToBase64String(hash);
  131. string AcceptKey = "HTTP/1.1 101 Switching ProtocolsrnUpgrade: websocketrnConnection: UpgradernSec-WebSocket-Protocol: " + headers[5].Trim() + "rnSec-WebSocket-Accept: " + handshake.Trim() + "rnrn";
  132. send_handshake(AcceptKey, sock);
  133. message_listener(sock);
  134. }
  135.  
  136. }
  137.  
  138. private static void close_frame(Socket sock)
  139. {
  140.  
  141. Byte[] frame = new Byte[2];
  142. frame[0] = (Byte)136;
  143. frame[1] = 0;
  144. try
  145. {
  146. sock.Send(frame);
  147.  
  148. }
  149. catch (SocketException e)
  150. {
  151. Console.Write("Error Occured" + e.Message);
  152. }
  153.  
  154.  
  155. }
  156. private static void message_listener(Socket insock)
  157. {
  158. start(insock);
  159.  
  160. void start(Socket sock) {
  161. Console.WriteLine("Looping Handle: " + sock.Handle);
  162. byte[] m_buffer = new byte[5000];
  163. try
  164. {
  165. sock.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.None, ar => { int dat = sock.EndReceive(ar); processdata(m_buffer, dat, ar); }, sock);
  166.  
  167. }
  168. catch (Exception e) {
  169.  
  170. Console.WriteLine("Error Occured Begin Receive: "+ e.Message);
  171. }
  172.  
  173.  
  174. }
  175.  
  176. void processdata(byte[] r_buffer, int size,IAsyncResult AR)
  177. {
  178.  
  179. Socket sockp = ((Socket)AR.AsyncState);
  180.  
  181. Console.WriteLine("Data Received: " + size);
  182. Console.WriteLine("IAsync Result: " + AR.AsyncState);
  183. Console.WriteLine("Opcode"+ (r_buffer[0] & 81));
  184. switch (r_buffer[0]&81) {
  185. case 1:
  186. datadecode(r_buffer);
  187. start(sockp);
  188. break;
  189. case 0:
  190. if (size==6) {
  191. string myKey = clients.FirstOrDefault(x => x.Value == sockp).Key;
  192. if (myKey!=null) {
  193. close_frame(sockp);
  194. sockp.Shutdown(SocketShutdown.Both);
  195. sockp.Close();
  196. sockp.Dispose();
  197. clients.Remove(myKey);
  198. }
  199. else {
  200.  
  201. sockp.Shutdown(SocketShutdown.Both);
  202. sockp.Close();
  203. sockp.Dispose();
  204.  
  205. }
  206.  
  207. }
  208. else {
  209. sockp.Shutdown(SocketShutdown.Both);
  210. sockp.Close();
  211. sockp.Dispose();
  212. string myKey = clients.FirstOrDefault(x => x.Value == sockp).Key;
  213. clients.Remove(myKey);
  214. }
  215. break;
  216. default:
  217. Console.WriteLine("Default Switch");
  218. break;
  219.  
  220. }
  221.  
  222. }
  223.  
  224. }
  225.  
  226. private static void send_data(String data, Socket socket)
  227. {
  228. byte[] r_data = EncodeMessageToSend(data);
  229. try
  230. {
  231. Console.Write("Sending Handshake:n");
  232. socket.BeginSend(r_data, 0, r_data.Length, SocketFlags.None, new AsyncCallback(sent), socket);
  233. }
  234. catch (SocketException e)
  235. {
  236. Console.WriteLine("Socket Error Occured When sending data 1: " + e.Message);
  237. }
  238. }
  239.  
  240.  
  241. private static void send_handshake(String data, Socket socket)
  242. {
  243. byte[] send_key = Encoding.UTF8.GetBytes(data);
  244. try {
  245. Console.Write("Sending Handshake:n");
  246. socket.BeginSend(send_key, 0, send_key.Length, SocketFlags.None, new AsyncCallback(sent), socket);
  247. } catch (SocketException e) {
  248. Console.WriteLine("Socket Error Occured When sending data 1: " + e.Message);
  249. }
  250. }
  251.  
  252. private static void sent(IAsyncResult AR)
  253. {
  254. Socket sock = (Socket)AR.AsyncState;
  255. try {
  256. sock.EndSend(AR);
  257.  
  258. }
  259. catch (SocketException e){
  260.  
  261. Console.WriteLine("Socket Error Occured When sending data 2: " + e.Message);
  262. }
  263. }
  264.  
  265.  
  266. private static List<string> retriveheaders(String Data)
  267. {
  268. Console.Write("Retriveing Headersn");
  269.  
  270. List<string> headers = new List<string>();
  271.  
  272. headers.Add(Regex.Match(Data, "(?<=GET /)(.*)(?= HTTP)").ToString());
  273. headers.Add(Regex.Match(Data, "(?<=Host: )(.*)[?=rn*]").ToString());
  274. headers.Add(Regex.Match(Data, "(?<=Upgrade: )(.*)[?=rn]").ToString());
  275. headers.Add(Regex.Match(Data, "(?<=Connection: )(.*)[?=rn]").ToString());
  276. headers.Add(Regex.Match(Data, "(?<=Sec-WebSocket-Key: )(.*)[?=rn]").ToString());
  277. headers.Add(Regex.Match(Data, "(?<=Sec-WebSocket-Protocol: )(.*)[?=rn]").ToString());
  278. headers.Add(Regex.Match(Data, "(?<=Sec-WebSocket-Version: )(.*)[?=rn]").ToString());
  279. headers.Add(Regex.Match(Data, "(?<=Origin: )(.*)rn").ToString());
  280. headers.Add(Regex.Match(Data, "rn(.*)$").ToString());
  281.  
  282. return headers;
  283.  
  284. }
  285. private static Byte[] EncodeMessageToSend(String message)
  286. {
  287. Byte[] response;
  288. Byte[] bytesRaw = Encoding.UTF8.GetBytes(message);
  289. Byte[] frame = new Byte[10];
  290.  
  291. Int32 indexStartRawData = -1;
  292. Int32 length = bytesRaw.Length;
  293.  
  294. frame[0] = (Byte)129;
  295. if (length <= 125)
  296. {
  297. frame[1] = (Byte)length;
  298. indexStartRawData = 2;
  299. }
  300. else if (length >= 126 && length <= 65535)
  301. {
  302. frame[1] = (Byte)126;
  303. frame[2] = (Byte)((length >> 8) & 255);
  304. frame[3] = (Byte)(length & 255);
  305. indexStartRawData = 4;
  306. }
  307. else
  308. {
  309. frame[1] = (Byte)127;
  310. frame[2] = (Byte)((length >> 56) & 255);
  311. frame[3] = (Byte)((length >> 48) & 255);
  312. frame[4] = (Byte)((length >> 40) & 255);
  313. frame[5] = (Byte)((length >> 32) & 255);
  314. frame[6] = (Byte)((length >> 24) & 255);
  315. frame[7] = (Byte)((length >> 16) & 255);
  316. frame[8] = (Byte)((length >> 8) & 255);
  317. frame[9] = (Byte)(length & 255);
  318.  
  319. indexStartRawData = 10;
  320. }
  321.  
  322. response = new Byte[indexStartRawData + length];
  323.  
  324. Int32 i, reponseIdx = 0;
  325.  
  326. //Add the frame bytes to the reponse
  327. for (i = 0; i < indexStartRawData; i++)
  328. {
  329. response[reponseIdx] = frame[i];
  330. reponseIdx++;
  331. }
  332.  
  333. //Add the data bytes to the response
  334. for (i = 0; i < length; i++)
  335. {
  336. response[reponseIdx] = bytesRaw[i];
  337. reponseIdx++;
  338. }
  339.  
  340. return response;
  341. }
  342.  
  343. private static void datadecode(byte[] rawdata)
  344. {
  345. Console.WriteLine("Message Unmaskingn");
  346.  
  347. Thread.Sleep(10000);
  348.  
  349. var fin = rawdata[0] & 0x81;
  350.  
  351. bool res = fin != 129;
  352. Console.WriteLine("Opcode:" + res);
  353. var Lenght = rawdata[1] & 127;
  354. byte b = rawdata[1];
  355. int totalLength = 0;
  356. int keyIndex = 0;
  357. int dataLength = 0;
  358.  
  359.  
  360. if (Lenght <= 125)
  361. {
  362.  
  363. keyIndex = 2;
  364. totalLength = Lenght + 6;
  365. dataLength = Lenght;
  366.  
  367. }
  368.  
  369. if (Lenght == 126)
  370. {
  371.  
  372. dataLength = (int)BitConverter.ToUInt16(new byte[] { rawdata[3], rawdata[2] }, 0);
  373. keyIndex = 4;
  374. totalLength = dataLength + 8;
  375.  
  376. }
  377. if (Lenght == 127)
  378. {
  379.  
  380. dataLength = (int)BitConverter.ToInt64(new byte[] { rawdata[9], rawdata[8], rawdata[7], rawdata[6], rawdata[5], rawdata[4], rawdata[3], rawdata[2] }, 0);
  381. keyIndex = 10;
  382. totalLength = dataLength + 14;
  383.  
  384. }
  385.  
  386. byte[] key = new byte[] { rawdata[keyIndex], rawdata[keyIndex + 1], rawdata[keyIndex + 2], rawdata[keyIndex + 3] };
  387.  
  388. int dataIndex = keyIndex + 4;
  389. int count = 0;
  390.  
  391.  
  392. for (int i = dataIndex; i < totalLength; i++)
  393. {
  394. rawdata[i] = (byte)(rawdata[i] ^ key[count % 4]);
  395. count++;
  396. }
  397.  
  398. string message = Encoding.ASCII.GetString(rawdata, dataIndex, dataLength);
  399.  
  400. Console.WriteLine("Message Recieved:" + message);
  401.  
  402.  
  403. }
  404.  
  405. }
  406. }
Add Comment
Please, Sign In to add comment