Annotation of parser3/src/main/untaint.C, revision 1.117

1.7       paf         1: /** @file
1.8       paf         2:        Parser: String class part: untaint mechanizm.
                      3: 
1.117   ! paf         4:        Copyright(c) 2001-2003 ArtLebedev Group (http://www.artlebedev.com)
1.89      paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.103     paf         6: */
1.8       paf         7: 
1.117   ! paf         8: static const char* IDENT_UNTAINT_C="$Date: 2003/04/18 10:36:03 $";
        !             9: 
1.1       paf        10: 
                     11: #include "pa_string.h"
                     12: #include "pa_hash.h"
                     13: #include "pa_exception.h"
1.13      paf        14: #include "pa_table.h"
1.32      paf        15: #include "pa_globals.h"
1.58      parser     16: #include "pa_dictionary.h"
1.66      parser     17: #include "pa_common.h"
1.85      paf        18: #include "pa_charset.h"
1.117   ! paf        19: #include "pa_request_charsets.h"
        !            20: #include "pa_sapi.h"
1.1       paf        21: 
1.117   ! paf        22: extern "C" { // author forgot to do that
        !            23: #include "ec.h"
        !            24: }
1.91      paf        25: 
1.117   ! paf        26: #define PA_SQL
        !            27: 
        !            28: #ifdef PA_SQL
        !            29: #include "pa_sql_connection.h"
1.91      paf        30: #endif
                     31: 
1.117   ! paf        32: // defines
        !            33: 
        !            34: 
        !            35: #undef CORD_ec_append
        !            36: // redefining to intercept flushes and implement whitespace optimization
        !            37: // of all consequent white space chars leaving only first one
        !            38: #define CORD_ec_append(x, c) \
        !            39:     {  \
        !            40:        bool skip=false; \
        !            41:        if(optimize) switch(c) { \
        !            42:        case ' ': case '\r': case '\n': case '\t': \
        !            43:                if(whitespace) \
        !            44:                        skip=true; /*skipping subsequent*/ \
        !            45:                else \
        !            46:                        whitespace=true; \
        !            47:                break; \
        !            48:        default: \
        !            49:                whitespace=false; \
        !            50:                break; \
        !            51:        } \
        !            52:        if(!skip) { \
        !            53:                if ((x)[0].ec_bufptr == (x)[0].ec_buf + CORD_BUFSZ) { \
        !            54:                        CORD_ec_flush_buf(x); \
        !            55:                } \
        !            56:                *((x)[0].ec_bufptr)++ = (c); \
        !            57:        } \
        !            58:     }
        !            59: 
        !            60: 
1.18      paf        61: #define escape(action) \
1.117   ! paf        62:        for(; fragment_length--; CORD_next(pos)) { \
        !            63:                char c=CORD_pos_fetch(pos); \
        !            64:                action \
1.1       paf        65:        }
1.117   ! paf        66: #define _default  default: CORD_ec_append(result, c); break
        !            67: #define encode(need_encode_func, prefix, otherwise)  \
        !            68:        if(need_encode_func(c)) { \
        !            69:                static const char* hex="0123456789ABCDEF"; \
        !            70:                CORD_ec_append(result, prefix); \
        !            71:                CORD_ec_append(result, hex[((unsigned char)c)/0x10]); \
        !            72:                CORD_ec_append(result, hex[((unsigned char)c)%0x10]); \
        !            73:        } else \
        !            74:                CORD_ec_append(result, otherwise);
        !            75: #define to_char(c)  CORD_ec_append(result, c)
        !            76: #define to_string(s)  CORD_ec_append_cord(result, s)
1.4       paf        77: 
1.9       paf        78: inline bool need_file_encode(unsigned char c){
1.108     paf        79:        // russian letters and space ENABLED
                     80:        // encoding only these...
                     81:        return strchr(
                     82:                          "*?'\"<>|"
                     83: #ifndef WIN32
1.116     paf        84:                          ":\\"
1.31      paf        85: #endif
1.108     paf        86:                          , c)!=0;
1.9       paf        87: }
1.5       paf        88: inline bool need_uri_encode(unsigned char c){
1.13      paf        89:     if((c>='0') &&(c<='9') ||(c>='A') &&(c<='Z') ||(c>='a') &&(c<='z')) 
1.4       paf        90:                return false;
                     91: 
1.5       paf        92:     return !strchr("_-./", c);
                     93: }
