view kallithea/templates/summary/summary.html @ 6532:33b71a130b16

templates: properly escape inline JavaScript values TLDR: Kallithea has issues with escaping values for use in inline JS. Despite judicious poking of the code, no actual security vulnerabilities have been found, just lots of corner-case bugs. This patch fixes those, and hardens the code against actual security issues. The long version: To embed a Python value (typically a 'unicode' plain-text value) in a larger file, it must be escaped in a context specific manner. Example: >>> s = u'<script>alert("It\'s a trap!");</script>' 1) Escaped for insertion into HTML element context >>> print cgi.escape(s) &lt;script&gt;alert("It's a trap!");&lt;/script&gt; 2) Escaped for insertion into HTML element or attribute context >>> print h.escape(s) &lt;script&gt;alert(&#34;It&#39;s a trap!&#34;);&lt;/script&gt; This is the default Mako escaping, as usually used by Kallithea. 3) Encoded as JSON >>> print json.dumps(s) "<script>alert(\"It's a trap!\");</script>" 4) Escaped for insertion into a JavaScript file >>> print '(' + json.dumps(s) + ')' ("<script>alert(\"It's a trap!\");</script>") The parentheses are not actually required for strings, but may be needed to avoid syntax errors if the value is a number or dict (object). 5) Escaped for insertion into a HTML inline <script> element >>> print h.js(s) ("\x3cscript\x3ealert(\"It's a trap!\");\x3c/script\x3e") Here, we need to combine JS and HTML escaping, further complicated by the fact that "<script>" tag contents can either be parsed in XHTML mode (in which case '<', '>' and '&' must additionally be XML escaped) or HTML mode (in which case '</script>' must be escaped, but not using HTML escaping, which is not available in HTML "<script>" tags). Therefore, the XML special characters (which can only occur in string literals) are escaped using JavaScript string literal escape sequences. (This, incidentally, is why modern web security best practices ban all use of inline JavaScript...) Unsurprisingly, Kallithea does not do (5) correctly. In most cases, Kallithea might slap a pair of single quotes around the HTML escaped Python value. A typical benign example: $('#child_link').html('${_('No revisions')}'); This works in English, but if a localized version of the string contains an apostrophe, the result will be broken JavaScript. In the more severe cases, where the text is user controllable, it leaves the door open to injections. In this example, the script inserts the string as HTML, so Mako's implicit HTML escaping makes sense; but in many other cases, HTML escaping is actually an error, because the value is not used by the script in an HTML context. The good news is that the HTML escaping thwarts attempts at XSS, since it's impossible to inject syntactically valid JavaScript of any useful complexity. It does allow JavaScript errors and gibberish to appear on the page, though. In these cases, the escaping has been fixed to use either the new 'h.js' helper, which does JavaScript escaping (but not HTML escaping), OR the new 'h.jshtml' helper (which does both), in those cases where it was unclear if the value might be used (by the script) in an HTML context. Some of these can probably be "relaxed" from h.jshtml to h.js later, but for now, using h.jshtml fixes escaping and doesn't introduce new errors. In a few places, Kallithea JSON encodes values in the controller, then inserts the JSON (without any further escaping) into <script> tags. This is also wrong, and carries actual risk of XSS vulnerabilities. However, in all cases, security vulnerabilities were narrowly avoided due to other filtering in Kallithea. (E.g. many special characters are banned from appearing in usernames.) In these cases, the escaping has been fixed and moved to the template, making it immediately visible that proper escaping has been performed. Mini-FAQ (frequently anticipated questions): Q: Why do everything in one big, hard to review patch? Q: Why add escaping in specific case FOO, it doesn't seem needed? Because the goal here is to have "escape everywhere" as the default policy, rather than identifying individual bugs and fixing them one by one by adding escaping where needed. As such, this patch surely introduces a lot of needless escaping. This is no different from how Mako/Pylons HTML escape everything by default, even when not needed: it's errs on the side of needless work, to prevent erring on the side of skipping required (and security critical) work. As for reviewability, the most important thing to notice is not where escaping has been introduced, but any places where it might have been missed (or where h.jshtml is needed, but h.js is used). Q: The added escaping is kinda verbose/ugly. That is not a question, but yes, I agree. Hopefully it'll encourage us to move away from inline JavaScript altogether. That's a significantly larger job, though; with luck this patch will keep us safe and secure until such a time as we can implement the real fix. Q: Why not use Mako filter syntax ("${val|h.js}")? Because of long-standing Mako bug #140, preventing use of 'h' in filters. Q: Why not work around bug #140, or even use straight "${val|js}"? Because Mako still applies the default h.escape filter before the explicitly specified filters. Q: Where do we go from here? Longer term, we should stop doing variable expansions in script blocks, and instead pass data to JS via e.g. data attributes, or asynchronously using AJAX calls. Once we've done that, we can remove inline JavaScript altogether in favor of separate script files, and set a strict Content Security Policy explicitly blocking inline scripting, and thus also the most common kind of cross-site scripting attack.
author Søren Løvborg <sorenl@unity3d.com>
date Tue, 28 Feb 2017 17:19:00 +0100
parents 482c531e62ef
children 7bca124ef278
line wrap: on
line source

<%inherit file="/base/base.html"/>

<%block name="title">
    ${_('%s Summary') % c.repo_name}
</%block>

<%def name="breadcrumbs_links()">
    ${_('Summary')}

    ## locking icon
    %if c.db_repo.enable_locking:
     %if c.db_repo.locked[0]:
       <span class="locking_locked icon-block" data-toggle="tooltip" title="${_('Repository locked by %s') % h.person_by_id(c.db_repo.locked[0])}"></span>
     %else:
       <span class="locking_unlocked icon-ok" data-toggle="tooltip" title="${_('Repository unlocked')}"></span>
     %endif
    %endif

    ##FORK
    %if c.db_repo.fork:
    <span>
        - <i class="icon-fork"></i> ${_('Fork of')} "<a href="${h.url('summary_home',repo_name=c.db_repo.fork.repo_name)}">${c.db_repo.fork.repo_name}</a>"
    </span>
    %endif

    ##REMOTE
    %if c.db_repo.clone_uri:
    <span>
       - <i class="icon-fork"></i> ${_('Clone from')} "<a href="${h.url(str(h.hide_credentials(c.db_repo.clone_uri)))}">${h.hide_credentials(c.db_repo.clone_uri)}</a>"
    <span>
    %endif
</%def>

<%block name="header_menu">
    ${self.menu('repositories')}
</%block>

<%block name="head_extra">
  <link href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=request.authuser.api_key)}" rel="alternate" title="${_('%s ATOM feed') % c.repo_name}" type="application/atom+xml" />
  <link href="${h.url('rss_feed_home',repo_name=c.db_repo.repo_name,api_key=request.authuser.api_key)}" rel="alternate" title="${_('%s RSS feed') % c.repo_name}" type="application/rss+xml" />

  <script>
  redirect_hash_branch = function(){
    var branch = window.location.hash.replace(/^#(.*)/, '$1');
    if (branch){
      window.location = ${h.js(h.url('changelog_home',repo_name=c.repo_name,branch='__BRANCH__'))}
        .replace('__BRANCH__',branch);
    }
  }
  redirect_hash_branch();
  window.onhashchange = function() {
    redirect_hash_branch();
  };
  </script>
</%block>

<%def name="main()">
${self.repo_context_bar('summary')}
<%
summary = lambda n:{False:'summary-short'}.get(n)
%>
<div class="panel panel-primary">
    <div class="panel-heading clearfix">
        ${self.breadcrumbs()}
    </div>
    <div id="summary-panel-body" class="form panel-body">
        <div id="summary" class="form-horizontal">
            <div class="form-group form-inline clearfix">
                <label>${_('Clone URL')}:</label>
                <div id="clone-url">
                  <div id="clone_by_name" class="input-group">
                    <span class="input-group-addon">${self.repotag(c.db_repo)}</span>
                    <input class="form-control" size="80" readonly="readonly" value="${c.clone_repo_url}"/>
                    <span class="input-group-addon btn">${_('Show by ID')}</span>
                  </div>
                  <div id="clone_by_id" class="input-group" style="display:none">
                    <span class="input-group-addon">${self.repotag(c.db_repo)}</span>
                    <input class="form-control" size="80" readonly="readonly" value="${c.clone_repo_url_id}"/>
                    <span class="input-group-addon btn">${_('Show by Name')}</span>
                  </div>
                </div>
            </div>

            <div class="form-group clearfix">
              <label>${_('Description')}:</label>
              <div class="${summary(c.show_stats)} desc">${h.urlify_text(c.db_repo.description, stylize=c.visual.stylify_metatags)}</div>
            </div>

            <div class="form-group clearfix">
              <label>${_('Trending files')}:</label>
              <div class="${summary(c.show_stats)}">
                %if c.show_stats:
                <div id="lang_stats"></div>
                %else:
                   ${_('Statistics are disabled for this repository')}
                   %if h.HasPermissionAny('hg.admin')('enable stats on from summary'):
                        ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name, anchor='repo_enable_statistics'),class_="btn btn-default btn-xs")}
                   %endif
                %endif
              </div>
            </div>

            <div class="form-group clearfix">
              <label>${_('Download')}:</label>
              <div class="${summary(c.show_stats)}">
                %if len(c.db_repo_scm_instance.revisions) == 0:
                  ${_('There are no downloads yet')}
                %elif not c.enable_downloads:
                  ${_('Downloads are disabled for this repository')}
                    %if h.HasPermissionAny('hg.admin')('enable downloads on from summary'):
                        ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name, anchor='repo_enable_downloads'),class_="btn btn-default btn-xs")}
                    %endif
                %else:
                    <span id="${'zip_link'}">
                        <a class="btn btn-default btn-sm" href="${h.url('files_archive_home',repo_name=c.db_repo.repo_name,fname='tip.zip')}"><i class="icon-file-zip"></i> ${_('Download as zip')}</a>
                    </span>
                    ${h.hidden('download_options')}
                    <span style="vertical-align: bottom">
                      <label data-toggle="tooltip" title="${_('Check this to download archive with subrepos')}">
                          <input id="archive_subrepos" type="checkbox" name="subrepos" />
                          ${_('With subrepos')}
                      </label>
                    </span>
                %endif
              </div>
            </div>
        </div>
        <ul id="summary-menu-stats" class="list-group">
            <li class="list-group-item">
               <a title="${_('Owner')} ${c.db_repo.owner.email}">
                <i class="icon-user"></i> ${c.db_repo.owner.username}
                ${h.gravatar_div(c.db_repo.owner.email, size=18, div_class="pull-right", div_style="margin: 0", div_title=c.db_repo.owner.full_name)}
              </a>
            </li>
            <li class="list-group-item">
               <a title="${_('Followers')}" href="${h.url('repo_followers_home',repo_name=c.repo_name)}">
                <i class="icon-heart"></i> ${_('Followers')}
                <span class="badge pull-right" id="current_followers_count">${c.repository_followers}</span>
              </a>
            </li>
            <li class="list-group-item">
              <a title="${_('Forks')}" href="${h.url('repo_forks_home',repo_name=c.repo_name)}">
                <i class="icon-fork"></i> ${_('Forks')}
                <span class="badge pull-right">${c.repository_forks}</span>
              </a>
            </li>

            %if request.authuser.username != 'default':
            <li class="list-group-item clearfix">
              <a href="#" onclick="javascript:showRepoSize('repo_size_2','${c.db_repo.repo_name}')">
                <i class="icon-ruler"></i> ${_('Repository Size')}
                <span class="badge pull-right" id="repo_size_2"></span>
              </a>
            </li>
            %endif

            <li class="list-group-item">
            %if request.authuser.username != 'default':
              <a href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=request.authuser.api_key)}"><i class="icon-rss-squared"></i> ${_('Feed')}</a>
            %else:
              <a href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name)}"><i class="icon-rss-squared"></i> ${_('Feed')}</a>
            %endif
            </li>

            %if c.show_stats:
            <li class="list-group-item">
              <a title="${_('Statistics')}" href="${h.url('repo_stats_home',repo_name=c.repo_name)}">
                <i class="icon-graph"></i> ${_('Statistics')}
              </a>
            </li>
            %endif
        </ul>
    </div>
