ns_turn_msg.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481
  1. /*
  2. * SPDX-License-Identifier: BSD-3-Clause
  3. *
  4. * https://opensource.org/license/bsd-3-clause
  5. *
  6. * Copyright (C) 2011, 2012, 2013 Citrix Systems
  7. *
  8. * All rights reserved.
  9. *
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions
  12. * are met:
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in the
  17. * documentation and/or other materials provided with the distribution.
  18. * 3. Neither the name of the project nor the names of its contributors
  19. * may be used to endorse or promote products derived from this software
  20. * without specific prior written permission.
  21. *
  22. * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
  23. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  24. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  25. * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
  26. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  27. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  28. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  29. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  30. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  31. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  32. * SUCH DAMAGE.
  33. */
  34. #include "ns_turn_msg.h"
  35. #include "ns_turn_msg_addr.h"
  36. ///////////// Security functions implementation from ns_turn_msg.h ///////////
  37. #include "ns_turn_openssl.h"
  38. #include "ns_turn_utils.h"
  39. ///////////
  40. #include <ctype.h> // for tolower
  41. #include <stdbool.h>
  42. #include <stdio.h> // for fprintf, printf, stderr, snprintf
  43. #include <stdlib.h>
  44. #include <string.h> // for memcpy, strlen, memset, strncpy, strcmp
  45. ///////////
  46. #define FINGERPRINT_XOR 0x5354554e
  47. ///////////
  48. int stun_method_str(uint16_t method, char *smethod) {
  49. int ret = 0;
  50. const char *s = "UNKNOWN";
  51. switch (method) {
  52. case STUN_METHOD_BINDING:
  53. s = "BINDING";
  54. break;
  55. case STUN_METHOD_ALLOCATE:
  56. s = "ALLOCATE";
  57. break;
  58. case STUN_METHOD_REFRESH:
  59. s = "REFRESH";
  60. break;
  61. case STUN_METHOD_SEND:
  62. s = "SEND";
  63. break;
  64. case STUN_METHOD_DATA:
  65. s = "DATA";
  66. break;
  67. case STUN_METHOD_CREATE_PERMISSION:
  68. s = "CREATE_PERMISSION";
  69. break;
  70. case STUN_METHOD_CHANNEL_BIND:
  71. s = "CHANNEL_BIND";
  72. break;
  73. case STUN_METHOD_CONNECT:
  74. s = "CONNECT";
  75. break;
  76. case STUN_METHOD_CONNECTION_BIND:
  77. s = "CONNECTION_BIND";
  78. break;
  79. case STUN_METHOD_CONNECTION_ATTEMPT:
  80. s = "CONNECTION_ATTEMPT";
  81. break;
  82. default:
  83. ret = -1;
  84. };
  85. if (smethod) {
  86. strcpy(smethod, s);
  87. }
  88. return ret;
  89. }
  90. long turn_random_number(void) {
  91. long ret = 0;
  92. if (!RAND_bytes((unsigned char *)&ret, sizeof(ret)))
  93. #if defined(WINDOWS)
  94. ret = rand();
  95. #else
  96. ret = random();
  97. #endif
  98. return ret;
  99. }
  100. static void generate_random_nonce(unsigned char *nonce, size_t sz) {
  101. if (!RAND_bytes(nonce, (int)sz)) {
  102. for (size_t i = 0; i < sz; ++i) {
  103. nonce[i] = (unsigned char)turn_random_number();
  104. }
  105. }
  106. }
  107. static void turn_random_tid_size(void *id) {
  108. uint32_t *ar = (uint32_t *)id;
  109. if (!RAND_bytes((unsigned char *)ar, 12)) {
  110. for (size_t i = 0; i < 3; ++i) {
  111. ar[i] = (uint32_t)turn_random_number();
  112. }
  113. }
  114. }
  115. bool stun_calculate_hmac(const uint8_t *buf, size_t len, const uint8_t *key, size_t keylen, uint8_t *hmac,
  116. unsigned int *hmac_len, SHATYPE shatype) {
  117. ERR_clear_error();
  118. UNUSED_ARG(shatype);
  119. if (shatype == SHATYPE_SHA256) {
  120. #if !defined(OPENSSL_NO_SHA256) && defined(SHA256_DIGEST_LENGTH)
  121. if (!HMAC(EVP_sha256(), key, (int)keylen, buf, len, hmac, hmac_len)) {
  122. return false;
  123. }
  124. #else
  125. fprintf(stderr, "SHA256 is not supported\n");
  126. return false;
  127. #endif
  128. } else if (shatype == SHATYPE_SHA384) {
  129. #if !defined(OPENSSL_NO_SHA384) && defined(SHA384_DIGEST_LENGTH)
  130. if (!HMAC(EVP_sha384(), key, (int)keylen, buf, len, hmac, hmac_len)) {
  131. return false;
  132. }
  133. #else
  134. fprintf(stderr, "SHA384 is not supported\n");
  135. return false;
  136. #endif
  137. } else if (shatype == SHATYPE_SHA512) {
  138. #if !defined(OPENSSL_NO_SHA512) && defined(SHA512_DIGEST_LENGTH)
  139. if (!HMAC(EVP_sha512(), key, (int)keylen, buf, len, hmac, hmac_len)) {
  140. return false;
  141. }
  142. #else
  143. fprintf(stderr, "SHA512 is not supported\n");
  144. return false;
  145. #endif
  146. } else if (!HMAC(EVP_sha1(), key, (int)keylen, buf, len, hmac, hmac_len)) {
  147. return false;
  148. }
  149. return true;
  150. }
  151. bool stun_produce_integrity_key_str(const uint8_t *uname, const uint8_t *realm, const uint8_t *upwd, hmackey_t key,
  152. SHATYPE shatype) {
  153. bool ret;
  154. ERR_clear_error();
  155. UNUSED_ARG(shatype);
  156. size_t ulen = strlen((const char *)uname);
  157. size_t rlen = strlen((const char *)realm);
  158. size_t plen = strlen((const char *)upwd);
  159. size_t sz = ulen + 1 + rlen + 1 + plen + 1 + 10;
  160. size_t strl = ulen + 1 + rlen + 1 + plen;
  161. uint8_t *str = (uint8_t *)malloc(sz + 1);
  162. strncpy((char *)str, (const char *)uname, sz);
  163. str[ulen] = ':';
  164. strncpy((char *)str + ulen + 1, (const char *)realm, sz - ulen - 1);
  165. str[ulen + 1 + rlen] = ':';
  166. strncpy((char *)str + ulen + 1 + rlen + 1, (const char *)upwd, sz - ulen - 1 - rlen - 1);
  167. str[strl] = 0;
  168. if (shatype == SHATYPE_SHA256) {
  169. #if !defined(OPENSSL_NO_SHA256) && defined(SHA256_DIGEST_LENGTH)
  170. unsigned int keylen = 0;
  171. EVP_MD_CTX *ctx = EVP_MD_CTX_new();
  172. EVP_DigestInit(ctx, EVP_sha256());
  173. EVP_DigestUpdate(ctx, str, strl);
  174. EVP_DigestFinal(ctx, key, &keylen);
  175. EVP_MD_CTX_free(ctx);
  176. ret = true;
  177. #else
  178. fprintf(stderr, "SHA256 is not supported\n");
  179. ret = false;
  180. #endif
  181. } else if (shatype == SHATYPE_SHA384) {
  182. #if !defined(OPENSSL_NO_SHA384) && defined(SHA384_DIGEST_LENGTH)
  183. unsigned int keylen = 0;
  184. EVP_MD_CTX *ctx = EVP_MD_CTX_new();
  185. EVP_DigestInit(ctx, EVP_sha384());
  186. EVP_DigestUpdate(ctx, str, strl);
  187. EVP_DigestFinal(ctx, key, &keylen);
  188. EVP_MD_CTX_free(ctx);
  189. ret = true;
  190. #else
  191. fprintf(stderr, "SHA384 is not supported\n");
  192. ret = false;
  193. #endif
  194. } else if (shatype == SHATYPE_SHA512) {
  195. #if !defined(OPENSSL_NO_SHA512) && defined(SHA512_DIGEST_LENGTH)
  196. unsigned int keylen = 0;
  197. EVP_MD_CTX *ctx = EVP_MD_CTX_new();
  198. EVP_DigestInit(ctx, EVP_sha512());
  199. EVP_DigestUpdate(ctx, str, strl);
  200. EVP_DigestFinal(ctx, key, &keylen);
  201. EVP_MD_CTX_free(ctx);
  202. ret = true;
  203. #else
  204. fprintf(stderr, "SHA512 is not supported\n");
  205. ret = false;
  206. #endif
  207. } else {
  208. #if OPENSSL_VERSION_NUMBER >= 0x30000000L
  209. unsigned int keylen = 0;
  210. EVP_MD_CTX *ctx = EVP_MD_CTX_new();
  211. if (EVP_default_properties_is_fips_enabled(NULL)) {
  212. EVP_default_properties_enable_fips(NULL, 0);
  213. }
  214. EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
  215. EVP_DigestUpdate(ctx, str, strl);
  216. EVP_DigestFinal(ctx, key, &keylen);
  217. EVP_MD_CTX_free(ctx);
  218. #else // OPENSSL_VERSION_NUMBER < 0x30000000L
  219. unsigned int keylen = 0;
  220. EVP_MD_CTX *ctx = EVP_MD_CTX_new();
  221. #if defined EVP_MD_CTX_FLAG_NON_FIPS_ALLOW && !defined(LIBRESSL_VERSION_NUMBER)
  222. if (FIPS_mode()) {
  223. EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  224. }
  225. #endif
  226. EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
  227. EVP_DigestUpdate(ctx, str, strl);
  228. EVP_DigestFinal(ctx, key, &keylen);
  229. EVP_MD_CTX_free(ctx);
  230. #endif // OPENSSL_VERSION_NUMBER >= 0X30000000L
  231. ret = true;
  232. }
  233. free(str);
  234. return ret;
  235. }
  236. #define PWD_SALT_SIZE (8)
  237. static void readable_string(unsigned char *orig, unsigned char *out, size_t sz) {
  238. out[0] = '\0';
  239. for (size_t i = 0; i < sz; ++i) {
  240. snprintf((char *)(out + (i * 2)), 3, "%02x", (unsigned int)orig[i]);
  241. }
  242. out[sz * 2] = 0;
  243. }
  244. static void generate_enc_password(const char *pwd, char *result, const unsigned char *orig_salt) {
  245. unsigned char salt[PWD_SALT_SIZE + 1];
  246. if (!orig_salt) {
  247. generate_random_nonce(salt, PWD_SALT_SIZE);
  248. } else {
  249. memcpy(salt, orig_salt, PWD_SALT_SIZE);
  250. salt[PWD_SALT_SIZE] = 0;
  251. }
  252. unsigned char rsalt[PWD_SALT_SIZE * 2 + 1];
  253. readable_string(salt, rsalt, PWD_SALT_SIZE);
  254. result[0] = '$';
  255. result[1] = '5';
  256. result[2] = '$';
  257. memcpy(result + 3, (char *)rsalt, PWD_SALT_SIZE + PWD_SALT_SIZE);
  258. result[3 + PWD_SALT_SIZE + PWD_SALT_SIZE] = '$';
  259. unsigned char *out = (unsigned char *)(result + 3 + PWD_SALT_SIZE + PWD_SALT_SIZE + 1);
  260. {
  261. EVP_MD_CTX *ctx = EVP_MD_CTX_new();
  262. #if !defined(OPENSSL_NO_SHA256) && defined(SHA256_DIGEST_LENGTH)
  263. EVP_DigestInit(ctx, EVP_sha256());
  264. #else
  265. EVP_DigestInit(ctx, EVP_sha1());
  266. #endif
  267. EVP_DigestUpdate(ctx, salt, PWD_SALT_SIZE);
  268. EVP_DigestUpdate(ctx, pwd, strlen(pwd));
  269. {
  270. unsigned char hash[129];
  271. unsigned int keylen = 0;
  272. EVP_DigestFinal(ctx, hash, &keylen);
  273. readable_string(hash, out, keylen);
  274. }
  275. EVP_MD_CTX_free(ctx);
  276. }
  277. }
  278. void generate_new_enc_password(const char *pwd, char *result) { generate_enc_password(pwd, result, NULL); }
  279. static bool encrypted_password(const char *pin, unsigned char *salt) {
  280. static const size_t min_len = 3 + PWD_SALT_SIZE + PWD_SALT_SIZE + 1 + 32;
  281. if (strlen(pin) >= min_len) {
  282. if ((pin[0] == '$') && (pin[1] == '5') && (pin[2] == '$') && (pin[3 + PWD_SALT_SIZE + PWD_SALT_SIZE] == '$')) {
  283. for (size_t i = 0; i < PWD_SALT_SIZE; ++i) {
  284. const char *c = pin + 3 + i + i;
  285. char sc[3];
  286. sc[0] = c[0];
  287. sc[1] = c[1];
  288. sc[2] = 0;
  289. salt[i] = (unsigned char)strtoul(sc, NULL, 16);
  290. }
  291. return true;
  292. }
  293. }
  294. return false;
  295. }
  296. bool check_password_equal(const char *pin, const char *pwd) {
  297. unsigned char salt[PWD_SALT_SIZE];
  298. if (!encrypted_password(pwd, salt)) {
  299. return 0 == strcmp(pin, pwd);
  300. }
  301. char enc_pin[257];
  302. generate_enc_password(pin, enc_pin, salt);
  303. return 0 == strcmp(enc_pin, pwd);
  304. }
  305. /////////////////////////////////////////////////////////////////
  306. static uint32_t ns_crc32(const uint8_t *buffer, uint32_t len);
  307. /////////////////////////////////////////////////////////////////
  308. int stun_get_command_message_len_str(const uint8_t *buf, size_t len) {
  309. if (len < STUN_HEADER_LENGTH) {
  310. return -1;
  311. }
  312. /* Validate the size the buffer claims to be */
  313. size_t bufLen = (size_t)(nswap16(((const uint16_t *)(buf))[1]) + STUN_HEADER_LENGTH);
  314. if (bufLen > len) {
  315. return -1;
  316. }
  317. return bufLen;
  318. }
  319. static bool stun_set_command_message_len_str(uint8_t *buf, int len) {
  320. if (len < STUN_HEADER_LENGTH) {
  321. return false;
  322. }
  323. ((uint16_t *)buf)[1] = nswap16((uint16_t)(len - STUN_HEADER_LENGTH));
  324. return true;
  325. }
  326. /////////// Low-level binary //////////////////////////////////////////////
  327. uint16_t stun_make_type(uint16_t method) {
  328. method = method & 0x0FFF;
  329. return ((method & 0x000F) | ((method & 0x0070) << 1) | ((method & 0x0380) << 2) | ((method & 0x0C00) << 2));
  330. }
  331. uint16_t stun_get_method_str(const uint8_t *buf, size_t len) {
  332. if (!buf || len < 2) {
  333. return (uint16_t)-1;
  334. }
  335. uint16_t tt = nswap16(((const uint16_t *)buf)[0]);
  336. return (tt & 0x000F) | ((tt & 0x00E0) >> 1) | ((tt & 0x0E00) >> 2) | ((tt & 0x3000) >> 2);
  337. }
  338. uint16_t stun_get_msg_type_str(const uint8_t *buf, size_t len) {
  339. if (!buf || len < 2) {
  340. return (uint16_t)-1;
  341. }
  342. return ((nswap16(((const uint16_t *)buf)[0])) & 0x3FFF);
  343. }
  344. bool is_channel_msg_str(const uint8_t *buf, size_t blen) {
  345. return (buf && blen >= 4 && STUN_VALID_CHANNEL(nswap16(((const uint16_t *)buf)[0])));
  346. }
  347. /////////////// message types /////////////////////////////////
  348. bool stun_is_command_message_str(const uint8_t *buf, size_t blen) {
  349. if (buf && blen >= STUN_HEADER_LENGTH) {
  350. if (!STUN_VALID_CHANNEL(nswap16(((const uint16_t *)buf)[0]))) {
  351. if ((((uint8_t)buf[0]) & ((uint8_t)(0xC0))) == 0) {
  352. if (nswap32(((const uint32_t *)(buf))[1]) == STUN_MAGIC_COOKIE) {
  353. uint16_t len = nswap16(((const uint16_t *)(buf))[1]);
  354. if ((len & 0x0003) == 0) {
  355. if ((size_t)(len + STUN_HEADER_LENGTH) == blen) {
  356. return true;
  357. }
  358. }
  359. }
  360. }
  361. }
  362. }
  363. return false;
  364. }
  365. bool old_stun_is_command_message_str(const uint8_t *buf, size_t blen, uint32_t *cookie) {
  366. if (buf && blen >= STUN_HEADER_LENGTH) {
  367. if (!STUN_VALID_CHANNEL(nswap16(((const uint16_t *)buf)[0]))) {
  368. if ((((uint8_t)buf[0]) & ((uint8_t)(0xC0))) == 0) {
  369. if (nswap32(((const uint32_t *)(buf))[1]) != STUN_MAGIC_COOKIE) {
  370. uint16_t len = nswap16(((const uint16_t *)(buf))[1]);
  371. if ((len & 0x0003) == 0) {
  372. if ((size_t)(len + STUN_HEADER_LENGTH) == blen) {
  373. *cookie = nswap32(((const uint32_t *)(buf))[1]);
  374. return true;
  375. }
  376. }
  377. }
  378. }
  379. }
  380. }
  381. return false;
  382. }
  383. bool stun_is_command_message_full_check_str(const uint8_t *buf, size_t blen, int must_check_fingerprint,
  384. int *fingerprint_present) {
  385. if (!stun_is_command_message_str(buf, blen)) {
  386. return false;
  387. }
  388. stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, blen, STUN_ATTRIBUTE_FINGERPRINT);
  389. if (!sar) {
  390. if (fingerprint_present) {
  391. *fingerprint_present = 0;
  392. }
  393. if (stun_get_method_str(buf, blen) == STUN_METHOD_BINDING) {
  394. return true;
  395. }
  396. return !must_check_fingerprint;
  397. }
  398. if (stun_attr_get_len(sar) != 4) {
  399. return false;
  400. }
  401. const uint32_t *fingerprint = (const uint32_t *)stun_attr_get_value(sar);
  402. if (!fingerprint) {
  403. return !must_check_fingerprint;
  404. }
  405. uint32_t crc32len = (uint32_t)((((const uint8_t *)fingerprint) - buf) - 4);
  406. bool ret = (*fingerprint == nswap32(ns_crc32(buf, crc32len) ^ ((uint32_t)FINGERPRINT_XOR)));
  407. if (ret && fingerprint_present) {
  408. *fingerprint_present = ret;
  409. }
  410. return ret;
  411. }
  412. bool stun_is_request_str(const uint8_t *buf, size_t len) {
  413. if (is_channel_msg_str(buf, len)) {
  414. return false;
  415. }
  416. return IS_STUN_REQUEST(stun_get_msg_type_str(buf, len));
  417. }
  418. bool stun_is_success_response_str(const uint8_t *buf, size_t len) {
  419. if (is_channel_msg_str(buf, len)) {
  420. return false;
  421. }
  422. return IS_STUN_SUCCESS_RESP(stun_get_msg_type_str(buf, len));
  423. }
  424. bool stun_is_error_response_str(const uint8_t *buf, size_t len, int *err_code, uint8_t *err_msg, size_t err_msg_size) {
  425. if (is_channel_msg_str(buf, len)) {
  426. return false;
  427. }
  428. if (IS_STUN_ERR_RESP(stun_get_msg_type_str(buf, len))) {
  429. if (err_code) {
  430. stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_ERROR_CODE);
  431. if (sar) {
  432. if (stun_attr_get_len(sar) >= 4) {
  433. const uint8_t *val = (const uint8_t *)stun_attr_get_value(sar);
  434. *err_code = (int)(val[2] * 100 + val[3]);
  435. if (err_msg && err_msg_size > 0) {
  436. err_msg[0] = 0;
  437. if (stun_attr_get_len(sar) > 4) {
  438. size_t msg_len = stun_attr_get_len(sar) - 4;
  439. if (msg_len > (err_msg_size - 1)) {
  440. msg_len = err_msg_size - 1;
  441. }
  442. memcpy(err_msg, val + 4, msg_len);
  443. err_msg[msg_len] = 0;
  444. }
  445. }
  446. }
  447. }
  448. }
  449. return true;
  450. }
  451. return false;
  452. }
  453. bool stun_is_challenge_response_str(const uint8_t *buf, size_t len, int *err_code, uint8_t *err_msg,
  454. size_t err_msg_size, uint8_t *realm, uint8_t *nonce, uint8_t *server_name,
  455. bool *oauth) {
  456. bool ret = stun_is_error_response_str(buf, len, err_code, err_msg, err_msg_size);
  457. if (ret && (((*err_code) == 401) || ((*err_code) == 438))) {
  458. stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_REALM);
  459. if (sar) {
  460. bool found_oauth = false;
  461. const uint8_t *value = stun_attr_get_value(sar);
  462. if (value) {
  463. size_t vlen = (size_t)stun_attr_get_len(sar);
  464. vlen = min(vlen, (size_t)STUN_MAX_REALM_SIZE);
  465. memcpy(realm, value, vlen);
  466. realm[vlen] = 0;
  467. {
  468. sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_THIRD_PARTY_AUTHORIZATION);
  469. if (sar) {
  470. value = stun_attr_get_value(sar);
  471. if (value) {
  472. vlen = (size_t)stun_attr_get_len(sar);
  473. vlen = min(vlen, (size_t)STUN_MAX_SERVER_NAME_SIZE);
  474. if (vlen > 0) {
  475. if (server_name) {
  476. memcpy(server_name, value, vlen);
  477. }
  478. found_oauth = true;
  479. }
  480. }
  481. }
  482. }
  483. sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_NONCE);
  484. if (sar) {
  485. value = stun_attr_get_value(sar);
  486. if (value) {
  487. vlen = (size_t)stun_attr_get_len(sar);
  488. vlen = min(vlen, (size_t)STUN_MAX_NONCE_SIZE);
  489. memcpy(nonce, value, vlen);
  490. nonce[vlen] = 0;
  491. if (oauth) {
  492. *oauth = found_oauth;
  493. }
  494. return true;
  495. }
  496. }
  497. }
  498. }
  499. }
  500. return false;
  501. }
  502. bool stun_is_response_str(const uint8_t *buf, size_t len) {
  503. if (is_channel_msg_str(buf, len)) {
  504. return false;
  505. }
  506. if (IS_STUN_SUCCESS_RESP(stun_get_msg_type_str(buf, len))) {
  507. return true;
  508. }
  509. if (IS_STUN_ERR_RESP(stun_get_msg_type_str(buf, len))) {
  510. return true;
  511. }
  512. return false;
  513. }
  514. bool stun_is_indication_str(const uint8_t *buf, size_t len) {
  515. if (is_channel_msg_str(buf, len)) {
  516. return false;
  517. }
  518. return IS_STUN_INDICATION(stun_get_msg_type_str(buf, len));
  519. }
  520. uint16_t stun_make_request(uint16_t method) { return GET_STUN_REQUEST(stun_make_type(method)); }
  521. uint16_t stun_make_indication(uint16_t method) { return GET_STUN_INDICATION(stun_make_type(method)); }
  522. uint16_t stun_make_success_response(uint16_t method) { return GET_STUN_SUCCESS_RESP(stun_make_type(method)); }
  523. uint16_t stun_make_error_response(uint16_t method) { return GET_STUN_ERR_RESP(stun_make_type(method)); }
  524. //////////////// INIT ////////////////////////////////////////////
  525. void stun_init_buffer_str(uint8_t *buf, size_t *len) {
  526. *len = STUN_HEADER_LENGTH;
  527. memset(buf, 0, *len);
  528. }
  529. void stun_init_command_str(uint16_t message_type, uint8_t *buf, size_t *len) {
  530. stun_init_buffer_str(buf, len);
  531. message_type &= (uint16_t)(0x3FFF);
  532. ((uint16_t *)buf)[0] = nswap16(message_type);
  533. ((uint16_t *)buf)[1] = 0;
  534. ((uint32_t *)buf)[1] = nswap32(STUN_MAGIC_COOKIE);
  535. stun_tid_generate_in_message_str(buf, NULL);
  536. }
  537. void old_stun_init_command_str(uint16_t message_type, uint8_t *buf, size_t *len, uint32_t cookie) {
  538. stun_init_buffer_str(buf, len);
  539. message_type &= (uint16_t)(0x3FFF);
  540. ((uint16_t *)buf)[0] = nswap16(message_type);
  541. ((uint16_t *)buf)[1] = 0;
  542. ((uint32_t *)buf)[1] = nswap32(cookie);
  543. stun_tid_generate_in_message_str(buf, NULL);
  544. }
  545. void stun_init_request_str(uint16_t method, uint8_t *buf, size_t *len) {
  546. stun_init_command_str(stun_make_request(method), buf, len);
  547. }
  548. void stun_init_indication_str(uint16_t method, uint8_t *buf, size_t *len) {
  549. stun_init_command_str(stun_make_indication(method), buf, len);
  550. }
  551. void stun_init_success_response_str(uint16_t method, uint8_t *buf, size_t *len, stun_tid *id) {
  552. stun_init_command_str(stun_make_success_response(method), buf, len);
  553. if (id) {
  554. stun_tid_message_cpy(buf, id);
  555. }
  556. }
  557. void old_stun_init_success_response_str(uint16_t method, uint8_t *buf, size_t *len, stun_tid *id, uint32_t cookie) {
  558. old_stun_init_command_str(stun_make_success_response(method), buf, len, cookie);
  559. if (id) {
  560. stun_tid_message_cpy(buf, id);
  561. }
  562. }
  563. const uint8_t *get_default_reason(int error_code) {
  564. const char *reason = "Unknown error";
  565. switch (error_code) {
  566. case 300:
  567. reason = "Try Alternate";
  568. break;
  569. case 400:
  570. reason = "Bad Request";
  571. break;
  572. case 401:
  573. reason = "Unauthorized";
  574. break;
  575. case 403:
  576. reason = "Forbidden";
  577. break;
  578. case 404:
  579. reason = "Not Found";
  580. break;
  581. case 420:
  582. reason = "Unknown Attribute";
  583. break;
  584. case 437:
  585. reason = "Allocation Mismatch";
  586. break;
  587. case 438:
  588. reason = "Stale Nonce";
  589. break;
  590. case 440:
  591. reason = "Address Family not Supported";
  592. break;
  593. case 441:
  594. reason = "Wrong Credentials";
  595. break;
  596. case 442:
  597. reason = "Unsupported Transport Protocol";
  598. break;
  599. case 443:
  600. reason = "Peer Address Family Mismatch";
  601. break;
  602. case 446:
  603. reason = "Connection Already Exists";
  604. break;
  605. case 447:
  606. reason = "Connection Timeout or Failure";
  607. break;
  608. case 486:
  609. reason = "Allocation Quota Reached";
  610. break;
  611. case 487:
  612. reason = "Role Conflict";
  613. break;
  614. case 500:
  615. reason = "Server Error";
  616. break;
  617. case 508:
  618. reason = "Insufficient Capacity";
  619. break;
  620. default:;
  621. };
  622. return (const uint8_t *)reason;
  623. }
  624. static void stun_init_error_response_common_str(uint8_t *buf, size_t *len, uint16_t error_code, const uint8_t *reason,
  625. stun_tid *id) {
  626. if (!reason || !strcmp((const char *)reason, "Unknown error")) {
  627. reason = get_default_reason(error_code);
  628. }
  629. uint8_t avalue[513];
  630. avalue[0] = 0;
  631. avalue[1] = 0;
  632. avalue[2] = (uint8_t)(error_code / 100);
  633. avalue[3] = (uint8_t)(error_code % 100);
  634. strncpy((char *)(avalue + 4), (const char *)reason, sizeof(avalue) - 4);
  635. avalue[sizeof(avalue) - 1] = 0;
  636. int alen = 4 + (int)strlen((const char *)(avalue + 4));
  637. //"Manual" padding for compatibility with classic old stun:
  638. {
  639. int rem = alen % 4;
  640. if (rem) {
  641. alen += (4 - rem);
  642. }
  643. }
  644. stun_attr_add_str(buf, len, STUN_ATTRIBUTE_ERROR_CODE, (uint8_t *)avalue, alen);
  645. if (id) {
  646. stun_tid_message_cpy(buf, id);
  647. }
  648. }
  649. void old_stun_init_error_response_str(uint16_t method, uint8_t *buf, size_t *len, uint16_t error_code,
  650. const uint8_t *reason, stun_tid *id, uint32_t cookie) {
  651. old_stun_init_command_str(stun_make_error_response(method), buf, len, cookie);
  652. stun_init_error_response_common_str(buf, len, error_code, reason, id);
  653. }
  654. void stun_init_error_response_str(uint16_t method, uint8_t *buf, size_t *len, uint16_t error_code,
  655. const uint8_t *reason, stun_tid *id) {
  656. stun_init_command_str(stun_make_error_response(method), buf, len);
  657. stun_init_error_response_common_str(buf, len, error_code, reason, id);
  658. }
  659. /////////// CHANNEL ////////////////////////////////////////////////
  660. bool stun_init_channel_message_str(uint16_t chnumber, uint8_t *buf, size_t *len, int length, bool do_padding) {
  661. uint16_t rlen = (uint16_t)length;
  662. if (length < 0 || (MAX_STUN_MESSAGE_SIZE < (4 + length))) {
  663. return false;
  664. }
  665. ((uint16_t *)(buf))[0] = nswap16(chnumber);
  666. ((uint16_t *)(buf))[1] = nswap16((uint16_t)length);
  667. if (do_padding && (rlen & 0x0003)) {
  668. rlen = ((rlen >> 2) + 1) << 2;
  669. }
  670. *len = 4 + rlen;
  671. return true;
  672. }
  673. bool stun_is_channel_message_str(const uint8_t *buf, size_t *blen, uint16_t *chnumber, bool mandatory_padding) {
  674. uint16_t datalen_header;
  675. uint16_t datalen_actual;
  676. if (!blen || (*blen < 4)) {
  677. return false;
  678. }
  679. uint16_t chn = nswap16(((const uint16_t *)(buf))[0]);
  680. if (!STUN_VALID_CHANNEL(chn)) {
  681. return false;
  682. }
  683. if (*blen > (uint16_t)-1) {
  684. *blen = (uint16_t)-1;
  685. }
  686. datalen_actual = (uint16_t)(*blen) - 4;
  687. datalen_header = ((const uint16_t *)buf)[1];
  688. datalen_header = nswap16(datalen_header);
  689. if (datalen_header > datalen_actual) {
  690. return false;
  691. }
  692. if (datalen_header != datalen_actual) {
  693. /* maybe there are padding bytes for 32-bit alignment. Mandatory for TCP. Optional for UDP */
  694. if (datalen_actual & 0x0003) {
  695. if (mandatory_padding) {
  696. return false;
  697. } else if (datalen_header == 0) {
  698. return false;
  699. } else {
  700. uint16_t diff = datalen_actual - datalen_header;
  701. if (diff > 3) {
  702. return false;
  703. }
  704. }
  705. }
  706. }
  707. *blen = datalen_header + 4;
  708. if (chnumber) {
  709. *chnumber = chn;
  710. }
  711. return true;
  712. }
  713. ////////// STUN message ///////////////////////////////
  714. static inline bool sheadof(const char *head, const char *full, bool ignore_case) {
  715. while (*head) {
  716. if (*head != *full) {
  717. if (ignore_case && (tolower((int)*head) == tolower((int)*full))) {
  718. // OK
  719. } else {
  720. return false;
  721. }
  722. }
  723. ++head;
  724. ++full;
  725. }
  726. return true;
  727. }
  728. static inline const char *findstr(const char *hay, size_t slen, const char *needle, bool ignore_case) {
  729. const char *ret = NULL;
  730. if (hay && slen && needle) {
  731. size_t nlen = strlen(needle);
  732. if (nlen <= slen) {
  733. size_t smax = slen - nlen + 1;
  734. const char *sp = hay;
  735. for (size_t i = 0; i < smax; ++i) {
  736. if (sheadof(needle, sp + i, ignore_case)) {
  737. ret = sp + i;
  738. break;
  739. }
  740. }
  741. }
  742. }
  743. return ret;
  744. }
  745. int is_http(const char *s, size_t blen) {
  746. if (s && blen >= 12) {
  747. if ((strstr(s, "GET ") == s) || (strstr(s, "POST ") == s) || (strstr(s, "DELETE ") == s) ||
  748. (strstr(s, "PUT ") == s)) {
  749. const char *sp = findstr(s + 4, blen - 4, " HTTP/", false);
  750. if (sp) {
  751. sp += 6;
  752. size_t diff_blen = sp - s;
  753. if (diff_blen + 4 <= blen) {
  754. sp = findstr(sp, blen - diff_blen, "\r\n\r\n", false);
  755. if (sp) {
  756. int ret_len = (int)(sp - s + 4);
  757. const char *clheader = "content-length: ";
  758. const char *cl = findstr(s, sp - s, clheader, true);
  759. if (cl) {
  760. unsigned long clen = strtoul(cl + strlen(clheader), NULL, 10);
  761. if (clen > 0 && clen < (0x0FFFFFFF)) {
  762. ret_len += (int)clen;
  763. }
  764. }
  765. return ret_len;
  766. }
  767. }
  768. }
  769. }
  770. }
  771. return 0;
  772. }
  773. int stun_get_message_len_str(uint8_t *buf, size_t blen, int padding, size_t *app_len) {
  774. if (buf && blen) {
  775. /* STUN request/response ? */
  776. if (buf && blen >= STUN_HEADER_LENGTH) {
  777. if (!STUN_VALID_CHANNEL(nswap16(((const uint16_t *)buf)[0]))) {
  778. if ((((uint8_t)buf[0]) & ((uint8_t)(0xC0))) == 0) {
  779. if (nswap32(((const uint32_t *)(buf))[1]) == STUN_MAGIC_COOKIE) {
  780. uint16_t len = nswap16(((const uint16_t *)(buf))[1]);
  781. if ((len & 0x0003) == 0) {
  782. len += STUN_HEADER_LENGTH;
  783. if ((size_t)len <= blen) {
  784. *app_len = (size_t)len;
  785. return (int)len;
  786. }
  787. }
  788. }
  789. }
  790. }
  791. }
  792. // HTTP request ?
  793. {
  794. int http_len = is_http(((char *)buf), blen);
  795. if ((http_len > 0) && ((size_t)http_len <= blen)) {
  796. *app_len = (size_t)http_len;
  797. return http_len;
  798. }
  799. }
  800. /* STUN channel ? */
  801. if (blen >= 4) {
  802. uint16_t chn = nswap16(((const uint16_t *)(buf))[0]);
  803. if (STUN_VALID_CHANNEL(chn)) {
  804. uint16_t bret = (4 + (nswap16(((const uint16_t *)(buf))[1])));
  805. *app_len = bret;
  806. if (padding && (bret & 0x0003)) {
  807. bret = ((bret >> 2) + 1) << 2;
  808. }
  809. if (bret <= blen) {
  810. return bret;
  811. }
  812. }
  813. }
  814. }
  815. return -1;
  816. }
  817. ////////// ALLOCATE ///////////////////////////////////
  818. bool stun_set_allocate_request_str(uint8_t *buf, size_t *len, uint32_t lifetime, bool af4, bool af6, uint8_t transport,
  819. bool mobile, const char *rt, int ep) {
  820. stun_init_request_str(STUN_METHOD_ALLOCATE, buf, len);
  821. // REQUESTED-TRANSPORT
  822. {
  823. uint8_t field[4];
  824. field[0] = transport;
  825. field[1] = 0;
  826. field[2] = 0;
  827. field[3] = 0;
  828. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_TRANSPORT, field, sizeof(field))) {
  829. return false;
  830. }
  831. }
  832. // LIFETIME
  833. {
  834. if (lifetime < 1) {
  835. lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME;
  836. }
  837. uint32_t field = nswap32(lifetime);
  838. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_LIFETIME, (uint8_t *)(&field), sizeof(field))) {
  839. return false;
  840. }
  841. }
  842. // MICE
  843. if (mobile) {
  844. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MOBILITY_TICKET, (const uint8_t *)"", 0)) {
  845. return false;
  846. }
  847. }
  848. if (ep > -1) {
  849. uint8_t value = ep ? 0x80 : 0x00;
  850. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_EVEN_PORT, (const uint8_t *)&value, 1)) {
  851. return false;
  852. }
  853. }
  854. // RESERVATION-TOKEN, EVEN-PORT and DUAL-ALLOCATION are mutually exclusive:
  855. if (rt) {
  856. stun_attr_add_str(buf, len, STUN_ATTRIBUTE_RESERVATION_TOKEN, (const uint8_t *)rt, 8);
  857. } else {
  858. // ADRESS-FAMILY
  859. if (af4 && !af6) {
  860. uint8_t field[4];
  861. field[0] = (uint8_t)STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4;
  862. field[1] = 0;
  863. field[2] = 0;
  864. field[3] = 0;
  865. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY, field, sizeof(field))) {
  866. return false;
  867. }
  868. }
  869. if (af6 && !af4) {
  870. uint8_t field[4];
  871. field[0] = (uint8_t)STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6;
  872. field[1] = 0;
  873. field[2] = 0;
  874. field[3] = 0;
  875. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY, field, sizeof(field))) {
  876. return false;
  877. }
  878. }
  879. if (af4 && af6) {
  880. uint8_t field[4];
  881. field[0] = (uint8_t)STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6;
  882. field[1] = 0;
  883. field[2] = 0;
  884. field[3] = 0;
  885. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY, field, sizeof(field))) {
  886. return false;
  887. }
  888. }
  889. }
  890. return true;
  891. }
  892. bool stun_set_allocate_response_str(uint8_t *buf, size_t *len, stun_tid *tid, const ioa_addr *relayed_addr1,
  893. const ioa_addr *relayed_addr2, const ioa_addr *reflexive_addr, uint32_t lifetime,
  894. uint32_t max_lifetime, int error_code, const uint8_t *reason,
  895. uint64_t reservation_token, char *mobile_id) {
  896. if (!error_code) {
  897. stun_init_success_response_str(STUN_METHOD_ALLOCATE, buf, len, tid);
  898. if (relayed_addr1) {
  899. if (!stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS, relayed_addr1)) {
  900. return false;
  901. }
  902. }
  903. if (relayed_addr2) {
  904. if (!stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS, relayed_addr2)) {
  905. return false;
  906. }
  907. }
  908. if (reflexive_addr) {
  909. if (!stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, reflexive_addr)) {
  910. return false;
  911. }
  912. }
  913. if (reservation_token) {
  914. reservation_token = nswap64(reservation_token);
  915. stun_attr_add_str(buf, len, STUN_ATTRIBUTE_RESERVATION_TOKEN, (uint8_t *)(&reservation_token), 8);
  916. }
  917. {
  918. if (lifetime < 1) {
  919. lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME;
  920. } else if (lifetime > max_lifetime) {
  921. lifetime = max_lifetime;
  922. }
  923. uint32_t field = nswap32(lifetime);
  924. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_LIFETIME, (uint8_t *)(&field), sizeof(field))) {
  925. return false;
  926. }
  927. }
  928. if (mobile_id && *mobile_id) {
  929. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MOBILITY_TICKET, (uint8_t *)mobile_id, (int)strlen(mobile_id))) {
  930. return false;
  931. }
  932. }
  933. } else {
  934. stun_init_error_response_str(STUN_METHOD_ALLOCATE, buf, len, error_code, reason, tid);
  935. }
  936. return true;
  937. }
  938. /////////////// CHANNEL BIND ///////////////////////////////////////
  939. uint16_t stun_set_channel_bind_request_str(uint8_t *buf, size_t *len, const ioa_addr *peer_addr,
  940. uint16_t channel_number) {
  941. if (!STUN_VALID_CHANNEL(channel_number)) {
  942. channel_number = 0x4000 + ((uint16_t)(((uint32_t)turn_random_number()) % (0x7FFF - 0x4000 + 1)));
  943. }
  944. stun_init_request_str(STUN_METHOD_CHANNEL_BIND, buf, len);
  945. if (!stun_attr_add_channel_number_str(buf, len, channel_number)) {
  946. return 0;
  947. }
  948. if (!peer_addr) {
  949. ioa_addr ca;
  950. memset(&ca, 0, sizeof(ioa_addr));
  951. if (!stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &ca)) {
  952. return 0;
  953. }
  954. } else {
  955. if (!stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, peer_addr)) {
  956. return 0;
  957. }
  958. }
  959. return channel_number;
  960. }
  961. void stun_set_channel_bind_response_str(uint8_t *buf, size_t *len, stun_tid *tid, int error_code,
  962. const uint8_t *reason) {
  963. if (!error_code) {
  964. stun_init_success_response_str(STUN_METHOD_CHANNEL_BIND, buf, len, tid);
  965. } else {
  966. stun_init_error_response_str(STUN_METHOD_CHANNEL_BIND, buf, len, error_code, reason, tid);
  967. }
  968. }
  969. /////////////// BINDING ///////////////////////////////////////
  970. void stun_set_binding_request_str(uint8_t *buf, size_t *len) { stun_init_request_str(STUN_METHOD_BINDING, buf, len); }
  971. bool stun_set_binding_response_str(uint8_t *buf, size_t *len, stun_tid *tid, const ioa_addr *reflexive_addr,
  972. int error_code, const uint8_t *reason, uint32_t cookie, bool old_stun,
  973. bool stun_backward_compatibility)
  974. {
  975. if (!error_code) {
  976. if (!old_stun) {
  977. stun_init_success_response_str(STUN_METHOD_BINDING, buf, len, tid);
  978. } else {
  979. old_stun_init_success_response_str(STUN_METHOD_BINDING, buf, len, tid, cookie);
  980. }
  981. if (!old_stun && reflexive_addr) {
  982. if (!stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, reflexive_addr)) {
  983. return false;
  984. }
  985. }
  986. if (reflexive_addr) {
  987. if (stun_backward_compatibility &&
  988. !stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_MAPPED_ADDRESS, reflexive_addr)) {
  989. return false;
  990. }
  991. }
  992. } else if (!old_stun) {
  993. stun_init_error_response_str(STUN_METHOD_BINDING, buf, len, error_code, reason, tid);
  994. } else {
  995. old_stun_init_error_response_str(STUN_METHOD_BINDING, buf, len, error_code, reason, tid, cookie);
  996. }
  997. return true;
  998. }
  999. bool stun_is_binding_request_str(const uint8_t *buf, size_t len, size_t offset) {
  1000. if (offset < len) {
  1001. buf += offset;
  1002. len -= offset;
  1003. if (stun_is_command_message_str(buf, len)) {
  1004. if (stun_is_request_str(buf, len) && (stun_get_method_str(buf, len) == STUN_METHOD_BINDING)) {
  1005. return true;
  1006. }
  1007. }
  1008. }
  1009. return false;
  1010. }
  1011. bool stun_is_binding_response_str(const uint8_t *buf, size_t len) {
  1012. if (stun_is_command_message_str(buf, len) && (stun_get_method_str(buf, len) == STUN_METHOD_BINDING)) {
  1013. if (stun_is_response_str(buf, len)) {
  1014. return true;
  1015. }
  1016. }
  1017. return false;
  1018. }
  1019. /////////////////////////////// TID ///////////////////////////////
  1020. bool stun_tid_equals(const stun_tid *id1, const stun_tid *id2) {
  1021. if (!id1 || !id2) {
  1022. return false;
  1023. }
  1024. if (id1 == id2) {
  1025. return true;
  1026. }
  1027. for (size_t i = 0; i < STUN_TID_SIZE; ++i) {
  1028. if (id1->tsx_id[i] != id2->tsx_id[i]) {
  1029. return false;
  1030. }
  1031. }
  1032. return true;
  1033. }
  1034. void stun_tid_cpy(stun_tid *id1, const stun_tid *id2) {
  1035. if (!id1 || !id2) {
  1036. return;
  1037. }
  1038. memcpy(id1->tsx_id, id2->tsx_id, STUN_TID_SIZE);
  1039. }
  1040. static void stun_tid_string_cpy(uint8_t *s, const stun_tid *id) {
  1041. if (s && id) {
  1042. memcpy(s, id->tsx_id, STUN_TID_SIZE);
  1043. }
  1044. }
  1045. static void stun_tid_from_string(const uint8_t *s, stun_tid *id) {
  1046. if (s && id) {
  1047. memcpy(id->tsx_id, s, STUN_TID_SIZE);
  1048. }
  1049. }
  1050. void stun_tid_from_message_str(const uint8_t *buf, size_t len, stun_tid *id) {
  1051. UNUSED_ARG(len);
  1052. stun_tid_from_string(buf + 8, id);
  1053. }
  1054. void stun_tid_message_cpy(uint8_t *buf, const stun_tid *id) {
  1055. if (buf && id) {
  1056. stun_tid_string_cpy(buf + 8, id);
  1057. }
  1058. }
  1059. void stun_tid_generate(stun_tid *id) {
  1060. if (id) {
  1061. turn_random_tid_size(id->tsx_id);
  1062. }
  1063. }
  1064. void stun_tid_generate_in_message_str(uint8_t *buf, stun_tid *id) {
  1065. stun_tid tmp;
  1066. if (!id) {
  1067. id = &tmp;
  1068. }
  1069. stun_tid_generate(id);
  1070. stun_tid_message_cpy(buf, id);
  1071. }
  1072. /////////////////// TIME ////////////////////////////////////////////////////////
  1073. turn_time_t stun_adjust_allocate_lifetime(turn_time_t lifetime, turn_time_t max_allowed_lifetime,
  1074. turn_time_t max_lifetime) {
  1075. if (!lifetime) {
  1076. lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME;
  1077. } else if (lifetime < STUN_MIN_ALLOCATE_LIFETIME) {
  1078. lifetime = STUN_MIN_ALLOCATE_LIFETIME;
  1079. } else if (lifetime > max_allowed_lifetime) {
  1080. lifetime = max_allowed_lifetime;
  1081. }
  1082. if (max_lifetime && (max_lifetime < lifetime)) {
  1083. lifetime = max_lifetime;
  1084. }
  1085. return lifetime;
  1086. }
  1087. ////////////// ATTR /////////////////////////////////////////////////////////////
  1088. int stun_attr_get_type(stun_attr_ref attr) {
  1089. if (attr) {
  1090. return (int)(nswap16(((const uint16_t *)attr)[0]));
  1091. }
  1092. return -1;
  1093. }
  1094. int stun_attr_get_len(stun_attr_ref attr) {
  1095. if (attr) {
  1096. return (int)(nswap16(((const uint16_t *)attr)[1]));
  1097. }
  1098. return -1;
  1099. }
  1100. const uint8_t *stun_attr_get_value(stun_attr_ref attr) {
  1101. if (attr) {
  1102. int len = (int)(nswap16(((const uint16_t *)attr)[1]));
  1103. if (len < 1) {
  1104. return NULL;
  1105. }
  1106. return ((const uint8_t *)attr) + 4;
  1107. }
  1108. return NULL;
  1109. }
  1110. int stun_get_requested_address_family(stun_attr_ref attr) {
  1111. if (attr) {
  1112. int len = (int)(nswap16(((const uint16_t *)attr)[1]));
  1113. if (len != 4) {
  1114. return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_INVALID;
  1115. }
  1116. int val = ((const uint8_t *)attr)[4];
  1117. switch (val) {
  1118. case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4:
  1119. case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6:
  1120. return val;
  1121. default:
  1122. return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_INVALID;
  1123. };
  1124. }
  1125. return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT;
  1126. }
  1127. uint16_t stun_attr_get_channel_number(stun_attr_ref attr) {
  1128. if (attr) {
  1129. const uint8_t *value = stun_attr_get_value(attr);
  1130. if (value && (stun_attr_get_len(attr) >= 2)) {
  1131. uint16_t cn = nswap16(((const uint16_t *)value)[0]);
  1132. if (STUN_VALID_CHANNEL(cn)) {
  1133. return cn;
  1134. }
  1135. }
  1136. }
  1137. return 0;
  1138. }
  1139. band_limit_t stun_attr_get_bandwidth(stun_attr_ref attr) {
  1140. if (attr) {
  1141. const uint8_t *value = stun_attr_get_value(attr);
  1142. if (value && (stun_attr_get_len(attr) >= 4)) {
  1143. uint32_t bps = nswap32(((const uint32_t *)value)[0]);
  1144. return (band_limit_t)(bps << 7);
  1145. }
  1146. }
  1147. return 0;
  1148. }
  1149. uint64_t stun_attr_get_reservation_token_value(stun_attr_ref attr) {
  1150. if (attr) {
  1151. const uint8_t *value = stun_attr_get_value(attr);
  1152. if (value && (stun_attr_get_len(attr) == 8)) {
  1153. uint64_t token;
  1154. memcpy(&token, value, sizeof(uint64_t));
  1155. return nswap64(token);
  1156. }
  1157. }
  1158. return 0;
  1159. }
  1160. bool stun_attr_is_addr(stun_attr_ref attr) {
  1161. if (attr) {
  1162. switch (stun_attr_get_type(attr)) {
  1163. case STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS:
  1164. case STUN_ATTRIBUTE_XOR_PEER_ADDRESS:
  1165. case STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS:
  1166. case STUN_ATTRIBUTE_MAPPED_ADDRESS:
  1167. case STUN_ATTRIBUTE_ALTERNATE_SERVER:
  1168. case OLD_STUN_ATTRIBUTE_RESPONSE_ADDRESS:
  1169. case OLD_STUN_ATTRIBUTE_SOURCE_ADDRESS:
  1170. case OLD_STUN_ATTRIBUTE_CHANGED_ADDRESS:
  1171. case OLD_STUN_ATTRIBUTE_REFLECTED_FROM:
  1172. case STUN_ATTRIBUTE_RESPONSE_ORIGIN:
  1173. case STUN_ATTRIBUTE_OTHER_ADDRESS:
  1174. return true;
  1175. break;
  1176. default:;
  1177. };
  1178. }
  1179. return false;
  1180. }
  1181. uint8_t stun_attr_get_even_port(stun_attr_ref attr) {
  1182. if (attr) {
  1183. const uint8_t *value = stun_attr_get_value(attr);
  1184. if (value) {
  1185. if ((uint8_t)(value[0]) > 0x7F) {
  1186. return 1;
  1187. }
  1188. }
  1189. }
  1190. return 0;
  1191. }
  1192. stun_attr_ref stun_attr_get_first_by_type_str(const uint8_t *buf, size_t len, uint16_t attr_type) {
  1193. stun_attr_ref attr = stun_attr_get_first_str(buf, len);
  1194. while (attr) {
  1195. if (stun_attr_get_type(attr) == attr_type) {
  1196. return attr;
  1197. }
  1198. attr = stun_attr_get_next_str(buf, len, attr);
  1199. }
  1200. return NULL;
  1201. }
  1202. static stun_attr_ref stun_attr_check_valid(stun_attr_ref attr, size_t remaining) {
  1203. if (remaining >= 4) {
  1204. /* Read the size of the attribute */
  1205. size_t attrlen = stun_attr_get_len(attr);
  1206. remaining -= 4;
  1207. /* Round to boundary */
  1208. uint16_t rem4 = ((uint16_t)attrlen) & 0x0003;
  1209. if (rem4) {
  1210. attrlen = attrlen + 4 - (int)rem4;
  1211. }
  1212. /* Check that there's enough space remaining */
  1213. if (attrlen <= remaining) {
  1214. return attr;
  1215. }
  1216. }
  1217. return NULL;
  1218. }
  1219. stun_attr_ref stun_attr_get_first_str(const uint8_t *buf, size_t len) {
  1220. int bufLen = stun_get_command_message_len_str(buf, len);
  1221. if (bufLen > STUN_HEADER_LENGTH) {
  1222. stun_attr_ref attr = (stun_attr_ref)(buf + STUN_HEADER_LENGTH);
  1223. return stun_attr_check_valid(attr, bufLen - STUN_HEADER_LENGTH);
  1224. }
  1225. return NULL;
  1226. }
  1227. stun_attr_ref stun_attr_get_next_str(const uint8_t *buf, size_t len, stun_attr_ref prev) {
  1228. if (!prev) {
  1229. return stun_attr_get_first_str(buf, len);
  1230. } else {
  1231. const uint8_t *end = buf + stun_get_command_message_len_str(buf, len);
  1232. int attrlen = stun_attr_get_len(prev);
  1233. uint16_t rem4 = ((uint16_t)attrlen) & 0x0003;
  1234. if (rem4) {
  1235. attrlen = attrlen + 4 - (int)rem4;
  1236. }
  1237. /* Note the order here: operations on attrlen are untrusted as they may overflow */
  1238. if (attrlen < end - (const uint8_t *)prev - 4) {
  1239. const uint8_t *attr_end = (const uint8_t *)prev + 4 + attrlen;
  1240. return stun_attr_check_valid(attr_end, end - attr_end);
  1241. }
  1242. return NULL;
  1243. }
  1244. }
  1245. bool stun_attr_add_str(uint8_t *buf, size_t *len, uint16_t attr, const uint8_t *avalue, int alen) {
  1246. if (alen < 0) {
  1247. alen = 0;
  1248. }
  1249. uint8_t tmp[1];
  1250. if (!avalue) {
  1251. alen = 0;
  1252. avalue = tmp;
  1253. }
  1254. int clen = stun_get_command_message_len_str(buf, *len);
  1255. int newlen = clen + 4 + alen;
  1256. int newlenrem4 = newlen & 0x00000003;
  1257. int paddinglen = 0;
  1258. if (newlenrem4) {
  1259. paddinglen = 4 - newlenrem4;
  1260. newlen = newlen + paddinglen;
  1261. }
  1262. if (newlen >= MAX_STUN_MESSAGE_SIZE) {
  1263. return false;
  1264. }
  1265. uint8_t *attr_start = buf + clen;
  1266. uint16_t *attr_start_16t = (uint16_t *)attr_start;
  1267. stun_set_command_message_len_str(buf, newlen);
  1268. *len = newlen;
  1269. attr_start_16t[0] = nswap16(attr);
  1270. attr_start_16t[1] = nswap16(alen);
  1271. if (alen > 0) {
  1272. memcpy(attr_start + 4, avalue, alen);
  1273. }
  1274. // Write 0 padding to not leak data
  1275. memset(attr_start + 4 + alen, 0, paddinglen);
  1276. return true;
  1277. }
  1278. bool stun_attr_add_addr_str(uint8_t *buf, size_t *len, uint16_t attr_type, const ioa_addr *ca) {
  1279. stun_tid tid;
  1280. stun_tid_from_message_str(buf, *len, &tid);
  1281. int xor_ed = 0;
  1282. switch (attr_type) {
  1283. case STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS:
  1284. case STUN_ATTRIBUTE_XOR_PEER_ADDRESS:
  1285. case STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS:
  1286. xor_ed = 1;
  1287. break;
  1288. default:;
  1289. };
  1290. ioa_addr public_addr;
  1291. map_addr_from_private_to_public(ca, &public_addr);
  1292. uint8_t cfield[64];
  1293. int clen = 0;
  1294. if (stun_addr_encode(&public_addr, cfield, &clen, xor_ed, STUN_MAGIC_COOKIE, tid.tsx_id) < 0) {
  1295. return false;
  1296. }
  1297. if (!stun_attr_add_str(buf, len, attr_type, (uint8_t *)(&cfield), clen)) {
  1298. return false;
  1299. }
  1300. return true;
  1301. }
  1302. bool stun_attr_get_addr_str(const uint8_t *buf, size_t len, stun_attr_ref attr, ioa_addr *ca,
  1303. const ioa_addr *default_addr) {
  1304. stun_tid tid;
  1305. stun_tid_from_message_str(buf, len, &tid);
  1306. ioa_addr public_addr;
  1307. addr_set_any(ca);
  1308. addr_set_any(&public_addr);
  1309. int attr_type = stun_attr_get_type(attr);
  1310. if (attr_type < 0) {
  1311. return false;
  1312. }
  1313. int xor_ed = 0;
  1314. switch (attr_type) {
  1315. case STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS:
  1316. case STUN_ATTRIBUTE_XOR_PEER_ADDRESS:
  1317. case STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS:
  1318. xor_ed = 1;
  1319. break;
  1320. default:;
  1321. };
  1322. const uint8_t *cfield = stun_attr_get_value(attr);
  1323. if (!cfield) {
  1324. return false;
  1325. }
  1326. if (stun_addr_decode(&public_addr, cfield, stun_attr_get_len(attr), xor_ed, STUN_MAGIC_COOKIE, tid.tsx_id) < 0) {
  1327. return false;
  1328. }
  1329. map_addr_from_public_to_private(&public_addr, ca);
  1330. if (default_addr && addr_any_no_port(ca) && !addr_any_no_port(default_addr)) {
  1331. int port = addr_get_port(ca);
  1332. addr_cpy(ca, default_addr);
  1333. addr_set_port(ca, port);
  1334. }
  1335. return true;
  1336. }
  1337. bool stun_attr_get_first_addr_str(const uint8_t *buf, size_t len, uint16_t attr_type, ioa_addr *ca,
  1338. const ioa_addr *default_addr) {
  1339. stun_attr_ref attr = stun_attr_get_first_str(buf, len);
  1340. while (attr) {
  1341. if (stun_attr_is_addr(attr) && (attr_type == stun_attr_get_type(attr))) {
  1342. if (stun_attr_get_addr_str(buf, len, attr, ca, default_addr)) {
  1343. return true;
  1344. }
  1345. }
  1346. attr = stun_attr_get_next_str(buf, len, attr);
  1347. }
  1348. return false;
  1349. }
  1350. bool stun_attr_add_channel_number_str(uint8_t *buf, size_t *len, uint16_t chnumber) {
  1351. uint16_t field[2];
  1352. field[0] = nswap16(chnumber);
  1353. field[1] = 0;
  1354. return stun_attr_add_str(buf, len, STUN_ATTRIBUTE_CHANNEL_NUMBER, (uint8_t *)(field), sizeof(field));
  1355. }
  1356. bool stun_attr_add_bandwidth_str(uint8_t *buf, size_t *len, band_limit_t bps0) {
  1357. uint32_t bps = (uint32_t)(band_limit_t)(bps0 >> 7);
  1358. uint32_t field = nswap32(bps);
  1359. return stun_attr_add_str(buf, len, STUN_ATTRIBUTE_NEW_BANDWIDTH, (uint8_t *)(&field), sizeof(field));
  1360. }
  1361. bool stun_attr_add_address_error_code(uint8_t *buf, size_t *len, int requested_address_family, int error_code) {
  1362. const uint8_t *reason = get_default_reason(error_code);
  1363. uint8_t avalue[513];
  1364. avalue[0] = (uint8_t)requested_address_family;
  1365. avalue[1] = 0;
  1366. avalue[2] = (uint8_t)(error_code / 100);
  1367. avalue[3] = (uint8_t)(error_code % 100);
  1368. strncpy((char *)(avalue + 4), (const char *)reason, sizeof(avalue) - 4);
  1369. avalue[sizeof(avalue) - 1] = 0;
  1370. int alen = 4 + (int)strlen((const char *)(avalue + 4));
  1371. //"Manual" padding for compatibility with classic old stun:
  1372. {
  1373. int rem = alen % 4;
  1374. if (rem) {
  1375. alen += (4 - rem);
  1376. }
  1377. }
  1378. return stun_attr_add_str(buf, len, STUN_ATTRIBUTE_ADDRESS_ERROR_CODE, (uint8_t *)avalue, alen);
  1379. }
  1380. uint16_t stun_attr_get_first_channel_number_str(const uint8_t *buf, size_t len) {
  1381. stun_attr_ref attr = stun_attr_get_first_str(buf, len);
  1382. while (attr) {
  1383. if (stun_attr_get_type(attr) == STUN_ATTRIBUTE_CHANNEL_NUMBER) {
  1384. uint16_t ret = stun_attr_get_channel_number(attr);
  1385. if (STUN_VALID_CHANNEL(ret)) {
  1386. return ret;
  1387. }
  1388. }
  1389. attr = stun_attr_get_next_str(buf, len, attr);
  1390. }
  1391. return 0;
  1392. }
  1393. ////////////// FINGERPRINT ////////////////////////////
  1394. bool stun_attr_add_fingerprint_str(uint8_t *buf, size_t *len) {
  1395. uint32_t crc32 = 0;
  1396. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_FINGERPRINT, (uint8_t *)&crc32, 4)) {
  1397. return false;
  1398. }
  1399. crc32 = ns_crc32(buf, (int)*len - 8);
  1400. *((uint32_t *)(buf + *len - 4)) = nswap32(crc32 ^ ((uint32_t)FINGERPRINT_XOR));
  1401. return true;
  1402. }
  1403. ////////////// CRC ///////////////////////////////////////////////
  1404. #define CRC_MASK 0xFFFFFFFFUL
  1405. #define UPDATE_CRC(crc, c) crc = crctable[(uint8_t)crc ^ (uint8_t)(c)] ^ (crc >> 8)
  1406. static const uint32_t crctable[256] = {
  1407. 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832,
  1408. 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
  1409. 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a,
  1410. 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
  1411. 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
  1412. 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
  1413. 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab,
  1414. 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
  1415. 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4,
  1416. 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
  1417. 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074,
  1418. 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
  1419. 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525,
  1420. 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
  1421. 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
  1422. 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
  1423. 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76,
  1424. 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
  1425. 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6,
  1426. 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
  1427. 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7,
  1428. 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
  1429. 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7,
  1430. 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
  1431. 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
  1432. 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
  1433. 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330,
  1434. 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
  1435. 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
  1436. };
  1437. static uint32_t ns_crc32(const uint8_t *buffer, uint32_t len) {
  1438. uint32_t crc = CRC_MASK;
  1439. while (len--) {
  1440. UPDATE_CRC(crc, *buffer++);
  1441. }
  1442. return (~crc);
  1443. }
  1444. //////////// SASLprep RFC 4013 /////////////////////////////////////////
  1445. /* We support only basic ASCII table */
  1446. bool SASLprep(uint8_t *s) {
  1447. if (s) {
  1448. uint8_t *strin = s;
  1449. uint8_t *strout = s;
  1450. for (;;) {
  1451. uint8_t c = *strin;
  1452. if (!c) {
  1453. *strout = 0;
  1454. break;
  1455. }
  1456. switch (c) {
  1457. case 0xAD:
  1458. ++strin;
  1459. break;
  1460. case 0xA0:
  1461. case 0x20:
  1462. *strout = 0x20;
  1463. ++strout;
  1464. ++strin;
  1465. break;
  1466. case 0x7F:
  1467. return false;
  1468. default:
  1469. if (c < 0x1F) {
  1470. return false;
  1471. }
  1472. if (c >= 0x80 && c <= 0x9F) {
  1473. return false;
  1474. }
  1475. *strout = c;
  1476. ++strout;
  1477. ++strin;
  1478. };
  1479. }
  1480. }
  1481. return true;
  1482. }
  1483. //////////////// Message Integrity ////////////////////////////
  1484. size_t get_hmackey_size(SHATYPE shatype) {
  1485. if (shatype == SHATYPE_SHA256) {
  1486. return 32;
  1487. }
  1488. if (shatype == SHATYPE_SHA384) {
  1489. return 48;
  1490. }
  1491. if (shatype == SHATYPE_SHA512) {
  1492. return 64;
  1493. }
  1494. return 16;
  1495. }
  1496. void print_bin_func(const char *name, size_t len, const void *s, const char *func) {
  1497. printf("<%s>:<%s>:len=%d:[", func, name, (int)len);
  1498. for (size_t i = 0; i < len; i++) {
  1499. printf("%02x", (int)((const uint8_t *)s)[i]);
  1500. }
  1501. printf("]\n");
  1502. }
  1503. bool stun_attr_add_integrity_str(turn_credential_type ct, uint8_t *buf, size_t *len, hmackey_t key, password_t pwd,
  1504. SHATYPE shatype) {
  1505. uint8_t hmac[MAXSHASIZE];
  1506. unsigned int shasize;
  1507. switch (shatype) {
  1508. case SHATYPE_SHA256:
  1509. shasize = SHA256SIZEBYTES;
  1510. break;
  1511. case SHATYPE_SHA384:
  1512. shasize = SHA384SIZEBYTES;
  1513. break;
  1514. case SHATYPE_SHA512:
  1515. shasize = SHA512SIZEBYTES;
  1516. break;
  1517. default:
  1518. shasize = SHA1SIZEBYTES;
  1519. };
  1520. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MESSAGE_INTEGRITY, hmac, shasize)) {
  1521. return false;
  1522. }
  1523. if (ct == TURN_CREDENTIALS_SHORT_TERM) {
  1524. return stun_calculate_hmac(buf, *len - 4 - shasize, pwd, strlen((char *)pwd), buf + *len - shasize, &shasize,
  1525. shatype);
  1526. } else {
  1527. return stun_calculate_hmac(buf, *len - 4 - shasize, key, get_hmackey_size(shatype), buf + *len - shasize, &shasize,
  1528. shatype);
  1529. }
  1530. }
  1531. bool stun_attr_add_integrity_by_key_str(uint8_t *buf, size_t *len, const uint8_t *uname, const uint8_t *realm,
  1532. hmackey_t key, const uint8_t *nonce, SHATYPE shatype) {
  1533. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_USERNAME, uname, (int)strlen((const char *)uname))) {
  1534. return false;
  1535. }
  1536. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_NONCE, nonce, (int)strlen((const char *)nonce))) {
  1537. return false;
  1538. }
  1539. if (!stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REALM, realm, (int)strlen((const char *)realm))) {
  1540. return false;
  1541. }
  1542. password_t p;
  1543. return stun_attr_add_integrity_str(TURN_CREDENTIALS_LONG_TERM, buf, len, key, p, shatype);
  1544. }
  1545. bool stun_attr_add_integrity_by_user_str(uint8_t *buf, size_t *len, const uint8_t *uname, const uint8_t *realm,
  1546. const uint8_t *upwd, const uint8_t *nonce, SHATYPE shatype) {
  1547. hmackey_t key;
  1548. if (!stun_produce_integrity_key_str(uname, realm, upwd, key, shatype)) {
  1549. return false;
  1550. }
  1551. return stun_attr_add_integrity_by_key_str(buf, len, uname, realm, key, nonce, shatype);
  1552. }
  1553. bool stun_attr_add_integrity_by_user_short_term_str(uint8_t *buf, size_t *len, const uint8_t *uname, password_t pwd,
  1554. SHATYPE shatype) {
  1555. if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_USERNAME, uname, (int)strlen((const char *)uname))) {
  1556. return false;
  1557. }
  1558. hmackey_t key;
  1559. return stun_attr_add_integrity_str(TURN_CREDENTIALS_SHORT_TERM, buf, len, key, pwd, shatype);
  1560. }
  1561. /*
  1562. * Return -1 if failure, 0 if the integrity is not correct, 1 if OK
  1563. */
  1564. int stun_check_message_integrity_by_key_str(turn_credential_type ct, uint8_t *buf, size_t len, hmackey_t key,
  1565. password_t pwd, SHATYPE shatype) {
  1566. stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_MESSAGE_INTEGRITY);
  1567. if (!sar) {
  1568. return -1;
  1569. }
  1570. unsigned int shasize = 0;
  1571. switch (stun_attr_get_len(sar)) {
  1572. case SHA256SIZEBYTES:
  1573. shasize = SHA256SIZEBYTES;
  1574. if (shatype != SHATYPE_SHA256) {
  1575. return -1;
  1576. }
  1577. break;
  1578. case SHA384SIZEBYTES:
  1579. shasize = SHA384SIZEBYTES;
  1580. if (shatype != SHATYPE_SHA384) {
  1581. return -1;
  1582. }
  1583. break;
  1584. case SHA512SIZEBYTES:
  1585. shasize = SHA512SIZEBYTES;
  1586. if (shatype != SHATYPE_SHA512) {
  1587. return -1;
  1588. }
  1589. break;
  1590. case SHA1SIZEBYTES:
  1591. shasize = SHA1SIZEBYTES;
  1592. if (shatype != SHATYPE_SHA1) {
  1593. return -1;
  1594. }
  1595. break;
  1596. default:
  1597. return -1;
  1598. };
  1599. int orig_len = stun_get_command_message_len_str(buf, len);
  1600. if (orig_len < 0) {
  1601. return -1;
  1602. }
  1603. int new_len = (int)((const uint8_t *)sar - buf) + 4 + shasize;
  1604. if (new_len > orig_len) {
  1605. return -1;
  1606. }
  1607. if (!stun_set_command_message_len_str(buf, new_len)) {
  1608. return -1;
  1609. }
  1610. int res = 0;
  1611. uint8_t new_hmac[MAXSHASIZE] = {0};
  1612. if (ct == TURN_CREDENTIALS_SHORT_TERM) {
  1613. if (!stun_calculate_hmac(buf, (size_t)new_len - 4 - shasize, pwd, strlen((char *)pwd), new_hmac, &shasize,
  1614. shatype)) {
  1615. res = -1;
  1616. } else {
  1617. res = 0;
  1618. }
  1619. } else {
  1620. if (!stun_calculate_hmac(buf, (size_t)new_len - 4 - shasize, key, get_hmackey_size(shatype), new_hmac, &shasize,
  1621. shatype)) {
  1622. res = -1;
  1623. } else {
  1624. res = 0;
  1625. }
  1626. }
  1627. stun_set_command_message_len_str(buf, orig_len);
  1628. if (res < 0) {
  1629. return -1;
  1630. }
  1631. const uint8_t *old_hmac = stun_attr_get_value(sar);
  1632. if (!old_hmac) {
  1633. return -1;
  1634. }
  1635. if (0 != memcmp(old_hmac, new_hmac, shasize)) {
  1636. return 0;
  1637. }
  1638. return +1;
  1639. }
  1640. /*
  1641. * Return -1 if failure, 0 if the integrity is not correct, 1 if OK
  1642. */
  1643. int stun_check_message_integrity_str(turn_credential_type ct, uint8_t *buf, size_t len, const uint8_t *uname,
  1644. const uint8_t *realm, const uint8_t *upwd, SHATYPE shatype) {
  1645. hmackey_t key;
  1646. password_t pwd;
  1647. if (ct == TURN_CREDENTIALS_SHORT_TERM) {
  1648. strncpy((char *)pwd, (const char *)upwd, sizeof(password_t) - 1);
  1649. pwd[sizeof(password_t) - 1] = 0;
  1650. } else if (!stun_produce_integrity_key_str(uname, realm, upwd, key, shatype)) {
  1651. return -1;
  1652. }
  1653. return stun_check_message_integrity_by_key_str(ct, buf, len, key, pwd, shatype);
  1654. }
  1655. /* RFC 5780 */
  1656. bool stun_attr_get_change_request_str(stun_attr_ref attr, bool *change_ip, bool *change_port) {
  1657. if (stun_attr_get_len(attr) == 4) {
  1658. const uint8_t *value = stun_attr_get_value(attr);
  1659. if (value) {
  1660. *change_ip = (value[3] & 0x04);
  1661. *change_port = (value[3] & 0x02);
  1662. return true;
  1663. }
  1664. }
  1665. return false;
  1666. }
  1667. bool stun_attr_add_change_request_str(uint8_t *buf, size_t *len, bool change_ip, bool change_port) {
  1668. uint8_t avalue[4] = {0, 0, 0, 0};
  1669. if (change_ip) {
  1670. if (change_port) {
  1671. avalue[3] = 0x06;
  1672. } else {
  1673. avalue[3] = 0x04;
  1674. }
  1675. } else if (change_port) {
  1676. avalue[3] = 0x02;
  1677. }
  1678. return stun_attr_add_str(buf, len, STUN_ATTRIBUTE_CHANGE_REQUEST, avalue, 4);
  1679. }
  1680. int stun_attr_get_response_port_str(stun_attr_ref attr) {
  1681. if (stun_attr_get_len(attr) >= 2) {
  1682. const uint8_t *value = stun_attr_get_value(attr);
  1683. if (value) {
  1684. return nswap16(((const uint16_t *)value)[0]);
  1685. }
  1686. }
  1687. return -1;
  1688. }
  1689. bool stun_attr_add_response_port_str(uint8_t *buf, size_t *len, uint16_t port) {
  1690. uint8_t avalue[4] = {0, 0, 0, 0};
  1691. uint16_t *port_ptr = (uint16_t *)avalue;
  1692. *port_ptr = nswap16(port);
  1693. return stun_attr_add_str(buf, len, STUN_ATTRIBUTE_RESPONSE_PORT, avalue, 4);
  1694. }
  1695. int stun_attr_get_padding_len_str(stun_attr_ref attr) {
  1696. int len = stun_attr_get_len(attr);
  1697. if (len < 0) {
  1698. return -1;
  1699. }
  1700. return (uint16_t)len;
  1701. }
  1702. bool stun_attr_add_padding_str(uint8_t *buf, size_t *len, uint16_t padding_len) {
  1703. uint8_t avalue[0xFFFF];
  1704. memset(avalue, 0, padding_len);
  1705. return stun_attr_add_str(buf, len, STUN_ATTRIBUTE_PADDING, avalue, padding_len);
  1706. }
  1707. /* OAUTH */
  1708. #define OAUTH_ERROR(...) fprintf(stderr, __VA_ARGS__)
  1709. static void remove_spaces(char *s) {
  1710. char *sfns = s;
  1711. while (*sfns) {
  1712. if (*sfns != ' ') {
  1713. break;
  1714. }
  1715. ++sfns;
  1716. }
  1717. if (*sfns) {
  1718. if (sfns != s) {
  1719. while (*sfns && (*sfns != ' ')) {
  1720. *s = *sfns;
  1721. ++s;
  1722. ++sfns;
  1723. };
  1724. *s = 0;
  1725. } else {
  1726. while (*s) {
  1727. if (*s == ' ') {
  1728. *s = 0;
  1729. break;
  1730. }
  1731. ++s;
  1732. }
  1733. }
  1734. }
  1735. }
  1736. static void normalize_algorithm(char *s) {
  1737. char c = *s;
  1738. while (c) {
  1739. if (c == '_') {
  1740. *s = '-';
  1741. } else if ((c >= 'a') && (c <= 'z')) {
  1742. *s = c - 'a' + 'A';
  1743. }
  1744. ++s;
  1745. c = *s;
  1746. }
  1747. }
  1748. size_t calculate_enc_key_length(ENC_ALG a);
  1749. size_t calculate_enc_key_length(ENC_ALG a) {
  1750. switch (a) {
  1751. #if !defined(TURN_NO_GCM)
  1752. case A128GCM:
  1753. return 16;
  1754. #endif
  1755. default:
  1756. break;
  1757. };
  1758. return 32;
  1759. }
  1760. size_t calculate_auth_key_length(ENC_ALG a);
  1761. size_t calculate_auth_key_length(ENC_ALG a) {
  1762. switch (a) {
  1763. #if !defined(TURN_NO_GCM)
  1764. case A256GCM:
  1765. case A128GCM:
  1766. return 0;
  1767. #endif
  1768. default:
  1769. break;
  1770. };
  1771. return 0;
  1772. }
  1773. static bool calculate_key(char *key, size_t key_size, char *new_key, size_t new_key_size);
  1774. static bool calculate_key(char *key, size_t key_size, char *new_key, size_t new_key_size) {
  1775. UNUSED_ARG(key_size);
  1776. memcpy(new_key, key, new_key_size);
  1777. return true;
  1778. }
  1779. bool convert_oauth_key_data(const oauth_key_data *oakd0, oauth_key *key, char *err_msg, size_t err_msg_size) {
  1780. #if !defined(TURN_NO_OAUTH)
  1781. if (oakd0 && key) {
  1782. oauth_key_data oakd_obj;
  1783. memcpy(&oakd_obj, oakd0, sizeof(oauth_key_data));
  1784. oauth_key_data *oakd = &oakd_obj;
  1785. if (!(oakd->ikm_key_size)) {
  1786. if (err_msg) {
  1787. snprintf(err_msg, err_msg_size, "key is not defined");
  1788. }
  1789. }
  1790. remove_spaces(oakd->kid);
  1791. remove_spaces(oakd->as_rs_alg);
  1792. normalize_algorithm(oakd->as_rs_alg);
  1793. if (!(oakd->kid[0])) {
  1794. if (err_msg) {
  1795. snprintf(err_msg, err_msg_size, "KID is not defined");
  1796. }
  1797. OAUTH_ERROR("KID is not defined\n");
  1798. return false;
  1799. }
  1800. memset(key, 0, sizeof(oauth_key));
  1801. STRCPY(key->kid, oakd->kid);
  1802. memcpy(key->ikm_key, oakd->ikm_key, sizeof(key->ikm_key));
  1803. key->ikm_key_size = oakd->ikm_key_size;
  1804. key->timestamp = oakd->timestamp;
  1805. key->lifetime = oakd->lifetime;
  1806. if (!(key->timestamp)) {
  1807. key->timestamp = OAUTH_DEFAULT_TIMESTAMP;
  1808. }
  1809. if (!(key->lifetime)) {
  1810. key->lifetime = OAUTH_DEFAULT_LIFETIME;
  1811. }
  1812. key->as_rs_alg = ENC_ALG_ERROR;
  1813. #if !defined(TURN_NO_GCM)
  1814. key->as_rs_alg = ENC_ALG_DEFAULT;
  1815. if (!strcmp(oakd->as_rs_alg, "A128GCM")) {
  1816. key->as_rs_alg = A128GCM;
  1817. key->auth_key_size = 0;
  1818. key->auth_key[0] = 0;
  1819. } else if (!strcmp(oakd->as_rs_alg, "A256GCM")) {
  1820. key->as_rs_alg = A256GCM;
  1821. key->auth_key_size = 0;
  1822. key->auth_key[0] = 0;
  1823. } else
  1824. #endif
  1825. {
  1826. if (err_msg) {
  1827. snprintf(err_msg, err_msg_size, "Wrong oAuth token encryption algorithm: %s (2)\n", oakd->as_rs_alg);
  1828. }
  1829. OAUTH_ERROR("Wrong oAuth token encryption algorithm: %s (3)\n", oakd->as_rs_alg);
  1830. return false;
  1831. }
  1832. #if !defined(TURN_NO_GCM)
  1833. key->auth_key_size = calculate_auth_key_length(key->as_rs_alg);
  1834. if (key->auth_key_size) {
  1835. if (!calculate_key(key->ikm_key, key->ikm_key_size, key->auth_key, key->auth_key_size)) {
  1836. return false;
  1837. }
  1838. }
  1839. key->as_rs_key_size = calculate_enc_key_length(key->as_rs_alg);
  1840. if (!calculate_key(key->ikm_key, key->ikm_key_size, key->as_rs_key, key->as_rs_key_size)) {
  1841. return false;
  1842. }
  1843. #endif
  1844. }
  1845. return true;
  1846. #else
  1847. OAUTH_ERROR("Oauth support not included");
  1848. return false;
  1849. #endif
  1850. }
  1851. #if !defined(TURN_NO_OAUTH)
  1852. const EVP_CIPHER *get_cipher_type(ENC_ALG enc_alg);
  1853. const EVP_CIPHER *get_cipher_type(ENC_ALG enc_alg) {
  1854. switch (enc_alg) {
  1855. #if !defined(TURN_NO_GCM)
  1856. case A128GCM:
  1857. return EVP_aes_128_gcm();
  1858. case A256GCM:
  1859. return EVP_aes_256_gcm();
  1860. #endif
  1861. default:
  1862. break;
  1863. }
  1864. OAUTH_ERROR("%s: Unsupported enc algorithm: %d\n", __FUNCTION__, (int)enc_alg);
  1865. return NULL;
  1866. }
  1867. int my_EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl);
  1868. int my_EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) {
  1869. int cycle = 0;
  1870. int out_len = 0;
  1871. while ((out_len < inl) && (++cycle < 128)) {
  1872. int tmp_outl = 0;
  1873. unsigned char *ptr = NULL;
  1874. if (out) {
  1875. ptr = out + out_len;
  1876. }
  1877. int ret = EVP_EncryptUpdate(ctx, ptr, &tmp_outl, in + out_len, inl - out_len);
  1878. out_len += tmp_outl;
  1879. if (ret < 1) {
  1880. return ret;
  1881. }
  1882. }
  1883. *outl = out_len;
  1884. return 1;
  1885. }
  1886. int my_EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl);
  1887. int my_EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) {
  1888. int cycle = 0;
  1889. int out_len = 0;
  1890. while ((out_len < inl) && (++cycle < 128)) {
  1891. int tmp_outl = 0;
  1892. unsigned char *ptr = NULL;
  1893. if (out) {
  1894. ptr = out + out_len;
  1895. }
  1896. int ret = EVP_DecryptUpdate(ctx, ptr, &tmp_outl, in + out_len, inl - out_len);
  1897. out_len += tmp_outl;
  1898. if (ret < 1) {
  1899. return ret;
  1900. }
  1901. }
  1902. *outl = out_len;
  1903. return 1;
  1904. }
  1905. #if !defined(TURN_NO_GCM)
  1906. static bool encode_oauth_token_gcm(const uint8_t *server_name, encoded_oauth_token *etoken, const oauth_key *key,
  1907. const oauth_token *dtoken, const uint8_t *nonce0) {
  1908. if (server_name && etoken && key && dtoken && (dtoken->enc_block.key_length <= MAXSHASIZE)) {
  1909. unsigned char orig_field[MAX_ENCODED_OAUTH_TOKEN_SIZE];
  1910. memset(orig_field, 0, sizeof(orig_field));
  1911. unsigned char nonce[OAUTH_GCM_NONCE_SIZE];
  1912. if (nonce0) {
  1913. memcpy(nonce, nonce0, sizeof(nonce));
  1914. } else {
  1915. generate_random_nonce(nonce, sizeof(nonce));
  1916. }
  1917. size_t len = 0;
  1918. *((uint16_t *)(orig_field + len)) = nswap16(OAUTH_GCM_NONCE_SIZE);
  1919. len += 2;
  1920. memcpy(orig_field + len, nonce, OAUTH_GCM_NONCE_SIZE);
  1921. len += OAUTH_GCM_NONCE_SIZE;
  1922. *((uint16_t *)(orig_field + len)) = nswap16(dtoken->enc_block.key_length);
  1923. len += 2;
  1924. memcpy(orig_field + len, dtoken->enc_block.mac_key, dtoken->enc_block.key_length);
  1925. len += dtoken->enc_block.key_length;
  1926. uint64_t ts = nswap64(dtoken->enc_block.timestamp);
  1927. memcpy((orig_field + len), &ts, sizeof(ts));
  1928. len += sizeof(ts);
  1929. *((uint32_t *)(orig_field + len)) = nswap32(dtoken->enc_block.lifetime);
  1930. len += 4;
  1931. const EVP_CIPHER *cipher = get_cipher_type(key->as_rs_alg);
  1932. if (!cipher) {
  1933. return false;
  1934. }
  1935. EVP_CIPHER_CTX *ctxp = EVP_CIPHER_CTX_new();
  1936. EVP_CIPHER_CTX_init(ctxp);
  1937. /* Initialize the encryption operation. */
  1938. if (1 != EVP_EncryptInit_ex(ctxp, cipher, NULL, NULL, NULL)) {
  1939. return -1;
  1940. }
  1941. EVP_CIPHER_CTX_set_padding(ctxp, 1);
  1942. /* Set IV length if default 12 bytes (96 bits) is not appropriate */
  1943. if (1 != EVP_CIPHER_CTX_ctrl(ctxp, EVP_CTRL_GCM_SET_IVLEN, OAUTH_GCM_NONCE_SIZE, NULL)) {
  1944. return false;
  1945. }
  1946. /* Initialize key and IV */
  1947. if (1 != EVP_EncryptInit_ex(ctxp, NULL, NULL, (const unsigned char *)key->as_rs_key, nonce)) {
  1948. return false;
  1949. }
  1950. int outl = 0;
  1951. size_t sn_len = strlen((const char *)server_name);
  1952. /* Provide any AAD data. This can be called zero or more times as
  1953. * required
  1954. */
  1955. if (1 != my_EVP_EncryptUpdate(ctxp, NULL, &outl, server_name, (int)sn_len)) {
  1956. return false;
  1957. }
  1958. outl = 0;
  1959. unsigned char *encoded_field = (unsigned char *)etoken->token;
  1960. memcpy(encoded_field, orig_field, OAUTH_GCM_NONCE_SIZE + 2);
  1961. encoded_field += OAUTH_GCM_NONCE_SIZE + 2;
  1962. unsigned char *start_field = orig_field + OAUTH_GCM_NONCE_SIZE + 2;
  1963. len -= OAUTH_GCM_NONCE_SIZE + 2;
  1964. if (1 != my_EVP_EncryptUpdate(ctxp, encoded_field, &outl, start_field, (int)len)) {
  1965. return -1;
  1966. }
  1967. int tmp_outl = 0;
  1968. EVP_EncryptFinal_ex(ctxp, encoded_field + outl, &tmp_outl);
  1969. outl += tmp_outl;
  1970. EVP_CIPHER_CTX_ctrl(ctxp, EVP_CTRL_GCM_GET_TAG, OAUTH_GCM_TAG_SIZE, encoded_field + outl);
  1971. outl += OAUTH_GCM_TAG_SIZE;
  1972. etoken->size = 2 + OAUTH_GCM_NONCE_SIZE + outl;
  1973. EVP_CIPHER_CTX_free(ctxp);
  1974. return true;
  1975. }
  1976. return false;
  1977. }
  1978. static bool decode_oauth_token_gcm(const uint8_t *server_name, const encoded_oauth_token *etoken, const oauth_key *key,
  1979. oauth_token *dtoken) {
  1980. if (server_name && etoken && key && dtoken) {
  1981. unsigned char snl[2];
  1982. memcpy(snl, (const unsigned char *)(etoken->token), 2);
  1983. const unsigned char *csnl = snl;
  1984. uint16_t nonce_len = nswap16(*((const uint16_t *)csnl));
  1985. dtoken->enc_block.nonce_length = nonce_len;
  1986. size_t min_encoded_field_size = 2 + 4 + 8 + nonce_len + 2 + OAUTH_GCM_TAG_SIZE + 1;
  1987. if (etoken->size < min_encoded_field_size) {
  1988. OAUTH_ERROR("%s: token size too small: %d\n", __FUNCTION__, (int)etoken->size);
  1989. return false;
  1990. }
  1991. const unsigned char *encoded_field = (const unsigned char *)(etoken->token + nonce_len + 2);
  1992. unsigned int encoded_field_size = (unsigned int)etoken->size - nonce_len - 2 - OAUTH_GCM_TAG_SIZE;
  1993. const unsigned char *nonce = ((const unsigned char *)etoken->token + 2);
  1994. memcpy(dtoken->enc_block.nonce, nonce, nonce_len);
  1995. unsigned char tag[OAUTH_GCM_TAG_SIZE];
  1996. memcpy(tag, ((const unsigned char *)etoken->token) + nonce_len + 2 + encoded_field_size, sizeof(tag));
  1997. unsigned char decoded_field[MAX_ENCODED_OAUTH_TOKEN_SIZE];
  1998. const EVP_CIPHER *cipher = get_cipher_type(key->as_rs_alg);
  1999. if (!cipher) {
  2000. OAUTH_ERROR("%s: Cannot find cipher for algorithm: %d\n", __FUNCTION__, (int)key->as_rs_alg);
  2001. return false;
  2002. }
  2003. EVP_CIPHER_CTX *ctxp = EVP_CIPHER_CTX_new();
  2004. EVP_CIPHER_CTX_init(ctxp);
  2005. /* Initialize the decryption operation. */
  2006. if (1 != EVP_DecryptInit_ex(ctxp, cipher, NULL, NULL, NULL)) {
  2007. OAUTH_ERROR("%s: Cannot initialize decryption\n", __FUNCTION__);
  2008. return false;
  2009. }
  2010. // EVP_CIPHER_CTX_set_padding(&ctx,1);
  2011. /* Set IV length if default 12 bytes (96 bits) is not appropriate */
  2012. if (1 != EVP_CIPHER_CTX_ctrl(ctxp, EVP_CTRL_GCM_SET_IVLEN, nonce_len, NULL)) {
  2013. OAUTH_ERROR("%s: Cannot set nonce length\n", __FUNCTION__);
  2014. return false;
  2015. }
  2016. /* Initialize key and IV */
  2017. if (1 != EVP_DecryptInit_ex(ctxp, NULL, NULL, (const unsigned char *)key->as_rs_key, nonce)) {
  2018. OAUTH_ERROR("%s: Cannot set nonce\n", __FUNCTION__);
  2019. return false;
  2020. }
  2021. /* Set expected tag value. A restriction in OpenSSL 1.0.1c and earlier
  2022. + * required the tag before any AAD or ciphertext */
  2023. EVP_CIPHER_CTX_ctrl(ctxp, EVP_CTRL_GCM_SET_TAG, OAUTH_GCM_TAG_SIZE, tag);
  2024. int outl = 0;
  2025. size_t sn_len = strlen((const char *)server_name);
  2026. /* Provide any AAD data. This can be called zero or more times as
  2027. * required
  2028. */
  2029. if (1 != my_EVP_DecryptUpdate(ctxp, NULL, &outl, server_name, (int)sn_len)) {
  2030. OAUTH_ERROR("%s: Cannot decrypt update server_name: %s, len=%d\n", __FUNCTION__, server_name, (int)sn_len);
  2031. return false;
  2032. }
  2033. if (1 != my_EVP_DecryptUpdate(ctxp, decoded_field, &outl, encoded_field, (int)encoded_field_size)) {
  2034. OAUTH_ERROR("%s: Cannot decrypt update\n", __FUNCTION__);
  2035. return false;
  2036. }
  2037. int tmp_outl = 0;
  2038. if (EVP_DecryptFinal_ex(ctxp, decoded_field + outl, &tmp_outl) < 1) {
  2039. EVP_CIPHER_CTX_free(ctxp);
  2040. OAUTH_ERROR("%s: token integrity check failed\n", __FUNCTION__);
  2041. return false;
  2042. }
  2043. outl += tmp_outl;
  2044. EVP_CIPHER_CTX_free(ctxp);
  2045. size_t len = 0;
  2046. dtoken->enc_block.key_length = nswap16(*((uint16_t *)(decoded_field + len)));
  2047. len += 2;
  2048. memcpy(dtoken->enc_block.mac_key, decoded_field + len, dtoken->enc_block.key_length);
  2049. len += dtoken->enc_block.key_length;
  2050. uint64_t ts;
  2051. memcpy(&ts, (decoded_field + len), sizeof(ts));
  2052. dtoken->enc_block.timestamp = nswap64(ts);
  2053. len += sizeof(ts);
  2054. uint32_t lt;
  2055. memcpy(&lt, (decoded_field + len), sizeof(lt));
  2056. dtoken->enc_block.lifetime = nswap32(lt);
  2057. len += sizeof(lt);
  2058. return true;
  2059. }
  2060. return false;
  2061. }
  2062. #endif
  2063. #endif
  2064. bool encode_oauth_token(const uint8_t *server_name, encoded_oauth_token *etoken, const oauth_key *key,
  2065. const oauth_token *dtoken, const uint8_t *nonce) {
  2066. #if !defined(TURN_NO_OAUTH)
  2067. UNUSED_ARG(nonce);
  2068. if (server_name && etoken && key && dtoken) {
  2069. switch (key->as_rs_alg) {
  2070. #if !defined(TURN_NO_GCM)
  2071. case A256GCM:
  2072. case A128GCM:
  2073. return encode_oauth_token_gcm(server_name, etoken, key, dtoken, nonce);
  2074. #endif
  2075. default:
  2076. fprintf(stderr, "Unsupported AS_RS algorithm: %d\n", (int)key->as_rs_alg);
  2077. break;
  2078. };
  2079. }
  2080. return false;
  2081. #else
  2082. OAUTH_ERROR("Oauth support not included");
  2083. return false;
  2084. #endif
  2085. }
  2086. bool decode_oauth_token(const uint8_t *server_name, const encoded_oauth_token *etoken, const oauth_key *key,
  2087. oauth_token *dtoken) {
  2088. #if !defined(TURN_NO_OAUTH)
  2089. if (server_name && etoken && key && dtoken) {
  2090. switch (key->as_rs_alg) {
  2091. #if !defined(TURN_NO_GCM)
  2092. case A256GCM:
  2093. case A128GCM:
  2094. return decode_oauth_token_gcm(server_name, etoken, key, dtoken);
  2095. #endif
  2096. default:
  2097. fprintf(stderr, "Unsupported AS_RS algorithm: %d\n", (int)key->as_rs_alg);
  2098. break;
  2099. };
  2100. }
  2101. return false;
  2102. #else
  2103. OAUTH_ERROR("Oauth support not included");
  2104. return false;
  2105. #endif
  2106. }
  2107. ///////////////////////////////////////////////////////////////