1.36      paf        94: inline bool need_http_header_encode(unsigned char c){
1.18      paf        95:     if(strchr(" , :", c))
1.5       paf        96:                return false;
                     97: 
                     98:        return need_uri_encode(c);
1.4       paf        99: }
1.1       paf       100: 
1.56      parser    101: //
                    102: 
1.117   ! paf       103: static const char*  String_Untaint_lang_name[]={
1.56      parser    104:        "U", ///< zero value handy for hash lookup @see untaint_lang_name2enum
                    105:        "C", ///< clean
                    106:        "T",  ///< tainted, untaint language as assigned later 
                    107:        // untaint languages. assigned by ^untaint[lang]{...}
                    108:        "P",
                    109:                /**<
                    110:                        leave language built into string being appended.
                    111:                        just a flag, that value not stored
                    112:                */
                    113:        "A",     ///< leave all characters intact
1.68      parser    114:        "F", ///< file specification
                    115:        "H",    ///< ext in HTTP response header
1.56      parser    116:        "M",    ///< text in mail header
                    117:        "URI",       ///< text in uri
                    118:        "T",     ///< ^table:set body
                    119:        "SQL",       ///< ^table:sql body
                    120:        "JS",        ///< JavaScript code
1.68      parser    121:        "XML",          ///< ^dom:set xml
1.82      paf       122:        "HTML"      ///< HTML code (for editing)
1.56      parser    123: };
                    124: 
                    125: 
1.1       paf       126: // String
                    127: 
1.41      paf       128: /*
                    129: 
                    130: HTTP-header    = field-name ":" [ field-value ] CRLF
                    131: 
                    132:        field-name     = token
                    133:        field-value    = *( field-content | LWS )
                    134: 
                    135:        field-content  = <the OCTETs making up the field-value
                    136:                         and consisting of either *TEXT or combinations
                    137:                         of token, tspecials, and quoted-string>
                    138: 
                    139: 
                    140: 
                    141: word           = token | quoted-string
                    142: 
                    143: token          = 1*<any CHAR except CTLs or tspecials>
                    144: 
                    145: 
                    146: 
                    147: tspecials      = "(" | ")" | "<" | ">" | "@"
                    148:                       | "," | ";" | ":" | "\" | <">
                    149:                       | "/" | "[" | "]" | "?" | "="
                    150:                       | "{" | "}" | SP | HT
                    151: 
                    152: SP             = <US-ASCII SP, space (32)>
                    153: HT             = <US-ASCII HT, horizontal-tab (9)>
                    154: 
                    155: LWS            = [CRLF] 1*( SP | HT )
                    156: TEXT           = <any OCTET except CTLs,
                    157:                         but including LWS>
                    158: 
                    159: quoted-pair    = "\" CHAR
                    160: 
                    161:   if(strchr("()<>@,;:\\\"/[]?={} \t", *ptr))
                    162: */
1.117   ! paf       163: inline bool need_quote_http_header(const char* ptr, size_t size) {
1.41      paf       164:        for(; size--; ptr++)
1.42      paf       165:                if(strchr(";\\\"= \t" /* excluded ()<>@, :/ ? []{} */, *ptr))
1.41      paf       166:                        return true;
                    167:        return false;
                    168: }
                    169: 
1.117   ! paf       170: 
1.91      paf       171: /** 
1.117   ! paf       172:        appends to other String,
1.91      paf       173:        marking all tainted pieces of it with @a lang.
1.92      paf       174:        or marking ALL pieces of it with a @a lang when @a forced to,
                    175:        and propagating OPTIMIZE language bit.
1.117   ! paf       176: */
        !           177: String& String::append_to(String& dest, Language lang, bool forced) const {
        !           178:        if(is_empty())
        !           179:                return dest;
1.91      paf       180: 
1.117   ! paf       181:        // first: letters
        !           182:        dest.body<<body;
1.94      paf       183: 
1.117   ! paf       184:        // next: fragment infos
        !           185:        
        !           186:        if(lang==L_PASS_APPENDED) // without language-change?
        !           187:                dest.fragments.append(fragments);
        !           188:        else if(forced) //forcing passed lang?
        !           189:                dest.fragments+=Fragment(lang, length());
        !           190:        else if(lang&L_OPTIMIZE_BIT) {
        !           191:                for(Array_iterator<ArrayFragment::element_type> i(fragments); i.has_next(); ) {
        !           192:                        const Fragment fragment=i.next();
        !           193:                        // main idea here:
        !           194:                        // tainted piece would get OPTIMIZED bit from 'lang'
        !           195:                        // clean piece would be marked OPTIMIZED manually
        !           196:                        // pieces with determined languages [not tainted|clean] would retain theirs langs
        !           197:                        dest.fragments+=Fragment(static_cast<Language>(
        !           198:                                fragment.lang==L_TAINTED?lang:(
        !           199:                                        fragment.lang==L_CLEAN?L_CLEAN|L_OPTIMIZE_BIT: // ORing with OPTIMIZED flag
        !           200:                                                fragment.lang)),
        !           201:                                fragment.length);
        !           202:                }
        !           203:        } else { // The core idea: tainted pieces got marked with context's lang
        !           204:                for(Array_iterator<ArrayFragment::element_type> i(fragments); i.has_next(); ) {
        !           205:                        const Fragment fragment=i.next();
        !           206:                        dest.fragments+=Fragment(
        !           207:                                fragment.lang==L_TAINTED?lang:fragment.lang,
        !           208:                                fragment.length);
1.93      paf       209:                }
1.91      paf       210:        }
                    211: 
1.117   ! paf       212:        ASSERT_STRING_INVARIANT(dest);
1.75      paf       213:        return dest;
1.51      parser    214: }
                    215: 
