ws_bert_login.d 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. alias int8 = byte; // -128 — 127
  2. alias int16 = short; // -32768 — 32767
  3. alias int32 = int; // -2147483648 — 2147483647
  4. alias int64 = long; // -9223372036854775808 — 9223372036854775807
  5. alias uint8 = ubyte; // 0 — 255
  6. alias uint16 = ushort; // 0 — 65535
  7. alias uint32 = uint; // 0 — 4294967295
  8. alias uint64 = ulong; // 0 — 18446744073709551615
  9. alias f32 = float;
  10. alias f64 = double;
  11. // char '\xFF' unsigned 8 bit (UTF-8 code unit)
  12. // wchar '\uFFFF' unsigned 16 bit (UTF-16 code unit)
  13. // dchar '\U0000FFFF' unsigned 32 bit (UTF-32 code unit)
  14. import vibe.core.core;
  15. import vibe.http.router;
  16. import vibe.http.server;
  17. import vibe.http.fileserver;
  18. import vibe.http.websockets;
  19. import vibe.core.log;
  20. import std.stdio;
  21. import std.string;
  22. import std.array;
  23. import std.conv : to;
  24. import bert; // https://github.com/221V/dlang_erl_bert https://git.4dev.win/game1/dlang_erl_bert
  25. import secured.symmetric; // https://github.com/221V/SecureD // https://github.com/221V/js_AES256CBC
  26. import secured.rsa;
  27. import session;
  28. import mustache;
  29. alias MustacheEngine!(string) Mustache;
  30. string byte_arr_to_str(ubyte[] arr){
  31. string[] str_arr;
  32. foreach(elem; arr){
  33. str_arr ~= to!string(elem);
  34. }
  35. return "[" ~ str_arr.join(",") ~ "]";
  36. }
  37. ubyte[] str_to_byte_arr(string str_arr){
  38. str_arr = str_arr.replace("[", "").replace("]", "");
  39. string[] parts = str_arr.split(",");
  40. ubyte[] result;
  41. result.reserve(parts.length);
  42. foreach(part; parts){
  43. result ~= to!ubyte(part.strip());
  44. }
  45. return result;
  46. }
  47. void ws_bert_handle(scope WebSocket sock){
  48. //foreach(pair; req.headers.byKeyValue()){
  49. // writeln("Header: ", pair.key, " = ", pair.value);
  50. //}
  51. // simple echo server + :)
  52. //string client_id = req.attributes.get("client_id", "");
  53. //writeln("96 client_id = ", client_id);
  54. // https://vibed.org/api/vibe.http.websockets/WebSocket
  55. // https://vibed.org/api/vibe.http.websockets/WebSocket.request
  56. // https://vibed.org/api/vibe.http.server/HTTPServerRequest
  57. //writeln("sock.request = ", sock.request); // GET /ws_login_test HTTP/1.1
  58. //writeln("sock.request.headers = ", sock.request.headers); // ["Host": "127.0.0.1:8080", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:135.0) Gecko/20100101 Firefox/135.0", "Accept": "*/*", "Accept-Language": "uk-UA,uk;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate, br, zstd", "Sec-WebSocket-Version": "13", "Origin": "http://127.0.0.1:8080", "Sec-WebSocket-Extensions": "permessage-deflate", "Sec-WebSocket-Key": "NW+zQGtSdkuSRHWuU/VevA==", "DNT": "1", "Sec-GPC": "1", "Connection": "keep-alive, Upgrade", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "websocket", "Sec-Fetch-Site": "same-origin", "Pragma": "no-cache", "Cache-Control": "no-cache", "Upgrade": "websocket"]
  59. //writeln("sock.request.context = ", sock.request.context); // []
  60. //writeln("sock.request.params = ", sock.request.params); // []
  61. //string client_id = req.params.get("client_id", "");
  62. while(sock.connected){
  63. //auto msg = sock.receiveText();
  64. //sock.send(msg ~ " :)");
  65. auto msg = sock.receiveBinary();
  66. if(msg == "1"){
  67. sock.send("0"); // ws PING - PONG
  68. }else{
  69. writeln("Received: ", msg);
  70. auto decoder = new BertDecoder( cast(ubyte[])msg.dup );
  71. auto decoded = decoder.decode();
  72. msg_match(decoded, sock);
  73. }
  74. }
  75. // todo delete data in userSessions here
  76. }
  77. void msg_match(BertValue decoded, WebSocket sock){
  78. writeln("Decoded: ", decoded.toString());
  79. auto rsa_keypair = new RSA(2048); // Only allows for (2048/8)-42 = 214 bytes to be asymmetrically RSA encrypted
  80. scope(exit) rsa_keypair.destroy();
  81. ubyte[] rsa_private_key = rsa_keypair.getPrivateKey(null);
  82. ubyte[] rsa_public_key = rsa_keypair.getPublicKey();
  83. //writeln("rsa_private_key = ", rsa_private_key);
  84. //writeln("rsa_public_key = ", rsa_public_key);
  85. //ubyte[214] plaintext214 = 2; // 2 being an arbitrary value
  86. auto plaintext214 = cast(ubyte[])"12345678testтест";
  87. ubyte[] encMessage214 = rsa_keypair.encrypt(plaintext214);
  88. //writeln("encMessage214.length = ", encMessage214.length); // 256
  89. //writeln("encMessage214 = ", encMessage214);
  90. ubyte[] decMessage214 = rsa_keypair.decrypt(encMessage214);
  91. //writeln("decMessage214 = ", decMessage214);
  92. writeln("decMessage214 = ", cast(string)decMessage214);
  93. ubyte[] key;
  94. ubyte[] iv;
  95. if(decoded.type_ == BertType.Tuple){
  96. auto decoded1 = decoded.tupleValue;
  97. if(decoded1.length == 1){
  98. if(auto num1 = cast(uint8)decoded1[0].intValue){ // we can use js AES for additional password encrypt for login-logout // ws.send(enc(tuple( number(1) )));
  99. if(num1 == 1){ // init login -- get key + iv for encrypt password and send to server
  100. /*
  101. ubyte[] test_pass = cast(ubyte[])"12345678";
  102. SymmetricKey key = generateSymmetricKey( SymmetricAlgorithm.AES256_CBC );
  103. EncryptedData enc = encrypt(key, test_pass);
  104. //auto iv_hex = toHexString!(LetterCase.lower)(enc.iv);
  105. //auto encrypt = toHexString!(LetterCase.lower)(enc.cipherText);
  106. auto iv_hex = enc.iv;
  107. auto encrypt = enc.cipherText;
  108. writeln("Key: ", key.key);
  109. //writeln("Key: ", key.toString); // base64 encoded string
  110. //writeln("IV: ", toHexString!(LetterCase.lower)(enc.iv));
  111. writeln("IV: ", iv_hex);
  112. //writeln("Encrypt: ", enc);
  113. writeln("Encrypt: ", encrypt);
  114. */
  115. SymmetricKeyIV rand_key_iv = generateSymmetricKeyIV(); // default SymmetricAlgorithm.AES256_CBC
  116. writeln("rand key: ", rand_key_iv.key);
  117. writeln("rand iv: ", rand_key_iv.iv);
  118. string client_id = generateCookie();
  119. userSessions[client_id ~ "_key"] = rand_key_iv.key;
  120. userSessions[client_id ~ "_iv"] = rand_key_iv.iv;
  121. /*
  122. //auto test_pass = cast(ubyte[])"12345678";
  123. auto test_pass = cast(ubyte[])"12345678testтест";
  124. auto key = cast(ubyte[])[34, 74, 12, 214, 126, 234, 101, 147, 13, 32, 244, 185, 45, 217, 142, 33, 213, 116, 63, 179, 84, 23, 138, 187, 134, 130, 234, 54, 48, 66, 20, 152];
  125. auto iv = cast(ubyte[])[62, 133, 213, 219, 194, 200, 76, 142, 202, 16, 12, 237, 163, 147, 65, 93];
  126. auto encrypted = encrypt(key, iv, test_pass, SymmetricAlgorithm.AES256_CBC);
  127. writeln("Encrypted: ", encrypted.cipherText); // [223, 86, 210, 55, 192, 240, 144, 50, 159, 4, 238, 182, 171, 185, 80, 48] // [90, 85, 212, 32, 94, 33, 182, 43, 20, 183, 121, 59, 232, 45, 180, 158, 153, 9, 54, 45, 244, 32, 85, 24, 162, 206, 56, 235, 107, 194, 143, 192]
  128. //auto encrypted_data = cast(ubyte[])[223, 86, 210, 55, 192, 240, 144, 50, 159, 4, 238, 182, 171, 185, 80, 48];
  129. auto encrypted_data = cast(ubyte[])[90, 85, 212, 32, 94, 33, 182, 43, 20, 183, 121, 59, 232, 45, 180, 158, 153, 9, 54, 45, 244, 32, 85, 24, 162, 206, 56, 235, 107, 194, 143, 192];
  130. ubyte[] decrypted = decrypt(key, iv, encrypted_data, SymmetricAlgorithm.AES256_CBC);
  131. writeln("Decrypted: ", decrypted); // [49, 50, 51, 52, 53, 54, 55, 56] // [49, 50, 51, 52, 53, 54, 55, 56, 116, 101, 115, 116, 209, 130, 208, 181, 209, 129, 209, 130]
  132. writeln("Decrypted: ", cast(string)decrypted); // "12345678" // "12345678testтест"
  133. */
  134. sock.send("{window.key = new Uint8Array(" ~ byte_arr_to_str(rand_key_iv.key) ~ ");" ~
  135. "window.iv = new Uint8Array(" ~ byte_arr_to_str(rand_key_iv.iv) ~ ");" ~
  136. "window.uid = '" ~ client_id ~ "';" ~
  137. "do_log_in();}");
  138. /*
  139. ubyte[] key = sock.context.get("aes_key", "");
  140. ubyte[] iv = sock.context.get("aes_iv", "");
  141. if( key.empty || iv.empty ){}else{
  142. sock.send("{window.key = new Uint8Array(" ~ byte_arr_to_str(key) ~ ");" ~
  143. "window.iv = new Uint8Array(" ~ byte_arr_to_str(iv) ~ ");" ~
  144. "do_log_in();}");
  145. }
  146. */
  147. } // else do nothing
  148. } // else do nothing
  149. }else if(decoded1.length == 4){ // {2, "uid", "login", "encrypted_pass"}
  150. if(auto code2 = cast(uint8)decoded1[0].intValue){ // 2
  151. if(code2 == 2){
  152. if(auto client_id = cast(string)decoded1[1].binaryValue){
  153. writeln("client_id = ", client_id);
  154. if(auto login_str = cast(string)decoded1[2].binaryValue){
  155. writeln("login_str = ", login_str);
  156. if(auto maybe_encrypted_pass = cast(string)decoded1[3].binaryValue){
  157. writeln("maybe_encrypted_pass = ", maybe_encrypted_pass, " ", typeof(maybe_encrypted_pass).stringof); // Decoded: {2, <<116,101,115,116,49>>, <<91,49,50,53,44,50,51,54,44,50,50,48,44,50,53,53,44,49,50,48,44,49,54,57,44,49,56,51,44,49,48,50,44,50,49,49,44,51,53,44,50,52,54,44,50,49,55,44,55,49,44,50,54,44,50,49,50,44,56,56,93>>} // maybe_encoded_pass = [125,236,220,255,120,169,183,102,211,35,246,217,71,26,212,88] string
  158. //sock.send("{console.log('" ~ str1 ~ " la-la-la" ~ "')}"); //
  159. try{
  160. auto encrypted_pass = str_to_byte_arr(maybe_encrypted_pass);
  161. writeln("encoded_pass = ", encrypted_pass);
  162. if( (client_id ~ "_key") in userSessions){
  163. key = userSessions[client_id ~ "_key"];
  164. }
  165. if( (client_id ~ "_iv") in userSessions){
  166. iv = userSessions[client_id ~ "_iv"];
  167. }
  168. writeln("key = ", key);
  169. writeln("iv = ", iv);
  170. ubyte[] pass = decrypt(key, iv, encrypted_pass, SymmetricAlgorithm.AES256_CBC);
  171. writeln("Decrypted: ", pass); // byte array
  172. writeln("Decrypted: ", cast(string)pass); // string
  173. }catch(Exception e){} // skip err, do nothing
  174. }
  175. } // else do nothing
  176. } // else do nothing
  177. } // else do nothing
  178. } // else do nothing
  179. }else if(decoded1.length == 3){
  180. if(auto num1 = cast(uint8)decoded1[0].intValue){
  181. writeln("num1 = ", num1, " ", typeof(num1).stringof); // ws.send(enc(tuple( number(1), number(42), number(777) ))); // Decoded: {1, 42, 777} // num1 = 1 ubyte
  182. sock.send("{console.log(" ~ to!string(num1 + 42) ~ ")}"); // got 43 in browser console
  183. } // else do nothing
  184. if(auto str1 = cast(string)decoded1[1].binaryValue){
  185. writeln("str1 = ", str1, " ", typeof(str1).stringof); // ws.send(enc(tuple( number(1), bin('blabla'), number(777) ))); // Decoded: {1, <<98,108,97,98,108,97>>, 777} // str1 = blabla string
  186. sock.send("{console.log('" ~ str1 ~ " la-la-la" ~ "')}"); // got 'blabla la-la-la' in browser console
  187. } // else do nothing
  188. // var big_value = bigInt("61196067033413");
  189. // ws.send(enc(tuple( number(1), bin('9'), bignum( big_value ) ))); // got as long for auto
  190. if(decoded1[2].type_ == BertType.Int){
  191. if(auto num3 = decoded1[2].intValue){
  192. writeln("num3 = ", num3, " ", typeof(num3).stringof); // ws.send(enc(tuple( number(1), bin('9'), number(1) ))); // Decoded: {1, <<57>>, 1} // num3 = 1 long
  193. } // else do nothing
  194. } // else do nothing
  195. // var big_value = bigInt("6119606703341361196067033413");
  196. // ws.send(enc(tuple( number(1), bin('9'), bignum( big_value ) ))); // got as BigInt
  197. if(decoded1[2].type_ == BertType.BigInt){
  198. if(auto num3b = decoded1[2].bigintValue){
  199. writeln("num3b = ", num3b, " ", typeof(num3b).stringof); // Decoded: {1, <<57>>, 6119606703341361196067033413} // num3b = 6119606703341361196067033413 BigInt
  200. } // else do nothing
  201. } // else do nothing
  202. if(decoded1[2].type_ == BertType.List){
  203. auto list1 = decoded1[2].listValue; // ws.send(enc(tuple( number(1), bin('blabla'), list( number(1), number(2), number(3) ) ))); // Decoded: {1, <<98,108,97,98,108,97>>, [1, 2, 3]}
  204. if(list1.length == 3){
  205. //if(auto num31 = cast(uint32)list1[0].intValue){
  206. if(auto num31 = list1[0].intValue){
  207. writeln("num31 = ", num31, " ", typeof(num31).stringof); // ws.send(enc(tuple( number(1), bin('9'), list( number(1), number(2), number(3) ) ))); // Decoded: {1, <<57>>, [1, 2, 3]} // num31 = 1 uint
  208. sock.send("{console.log(" ~ to!string(num31 + 77) ~ ")}"); // got 78 in browser console
  209. } // else do nothing
  210. } // else do nothing
  211. } // else do nothing
  212. } // else do nothing
  213. } // else do nothing
  214. }
  215. void login_test(HTTPServerRequest req, HTTPServerResponse res){
  216. //string client_id = generateCookie();
  217. //writeln("client_id: ", client_id); // client_id: tkoy8ybolXM95fpEqYRY
  218. //req.context["client_id"] = generateCookie();
  219. //req.params["client_id"] = generateCookie();
  220. //writeln("req.context = ", req.context); // req.context = ["client_id": MM2YjBQvSOSAdzLDZPNH]
  221. //writeln("req.params = ", req.params); // req.params = ["client_id": "Io-oRQ2DFXqBIShxs5z0"]
  222. Mustache mustache;
  223. auto context = new Mustache.Context;
  224. mustache.path = "priv";
  225. mustache.ext = "dtl";
  226. context["lang"] = "en";
  227. context["number1"] = 42;
  228. context.useSection("maybe1");
  229. context["part1"] = "<span>777</span>";
  230. context["result1"] = "Hello, World!\n";
  231. res.headers["Content-Type"] = "text/html; charset=utf-8";
  232. //res.writeBody("Hello, World!\n" ~ result);
  233. res.writeBody( mustache.render("login_test", context) );
  234. }