Diff for /parser3/src/main/untaint.C between versions 1.16 and 1.128

version 1.16, 2001/03/25 09:01:00 version 1.128, 2004/02/06 09:40:28
Line 1 Line 1
 /** @file  /** @file
         Parser: String class part: untaint mechanizm.          Parser: String class part: untaint mechanizm.
   
         Copyright(c) 2001 ArtLebedev Group(http://www.artlebedev.com)          Copyright(c) 2001-2003 ArtLebedev Group (http://www.artlebedev.com)
           Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
         Author: Alexander Petrosyan <paf@design.ru>(http://design.ru/paf)  
   
         $Id$  
 */  */
   
 #include "pa_config_includes.h"  static const char * const IDENT_UNTAINT_C="$Date$";
   
   
 #include "pa_pool.h"  
 #include "pa_string.h"  #include "pa_string.h"
 #include "pa_hash.h"  #include "pa_hash.h"
 #include "pa_exception.h"  #include "pa_exception.h"
 #include "pa_table.h"  #include "pa_table.h"
   #include "pa_globals.h"
   #include "pa_dictionary.h"
   #include "pa_common.h"
   #include "pa_charset.h"
   #include "pa_request_charsets.h"
   #include "pa_sapi.h"
   
   extern "C" { // author forgot to do that
   #include "ec.h"
   }
   
 #define escape(cases) \  #include "pa_sql_connection.h"
         { \  
                 const char *src=row->item.ptr; \  // defines
                 for(int size=row->item.size; size--; src++) \  
                         switch(*src) { \  #undef CORD_ec_append
                                 cases \  // redefining to intercept flushes and implement whitespace optimization
                         } \  // of all consequent white space chars leaving only first one
   #define CORD_ec_append(x, c) \
       {  \
           bool skip=false; \
           if(optimize) switch(c) { \
           case ' ': case '\r': case '\n': case '\t': \
                   if(whitespace) \
                           skip=true; /*skipping subsequent*/ \
                   else \
                           whitespace=true; \
                   break; \
           default: \
                   whitespace=false; \
                   break; \
           } \
           if(!skip) { \
                   if ((x)[0].ec_bufptr == (x)[0].ec_buf + CORD_BUFSZ) { \
                           CORD_ec_flush_buf(x); \
                   } \
                   *((x)[0].ec_bufptr)++ = (c); \
           } \
       }
   
   
   #define escape(action) \
           for(; fragment_length--; CORD_next(info->pos)) { \
                   char c=CORD_pos_fetch(info->pos); \
                   action \
         }          }
 #define to_char(a, c)  case a: *dest++=c; break  #define _default  default: CORD_ec_append(info->result, c); break
 #define _default  default: *dest++=*src; break  #define encode(need_encode_func, prefix, otherwise)  \
 #define to_string(a, b, bsize)  \          if(need_encode_func(c)) { \
                 case a: \                  static const char* hex="0123456789ABCDEF"; \
                         strncpy(dest, b, bsize); \                  CORD_ec_append(info->result, prefix); \
                         dest+=bsize; \                  CORD_ec_append(info->result, hex[((unsigned char)c)/0x10]); \
                 break                  CORD_ec_append(info->result, hex[((unsigned char)c)%0x10]); \
 #define encode(need_encode_func, prefix)  \          } else \
                 default: \                  CORD_ec_append(info->result, otherwise);
                         if(need_encode_func(*src)) { \  #define to_char(c)  { CORD_ec_append(info->result, c); whitespace=false; }
                                 static const char *hex="0123456789ABCDEF"; \  #define to_string(s)  { CORD_ec_append_cord(info->result, s); whitespace=false; }
                                 char chunk[3]={prefix}; \  
                                 chunk[1]=hex[((unsigned char)*src)/0x10]; \  
                                 chunk[2]=hex[((unsigned char)*src)%0x10]; \  
                                 strncpy(dest, chunk, 3);  dest+=3; \  
                         } else \  
                                 *dest++=*src; \  
                         break  
   
 inline bool need_file_encode(unsigned char c){  inline bool need_file_encode(unsigned char c){
     if((c>='0') &&(c<='9') ||(c>='A') &&(c<='Z') ||(c>='a') &&(c<='z'))           // russian letters and space ENABLED
                 return false;          // encoding only these...
           return strchr(
     return !strchr("./", c);                            "*?'\"<>|"
   #ifndef WIN32
                             ":\\"
   #endif
                             , c)!=0;
 }  }
 inline bool need_uri_encode(unsigned char c){  inline bool need_uri_encode(unsigned char c){
     if((c>='0') &&(c<='9') ||(c>='A') &&(c<='Z') ||(c>='a') &&(c<='z'))       if((c>='0') &&(c<='9') ||(c>='A') &&(c<='Z') ||(c>='a') &&(c<='z')) 
Line 55  inline bool need_uri_encode(unsigned cha Line 86  inline bool need_uri_encode(unsigned cha
   
     return !strchr("_-./", c);      return !strchr("_-./", c);
 }  }
 inline bool need_header_encode(unsigned char c){  inline bool need_http_header_encode(unsigned char c){
     if(strchr(" ,:", c))      if(strchr(" , :", c))
                 return false;                  return false;
   
         return need_uri_encode(c);          return need_uri_encode(c);
Line 64  inline bool need_header_encode(unsigned Line 95  inline bool need_header_encode(unsigned
   
 // String  // String
   
 static bool typo_present(Array::Item *value, const void *info) {  /*
         Array *row=static_cast<Array *>(value);  HTTP-header    = field-name ":" [ field-value ] CRLF
         const char *src=static_cast<const char *>(info);  
          field-name     = token
         int partial;         field-value    = *( field-content | LWS )
         row->get_string(0)->cmp(src, partial);  
         return          field-content  = <the OCTETs making up the field-value
                 partial==0 || // full match                          and consisting of either *TEXT or combinations
                 partial==1; // typo left column starts 'src'                          of token, tspecials, and quoted-string>
 }  
   
 /// @todo optimize whitespaces for all but 'html'  
 char *String::store_to(char *dest) const {  word           = token | quoted-string
         // $MAIN:html-typo table  
         Table *typo_table=static_cast<Table *>(pool().tag());  token          = 1*<any CHAR except CTLs or tspecials>
   
         const Chunk *chunk=&head;   
         do {  
                 const Chunk::Row *row=chunk->rows;  tspecials      = "(" | ")" | "<" | ">" | "@"
                 for(int i=0; i<chunk->count; i++) {                        | "," | ";" | ":" | "\" | <">
                         if(row==append_here)                        | "/" | "[" | "]" | "?" | "="
                                 goto break2;                        | "{" | "}" | SP | HT
   
                         // WARNING:  SP             = <US-ASCII SP, space (32)>
                         //      string can grow only UNTAINT_TIMES_BIGGER  HT             = <US-ASCII HT, horizontal-tab (9)>
                         switch(row->item.lang) {  
                         case UL_NO:  LWS            = [CRLF] 1*( SP | HT )
                                 // clean piece  TEXT           = <any OCTET except CTLs,
                         case UL_YES:                          but including LWS>
                                 // tainted piece, but undefined untaint language  
                                 // for VString.get_double of tainted values  quoted-pair    = "\" CHAR
                                 // for ^process{body} evaluation  
                         case UL_AS_IS:    if(strchr("()<>@,;:\\\"/[]?={} \t", *ptr))
                                 // tainted, untaint language: as-is  */
                                 memcpy(dest, row->item.ptr, row->item.size);   inline bool need_quote_http_header(const char* ptr, size_t size) {
                                 dest+=row->item.size;          for(; size--; ptr++)
                                 break;                  if(strchr(";\\\"= \t" /* excluded ()<>@, :/ ? []{} */, *ptr))
                         case UL_FILE_NAME:                          return true;
                                 // tainted, untaint language: file [name]          return false;
                                 escape(  }
                                         to_char(' ', '_');  
                                         encode(need_file_encode, '-');  #ifndef DOXYGEN
                                 );  struct Append_fragment_info {
                                 break;          String::Language lang;
                         case UL_URI:          String::Languages* dest_languages;
                                 // tainted, untaint language: uri          size_t dest_body_plan_length;
                                 escape(  };
                                         to_char(' ', '+');  #endif
                                         encode(need_uri_encode, '%');  int append_fragment_optimizing(char alang, size_t asize, Append_fragment_info* info) {
                                 );          const String::Language lang=(String::Language)(unsigned char)alang;
                                 break;          // main idea here:
                         case UL_HEADER:          // tainted piece would get OPTIMIZED bit from 'lang'
                                 // tainted, untaint language: header          // clean piece would be marked OPTIMIZED manually
                                 escape(          // pieces with determined languages [not tainted|clean] would retain theirs langs
                                         encode(need_header_encode, '%');          info->dest_languages->append(info->dest_body_plan_length, 
                                 );                  lang==String::L_TAINTED?
                                 break;                          info->lang
                         case UL_TABLE:                           :lang==String::L_CLEAN?
                                 // tainted, untaint language: table                                  (String::Language)(String::L_CLEAN|String::L_OPTIMIZE_BIT) // ORing with OPTIMIZED flag
                                 escape(                                  :lang,
                                         to_char('\t', ' ');                  asize);
                                         to_char('\n', ' ');          info->dest_body_plan_length+=asize;
                                         _default;  
                                 );          return 0; // 0=continue
                                 break;  }
                         case UL_SQL:  int append_fragment_nonoptimizing(char alang, size_t asize, Append_fragment_info* info) {
                                 // tainted, untaint language: sql          const String::Language lang=(String::Language)(unsigned char)alang;
                                 // TODO: зависимость от sql сервера          // The core idea: tainted pieces got marked with context's lang
                                 memset(dest, '?', row->item.size);           info->dest_languages->append(info->dest_body_plan_length, 
                                 dest+=row->item.size;                  lang==String::L_TAINTED?
                                 break;                          info->lang
                         case UL_JS:                          :lang,
                                 escape(                  asize);
                                         to_string('"', "\\\"", 2);          info->dest_body_plan_length+=asize;
                                         to_string('\'', "\\'", 2);  
                                         to_string('\n', "\\n", 2);          return 0; // 0=continue
                                         to_string('\\', "\\\\", 2);  }
                                         to_string('\xFF', "\\\xFF", 2);  
                                         _default;  /** 
                                 );          appends to other String,
                                 break;          marking all tainted pieces of it with @a lang.
                         case UL_HTML:          or marking ALL pieces of it with a @a lang when @a forced to,
                                 escape(          and propagating OPTIMIZE language bit.
                                         to_string('&', "&amp;", 5);  */
                                         to_string('>', "&gt;", 4);  String& String::append_to(String& dest, Language lang, bool forced) const {
                                         to_string('<', "&lt;",4);          if(is_empty())
                                         to_string('"', "&quot;",6);                  return dest;
                                         to_char('\t', ' ');  
                                         //TODO: XSLT to_string('\'', "&apos;", 6)          // first: fragment infos
                                         _default;          
                                 );          if(lang==L_PASS_APPENDED) // without language-change?
                                 break;                  dest.langs.append(dest.body, body.length(), langs);
                         case UL_HTML_TYPO: {          else if(forced) //forcing passed lang?
                                 // tainted, untaint language: html-typo                  dest.langs.append(dest.body, lang, length());
                                 char *html=(char *)malloc(size()*6/*"&quot;" the longest possible*/+1);          else { 
                                 size_t html_size;                  Append_fragment_info info={lang, &dest.langs, dest.body.length()};
                                 { // local dest              langs.for_each(body, lang&L_OPTIMIZE_BIT?
                                         char *dest=html;                          append_fragment_optimizing
                                         escape(                          :append_fragment_nonoptimizing, &info);
                                                 to_string('&', "&amp;", 5);          }
                                                 to_string('>', "&gt;", 4);  
                                                 to_string('<', "&lt;",4);          // next: letters
                                                 to_string('"', "&quot;",6);          dest.body<<body;
                                                 to_char('\t', ' ');  
                                                 // convinient name for typo match "\n"          ASSERT_STRING_INVARIANT(dest);
                                                 case '\r':           return dest;
                                                         *dest++='\\';  *dest++='n'; // \r -> \n  }
                                                         if(src[1]=='\n') // \r\n -> remove \n  
                                                                 src++;  /** http://www.ietf.org/rfc/rfc2047.txt
                                                         break;  RFC
                                                 to_string('\n', "\\n", 2);  (3) As a replacement for a 'word' entity within a 'phrase', for example,
                                                 //TODO: XSLT to_string('\'', "&apos;", 6)      one that precedes an address in a From, To, or Cc header.  The ABNF
                                                 _default;      definition for 'phrase' from RFC 822 thus becomes:
                                         );  
                                         *dest=0;      phrase = 1*( encoded-word / word )
                                         html_size=dest-html;  
                                 }      In this case the set of characters that may be used in a "Q"-encoded
                                 // typo table replacements      'encoded-word' is restricted to: <upper and lower case ASCII
                                 if(typo_table) {      letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
                                         const char *src=html;      (underscore, ASCII 95.)>.  An 'encoded-word' that appears within a
                                         do {      'phrase' MUST be separated from any adjacent 'word', 'text' or
                                                 // there is a row where first column starts 'src'      'special' by 'linear-white-space'.
                                                 if(Table::Item *item=typo_table->first_that(typo_present, src)) {  ...
                                                         // get a=>b values     (2) The 8-bit hexadecimal value 20 (e.g., ISO-8859-1 SPACE) may be
                                                         const String& a=*static_cast<Array *>(item)->get_string(0);         represented as "_" (underscore, ASCII 95.).  (This character may
                                                         const String& b=*static_cast<Array *>(item)->get_string(1);         not pass through some internetwork mail gateways, but its use
                                                         // empty 'a' check         will greatly enhance readability of "Q" encoded data with mail
                                                         if(a.size()==0) {         readers that do not support this encoding.)  Note that the "_"
                                                                 pool().set_tag(0); // avoid recursion         always represents hexadecimal 20, even if the SPACE character
                                                                 THROW(0, 0,         occupies a different code position in the character set in use.
                                                                         &a,  
                                                                         "typo table first column elements must not be empty");          paf: obviously, 
                                                         }                  without "=", or one could not differ "=E0" and "russian letter a"
                                                         // overflow check:                  and without "_", or in would mean 0x20
                                                         //   b allowed to be max UNTAINT_TIMES_BIGGER then a  */
                                                         if(b.size()>UNTAINT_TIMES_BIGGER*a.size()) {  inline bool mail_header_char_valid_within_Qencoded(char c) {
                                                                 pool().set_tag(0); // avoid recursion          return c>='A' && c<='Z'
                                                                 THROW(0, 0,                  || c>='a' && c<='Z'
                                                                         &b,                  || c>='0' && c<='9'
                                                                         "is %g times longer then '%s', "                  || strchr("!*+-/", c);
                                                                         "while maximum, handled by Parser, is %d",  }
                                                                                 ((double)b.size())/a.size(),   inline bool addr_spec_soon(const char *src) {
                                                                                 a.cstr(),          for(char c; (c=*src); src++)
                                                                                 UNTAINT_TIMES_BIGGER);                  if(c=='<')
                                                         }                          return true;
                   else if(!(c==' ' || c=='\t'))
                                                         // skip 'a' in 'src'                          return false;
                                                         src+=a.size();          return false;
                                                         // write 'b' to 'dest'  }
                                                         b.store_to(dest);  /**
                                                         dest+=b.size();          RFC 
                                                 } else          Upper case should be used for hexadecimal digits "A" through "F"
                                                         *dest++=*src++;          The 8-bit hexadecimal value 20 (e.g., ISO-8859-1 SPACE) 
                                         } while(*src);          may be represented as "_" 
                                 } else {  */
                                         memcpy(dest, html, html_size);  inline bool mail_header_nonspace_char(char c) {
                                         dest+=html_size;          return c != 0x20;
                                 }  }
   
   inline void ec_append(CORD_ec& result, bool& optimize, bool& whitespace, CORD_pos pos, size_t size) {
           while(size--) {
                   CORD_ec_append(result, CORD_pos_fetch(pos));
                   CORD_next(pos);
           }
   }
   inline void pa_CORD_pos_advance(CORD_pos pos, size_t n) {
           while(true) {
                   long avail=CORD_pos_chars_left(pos);
                   if(avail<=0) {
                           CORD_next(pos);
                           if(!--n)
                                 break;                                  break;
                   } else if((size_t)avail<n) {
                           CORD_pos_advance(pos, avail);
                           n-=avail;
                   } else { // avail>=n
                           CORD_pos_advance(pos, n);
                           break;
                   }
           }
   }
   
   #ifndef DOXYGEN
   struct Cstr_to_string_body_block_info {
           // input
           String::Language lang;
           SQL_Connection* connection;
           const Request_charsets* charsets;
           const String::Body* body;
   
           // output
           CORD_ec result;
   
           // private
           CORD_pos pos;
           size_t fragment_begin;
           bool whitespace;
   };
   #endif
   int cstr_to_string_body_block(char alang, size_t fragment_length, Cstr_to_string_body_block_info* info) {
           const String::Language fragment_lang=(String::Language)(unsigned char)alang;
           bool& whitespace=info->whitespace;
           size_t fragment_end=info->fragment_begin+fragment_length;
           //fprintf(stderr, "%d, %d\n", fragment.lang, fragment.length);
   
           
           String::Language to_lang=info->lang==String::L_UNSPECIFIED?fragment_lang:info->lang;
           bool optimize=(to_lang & String::L_OPTIMIZE_BIT)!=0;
           if(!optimize)
                   whitespace=false;
                   
           switch(to_lang & ~String::L_OPTIMIZE_BIT) {
           case String::L_CLEAN:
           case String::L_TAINTED:
           case String::L_AS_IS:
                   // clean piece
   
                   // tainted piece, but undefined untaint language
                   // for VString.as_double of tainted values
                   // for ^process{body} evaluation
   
                   // tainted, untaint language: as-is
                   ec_append(info->result, optimize, whitespace, info->pos, fragment_length);
                   break;
           case String::L_FILE_SPEC:
                   // tainted, untaint language: file [name]
                   escape(
                           // Macintosh has problems with small Russian letter 'r'
                           if( c=='\xF0' && info->charsets && info->charsets->source().NAME()=="WINDOWS-1251" ) {
                                   // fixing that letter for most common charset
                                   to_char('p');
                           } else // fallback to default
                                   encode(need_file_encode, '_', c); 
                   );
                   break;
           case String::L_URI:
                   // tainted, untaint language: uri
                   {
                           const char *fragment_str=info->body->mid(info->fragment_begin, fragment_length).cstr();
                           // skip source [we use recoded version]
                           pa_CORD_pos_advance(info->pos, fragment_length);
                           String::C output(fragment_str, fragment_length);
                           if(info->charsets) 
                                   output=Charset::transcode(output, 
                                           info->charsets->source(), 
                                           info->charsets->client());
   
                           char c;
                           for(const char* src=output.str; (c=*src++); ) 
                                   encode(need_uri_encode, '%', c);
                   }
                   break;
           case String::L_HTTP_HEADER:
                   // tainted, untaint language: http-field-content-text
                   escape(
                           encode(need_uri_encode, '%', c);
                   );
                   break;
           case String::L_MAIL_HEADER:
                   // tainted, untaint language: mail-header
                   // http://www.ietf.org/rfc/rfc2047.txt
                   if(info->charsets) {
                           size_t mail_size;
                           const char *mail_ptr=
                                   info->body->mid(info->fragment_begin, mail_size=fragment_length).cstr();
                           // skip source [we use recoded version]
                           pa_CORD_pos_advance(info->pos, mail_size);
   
                           const char* charset_name=info->charsets->mail().NAME().cstr();
   
                           // Subject: Re: parser3: =?koi8-r?Q?=D3=C5=CD=C9=CE=C1=D2?=
                           bool to_quoted_printable=false;
   
                           bool email=false;
                           uchar c;
                           for(const char* src=mail_ptr; (c=(uchar)*src++); ) {
                                   //RFC   + An 'encoded-word' MUST NOT appear in any portion of an 'addr-spec'.
                                   if(to_quoted_printable && (c==',' || addr_spec_soon(src) || c == '"')) {
                                           email=c=='<';
                                           to_string("?=");
                                           to_quoted_printable=false;
                                 }                                  }
                         default:                                  if(!email && (
                                 THROW(0,0,                                          !to_quoted_printable && (c & 0x80)  // starting quote-printable-encoding on first 8bit char
                                         this,                                          || to_quoted_printable && !mail_header_char_valid_within_Qencoded(c)
                                         "unknown untaint language #%d of %d piece",                                           )) {
                                                 static_cast<int>(row->item.lang),                                          if(!to_quoted_printable) {
                                                 i);                                                  to_string("=?");
                                                   to_string(charset_name);
                                                   to_string("?Q?");
                                                   to_quoted_printable=true;
                                           }
                                           encode(mail_header_nonspace_char, '=', '_'); 
                                   } else
                                           to_char(c);
                                   if(c=='>')
                                           email=false;
                         }                          }
                         row++;                          if(to_quoted_printable) // close
                 }                                  to_string("?=");
                 chunk=row->link;                  
         } while(chunk);                  } else
 break2:                          ec_append(info->result, optimize, whitespace, info->pos, fragment_length);
         return dest;                  break;
           case String::L_TABLE: 
                   // tainted, untaint language: table
                   escape(switch(c) {
                           case '\t': to_char(' ');  break;
                           case '\n': to_char(' ');  break;
                           _default;
                   });
                   break;
           case String::L_SQL:
                   // tainted, untaint language: sql
                   if(info->connection) {
                           const char *fragment_str=info->body->mid(info->fragment_begin, fragment_length).cstr();
                           // skip source [we use recoded version]
                           pa_CORD_pos_advance(info->pos, fragment_length);
   
                           to_string(info->connection->quote(fragment_str, fragment_length));
                   } else
                           throw Exception(0,
                                   0,
                                   "untaint in SQL language failed - no connection specified");
                   break;
           case String::L_JS:
                   escape(switch(c) {
                           case '"': to_string("\\\"");  break;
                           case '\'': to_string("\\'");  break;
                           case '\n': to_string("\\n");  break;
                           case '\\': to_string("\\\\");  break;
                           case '\xFF': to_string("\\\xFF");  break;
                           _default;
                   });
                   break;
           case String::L_XML:
                   escape(switch(c) {
                           case '&': to_string("&amp;");  break;
                           case '>': to_string("&gt;");  break;
                           case '<': to_string("&lt;");  break;
                           case '"': to_string("&quot;");  break;
                           case '\'': to_string("&apos;");  break;
                           _default;
                   });
                   break;
           case String::L_HTML:
                   escape(switch(c) {
                           case '&': to_string("&amp;");  break;
                           case '>': to_string("&gt;");  break;
                           case '<': to_string("&lt;");  break;
                           case '"': to_string("&quot;");  break;
                           _default;
                   });
                   break;
           default:
                   SAPI::abort("unknown untaint language #%d", 
                           static_cast<int>(to_lang)); // should never
                   break; // never
           }
   
           info->fragment_begin=fragment_end;
   
           return 0; // 0=continue
   }
   
   
   String::Body String::cstr_to_string_body(Language lang, 
                     SQL_Connection* connection,
                     const Request_charsets *charsets) const {
   
           Cstr_to_string_body_block_info info;
           // input
           info.lang=lang;
           info.connection=connection;
           info.charsets=charsets;
           info.body=&body;
           // output
           CORD_ec_init(info.result);
           // private
           body.set_pos(info.pos, 0);
           info.fragment_begin=0;
           info.whitespace=true;
   
           if(!is_empty())
                   langs.for_each(body, cstr_to_string_body_block, &info);
   
           return String::Body(CORD_ec_to_cord(info.result));
 }  }

Removed from v.1.16  
changed lines
  Added in v.1.128


E-mail: