sasl_io.c 32 KB

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