</div>


<div class="panel panel-primary">
    <div class="panel-heading">
        <div class="breadcrumbs panel-title">
        %if c.repo_changesets:
            ${h.link_to(_('Latest Changes'),h.url('changelog_home',repo_name=c.repo_name))}
        %else:
            ${_('Quick Start')}
         %endif
        </div>
    </div>
    <div class="panel-body">
        <div id="shortlog_data">
            <%include file='../changelog/changelog_summary_data.html'/>
        </div>
    </div>
</div>

%if c.readme_data:
<div id="readme" class="anchor">
</div>
<div class="panel panel-primary">
    <div class="panel-heading" title="${_('Readme file from revision %s:%s') % (c.db_repo.landing_rev[0], c.db_repo.landing_rev[1])}">
        <div class="breadcrumbs panel-title">
            <a href="${h.url('files_home',repo_name=c.repo_name,revision='tip',f_path=c.readme_file)}">${c.readme_file}</a>
        </div>
    </div>
    <div class="readme panel-body">
        ${c.readme_data|n}
    </div>
</div>
%endif

<script type="text/javascript">
$(document).ready(function(){
    $('#clone-url input').click(function(e){
        if($(this).hasClass('selected')){
            $(this).removeClass('selected');
            return ;
        }else{
            $(this).addClass('selected');
            $(this).select();
        }
    });

    var $clone_by_name = $('#clone_by_name');
    var $clone_by_id = $('#clone_by_id');
    $clone_by_name.find('.btn').click(function(e){
        $clone_by_name.hide();
        $clone_by_id.show();
    });
    $clone_by_id.find('.btn').click(function(e){
        $clone_by_id.hide();
        $clone_by_name.show();
    });

    var cache = {}
    $("#download_options").select2({
        placeholder: _TM['Select changeset'],
        dropdownAutoWidth: true,
        query: function(query){
          var key = 'cache';
          var cached = cache[key] ;
          if(cached) {
            var data = {results: []};
            //filter results
            $.each(cached.results, function(){
                var section = this.text;
                var children = [];
                $.each(this.children, function(){
                    if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                        children.push({'id': this.id, 'text': this.text});
                    }
                });
                data.results.push({'text': section, 'children': children});
            });
            query.callback(data);
          }else{
              $.ajax({
                url: pyroutes.url('repo_refs_data', {'repo_name': ${h.js(c.repo_name)}}),
                data: {},
                dataType: 'json',
                type: 'GET',
                success: function(data) {
                  cache[key] = data;
                  query.callback({results: data.results});
                }
              });
          }
        }
    });
    // on change of download options
    $('#download_options').change(function(e){
       var new_cs = e.added

       for(k in tmpl_links){
           var s = $('#'+k+'_link');
           if(s){
             var title_tmpl = ${h.jshtml(_('Download %s as %s') % ('__CS_NAME__','__CS_EXT__'))};
             title_tmpl= title_tmpl.replace('__CS_NAME__',new_cs.text);
             title_tmpl = title_tmpl.replace('__CS_EXT__',k);
             title_tmpl = '<i class="icon-file-zip"></i> '+ title_tmpl;
             var url = tmpl_links[k].replace('__CS__',new_cs.id);
             var subrepos = $('#archive_subrepos').is(':checked');
             url = url.replace('__SUB__',subrepos);
             url = url.replace('__NAME__',title_tmpl);

             s.html(url);
           }
       }
    });

    var tmpl_links = {};
    %for cnt,archive in enumerate(c.db_repo_scm_instance._get_archives()):
      tmpl_links[${h.jshtml(archive['type'])}] = ${h.js(h.link_to('__NAME__', h.url('files_archive_home',repo_name=c.db_repo.repo_name, fname='__CS__'+archive['extension'],subrepos='__SUB__'),class_='btn btn-default btn-sm'))};
    %endfor
});
</script>

