2010-06-10 Jakub Jelinek <jakub@redhat.com> Dan Rosenberg <dan.j.rosenberg@gmail.com> * jartool.c (extract_jar): Fix up checks for traversal to parent directories, disallow absolute paths, make the code slightly more efficient. --- fastjar/jartool.c.jj 2007-06-22 13:03:46.000000000 +0200 +++ fastjar/jartool.c 2010-10-06 18:38:35.614372000 +0200 @@ -1738,7 +1738,17 @@ int extract_jar(int fd, char **files, in struct stat sbuf; int depth = 0; - tmp_buff = malloc(sizeof(char) * strlen((const char *)filename)); + if(*filename == '/'){ + fprintf(stderr, "Absolute path names are not allowed.\n"); + exit(1); + } + + tmp_buff = malloc(strlen((const char *)filename)); + + if(tmp_buff == NULL) { + fprintf(stderr, "Out of memory.\n"); + exit(1); + } for(;;){ const ub1 *idx = (const unsigned char *)strchr((const char *)start, '/'); @@ -1746,25 +1756,28 @@ int extract_jar(int fd, char **files, in if(idx == NULL) break; else if(idx == start){ + tmp_buff[idx - filename] = '/'; start++; continue; } - start = idx + 1; - strncpy(tmp_buff, (const char *)filename, (idx - filename)); - tmp_buff[(idx - filename)] = '\0'; + memcpy(tmp_buff + (start - filename), (const char *)start, (idx - start)); + tmp_buff[idx - filename] = '\0'; #ifdef DEBUG printf("checking the existance of %s\n", tmp_buff); #endif - if(strcmp(tmp_buff, "..") == 0){ + if(idx - start == 2 && memcmp(start, "..", 2) == 0){ --depth; if (depth < 0){ fprintf(stderr, "Traversal to parent directories during unpacking!\n"); exit(1); } - } else if (strcmp(tmp_buff, ".") != 0) + } else if (idx - start != 1 || *start != '.') ++depth; + + start = idx + 1; + if(stat(tmp_buff, &sbuf) < 0){ if(errno != ENOENT){ perror("stat"); @@ -1775,6 +1788,7 @@ int extract_jar(int fd, char **files, in #ifdef DEBUG printf("Directory exists\n"); #endif + tmp_buff[idx - filename] = '/'; continue; }else { fprintf(stderr, "Hmmm.. %s exists but isn't a directory!\n", @@ -1792,10 +1806,11 @@ int extract_jar(int fd, char **files, in if(verbose && handle) printf("%10s: %s/\n", "created", tmp_buff); + tmp_buff[idx - filename] = '/'; } /* only a directory */ - if(strlen((const char *)start) == 0) + if(*start == '\0') dir = TRUE; #ifdef DEBUG @@ -1803,7 +1818,7 @@ int extract_jar(int fd, char **files, in #endif /* If the entry was just a directory, don't write to file, etc */ - if(strlen((const char *)start) == 0) + if(*start == '\0') f_fd = -1; free(tmp_buff); @@ -1888,7 +1903,8 @@ int extract_jar(int fd, char **files, in exit(1); } - close(f_fd); + if (f_fd != -1) + close(f_fd); if(verbose && dir == FALSE && handle) printf("%10s: %s\n",