sasl_io.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. /** BEGIN COPYRIGHT BLOCK
  2. * This Program is free software; you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation; version 2 of the License.
  5. *
  6. * This Program is distributed in the hope that it will be useful, but WITHOUT
  7. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  9. *
  10. * You should have received a copy of the GNU General Public License along with
  11. * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
  12. * Place, Suite 330, Boston, MA 02111-1307 USA.
  13. *
  14. * In addition, as a special exception, Red Hat, Inc. gives You the additional
  15. * right to link the code of this Program with code not covered under the GNU
  16. * General Public License ("Non-GPL Code") and to distribute linked combinations
  17. * including the two, subject to the limitations in this paragraph. Non-GPL Code
  18. * permitted under this exception must only link to the code of this Program
  19. * through those well defined interfaces identified in the file named EXCEPTION
  20. * found in the source code files (the "Approved Interfaces"). The files of
  21. * Non-GPL Code may instantiate templates or use macros or inline functions from
  22. * the Approved Interfaces without causing the resulting work to be covered by
  23. * the GNU General Public License. Only Red Hat, Inc. may make changes or
  24. * additions to the list of Approved Interfaces. You must obey the GNU General
  25. * Public License in all respects for all of the Program code and other code used
  26. * in conjunction with the Program except the Non-GPL Code covered by this
  27. * exception. If you modify this file, you may extend this exception to your
  28. * version of the file, but you are not obligated to do so. If you do not wish to
  29. * provide this exception without modification, you must delete this exception
  30. * statement from your version and license this file solely under the GPL without
  31. * exception.
  32. *
  33. *
  34. * Copyright (C) 2005 Red Hat, Inc.
  35. * All rights reserved.
  36. * END COPYRIGHT BLOCK **/
  37. #ifdef HAVE_CONFIG_H
  38. # include <config.h>
  39. #endif
  40. #include "slap.h"
  41. #include "slapi-plugin.h"
  42. #include "fe.h"
  43. #include <sasl.h>
  44. #include <arpa/inet.h>
  45. /*
  46. * I/O Shim Layer for SASL Encryption
  47. * The 'handle' is a pointer to a sasl_connection structure.
  48. */
  49. #define SASL_IO_BUFFER_SIZE 1024
  50. #define SASL_IO_BUFFER_NOT_ENCRYPTED -99
  51. #define SASL_IO_BUFFER_START_SIZE 7
  52. /*
  53. * SASL sends its encrypted PDU's with an embedded 4-byte length
  54. * at the beginning (in network byte order). We peek inside the
  55. * received data off the wire to find this length, and use it
  56. * to determine when we have read an entire SASL PDU.
  57. * So when we have that there is no need for the SASL layer
  58. * to do any fancy buffering with it, we always hand it
  59. * a full packet.
  60. */
  61. struct PRFilePrivate {
  62. char *decrypted_buffer;
  63. size_t decrypted_buffer_size;
  64. size_t decrypted_buffer_count;
  65. size_t decrypted_buffer_offset;
  66. char *encrypted_buffer;
  67. size_t encrypted_buffer_size;
  68. size_t encrypted_buffer_count;
  69. size_t encrypted_buffer_offset;
  70. Connection *conn; /* needed for connid and sasl_conn context */
  71. PRBool send_encrypted; /* can only send encrypted data after the first read -
  72. that is, we cannot send back an encrypted response
  73. to the bind request that established the sasl io */
  74. const char *send_buffer; /* encrypted buffer to send to client */
  75. unsigned int send_size; /* size of the encrypted buffer */
  76. unsigned int send_offset; /* number of bytes sent so far */
  77. };
  78. typedef PRFilePrivate sasl_io_private;
  79. static PRInt32 PR_CALLBACK
  80. sasl_io_recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
  81. PRIntervalTime timeout);
  82. static void
  83. debug_print_layers(PRFileDesc *fd)
  84. {
  85. #if 0
  86. PR_ASSERT(fd->higher == NULL); /* this is the topmost layer */
  87. while (fd) {
  88. PRSocketOptionData sod;
  89. PRInt32 err;
  90. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  91. "debug_print_layers: fd %d sasl_io_recv = %p\n",
  92. PR_FileDesc2NativeHandle(fd), sasl_io_recv );
  93. LDAPDebug( LDAP_DEBUG_CONNS,
  94. "debug_print_layers: fd name %s type = %d recv = %p\n",
  95. PR_GetNameForIdentity(fd->identity),
  96. PR_GetDescType(fd),
  97. fd->methods->recv ? fd->methods->recv : NULL );
  98. sod.option = PR_SockOpt_Nonblocking;
  99. if (PR_FAILURE == PR_GetSocketOption(fd, &sod)) {
  100. err = PR_GetError();
  101. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  102. "debug_print_layers: error getting nonblocking option: %d %s\n",
  103. err, slapd_pr_strerror(err) );
  104. } else {
  105. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  106. "debug_print_layers: non blocking %d\n", sod.value.non_blocking );
  107. }
  108. sod.option = PR_SockOpt_Reuseaddr;
  109. if (PR_FAILURE == PR_GetSocketOption(fd, &sod)) {
  110. err = PR_GetError();
  111. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  112. "debug_print_layers: error getting reuseaddr option: %d %s\n",
  113. err, slapd_pr_strerror(err) );
  114. } else {
  115. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  116. "debug_print_layers: reuseaddr %d\n", sod.value.reuse_addr );
  117. }
  118. sod.option = PR_SockOpt_RecvBufferSize;
  119. if (PR_FAILURE == PR_GetSocketOption(fd, &sod)) {
  120. err = PR_GetError();
  121. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  122. "debug_print_layers: error getting recvbuffer option: %d %s\n",
  123. err, slapd_pr_strerror(err) );
  124. } else {
  125. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  126. "debug_print_layers: recvbuffer %d\n", sod.value.recv_buffer_size );
  127. }
  128. fd = fd->lower;
  129. }
  130. #endif
  131. }
  132. static void
  133. sasl_io_init_buffers(sasl_io_private *sp)
  134. {
  135. sp->decrypted_buffer = slapi_ch_malloc(SASL_IO_BUFFER_SIZE);
  136. sp->decrypted_buffer_size = SASL_IO_BUFFER_SIZE;
  137. sp->encrypted_buffer = slapi_ch_malloc(SASL_IO_BUFFER_SIZE);
  138. sp->encrypted_buffer_size = SASL_IO_BUFFER_SIZE;
  139. }
  140. static void sasl_io_resize_encrypted_buffer(sasl_io_private *sp, size_t requested_size)
  141. {
  142. if (requested_size > sp->encrypted_buffer_size) {
  143. sp->encrypted_buffer = slapi_ch_realloc(sp->encrypted_buffer, requested_size);
  144. sp->encrypted_buffer_size = requested_size;
  145. }
  146. }
  147. static void sasl_io_resize_decrypted_buffer(sasl_io_private *sp, size_t requested_size)
  148. {
  149. if (requested_size > sp->decrypted_buffer_size) {
  150. sp->decrypted_buffer = slapi_ch_realloc(sp->decrypted_buffer, requested_size);
  151. sp->decrypted_buffer_size = requested_size;
  152. }
  153. }
  154. static int
  155. sasl_io_reading_packet(sasl_io_private *sp)
  156. {
  157. return (sp->encrypted_buffer_count > 0);
  158. }
  159. static int
  160. sasl_io_finished_packet(sasl_io_private *sp)
  161. {
  162. return (sp->encrypted_buffer_count && (sp->encrypted_buffer_offset == sp->encrypted_buffer_count) );
  163. }
  164. static const char* const sasl_LayerName = "SASL";
  165. static PRDescIdentity sasl_LayerID;
  166. static PRIOMethods sasl_IoMethods;
  167. static PRCallOnceType sasl_callOnce = {0,0};
  168. static sasl_io_private *
  169. sasl_get_io_private(PRFileDesc *fd)
  170. {
  171. sasl_io_private *sp;
  172. PR_ASSERT(fd != NULL);
  173. PR_ASSERT(fd->methods->file_type == PR_DESC_LAYERED);
  174. PR_ASSERT(fd->identity == sasl_LayerID);
  175. sp = (sasl_io_private *)fd->secret;
  176. return sp;
  177. }
  178. /*
  179. * return values:
  180. * 0 - connection was closed
  181. * 1 - success
  182. * -1 - error
  183. */
  184. static PRInt32
  185. sasl_io_start_packet(PRFileDesc *fd, PRIntn flags, PRIntervalTime timeout, PRInt32 *err)
  186. {
  187. unsigned char buffer[SASL_IO_BUFFER_START_SIZE];
  188. sasl_io_private *sp = sasl_get_io_private(fd);
  189. Connection *c = sp->conn;
  190. PRInt32 amount = sizeof(buffer);
  191. PRInt32 ret = 0;
  192. size_t packet_length = 0;
  193. size_t saslio_limit;
  194. *err = 0;
  195. debug_print_layers(fd);
  196. /* first we need the length bytes */
  197. ret = PR_Recv(fd->lower, buffer, amount, flags, timeout);
  198. LDAPDebug( LDAP_DEBUG_CONNS,
  199. "sasl_io_start_packet: read sasl packet length returned %d on connection %" NSPRIu64 "\n",
  200. ret, c->c_connid, 0 );
  201. if (ret <= 0) {
  202. *err = PR_GetError();
  203. if (ret == 0) {
  204. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  205. "sasl_io_start_packet: connection closed while reading sasl packet length on connection %" NSPRIu64 "\n",
  206. c->c_connid );
  207. } else {
  208. LDAPDebug( LDAP_DEBUG_CONNS,
  209. "sasl_io_start_packet: error reading sasl packet length on connection %" NSPRIu64 " %d:%s\n",
  210. c->c_connid, *err, slapd_pr_strerror(*err) );
  211. }
  212. return ret;
  213. }
  214. /*
  215. * Read the bytes and add them to sp->encrypted_buffer
  216. * - if offset < 7, tell caller we didn't read enough bytes yet
  217. * - if offset >= 7, decode the length and proceed.
  218. */
  219. if((ret + sp->encrypted_buffer_offset) > sp->encrypted_buffer_size){
  220. sasl_io_resize_encrypted_buffer(sp, ret + sp->encrypted_buffer_offset);
  221. }
  222. memcpy(sp->encrypted_buffer + sp->encrypted_buffer_offset, buffer, ret);
  223. sp->encrypted_buffer_offset += ret;
  224. if (sp->encrypted_buffer_offset < sizeof(buffer)) {
  225. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  226. "sasl_io_start_packet: read only %d bytes of sasl packet "
  227. "length on connection %" NSPRIu64 "\n", ret, c->c_connid );
  228. #if defined(EWOULDBLOCK)
  229. errno = EWOULDBLOCK;
  230. #elif defined(EAGAIN)
  231. errno = EAGAIN;
  232. #endif
  233. PR_SetError(PR_WOULD_BLOCK_ERROR, errno);
  234. return PR_FAILURE;
  235. }
  236. /*
  237. * Check if an LDAP operation was sent unencrypted
  238. */
  239. if(!sp->send_encrypted && *sp->encrypted_buffer == LDAP_TAG_MESSAGE){
  240. struct berval bv, tmp_bv;
  241. BerElement *ber = NULL;
  242. ber_len_t maxbersize = config_get_maxbersize();
  243. ber_len_t ber_len = 0;
  244. ber_tag_t tag;
  245. slapi_log_error( SLAPI_LOG_CONNS, "sasl_io_start_packet", "conn=%" NSPRIu64 " fd=%d "
  246. "Sent an LDAP message that was not encrypted.\n", c->c_connid, c->c_sd);
  247. /* Build a berval so we can get the length before reading in the entire packet */
  248. bv.bv_val = sp->encrypted_buffer;
  249. bv.bv_len = sp->encrypted_buffer_offset;
  250. if((ber_len = slapi_berval_get_msg_len(&bv, 0)) == -1){
  251. goto done;
  252. }
  253. /* Is the ldap operation too large? */
  254. if(ber_len > maxbersize){
  255. slapi_log_error( SLAPI_LOG_FATAL, "connection",
  256. "conn=%" NSPRIu64 " fd=%d Incoming BER Element was too long, max allowable "
  257. "is %" BERLEN_T " bytes. Change the nsslapd-maxbersize attribute in "
  258. "cn=config to increase.\n",
  259. c->c_connid, c->c_sd, maxbersize );
  260. PR_SetError(PR_IO_ERROR, 0);
  261. return PR_FAILURE;
  262. }
  263. /*
  264. * Bump the ber length by 2 for the tag/length we skipped over when calculating the berval length.
  265. * We now have the total "packet" size, so we know exactly what is left to read in.
  266. */
  267. ber_len += 2;
  268. /*
  269. * Read in the rest of the packet.
  270. *
  271. * sp->encrypted_buffer_offset is the total number of bytes that have been written
  272. * to the buffer. Once we have the complete LDAP packet we'll set it back to zero,
  273. * and adjust the sp->encrypted_buffer_count.
  274. */
  275. while(sp->encrypted_buffer_offset < ber_len){
  276. unsigned char mybuf[SASL_IO_BUFFER_SIZE];
  277. ret = PR_Recv(fd->lower, mybuf, SASL_IO_BUFFER_SIZE, flags, timeout);
  278. if (ret == PR_WOULD_BLOCK_ERROR || (ret == 0 && sp->encrypted_buffer_offset < ber_len)){
  279. /*
  280. * Need more data, go back and try to get more data from connection_read_operation()
  281. * We can return and continue to update sp->encrypted_buffer because we have
  282. * maintained the current size in encrypted_buffer_offset.
  283. */
  284. #if defined(EWOULDBLOCK)
  285. errno = EWOULDBLOCK;
  286. #elif defined(EAGAIN)
  287. errno = EAGAIN;
  288. #endif
  289. PR_SetError(PR_WOULD_BLOCK_ERROR, errno);
  290. return PR_FAILURE;
  291. } else if (ret > 0) {
  292. LDAPDebug( LDAP_DEBUG_CONNS,
  293. "Continued: read sasl packet length returned %d on connection %" NSPRIu64 "\n",
  294. ret, c->c_connid, 0 );
  295. if((ret + sp->encrypted_buffer_offset) > sp->encrypted_buffer_size){
  296. sasl_io_resize_encrypted_buffer(sp, ret + sp->encrypted_buffer_offset);
  297. }
  298. memcpy(sp->encrypted_buffer + sp->encrypted_buffer_offset, mybuf, ret );
  299. sp->encrypted_buffer_offset += ret;
  300. } else if (ret < 0){
  301. *err = PR_GetError();
  302. LDAPDebug( LDAP_DEBUG_CONNS, "sasl_io_start_packet: error reading sasl packet length on connection "
  303. "%" NSPRIu64 " %d:%s\n", c->c_connid, *err, slapd_pr_strerror(*err) );
  304. return ret;
  305. }
  306. }
  307. /*
  308. * Reset the berval with the updated buffer, and create the berElement
  309. */
  310. bv.bv_val = sp->encrypted_buffer;
  311. bv.bv_len = sp->encrypted_buffer_offset;
  312. if ( (ber = ber_init(&bv)) == NULL){
  313. goto done;
  314. }
  315. /*
  316. * Start parsing the berElement. First skip this tag, and move on to the
  317. * tag msgid
  318. */
  319. ber_skip_tag(ber, &ber_len);
  320. if( ber_peek_tag( ber, &ber_len ) == LDAP_TAG_MSGID) {
  321. /*
  322. * Skip the entire msgid element, so we can get to the LDAP op tag
  323. */
  324. if(ber_skip_element(ber, &tmp_bv) == LDAP_TAG_MSGID) {
  325. /*
  326. * We only allow unbind operations to be processed for unencrypted operations
  327. */
  328. if (( tag = ber_peek_tag( ber, &ber_len )) == LDAP_REQ_UNBIND ) {
  329. slapi_log_error( SLAPI_LOG_CONNS, "sasl_io_start_packet", "conn=%" NSPRIu64 " fd=%d "
  330. "Received unencrypted UNBIND operation.\n", c->c_connid, c->c_sd);
  331. sp->encrypted_buffer_count = sp->encrypted_buffer_offset;
  332. sp->encrypted_buffer_offset = 0;
  333. ber_free(ber, 1);
  334. return SASL_IO_BUFFER_NOT_ENCRYPTED;
  335. }
  336. slapi_log_error( SLAPI_LOG_CONNS, "sasl_io_start_packet", "conn=%" NSPRIu64 " fd=%d "
  337. "Error: received an LDAP message (tag 0x%lx) that was not encrypted.\n",
  338. c->c_connid, c->c_sd, tag);
  339. }
  340. }
  341. done:
  342. /* If we got here we have garbage, or a denied LDAP operation */
  343. slapi_log_error( SLAPI_LOG_CONNS, "sasl_io_start_packet", "conn=%" NSPRIu64 " fd=%d "
  344. "Error: received an invalid message that was not encrypted.\n",
  345. c->c_connid, c->c_sd);
  346. if (NULL != ber){
  347. ber_free(ber, 1);
  348. }
  349. PR_SetError(PR_IO_ERROR, 0);
  350. return PR_FAILURE;
  351. }
  352. /* At this point, sp->encrypted_buffer_offset == sizeof(buffer) */
  353. /* Decode the length */
  354. packet_length = ntohl(*(uint32_t *)sp->encrypted_buffer);
  355. /* add length itself (for Cyrus SASL library) */
  356. packet_length += sizeof(uint32_t);
  357. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  358. "read sasl packet length %ld on connection %" NSPRIu64 "\n",
  359. packet_length, c->c_connid );
  360. /* Check if the packet length is larger than our max allowed. A
  361. * setting of -1 means that we allow any size SASL IO packet. */
  362. saslio_limit = config_get_maxsasliosize();
  363. if(((long)saslio_limit != -1) && (packet_length > saslio_limit)) {
  364. LDAPDebug2Args( LDAP_DEBUG_ANY,
  365. "SASL encrypted packet length exceeds maximum allowed limit (length=%ld, limit=%ld)."
  366. " Change the nsslapd-maxsasliosize attribute in cn=config to increase limit.\n",
  367. packet_length, config_get_maxsasliosize() );
  368. PR_SetError(PR_BUFFER_OVERFLOW_ERROR, 0);
  369. *err = PR_BUFFER_OVERFLOW_ERROR;
  370. return -1;
  371. }
  372. sasl_io_resize_encrypted_buffer(sp, packet_length);
  373. /* Cyrus SASL implementation expects to have the length at the first
  374. 4 bytes */
  375. sp->encrypted_buffer_count = packet_length;
  376. return 1;
  377. }
  378. static PRInt32
  379. sasl_io_read_packet(PRFileDesc *fd, PRIntn flags, PRIntervalTime timeout, PRInt32 *err)
  380. {
  381. PRInt32 ret = 0;
  382. sasl_io_private *sp = sasl_get_io_private(fd);
  383. Connection *c = sp->conn;
  384. size_t bytes_remaining_to_read = sp->encrypted_buffer_count - sp->encrypted_buffer_offset;
  385. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  386. "sasl_io_read_packet: reading %d bytes for connection %" NSPRIu64 "\n",
  387. bytes_remaining_to_read,
  388. c->c_connid );
  389. ret = PR_Recv(fd->lower, sp->encrypted_buffer + sp->encrypted_buffer_offset, bytes_remaining_to_read, flags, timeout);
  390. if (ret <= 0) {
  391. *err = PR_GetError();
  392. if (ret == 0) {
  393. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  394. "sasl_io_read_packet: connection closed while reading sasl packet on connection %" NSPRIu64 "\n", c->c_connid );
  395. } else {
  396. LDAPDebug( LDAP_DEBUG_CONNS,
  397. "sasl_io_read_packet: error reading sasl packet on connection %" NSPRIu64 " %d:%s\n", c->c_connid, *err, slapd_pr_strerror(*err) );
  398. }
  399. return ret;
  400. }
  401. sp->encrypted_buffer_offset += ret;
  402. return ret;
  403. }
  404. static PRInt32 PR_CALLBACK
  405. sasl_io_recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
  406. PRIntervalTime timeout)
  407. {
  408. sasl_io_private *sp = sasl_get_io_private(fd);
  409. Connection *c = sp->conn;
  410. PRInt32 ret = 0;
  411. size_t bytes_in_buffer = 0;
  412. PRInt32 err = 0;
  413. /* Do we have decrypted data buffered from 'before' ? */
  414. bytes_in_buffer = sp->decrypted_buffer_count - sp->decrypted_buffer_offset;
  415. LDAPDebug( LDAP_DEBUG_CONNS,
  416. "sasl_io_recv for connection %" NSPRIu64 " len %d bytes_in_buffer %d\n", c->c_connid, len, bytes_in_buffer );
  417. LDAPDebug( LDAP_DEBUG_CONNS,
  418. "sasl_io_recv for connection %" NSPRIu64 " len %d encrypted buffer count %d\n", c->c_connid, len, sp->encrypted_buffer_count );
  419. if (0 == bytes_in_buffer) {
  420. /* If there wasn't buffered decrypted data, we need to get some... */
  421. if (!sasl_io_reading_packet(sp)) {
  422. /* First read the packet length and so on */
  423. ret = sasl_io_start_packet(fd, flags, timeout, &err);
  424. if (SASL_IO_BUFFER_NOT_ENCRYPTED == ret) {
  425. /*
  426. * Special case: we received unencrypted data that was actually
  427. * an unbind. Copy it to the buffer and return its length.
  428. */
  429. memcpy(buf, sp->encrypted_buffer, sp->encrypted_buffer_count);
  430. return sp->encrypted_buffer_count;
  431. }
  432. if (0 >= ret) {
  433. /* timeout, connection closed, or error */
  434. return ret;
  435. }
  436. }
  437. /* We now have the packet length
  438. * we now must read more data off the wire until we have the complete packet
  439. */
  440. ret = sasl_io_read_packet(fd, flags, timeout, &err);
  441. if (0 >= ret) {
  442. return ret; /* read packet will set pr error */
  443. }
  444. /* If we have not read the packet yet, we cannot return any decrypted data to the
  445. * caller - so just tell the caller we don't have enough data yet
  446. * this is equivalent to recv() returning EAGAIN on a non-blocking socket
  447. * the caller must handle this condition and poll() or similar to know
  448. * when more data arrives
  449. */
  450. if (!sasl_io_finished_packet(sp)) {
  451. LDAPDebug( LDAP_DEBUG_CONNS,
  452. "sasl_io_recv for connection %" NSPRIu64 " - not finished reading packet yet\n", c->c_connid, 0, 0 );
  453. #if defined(EWOULDBLOCK)
  454. errno = EWOULDBLOCK;
  455. #elif defined(EAGAIN)
  456. errno = EAGAIN;
  457. #endif
  458. PR_SetError(PR_WOULD_BLOCK_ERROR, errno);
  459. return PR_FAILURE;
  460. }
  461. /* We have the full encrypted buffer now - decrypt it */
  462. {
  463. const char *output_buffer = NULL;
  464. unsigned int output_length = 0;
  465. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  466. "sasl_io_recv finished reading packet for connection %" NSPRIu64 "\n", c->c_connid );
  467. /* Now decode it */
  468. ret = sasl_decode(c->c_sasl_conn,sp->encrypted_buffer,sp->encrypted_buffer_count,&output_buffer,&output_length);
  469. /* even if decode fails, need re-initialize the encrypted_buffer */
  470. sp->encrypted_buffer_offset = 0;
  471. sp->encrypted_buffer_count = 0;
  472. if (SASL_OK == ret) {
  473. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  474. "sasl_io_recv decoded packet length %d for connection %" NSPRIu64 "\n", output_length, c->c_connid );
  475. if (output_length) {
  476. sasl_io_resize_decrypted_buffer(sp,output_length);
  477. memcpy(sp->decrypted_buffer,output_buffer,output_length);
  478. sp->decrypted_buffer_count = output_length;
  479. sp->decrypted_buffer_offset = 0;
  480. bytes_in_buffer = output_length;
  481. }
  482. } else {
  483. LDAPDebug1Arg( LDAP_DEBUG_ANY,
  484. "sasl_io_recv failed to decode packet for connection %" NSPRIu64 "\n", c->c_connid );
  485. PR_SetError(PR_IO_ERROR, 0);
  486. return PR_FAILURE;
  487. }
  488. }
  489. }
  490. /* Finally, return data from the buffer to the caller */
  491. {
  492. size_t bytes_to_return = sp->decrypted_buffer_count - sp->decrypted_buffer_offset;
  493. if (bytes_to_return > len) {
  494. bytes_to_return = len;
  495. }
  496. /* Copy data from the decrypted buffer starting at the offset */
  497. memcpy(buf, sp->decrypted_buffer + sp->decrypted_buffer_offset, bytes_to_return);
  498. if (bytes_in_buffer == bytes_to_return) {
  499. sp->decrypted_buffer_offset = 0;
  500. sp->decrypted_buffer_count = 0;
  501. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  502. "sasl_io_recv all decrypted data returned for connection %" NSPRIu64 "\n", c->c_connid );
  503. } else {
  504. sp->decrypted_buffer_offset += bytes_to_return;
  505. LDAPDebug( LDAP_DEBUG_CONNS,
  506. "sasl_io_recv returning %d bytes to caller %d bytes left to return for connection %" NSPRIu64 "\n",
  507. bytes_to_return,
  508. sp->decrypted_buffer_count - sp->decrypted_buffer_offset,
  509. c->c_connid );
  510. }
  511. ret = bytes_to_return;
  512. }
  513. if (ret > 0) {
  514. /* we actually read something - we can now send encrypted data */
  515. sp->send_encrypted = PR_TRUE;
  516. }
  517. return ret;
  518. }
  519. static void
  520. reset_send_info(sasl_io_private *sp)
  521. {
  522. sp->send_buffer = NULL;
  523. sp->send_size = 0;
  524. sp->send_offset = 0;
  525. }
  526. PRInt32
  527. sasl_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
  528. PRIntn flags, PRIntervalTime timeout)
  529. {
  530. PRInt32 ret = 0;
  531. sasl_io_private *sp = sasl_get_io_private(fd);
  532. Connection *c = sp->conn;
  533. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  534. "sasl_io_send writing %d bytes\n", amount );
  535. if (sp->send_encrypted) {
  536. /* Get SASL to encrypt the buffer */
  537. if (NULL == sp->send_buffer) {
  538. ret = sasl_encode(c->c_sasl_conn, buf, amount, &sp->send_buffer, &sp->send_size);
  539. if (ret != SASL_OK) {
  540. const char *saslerr = sasl_errdetail(c->c_sasl_conn);
  541. LDAPDebug2Args( LDAP_DEBUG_ANY,
  542. "sasl_io_send could not encode %d bytes - sasl error %s\n",
  543. amount, saslerr ? saslerr : "unknown" );
  544. reset_send_info(sp);
  545. PR_SetError(PR_IO_ERROR, 0);
  546. return PR_FAILURE;
  547. }
  548. LDAPDebug1Arg( LDAP_DEBUG_CONNS,
  549. "sasl_io_send encoded as %d bytes\n", sp->send_size );
  550. sp->send_offset = 0;
  551. } else if ((amount > 0) && (sp->send_offset >= sp->send_size)) {
  552. /* something went wrong - we sent too many bytes */
  553. LDAPDebug2Args( LDAP_DEBUG_ANY,
  554. "sasl_io_send - client requested to send %d bytes but we "
  555. "already sent %d bytes\n", amount, (sp->send_offset >= sp->send_size));
  556. reset_send_info(sp);
  557. PR_SetError(PR_BUFFER_OVERFLOW_ERROR, EMSGSIZE);
  558. return PR_FAILURE;
  559. }
  560. ret = PR_Send(fd->lower, sp->send_buffer + sp->send_offset,
  561. sp->send_size - sp->send_offset, flags, timeout);
  562. /* we need to return the amount of cleartext sent */
  563. if (ret == (sp->send_size - sp->send_offset)) {
  564. ret = amount; /* sent amount of data requested by caller */
  565. reset_send_info(sp); /* done with this buffer, ready for next buffer */
  566. } else if (ret > 0) { /* could not send the entire encrypted buffer - tell caller we're blocked */
  567. LDAPDebug2Args( LDAP_DEBUG_CONNS,
  568. "sasl_io_send error: only sent %d of %d encoded bytes\n", ret,
  569. (sp->send_size - sp->send_offset) );
  570. sp->send_offset += ret;
  571. ret = PR_FAILURE;
  572. #if defined(EWOULDBLOCK)
  573. errno = EWOULDBLOCK;
  574. #elif defined(EAGAIN)
  575. errno = EAGAIN;
  576. #endif
  577. PR_SetError(PR_WOULD_BLOCK_ERROR, errno);
  578. }
  579. /* else - ret is error - caller will handle */
  580. } else {
  581. ret = PR_Send(fd->lower, buf, amount, flags, timeout);
  582. }
  583. return ret;
  584. }
  585. /*
  586. * Need to handle cases where caller uses PR_Write instead of
  587. * PR_Send on the network socket
  588. */
  589. static PRInt32 PR_CALLBACK
  590. sasl_io_write(PRFileDesc *fd, const void *buf, PRInt32 amount)
  591. {
  592. return sasl_io_send(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT);
  593. }
  594. static PRStatus PR_CALLBACK
  595. sasl_pop_IO_layer(PRFileDesc* stack, int doclose)
  596. {
  597. PRFileDesc* layer = NULL;
  598. sasl_io_private *sp = NULL;
  599. PRStatus rv = 0;
  600. PRDescIdentity id = PR_TOP_IO_LAYER;
  601. /* see if stack has the sasl io layer */
  602. if (!sasl_LayerID || !stack) {
  603. LDAPDebug0Args( LDAP_DEBUG_CONNS,
  604. "sasl_pop_IO_layer: no SASL IO layer\n" );
  605. return PR_SUCCESS;
  606. }
  607. /* if we're not being called during PR_Close, then we just want to
  608. pop the sasl io layer if it is on the stack */
  609. if (!doclose) {
  610. id = sasl_LayerID;
  611. if (!PR_GetIdentitiesLayer(stack, id)) {
  612. LDAPDebug0Args( LDAP_DEBUG_CONNS,
  613. "sasl_pop_IO_layer: no SASL IO layer\n" );
  614. return PR_SUCCESS;
  615. }
  616. }
  617. /* remove the layer from the stack */
  618. layer = PR_PopIOLayer(stack, id);
  619. if (!layer) {
  620. LDAPDebug0Args( LDAP_DEBUG_CONNS,
  621. "sasl_pop_IO_layer: error - could not pop SASL IO layer\n" );
  622. return PR_FAILURE;
  623. }
  624. /* get our private data and clean it up */
  625. sp = sasl_get_io_private(layer);
  626. if (sp) {
  627. LDAPDebug0Args( LDAP_DEBUG_CONNS,
  628. "sasl_pop_IO_layer: removing SASL IO layer\n" );
  629. /* Free the buffers */
  630. slapi_ch_free_string(&sp->encrypted_buffer);
  631. slapi_ch_free_string(&sp->decrypted_buffer);
  632. slapi_ch_free((void**)&sp);
  633. }
  634. layer->secret = NULL;
  635. if (layer->dtor) {
  636. layer->dtor(layer);
  637. }
  638. if (doclose) {
  639. rv = stack->methods->close(stack);
  640. } else {
  641. rv = PR_SUCCESS;
  642. }
  643. return rv;
  644. }
  645. static PRStatus PR_CALLBACK
  646. closeLayer(PRFileDesc* stack)
  647. {
  648. PRStatus rv = 0;
  649. LDAPDebug0Args( LDAP_DEBUG_CONNS,
  650. "closeLayer: closing SASL IO layer\n" );
  651. rv = sasl_pop_IO_layer(stack, 1 /* do close */);
  652. if (PR_SUCCESS != rv) {
  653. LDAPDebug0Args( LDAP_DEBUG_CONNS,
  654. "closeLayer: error closing SASL IO layer\n" );
  655. return rv;
  656. }
  657. return rv;
  658. }
  659. static PRStatus PR_CALLBACK
  660. initialize(void)
  661. {
  662. sasl_LayerID = PR_GetUniqueIdentity(sasl_LayerName);
  663. if (PR_INVALID_IO_LAYER == sasl_LayerID) {
  664. return PR_FAILURE;
  665. } else {
  666. const PRIOMethods* defaults = PR_GetDefaultIOMethods();
  667. if (!defaults) {
  668. return PR_FAILURE;
  669. } else {
  670. memcpy(&sasl_IoMethods, defaults, sizeof(sasl_IoMethods));
  671. }
  672. }
  673. /* Customize methods: */
  674. sasl_IoMethods.recv = sasl_io_recv;
  675. sasl_IoMethods.send = sasl_io_send;
  676. sasl_IoMethods.close = closeLayer;
  677. sasl_IoMethods.write = sasl_io_write; /* some code uses PR_Write instead of PR_Send */
  678. return PR_SUCCESS;
  679. }
  680. /*
  681. * Push the SASL I/O layer on top of the current NSPR I/O layer of the prfd used
  682. * by the connection.
  683. * must be called with the connection lock (c_mutex) held or in a condition in which
  684. * no other threads are accessing conn->c_prfd
  685. */
  686. int
  687. sasl_io_enable(Connection *c, void *data /* UNUSED */)
  688. {
  689. PRStatus rv = PR_CallOnce(&sasl_callOnce, initialize);
  690. if (PR_SUCCESS == rv) {
  691. PRFileDesc* layer = NULL;
  692. sasl_io_private *sp = NULL;
  693. if ( c->c_flags & CONN_FLAG_CLOSING ) {
  694. slapi_log_error( SLAPI_LOG_FATAL, "sasl_io_enable",
  695. "Cannot enable SASL security on connection in CLOSING state\n");
  696. return PR_FAILURE;
  697. }
  698. layer = PR_CreateIOLayerStub(sasl_LayerID, &sasl_IoMethods);
  699. sp = (sasl_io_private*) slapi_ch_calloc(1, sizeof(sasl_io_private));
  700. sasl_io_init_buffers(sp);
  701. layer->secret = sp;
  702. sp->conn = c;
  703. rv = PR_PushIOLayer(c->c_prfd, PR_TOP_IO_LAYER, layer);
  704. if (rv) {
  705. LDAPDebug( LDAP_DEBUG_ANY,
  706. "sasl_io_enable: error enabling sasl io on connection %" NSPRIu64 " %d:%s\n", c->c_connid, rv, slapd_pr_strerror(rv) );
  707. } else {
  708. LDAPDebug( LDAP_DEBUG_CONNS,
  709. "sasl_io_enable: enabled sasl io on connection %" NSPRIu64 " \n", c->c_connid, 0, 0 );
  710. debug_print_layers(c->c_prfd);
  711. }
  712. }
  713. return (int)rv;
  714. }
  715. /*
  716. * Remove the SASL I/O layer from the top of the current NSPR I/O layer of the prfd used
  717. * by the connection. Must either be called within the connection lock, or be
  718. * called while the connection (c_prfd) is not being referenced by another thread.
  719. */
  720. int
  721. sasl_io_cleanup(Connection *c, void *data /* UNUSED */)
  722. {
  723. int ret = 0;
  724. LDAPDebug( LDAP_DEBUG_CONNS,
  725. "sasl_io_cleanup for connection %" NSPRIu64 "\n", c->c_connid, 0, 0 );
  726. ret = sasl_pop_IO_layer(c->c_prfd, 0 /* do not close */);
  727. c->c_sasl_ssf = 0;
  728. return ret;
  729. }