security.c: Made block_write return a CURLcode.
[platform/upstream/curl.git] / lib / security.c
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 - 2010, 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 "setup.h"
45
46 #ifndef CURL_DISABLE_FTP
47 #if defined(HAVE_KRB4) || defined(HAVE_GSSAPI)
48
49 #define _MPRINTF_REPLACE /* we want curl-functions instead of native ones */
50 #include <curl/mprintf.h>
51
52 #include <stdlib.h>
53 #include <string.h>
54
55 #ifdef HAVE_NETDB_H
56 #include <netdb.h>
57 #endif
58
59 #ifdef HAVE_UNISTD_H
60 #include <unistd.h>
61 #endif
62
63 #include "urldata.h"
64 #include "krb4.h"
65 #include "curl_base64.h"
66 #include "sendf.h"
67 #include "ftp.h"
68 #include "curl_memory.h"
69 #include "rawstr.h"
70
71 /* The last #include file should be: */
72 #include "memdebug.h"
73
74 static const struct {
75   enum protection_level level;
76   const char *name;
77 } level_names[] = {
78   { prot_clear, "clear" },
79   { prot_safe, "safe" },
80   { prot_confidential, "confidential" },
81   { prot_private, "private" }
82 };
83
84 static enum protection_level
85 name_to_level(const char *name)
86 {
87   int i;
88   for(i = 0; i < (int)sizeof(level_names)/(int)sizeof(level_names[0]); i++)
89     if(checkprefix(name, level_names[i].name))
90       return level_names[i].level;
91   return (enum protection_level)-1;
92 }
93
94 static const struct Curl_sec_client_mech * const mechs[] = {
95 #if defined(HAVE_GSSAPI)
96   &Curl_krb5_client_mech,
97 #endif
98 #if defined(HAVE_KRB4)
99   &Curl_krb4_client_mech,
100 #endif
101   NULL
102 };
103
104
105 /* Read |len| from the socket |fd| and store it in |to|. Return a
106    CURLcode saying whether an error occured or CURLE_OK if |len| was read. */
107 static CURLcode
108 socket_read(curl_socket_t fd, void *to, size_t len)
109 {
110   char *to_p = to;
111   CURLcode code;
112   ssize_t nread;
113
114   while(len > 0) {
115     code = Curl_read_plain(fd, to_p, len, &nread);
116     if(code == CURLE_OK) {
117       len -= nread;
118       to_p += nread;
119     }
120     else {
121       /* FIXME: We are doing a busy wait */
122       if(code == CURLE_AGAIN)
123         continue;
124       return code;
125     }
126   }
127   return CURLE_OK;
128 }
129
130
131 /* Write |len| bytes from the buffer |to| to the socket |fd|. Return a
132    CURLcode saying whether an error occured or CURLE_OK if |len| was written. */
133 static CURLcode
134 socket_write(struct connectdata *conn, curl_socket_t fd, const void *to, size_t len)
135 {
136   const char *to_p = to;
137   CURLcode code;
138   ssize_t written;
139
140   while(len > 0) {
141     code = Curl_write_plain(conn, fd, to_p, len, &written);
142     if(code == CURLE_OK) {
143       len -= written;
144       to_p += written;
145     }
146     else {
147       /* FIXME: We are doing a busy wait */
148       if(code == CURLE_AGAIN)
149         continue;
150       return code;
151     }
152   }
153   return CURLE_OK;
154 }
155
156 static CURLcode read_data(struct connectdata *conn,
157                           curl_socket_t fd,
158                           struct krb4buffer *buf)
159 {
160   int len;
161   void* tmp;
162   CURLcode ret;
163
164   ret = socket_read(fd, &len, sizeof(len));
165   if (ret != CURLE_OK)
166     return ret;
167
168   len = ntohl(len);
169   tmp = realloc(buf->data, len);
170   if (tmp == NULL)
171     return CURLE_OUT_OF_MEMORY;
172
173   ret = socket_read(fd, buf->data, len);
174   if (ret != CURLE_OK)
175     return ret;
176   buf->size = (conn->mech->decode)(conn->app_data, buf->data, len,
177                                    conn->data_prot, conn);
178   buf->index = 0;
179   return CURLE_OK;
180 }
181
182 static size_t
183 buffer_read(struct krb4buffer *buf, void *data, size_t len)
184 {
185   if(buf->size - buf->index < len)
186     len = buf->size - buf->index;
187   memcpy(data, (char*)buf->data + buf->index, len);
188   buf->index += len;
189   return len;
190 }
191
192 static ssize_t sec_read(struct connectdata *conn, int num,
193                         char *buffer, size_t length, CURLcode *err)
194 {
195   size_t len;
196   int rx = 0;
197   curl_socket_t fd = conn->sock[num];
198
199   *err = CURLE_OK;
200
201   if(conn->in_buffer.eof_flag) {
202     conn->in_buffer.eof_flag = 0;
203     return 0;
204   }
205
206   len = buffer_read(&conn->in_buffer, buffer, length);
207   length -= len;
208   rx += len;
209   buffer = (char*)buffer + len;
210
211   while(length) {
212     if(read_data(conn, fd, &conn->in_buffer) != CURLE_OK)
213       return -1;
214     if(conn->in_buffer.size == 0) {
215       if(rx)
216         conn->in_buffer.eof_flag = 1;
217       return rx;
218     }
219     len = buffer_read(&conn->in_buffer, buffer, length);
220     length -= len;
221     rx += len;
222     buffer = (char*)buffer + len;
223   }
224   return rx;
225 }
226
227 static int
228 sec_send(struct connectdata *conn, int fd, const char *from, int length)
229 {
230   int bytes;
231   void *buf;
232   enum protection_level protlevel = conn->data_prot;
233   int iscmd = protlevel == prot_cmd;
234
235   if(iscmd) {
236     if(!strncmp(from, "PASS ", 5) || !strncmp(from, "ACCT ", 5))
237       protlevel = prot_private;
238     else
239       protlevel = conn->command_prot;
240   }
241   bytes = (conn->mech->encode)(conn->app_data, from, length, protlevel,
242                                &buf, conn);
243   if(iscmd) {
244     char *cmdbuf;
245
246     bytes = Curl_base64_encode(conn->data, (char *)buf, bytes, &cmdbuf);
247     if(bytes > 0) {
248       if(protlevel == prot_private)
249         socket_write(conn, fd, "ENC ", 4);
250       else
251         socket_write(conn, fd, "MIC ", 4);
252       socket_write(conn, fd, cmdbuf, bytes);
253       socket_write(conn, fd, "\r\n", 2);
254       Curl_infof(conn->data, "%s %s\n",
255                  protlevel == prot_private ? "ENC" : "MIC", cmdbuf);
256       free(cmdbuf);
257     }
258   }
259   else {
260     bytes = htonl(bytes);
261     socket_write(conn, fd, &bytes, sizeof(bytes));
262     socket_write(conn, fd, buf, ntohl(bytes));
263   }
264   free(buf);
265   return length;
266 }
267
268 static ssize_t sec_write(struct connectdata *conn, int fd,
269                          const char *buffer, int length)
270 {
271   int len = conn->buffer_size;
272   int tx = 0;
273
274   len -= (conn->mech->overhead)(conn->app_data, conn->data_prot, len);
275   if(len <= 0)
276     len = length;
277   while(length){
278     if(length < len)
279       len = length;
280     sec_send(conn, fd, buffer, len);
281     length -= len;
282     buffer += len;
283     tx += len;
284   }
285   return tx;
286 }
287
288 int
289 Curl_sec_fflush_fd(struct connectdata *conn, int fd)
290 {
291   if(conn->data_prot != prot_clear) {
292     if(conn->out_buffer.index > 0){
293       sec_write(conn, fd, conn->out_buffer.data, conn->out_buffer.index);
294       conn->out_buffer.index = 0;
295     }
296     sec_send(conn, fd, NULL, 0);
297   }
298   return 0;
299 }
300
301 static ssize_t _sec_send(struct connectdata *conn, int num,
302                          const void *buffer, size_t length, CURLcode *err)
303 {
304   curl_socket_t fd = conn->sock[num];
305   *err = CURLE_OK;
306   return sec_write(conn, fd, buffer, length);
307 }
308
309 int
310 Curl_sec_read_msg(struct connectdata *conn, char *s, int level)
311 {
312   int len;
313   unsigned char *buf;
314   int code;
315
316   len = Curl_base64_decode(s + 4, &buf); /* XXX */
317   if(len > 0)
318     len = (conn->mech->decode)(conn->app_data, buf, len, level, conn);
319   else
320     return -1;
321
322   if(len < 0) {
323     free(buf);
324     return -1;
325   }
326
327   if(conn->data->set.verbose) {
328     buf[len] = '\n';
329     Curl_debug(conn->data, CURLINFO_HEADER_IN, (char *)buf, len + 1, conn);
330   }
331
332   buf[len] = '\0';
333
334   if(buf[3] == '-')
335     code = 0;
336   else
337     sscanf((char *)buf, "%d", &code);
338   if(buf[len-1] == '\n')
339     buf[len-1] = '\0';
340   strcpy(s, (char *)buf);
341   free(buf);
342   return code;
343 }
344
345 enum protection_level
346 Curl_set_command_prot(struct connectdata *conn, enum protection_level level)
347 {
348   enum protection_level old = conn->command_prot;
349   conn->command_prot = level;
350   return old;
351 }
352
353 static int
354 sec_prot_internal(struct connectdata *conn, int level)
355 {
356   char *p;
357   unsigned int s = 1048576;
358   ssize_t nread;
359
360   if(!conn->sec_complete){
361     infof(conn->data, "No security data exchange has taken place.\n");
362     return -1;
363   }
364
365   if(level){
366     int code;
367     if(Curl_ftpsendf(conn, "PBSZ %u", s))
368       return -1;
369
370     if(Curl_GetFTPResponse(&nread, conn, &code))
371       return -1;
372
373     if(code/100 != 2){
374       failf(conn->data, "Failed to set protection buffer size.");
375       return -1;
376     }
377     conn->buffer_size = s;
378
379     p = strstr(conn->data->state.buffer, "PBSZ=");
380     if(p)
381       sscanf(p, "PBSZ=%u", &s);
382     if(s < conn->buffer_size)
383       conn->buffer_size = s;
384   }
385
386   if(Curl_ftpsendf(conn, "PROT %c", level["CSEP"]))
387     return -1;
388
389   if(Curl_GetFTPResponse(&nread, conn, NULL))
390     return -1;
391
392   if(conn->data->state.buffer[0] != '2'){
393     failf(conn->data, "Failed to set protection level.");
394     return -1;
395   }
396
397   conn->data_prot = (enum protection_level)level;
398   if(level == prot_private)
399     conn->command_prot = (enum protection_level)level;
400   return 0;
401 }
402
403 void
404 Curl_sec_set_protection_level(struct connectdata *conn)
405 {
406   if(conn->sec_complete && conn->data_prot != conn->request_data_prot)
407     sec_prot_internal(conn, conn->request_data_prot);
408 }
409
410
411 int
412 Curl_sec_request_prot(struct connectdata *conn, const char *level)
413 {
414   int l = name_to_level(level);
415   if(l == -1)
416     return -1;
417   conn->request_data_prot = (enum protection_level)l;
418   return 0;
419 }
420
421 int
422 Curl_sec_login(struct connectdata *conn)
423 {
424   int ret;
425   const struct Curl_sec_client_mech * const *m;
426   ssize_t nread;
427   struct SessionHandle *data=conn->data;
428   int ftpcode;
429
430   for(m = mechs; *m && (*m)->name; m++) {
431     void *tmp;
432
433     tmp = realloc(conn->app_data, (*m)->size);
434     if(tmp == NULL) {
435       failf (data, "realloc %u failed", (*m)->size);
436       return -1;
437     }
438     conn->app_data = tmp;
439
440     if((*m)->init && (*(*m)->init)(conn->app_data) != 0) {
441       infof(data, "Skipping %s...\n", (*m)->name);
442       continue;
443     }
444     infof(data, "Trying %s...\n", (*m)->name);
445
446     if(Curl_ftpsendf(conn, "AUTH %s", (*m)->name))
447       return -1;
448
449     if(Curl_GetFTPResponse(&nread, conn, &ftpcode))
450       return -1;
451
452     if(conn->data->state.buffer[0] != '3'){
453       switch(ftpcode) {
454       case 504:
455         infof(data,
456               "%s is not supported by the server.\n", (*m)->name);
457         break;
458       case 534:
459         infof(data, "%s rejected as security mechanism.\n", (*m)->name);
460         break;
461       default:
462         if(conn->data->state.buffer[0] == '5') {
463           infof(data, "The server doesn't support the FTP "
464                 "security extensions.\n");
465           return -1;
466         }
467         break;
468       }
469       continue;
470     }
471
472     ret = (*(*m)->auth)(conn->app_data, conn);
473
474     if(ret == AUTH_CONTINUE)
475       continue;
476     else if(ret != AUTH_OK){
477       /* mechanism is supposed to output error string */
478       return -1;
479     }
480     conn->mech = *m;
481     conn->sec_complete = 1;
482     if (conn->data_prot != prot_clear) {
483       conn->recv[FIRSTSOCKET] = sec_read;
484       conn->send[FIRSTSOCKET] = _sec_send;
485       conn->recv[SECONDARYSOCKET] = sec_read;
486       conn->send[SECONDARYSOCKET] = _sec_send;
487     }
488     conn->command_prot = prot_safe;
489     /* Set the requested protection level */
490     /* BLOCKING */
491     Curl_sec_set_protection_level(conn);
492     break;
493   }
494
495   return *m == NULL;
496 }
497
498 void
499 Curl_sec_end(struct connectdata *conn)
500 {
501   if(conn->mech != NULL) {
502     if(conn->mech->end)
503       (conn->mech->end)(conn->app_data);
504     memset(conn->app_data, 0, conn->mech->size);
505     free(conn->app_data);
506     conn->app_data = NULL;
507   }
508   conn->sec_complete = 0;
509   conn->data_prot = (enum protection_level)0;
510   conn->mech=NULL;
511 }
512
513 #endif /* HAVE_KRB4 || HAVE_GSSAPI */
514
515 #endif /* CURL_DISABLE_FTP */