1.109     paf       216: /** http://www.ietf.org/rfc/rfc2047.txt
                    217: RFC
                    218: (3) As a replacement for a 'word' entity within a 'phrase', for example,
                    219:     one that precedes an address in a From, To, or Cc header.  The ABNF
                    220:     definition for 'phrase' from RFC 822 thus becomes:
                    221: 
                    222:     phrase = 1*( encoded-word / word )
                    223: 
                    224:     In this case the set of characters that may be used in a "Q"-encoded
                    225:     'encoded-word' is restricted to: <upper and lower case ASCII
                    226:     letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
                    227:     (underscore, ASCII 95.)>.  An 'encoded-word' that appears within a
                    228:     'phrase' MUST be separated from any adjacent 'word', 'text' or
                    229:     'special' by 'linear-white-space'.
                    230: ...
                    231:    (2) The 8-bit hexadecimal value 20 (e.g., ISO-8859-1 SPACE) may be
                    232:        represented as "_" (underscore, ASCII 95.).  (This character may
                    233:        not pass through some internetwork mail gateways, but its use
                    234:        will greatly enhance readability of "Q" encoded data with mail
                    235:        readers that do not support this encoding.)  Note that the "_"
                    236:        always represents hexadecimal 20, even if the SPACE character
                    237:        occupies a different code position in the character set in use.
                    238: 
                    239:        paf: obviously, 
                    240:                without "=", or one could not differ "=E0" and "russian letter a"
                    241:                and without "_", or in would mean 0x20
                    242: */
1.117   ! paf       243: inline bool mail_header_char_valid_within_Qencoded(char c) {
1.109     paf       244:        return c>='A' && c<='Z'
                    245:                || c>='a' && c<='Z'
                    246:                || c>='0' && c<='9'
                    247:                || strchr("!*+-/", c);
                    248: }
