• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* This source code was modified by Martin Hedenfalk <mhe@stacken.kth.se> for
2  * use in Curl. His latest changes were done 2000-09-18.
3  *
4  * It has since been patched and modified a lot by Daniel Stenberg
5  * <daniel@haxx.se> to make it better applied to curl conditions, and to make
6  * it not use globals, pollute name space and more. This source code awaits a
7  * rewrite to work around the paragraph 2 in the BSD licenses as explained
8  * below.
9  *
10  * Copyright (c) 1998, 1999 Kungliga Tekniska H�gskolan
11  * (Royal Institute of Technology, Stockholm, Sweden).
12  *
13  * Copyright (C) 2001 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
14  *
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  *
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  *
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * 3. Neither the name of the Institute nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.  */
43 
44 #include "curl_setup.h"
45 
46 #ifndef CURL_DISABLE_FTP
47 #ifdef HAVE_GSSAPI
48 
49 #ifdef HAVE_NETDB_H
50 #include <netdb.h>
51 #endif
52 
53 #ifdef HAVE_LIMITS_H
54 #include <limits.h>
55 #endif
56 
57 #include "urldata.h"
58 #include "curl_base64.h"
59 #include "curl_memory.h"
60 #include "curl_sec.h"
61 #include "ftp.h"
62 #include "sendf.h"
63 #include "strcase.h"
64 #include "warnless.h"
65 #include "strdup.h"
66 /* The last #include file should be: */
67 #include "memdebug.h"
68 
69 static const struct {
70   enum protection_level level;
71   const char *name;
72 } level_names[] = {
73   { PROT_CLEAR, "clear" },
74   { PROT_SAFE, "safe" },
75   { PROT_CONFIDENTIAL, "confidential" },
76   { PROT_PRIVATE, "private" }
77 };
78 
79 static enum protection_level
name_to_level(const char * name)80 name_to_level(const char *name)
81 {
82   int i;
83   for(i = 0; i < (int)sizeof(level_names)/(int)sizeof(level_names[0]); i++)
84     if(checkprefix(name, level_names[i].name))
85       return level_names[i].level;
86   return PROT_NONE;
87 }
88 
89 /* Convert a protocol |level| to its char representation.
90    We take an int to catch programming mistakes. */
level_to_char(int level)91 static char level_to_char(int level)
92 {
93   switch(level) {
94   case PROT_CLEAR:
95     return 'C';
96   case PROT_SAFE:
97     return 'S';
98   case PROT_CONFIDENTIAL:
99     return 'E';
100   case PROT_PRIVATE:
101     return 'P';
102   case PROT_CMD:
103     /* Fall through */
104   default:
105     /* Those 2 cases should not be reached! */
106     break;
107   }
108   DEBUGASSERT(0);
109   /* Default to the most secure alternative. */
110   return 'P';
111 }
112 
113 /* Send an FTP command defined by |message| and the optional arguments. The
114    function returns the ftp_code. If an error occurs, -1 is returned. */
ftp_send_command(struct connectdata * conn,const char * message,...)115 static int ftp_send_command(struct connectdata *conn, const char *message, ...)
116 {
117   int ftp_code;
118   ssize_t nread=0;
119   va_list args;
120   char print_buffer[50];
121 
122   va_start(args, message);
123   vsnprintf(print_buffer, sizeof(print_buffer), message, args);
124   va_end(args);
125 
126   if(Curl_ftpsend(conn, print_buffer)) {
127     ftp_code = -1;
128   }
129   else {
130     if(Curl_GetFTPResponse(&nread, conn, &ftp_code))
131       ftp_code = -1;
132   }
133 
134   (void)nread; /* Unused */
135   return ftp_code;
136 }
137 
138 /* Read |len| from the socket |fd| and store it in |to|. Return a CURLcode
139    saying whether an error occurred or CURLE_OK if |len| was read. */
140 static CURLcode
socket_read(curl_socket_t fd,void * to,size_t len)141 socket_read(curl_socket_t fd, void *to, size_t len)
142 {
143   char *to_p = to;
144   CURLcode result;
145   ssize_t nread;
146 
147   while(len > 0) {
148     result = Curl_read_plain(fd, to_p, len, &nread);
149     if(!result) {
150       len -= nread;
151       to_p += nread;
152     }
153     else {
154       /* FIXME: We are doing a busy wait */
155       if(result == CURLE_AGAIN)
156         continue;
157       return result;
158     }
159   }
160   return CURLE_OK;
161 }
162 
163 
164 /* Write |len| bytes from the buffer |to| to the socket |fd|. Return a
165    CURLcode saying whether an error occurred or CURLE_OK if |len| was
166    written. */
167 static CURLcode
socket_write(struct connectdata * conn,curl_socket_t fd,const void * to,size_t len)168 socket_write(struct connectdata *conn, curl_socket_t fd, const void *to,
169              size_t len)
170 {
171   const char *to_p = to;
172   CURLcode result;
173   ssize_t written;
174 
175   while(len > 0) {
176     result = Curl_write_plain(conn, fd, to_p, len, &written);
177     if(!result) {
178       len -= written;
179       to_p += written;
180     }
181     else {
182       /* FIXME: We are doing a busy wait */
183       if(result == CURLE_AGAIN)
184         continue;
185       return result;
186     }
187   }
188   return CURLE_OK;
189 }
190 
read_data(struct connectdata * conn,curl_socket_t fd,struct krb5buffer * buf)191 static CURLcode read_data(struct connectdata *conn,
192                           curl_socket_t fd,
193                           struct krb5buffer *buf)
194 {
195   int len;
196   void *tmp = NULL;
197   CURLcode result;
198 
199   result = socket_read(fd, &len, sizeof(len));
200   if(result)
201     return result;
202 
203   if(len) {
204     /* only realloc if there was a length */
205     len = ntohl(len);
206     tmp = Curl_saferealloc(buf->data, len);
207   }
208   if(tmp == NULL)
209     return CURLE_OUT_OF_MEMORY;
210 
211   buf->data = tmp;
212   result = socket_read(fd, buf->data, len);
213   if(result)
214     return result;
215   buf->size = conn->mech->decode(conn->app_data, buf->data, len,
216                                  conn->data_prot, conn);
217   buf->index = 0;
218   return CURLE_OK;
219 }
220 
221 static size_t
buffer_read(struct krb5buffer * buf,void * data,size_t len)222 buffer_read(struct krb5buffer *buf, void *data, size_t len)
223 {
224   if(buf->size - buf->index < len)
225     len = buf->size - buf->index;
226   memcpy(data, (char *)buf->data + buf->index, len);
227   buf->index += len;
228   return len;
229 }
230 
231 /* Matches Curl_recv signature */
sec_recv(struct connectdata * conn,int sockindex,char * buffer,size_t len,CURLcode * err)232 static ssize_t sec_recv(struct connectdata *conn, int sockindex,
233                         char *buffer, size_t len, CURLcode *err)
234 {
235   size_t bytes_read;
236   size_t total_read = 0;
237   curl_socket_t fd = conn->sock[sockindex];
238 
239   *err = CURLE_OK;
240 
241   /* Handle clear text response. */
242   if(conn->sec_complete == 0 || conn->data_prot == PROT_CLEAR)
243       return read(fd, buffer, len);
244 
245   if(conn->in_buffer.eof_flag) {
246     conn->in_buffer.eof_flag = 0;
247     return 0;
248   }
249 
250   bytes_read = buffer_read(&conn->in_buffer, buffer, len);
251   len -= bytes_read;
252   total_read += bytes_read;
253   buffer += bytes_read;
254 
255   while(len > 0) {
256     if(read_data(conn, fd, &conn->in_buffer))
257       return -1;
258     if(conn->in_buffer.size == 0) {
259       if(bytes_read > 0)
260         conn->in_buffer.eof_flag = 1;
261       return bytes_read;
262     }
263     bytes_read = buffer_read(&conn->in_buffer, buffer, len);
264     len -= bytes_read;
265     total_read += bytes_read;
266     buffer += bytes_read;
267   }
268   /* FIXME: Check for overflow */
269   return total_read;
270 }
271 
272 /* Send |length| bytes from |from| to the |fd| socket taking care of encoding
273    and negociating with the server. |from| can be NULL. */
274 /* FIXME: We don't check for errors nor report any! */
do_sec_send(struct connectdata * conn,curl_socket_t fd,const char * from,int length)275 static void do_sec_send(struct connectdata *conn, curl_socket_t fd,
276                         const char *from, int length)
277 {
278   int bytes, htonl_bytes; /* 32-bit integers for htonl */
279   char *buffer = NULL;
280   char *cmd_buffer;
281   size_t cmd_size = 0;
282   CURLcode error;
283   enum protection_level prot_level = conn->data_prot;
284   bool iscmd = (prot_level == PROT_CMD)?TRUE:FALSE;
285 
286   DEBUGASSERT(prot_level > PROT_NONE && prot_level < PROT_LAST);
287 
288   if(iscmd) {
289     if(!strncmp(from, "PASS ", 5) || !strncmp(from, "ACCT ", 5))
290       prot_level = PROT_PRIVATE;
291     else
292       prot_level = conn->command_prot;
293   }
294   bytes = conn->mech->encode(conn->app_data, from, length, prot_level,
295                              (void **)&buffer);
296   if(!buffer || bytes <= 0)
297     return; /* error */
298 
299   if(iscmd) {
300     error = Curl_base64_encode(conn->data, buffer, curlx_sitouz(bytes),
301                                &cmd_buffer, &cmd_size);
302     if(error) {
303       free(buffer);
304       return; /* error */
305     }
306     if(cmd_size > 0) {
307       static const char *enc = "ENC ";
308       static const char *mic = "MIC ";
309       if(prot_level == PROT_PRIVATE)
310         socket_write(conn, fd, enc, 4);
311       else
312         socket_write(conn, fd, mic, 4);
313 
314       socket_write(conn, fd, cmd_buffer, cmd_size);
315       socket_write(conn, fd, "\r\n", 2);
316       infof(conn->data, "Send: %s%s\n", prot_level == PROT_PRIVATE?enc:mic,
317             cmd_buffer);
318       free(cmd_buffer);
319     }
320   }
321   else {
322     htonl_bytes = htonl(bytes);
323     socket_write(conn, fd, &htonl_bytes, sizeof(htonl_bytes));
324     socket_write(conn, fd, buffer, curlx_sitouz(bytes));
325   }
326   free(buffer);
327 }
328 
sec_write(struct connectdata * conn,curl_socket_t fd,const char * buffer,size_t length)329 static ssize_t sec_write(struct connectdata *conn, curl_socket_t fd,
330                          const char *buffer, size_t length)
331 {
332   ssize_t tx = 0, len = conn->buffer_size;
333 
334   len -= conn->mech->overhead(conn->app_data, conn->data_prot,
335                               curlx_sztosi(len));
336   if(len <= 0)
337     len = length;
338   while(length) {
339     if(length < (size_t)len)
340       len = length;
341 
342     do_sec_send(conn, fd, buffer, curlx_sztosi(len));
343     length -= len;
344     buffer += len;
345     tx += len;
346   }
347   return tx;
348 }
349 
350 /* Matches Curl_send signature */
sec_send(struct connectdata * conn,int sockindex,const void * buffer,size_t len,CURLcode * err)351 static ssize_t sec_send(struct connectdata *conn, int sockindex,
352                         const void *buffer, size_t len, CURLcode *err)
353 {
354   curl_socket_t fd = conn->sock[sockindex];
355   *err = CURLE_OK;
356   return sec_write(conn, fd, buffer, len);
357 }
358 
Curl_sec_read_msg(struct connectdata * conn,char * buffer,enum protection_level level)359 int Curl_sec_read_msg(struct connectdata *conn, char *buffer,
360                       enum protection_level level)
361 {
362   /* decoded_len should be size_t or ssize_t but conn->mech->decode returns an
363      int */
364   int decoded_len;
365   char *buf;
366   int ret_code = 0;
367   size_t decoded_sz = 0;
368   CURLcode error;
369 
370   DEBUGASSERT(level > PROT_NONE && level < PROT_LAST);
371 
372   error = Curl_base64_decode(buffer + 4, (unsigned char **)&buf, &decoded_sz);
373   if(error || decoded_sz == 0)
374     return -1;
375 
376   if(decoded_sz > (size_t)INT_MAX) {
377     free(buf);
378     return -1;
379   }
380   decoded_len = curlx_uztosi(decoded_sz);
381 
382   decoded_len = conn->mech->decode(conn->app_data, buf, decoded_len,
383                                    level, conn);
384   if(decoded_len <= 0) {
385     free(buf);
386     return -1;
387   }
388 
389   if(conn->data->set.verbose) {
390     buf[decoded_len] = '\n';
391     Curl_debug(conn->data, CURLINFO_HEADER_IN, buf, decoded_len + 1, conn);
392   }
393 
394   buf[decoded_len] = '\0';
395   if(decoded_len <= 3)
396     /* suspiciously short */
397     return 0;
398 
399   if(buf[3] != '-')
400     /* safe to ignore return code */
401     (void)sscanf(buf, "%d", &ret_code);
402 
403   if(buf[decoded_len - 1] == '\n')
404     buf[decoded_len - 1] = '\0';
405   /* FIXME: Is |buffer| length always greater than |decoded_len|? */
406   strcpy(buffer, buf);
407   free(buf);
408   return ret_code;
409 }
410 
411 /* FIXME: The error code returned here is never checked. */
sec_set_protection_level(struct connectdata * conn)412 static int sec_set_protection_level(struct connectdata *conn)
413 {
414   int code;
415   char *pbsz;
416   static unsigned int buffer_size = 1 << 20; /* 1048576 */
417   enum protection_level level = conn->request_data_prot;
418 
419   DEBUGASSERT(level > PROT_NONE && level < PROT_LAST);
420 
421   if(!conn->sec_complete) {
422     infof(conn->data, "Trying to change the protection level after the"
423                       "completion of the data exchange.\n");
424     return -1;
425   }
426 
427   /* Bail out if we try to set up the same level */
428   if(conn->data_prot == level)
429     return 0;
430 
431   if(level) {
432     code = ftp_send_command(conn, "PBSZ %u", buffer_size);
433     if(code < 0)
434       return -1;
435 
436     if(code/100 != 2) {
437       failf(conn->data, "Failed to set the protection's buffer size.");
438       return -1;
439     }
440     conn->buffer_size = buffer_size;
441 
442     pbsz = strstr(conn->data->state.buffer, "PBSZ=");
443     if(pbsz) {
444       /* ignore return code, use default value if it fails */
445       (void)sscanf(pbsz, "PBSZ=%u", &buffer_size);
446       if(buffer_size < conn->buffer_size)
447         conn->buffer_size = buffer_size;
448     }
449   }
450 
451   /* Now try to negiociate the protection level. */
452   code = ftp_send_command(conn, "PROT %c", level_to_char(level));
453 
454   if(code < 0)
455     return -1;
456 
457   if(code/100 != 2) {
458     failf(conn->data, "Failed to set the protection level.");
459     return -1;
460   }
461 
462   conn->data_prot = level;
463   if(level == PROT_PRIVATE)
464     conn->command_prot = level;
465 
466   return 0;
467 }
468 
469 int
Curl_sec_request_prot(struct connectdata * conn,const char * level)470 Curl_sec_request_prot(struct connectdata *conn, const char *level)
471 {
472   enum protection_level l = name_to_level(level);
473   if(l == PROT_NONE)
474     return -1;
475   DEBUGASSERT(l > PROT_NONE && l < PROT_LAST);
476   conn->request_data_prot = l;
477   return 0;
478 }
479 
choose_mech(struct connectdata * conn)480 static CURLcode choose_mech(struct connectdata *conn)
481 {
482   int ret;
483   struct Curl_easy *data = conn->data;
484   void *tmp_allocation;
485   const struct Curl_sec_client_mech *mech = &Curl_krb5_client_mech;
486 
487   tmp_allocation = realloc(conn->app_data, mech->size);
488   if(tmp_allocation == NULL) {
489     failf(data, "Failed realloc of size %u", mech->size);
490     mech = NULL;
491     return CURLE_OUT_OF_MEMORY;
492   }
493   conn->app_data = tmp_allocation;
494 
495   if(mech->init) {
496     ret = mech->init(conn->app_data);
497     if(ret) {
498       infof(data, "Failed initialization for %s. Skipping it.\n",
499             mech->name);
500       return CURLE_FAILED_INIT;
501     }
502   }
503 
504   infof(data, "Trying mechanism %s...\n", mech->name);
505   ret = ftp_send_command(conn, "AUTH %s", mech->name);
506   if(ret < 0)
507     /* FIXME: This error is too generic but it is OK for now. */
508     return CURLE_COULDNT_CONNECT;
509 
510   if(ret/100 != 3) {
511     switch(ret) {
512     case 504:
513       infof(data, "Mechanism %s is not supported by the server (server "
514             "returned ftp code: 504).\n", mech->name);
515       break;
516     case 534:
517       infof(data, "Mechanism %s was rejected by the server (server returned "
518             "ftp code: 534).\n", mech->name);
519       break;
520     default:
521       if(ret/100 == 5) {
522         infof(data, "server does not support the security extensions\n");
523         return CURLE_USE_SSL_FAILED;
524       }
525       break;
526     }
527     return CURLE_LOGIN_DENIED;
528   }
529 
530   /* Authenticate */
531   ret = mech->auth(conn->app_data, conn);
532 
533   if(ret != AUTH_CONTINUE) {
534     if(ret != AUTH_OK) {
535       /* Mechanism has dumped the error to stderr, don't error here. */
536       return -1;
537     }
538     DEBUGASSERT(ret == AUTH_OK);
539 
540     conn->mech = mech;
541     conn->sec_complete = 1;
542     conn->recv[FIRSTSOCKET] = sec_recv;
543     conn->send[FIRSTSOCKET] = sec_send;
544     conn->recv[SECONDARYSOCKET] = sec_recv;
545     conn->send[SECONDARYSOCKET] = sec_send;
546     conn->command_prot = PROT_SAFE;
547     /* Set the requested protection level */
548     /* BLOCKING */
549     (void)sec_set_protection_level(conn);
550   }
551 
552   return CURLE_OK;
553 }
554 
555 CURLcode
Curl_sec_login(struct connectdata * conn)556 Curl_sec_login(struct connectdata *conn)
557 {
558   return choose_mech(conn);
559 }
560 
561 
562 void
Curl_sec_end(struct connectdata * conn)563 Curl_sec_end(struct connectdata *conn)
564 {
565   if(conn->mech != NULL && conn->mech->end)
566     conn->mech->end(conn->app_data);
567   free(conn->app_data);
568   conn->app_data = NULL;
569   if(conn->in_buffer.data) {
570     free(conn->in_buffer.data);
571     conn->in_buffer.data = NULL;
572     conn->in_buffer.size = 0;
573     conn->in_buffer.index = 0;
574     /* FIXME: Is this really needed? */
575     conn->in_buffer.eof_flag = 0;
576   }
577   conn->sec_complete = 0;
578   conn->data_prot = PROT_CLEAR;
579   conn->mech = NULL;
580 }
581 
582 #endif /* HAVE_GSSAPI */
583 
584 #endif /* CURL_DISABLE_FTP */
585