%if c.show_stats:
<script type="text/javascript">
$(document).ready(function(){
    var data = ${h.js(c.trending_languages)};
    var total = 0;
    var no_data = true;
    var tbl = document.createElement('table');
    tbl.setAttribute('class','table');
    var cnt = 0;
    for (var i=0;i<data.length;i++){
        total+= data[i][1].count;
    }
    for (var i=0;i<data.length;i++){
        cnt += 1;
        no_data = false;

        var hide = cnt>2;
        var tr = document.createElement('tr');
        if (hide){
            tr.setAttribute('style','display:none');
            tr.setAttribute('class','stats_hidden');
        }
        var k = data[i][0];
        var obj = data[i][1];
        var percentage = Math.round((obj.count/total*100),2);

        var td1 = document.createElement('td');
        td1.width = 250;
        var trending_language_label = document.createElement('div');
        trending_language_label.innerHTML = obj.desc+" ("+k+")";
        td1.appendChild(trending_language_label);

        var td2 = document.createElement('td');
        td2.setAttribute('style','padding-right:14px !important');
        var trending_language = document.createElement('div');
        var nr_files = obj.count + ' ' + ${h.jshtml(_('files'))};

        trending_language.title = k+" "+nr_files;

        if (percentage>22){
            trending_language.innerHTML = "<b class='progress-bar' role='progressbar'"
                + "aria-valuemin='0' aria-valuemax='100' aria-valuenow='" + percentage
                + "' style='width: " + percentage + "%;'>" + percentage + "%, " + nr_files + "</b>";
        }
        else{
            trending_language.innerHTML = "<b class='progress-bar' role='progressbar'"
                + "aria-valuemin='0' aria-valuemax='100' aria-valuenow='" + percentage
                + "' style='width: " + percentage + "%;'>" + percentage + "%</b>";
        }

        td2.appendChild(trending_language);

        tr.appendChild(td1);
        tr.appendChild(td2);
        tbl.appendChild(tr);
        if(cnt == 3){
            var show_more = document.createElement('tr');
            var td = document.createElement('td');
            lnk = document.createElement('a');

            lnk.href='#';
            lnk.innerHTML = ${h.jshtml(_('Show more'))};
            lnk.id='code_stats_show_more';
            td.appendChild(lnk);

            show_more.appendChild(td);
            show_more.appendChild(document.createElement('td'));
            tbl.appendChild(show_more);
        }

    }
    if (data.length == 0) {
        tbl.innerHTML = '<tr><td>' + ${h.jshtml(_('No data ready yet'))} + '</td></tr>';
    }

    $('#lang_stats').append(tbl);
    $('#code_stats_show_more').click(function(){
        $('.stats_hidden').show();
        $('#code_stats_show_more').hide();
    });
});
</script>
%endif

## Shortlog paging
<script type="text/javascript">
  $(document).ready(function(){
    var $shortlog_data = $('#shortlog_data');
    $shortlog_data.on('click','.pager_link',function(e){
      asynchtml(e.target.href, $shortlog_data, function(){tooltip_activate();});
      e.preventDefault();
    });
  });
</script>

</%def>