1.117   ! paf       249: /**
        !           250:        RFC 
        !           251:        Upper case should be used for hexadecimal digits "A" through "F"
        !           252:        The 8-bit hexadecimal value 20 (e.g., ISO-8859-1 SPACE) 
        !           253:        may be represented as "_" 
        !           254: */
        !           255: inline bool mail_header_nonspace_char(char c) {
        !           256:        return c != 0x20;
        !           257: }
        !           258: inline void ec_append(CORD_ec& result, bool& optimize, bool& whitespace, CORD_pos pos, size_t size) {
        !           259:        while(size--) {
        !           260:                CORD_ec_append(result, CORD_pos_fetch(pos));
        !           261:                CORD_next(pos);
        !           262:        }
        !           263: }
        !           264: inline void pa_CORD_pos_advance(CORD_pos pos, size_t n) {
        !           265:        while(true) {
        !           266:                size_t avail=CORD_pos_chars_left(pos);
        !           267:                if(avail==0) {
        !           268:                        CORD_next(pos);
        !           269:                        if(!--n)
        !           270:                                break;
        !           271:                } else if(avail<n) {
        !           272:                        CORD_pos_advance(pos, avail);
        !           273:                        n-=avail;
        !           274:                } else { // avail>=n
        !           275:                        CORD_pos_advance(pos, n);
        !           276:                        break;
        !           277:                }
        !           278:        }
        !           279: }
        !           280: StringBody String::cstr_to_string_body(Language lang, 
        !           281:                  SQL_Connection* connection,
        !           282:                  const Request_charsets *charsets) const {
        !           283:        CORD_ec result; CORD_ec_init(result);
        !           284:        CORD_pos pos; body.set_pos(pos, 0);
        !           285: 
1.44      paf       286:        bool whitespace=true;
1.117   ! paf       287: 
        !           288:        size_t fragment_begin=0;
        !           289:        size_t fragment_end;
        !           290:        for(Array_iterator<Fragment> i(fragments); i.has_next(); fragment_begin=fragment_end) {
        !           291:                const Fragment fragment=i.next();
        !           292:                size_t fragment_length=fragment.length;
        !           293:                fragment_end=fragment_begin+fragment_length;
        !           294:                //fprintf(stderr, "%d, %d\n", fragment.lang, fragment.length);
        !           295: 
        !           296:                Language to_lang=lang==L_UNSPECIFIED?fragment.lang:lang;
        !           297:                bool optimize=(to_lang & L_OPTIMIZE_BIT)!=0;
        !           298:                if(!optimize)
        !           299:                        whitespace=false;
        !           300:                        
        !           301:                switch(to_lang & ~L_OPTIMIZE_BIT) {
        !           302:                case L_CLEAN:
        !           303:                case L_TAINTED:
        !           304:                case L_AS_IS:
1.77      paf       305:                        // clean piece
                    306: 
                    307:                        // tainted piece, but undefined untaint language
                    308:                        // for VString.as_double of tainted values
                    309:                        // for ^process{body} evaluation
                    310: 
                    311:                        // tainted, untaint language: as-is
1.117   ! paf       312:                        ec_append(result, optimize, whitespace, pos, fragment_length);
1.77      paf       313:                        break;
1.117   ! paf       314:                case L_FILE_SPEC:
1.77      paf       315:                        // tainted, untaint language: file [name]
1.83      paf       316:                        escape(
1.113     paf       317:                                // Macintosh has problems with small Russian letter 'r'
1.117   ! paf       318:                                if( c=='\xF0' && charsets && charsets->source().NAME()=="WINDOWS-1251" ) {
1.113     paf       319:                                        // fixing that letter for most common charset
1.117   ! paf       320:                                        to_char('p');
1.114     paf       321:                                } else // fallback to default
1.117   ! paf       322:                                        encode(need_file_encode, '_', c); 
1.83      paf       323:                        );
1.77      paf       324:                        break;
1.117   ! paf       325:                case L_URI:
1.77      paf       326:                        // tainted, untaint language: uri
1.85      paf       327:                        {
1.117   ! paf       328:                                const char *fragment_str=body.mid(fragment_begin, fragment_length).cstr();
        !           329:                                // skip source [we use recoded version]
        !           330:                                pa_CORD_pos_advance(pos, fragment_length);
        !           331:                                String::C output(fragment_str, fragment_length);
        !           332:                                if(charsets) 
        !           333:                                        output=Charset::transcode(output, 
        !           334:                                                charsets->source(), 
        !           335:                                                charsets->client());
        !           336: 
        !           337:                                char c;
        !           338:                                for(const char* src=output.str; c=*src++; ) 
        !           339:                                        encode(need_uri_encode, '%', c);
1.85      paf       340:                        }
1.77      paf       341:                        break;
1.117   ! paf       342:                case L_HTTP_HEADER:
1.77      paf       343:                        // tainted, untaint language: http-field-content-text
1.108     paf       344:                        escape(
1.117   ! paf       345:                                encode(need_uri_encode, '%', c);
1.108     paf       346:                        );
1.77      paf       347:                        break;
1.117   ! paf       348:                case L_MAIL_HEADER:
1.77      paf       349:                        // tainted, untaint language: mail-header
1.105     paf       350:                        // http://www.ietf.org/rfc/rfc2047.txt
1.117   ! paf       351:                        if(charsets) {
1.87      paf       352:                                size_t mail_size;
1.117   ! paf       353:                                const char *mail_ptr=
        !           354:                                        body.mid(fragment_begin, mail_size=fragment_length).cstr();
        !           355:                                // skip source [we use recoded version]
        !           356:                                pa_CORD_pos_advance(pos, mail_size);
        !           357: 
        !           358:                                const char* charset_name=charsets->mail().NAME().cstr();
1.87      paf       359: 
1.77      paf       360:                                // Subject: Re: parser3: =?koi8-r?Q?=D3=C5=CD=C9=CE=C1=D2?=
                    361:                                bool to_quoted_printable=false;
1.105     paf       362: 
1.111     paf       363:                                bool email=false;
1.117   ! paf       364:                                uchar c;
        !           365:                                for(const char* src=mail_ptr; c=(uchar)*src++; ) {
1.111     paf       366:                                        //RFC   + An 'encoded-word' MUST NOT appear in any portion of an 'addr-spec'.
1.117   ! paf       367:                                        if(to_quoted_printable && (c==',' || c=='<')) {
        !           368:                                                email=c=='<';
        !           369:                                                to_string("?=");
1.107     paf       370:                                                to_quoted_printable=false;
1.105     paf       371:                                        }
1.111     paf       372:                                        if(!email && (
1.117   ! paf       373:                                                !to_quoted_printable && (c & 0x80)  // starting quote-printable-encoding on first 8bit char
        !           374:                                                || to_quoted_printable && !mail_header_char_valid_within_Qencoded(c)
1.105     paf       375:                                                )) {
1.77      paf       376:                                                if(!to_quoted_printable) {
1.117   ! paf       377:                                                        to_string("=?");
        !           378:                                                        to_string(charset_name);
        !           379:                                                        to_string("?Q?");
1.77      paf       380:                                                        to_quoted_printable=true;
                    381:                                                }
1.117   ! paf       382:                                                encode(mail_header_nonspace_char, '=', '_'); 
1.105     paf       383:                                        } else
1.117   ! paf       384:                                                to_char(c);
        !           385:                                        if(c=='>')
1.111     paf       386:                                                email=false;
1.44      paf       387:                                }
1.112     paf       388:                                if(to_quoted_printable) // close
1.117   ! paf       389:                                        to_string("?=");
1.87      paf       390:                        
1.117   ! paf       391:                        } else
        !           392:                                ec_append(result, optimize, whitespace, pos, fragment_length);
1.77      paf       393:                        break;
1.117   ! paf       394:                case L_TABLE: 
1.77      paf       395:                        // tainted, untaint language: table
1.117   ! paf       396:                        escape(switch(c) {
1.77      paf       397:                                case '\t': to_char(' ');  break;
                    398:                                case '\n': to_char(' ');  break;
                    399:                                _default;
                    400:                        });
                    401:                        break;
1.117   ! paf       402: #ifdef PA_SQL
        !           403:                case L_SQL:
1.77      paf       404:                        // tainted, untaint language: sql
1.117   ! paf       405:                        if(connection) {
        !           406:                                const char *fragment_str=body.mid(fragment_begin, fragment_length).cstr();
        !           407:                                // skip source [we use recoded version]
        !           408:                                pa_CORD_pos_advance(pos, fragment_length);
        !           409: 
        !           410:                                to_string(connection->quote(fragment_str, fragment_length));
        !           411:                        } else
1.99      paf       412:                                throw Exception(0,
1.117   ! paf       413:                                        0,
1.77      paf       414:                                        "untaint in SQL language failed - no connection specified");
                    415:                        break;
1.117   ! paf       416: #endif
        !           417:                case L_JS:
        !           418:                        escape(switch(c) {
        !           419:                                case '"': to_string("\\\"");  break;
        !           420:                                case '\'': to_string("\\'");  break;
        !           421:                                case '\n': to_string("\\n");  break;
        !           422:                                case '\\': to_string("\\\\");  break;
        !           423:                                case '\xFF': to_string("\\\xFF");  break;
1.77      paf       424:                                _default;
                    425:                        });
                    426:                        break;
1.117   ! paf       427:                case L_XML:
        !           428:                        escape(switch(c) {
        !           429:                                case '&': to_string("&amp;");  break;
        !           430:                                case '>': to_string("&gt;");  break;
        !           431:                                case '<': to_string("&lt;");  break;
        !           432:                                case '"': to_string("&quot;");  break;
        !           433:                                case '\'': to_string("&apos;");  break;
1.77      paf       434:                                _default;
                    435:                        });
                    436:                        break;
1.117   ! paf       437:                case L_HTML:
        !           438:                        escape(switch(c) {
        !           439:                                case '&': to_string("&amp;");  break;
        !           440:                                case '>': to_string("&gt;");  break;
        !           441:                                case '<': to_string("&lt;");  break;
        !           442:                                case '"': to_string("&quot;");  break;
1.77      paf       443:                                _default;
                    444:                        });
                    445:                        break;
                    446:                default:
1.117   ! paf       447:                        SAPI::die("unknown untaint language #%d", 
        !           448:                                static_cast<int>(to_lang)); // should never
1.77      paf       449:                        break; // never
1.76      paf       450:                }
1.117   ! paf       451:        }
1.55      parser    452: 
1.117   ! paf       453:        return StringBody(CORD_ec_to_cord(result));
1.1       paf       454: }

E-mail: