CVE-2021-21377 (published 2021-03-23T16:15Z)

OMERO.web is open source Django-based software for managing microscopy imaging. OMERO.web before version 5.9.0 supports redirection to a given URL after performing login or switching the group context. These URLs are not validated, allowing redirection to untrusted sites. OMERO.web 5.9.0 adds URL validation before redirecting. External URLs are not considered valid, unless specified in the omero.web.redirect_allowed_hosts setting.

Severity: MEDIUM
CVSS v2 base score: 4.9 (AV:N/AC:M/Au:S/C:P/I:P/A:N)
CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-601
cwe_name: URL Redirection to Untrusted Site ('Open Redirect')
description: A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
extended_description: An http parameter may contain a URL value and could cause the web application to redirect the request to the specified URL. By modifying the URL value to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials. Because the server name in the modified link is identical to the original site, phishing attempts have a more trustworthy appearance. Whether this issue poses a vulnerability will be subject to the intended behavior of the application. For example, a search engine might intentionally provide redirects to arbitrary URLs.
         

Fix information:
repo_url: https://github.com/ome/omero-web
commit_details: repo_url: https://github.com/ome/omero-web
author: Jean-Marie Burel
author_date: 2021-03-17 08:35:48+00:00
msg: SV commits
repository: repo_url: https://github.com/ome/omero-web
repo_name: ome/omero-web
description: Django-based OMERO.web client
repo_language: Python
owner: ome
file_changes: filename: CHANGELOG.md
change_type: ModificationType.MODIFY
diff: @@ -22,6 +22,10 @@
 - Fix partial loading of annotations ([#256](https://github.com/ome/omero-web/pull/256))
 - Fix ignored limit in webgateway/table endpoint ([#268](https://github.com/ome/omero-web/pull/268))
 
+- Security vulnerability fixes for
+  [2021-SV1](https://www.openmicroscopy.org/security/advisories/2021-SV1-user-context/),
+  [2021-SV2](https://www.openmicroscopy.org/security/advisories/2021-SV2-url-validation/)
+
 5.8.1 (September 2020)
 ----------------------
 

programming_language: Markdown
filename: decorators.py
change_type: ModificationType.MODIFY
diff: @@ -582,7 +582,8 @@ class render_response(object):
 
     def prepare_context(self, request, context, *args, **kwargs):
         """ Hook for adding additional data to the context dict """
-        pass
+        context["html"] = context.get("html", {})
+        context["html"]["meta_referrer"] = settings.HTML_META_REFERRER
 
     def __call__(ctx, f):
         """ Here we wrap the view method f and return the wrapped method """

programming_language: Python
filename: settings.py
change_type: ModificationType.MODIFY
diff: @@ -508,6 +508,12 @@ CUSTOM_SETTINGS_MAPPINGS = {
         leave_none_unset,
         "The name to use for session cookies",
     ],
+    "omero.web.session_cookie_path": [
+        "SESSION_COOKIE_PATH",
+        None,
+        leave_none_unset,
+        "The path to use for session cookies",
+    ],
     "omero.web.session_cookie_secure": [
         "SESSION_COOKIE_SECURE",
         "false",
@@ -866,6 +872,16 @@ CUSTOM_SETTINGS_MAPPINGS = {
             ' {"experimenter": -1}}\'``'
         ),
     ],
+    "omero.web.redirect_allowed_hosts": [
+        "REDIRECT_ALLOWED_HOSTS",
+        "[]",
+        json.loads,
+        (
+            "If you wish to allow redirects to an external site, "
+            "the domains must be listed here. "
+            'For example ["openmicroscopy.org"].'
+        ),
+    ],
     "omero.web.login.show_client_downloads": [
         "SHOW_CLIENT_DOWNLOADS",
         "true",
@@ -1022,6 +1038,20 @@ CUSTOM_SETTINGS_MAPPINGS = {
             "will be authorized to make cross-site HTTP requests."
         ),
     ],
+    "omero.web.html_meta_referrer": [
+        "HTML_META_REFERRER",
+        "origin-when-crossorigin",
+        str,
+        (
+            "Default content for the HTML Meta referrer tag. "
+            "See https://www.w3.org/TR/referrer-policy/#referrer-policies for "
+            "allowed values and https://caniuse.com/#feat=referrer-policy for "
+            "browser compatibility. "
+            "Warning: Internet Explorer 11 does not support the default value "
+            'of this setting, you may want to change this to "origin" after '
+            "reviewing the linked documentation."
+        ),
+    ],
     "omero.web.x_frame_options": [
         "X_FRAME_OPTIONS",
         "SAMEORIGIN",

programming_language: Python
filename: decorators.py
change_type: ModificationType.MODIFY
diff: @@ -35,7 +35,6 @@ from django.core.urlresolvers import NoReverseMatch
 
 from omeroweb.webclient.forms import GlobalSearchForm
 from omeroweb.utils import reverse_with_params
-from omeroweb.webgateway.marshal import eventContextMarshal
 
 logger = logging.getLogger(__name__)
 
@@ -116,6 +115,8 @@ class render_response(omeroweb.decorators.render_response):
         context.
         """
 
+        super(render_response, self).prepare_context(request, context, *args, **kwargs)
+
         # we expect @login_required to pass us 'conn', but just in case...
         if "conn" not in kwargs:
             return
@@ -134,7 +135,6 @@ class render_response(omeroweb.decorators.render_response):
         public_user = omeroweb.decorators.is_public_user(request)
         if public_user is not None:
             context["ome"]["is_public_user"] = public_user
-        context["ome"]["eventContext"] = eventContextMarshal(conn.getEventContext())
         context["ome"]["user"] = conn.getUser
         context["ome"]["user_id"] = request.session.get("user_id", conn.getUserId())
         context["ome"]["group_id"] = request.session.get("group_id", None)

programming_language: Python
filename: forms.py
change_type: ModificationType.MODIFY
diff: @@ -37,7 +37,6 @@ from .custom_forms import MetadataModelChoiceField
 from .custom_forms import AnnotationModelMultipleChoiceField
 from .custom_forms import ObjectModelMultipleChoiceField
 from omeroweb.webadmin.custom_forms import ExperimenterModelMultipleChoiceField
-from omeroweb.webadmin.custom_forms import GroupModelMultipleChoiceField
 from omeroweb.webadmin.custom_forms import GroupModelChoiceField
 from omeroweb.webclient.webclient_utils import formatPercentFraction
 
@@ -127,23 +126,6 @@ class ShareForm(NonASCIIForm):
         return self.cleaned_data["expiration"]
 
 
-class BasketShareForm(ShareForm):
-    def __init__(self, *args, **kwargs):
-        super(BasketShareForm, self).__init__(*args, **kwargs)
-
-        try:
-            self.fields["image"] = GroupModelMultipleChoiceField(
-                queryset=kwargs["initial"]["images"],
-                initial=kwargs["initial"]["selected"],
-                widget=forms.SelectMultiple(attrs={"size": 10}),
-            )
-        except Exception:
-            self.fields["image"] = GroupModelMultipleChoiceField(
-                queryset=kwargs["initial"]["images"],
-                widget=forms.SelectMultiple(attrs={"size": 10}),
-            )
-
-
 class ContainerForm(NonASCIIForm):
 
     name = forms.CharField(max_length=250, widget=forms.TextInput(attrs={"size": 45}))

programming_language: Python
filename: ome.tree.js
change_type: ModificationType.MODIFY
diff: @@ -1151,8 +1151,8 @@ $(function() {
 
                 var userId = WEBCLIENT.active_user.id,
                     // admin may be viewing a Group that they are not a member of
-                    memberOfGroup = WEBCLIENT.eventContext.memberOfGroups.indexOf(WEBCLIENT.active_group_id) > -1,
-                    writeOwned = WEBCLIENT.eventContext.adminPrivileges.indexOf("WriteOwned") > -1,
+                    memberOfGroup = WEBCLIENT.member_of_groups.indexOf(WEBCLIENT.active_group_id) > -1,
+                    writeOwned = WEBCLIENT.current_admin_privileges.indexOf("WriteOwned") > -1,
                     allMembers = userId === -1,
                     // canCreate if looking at your own data or 'All Members' OR User's data && writeOwned
                     canCreate = (userId === WEBCLIENT.USER.id || (allMembers && memberOfGroup) ||

programming_language: JavaScript
filename: base_container.html
change_type: ModificationType.MODIFY
diff: @@ -166,7 +166,7 @@
         WEBCLIENT.active_group_id = {{ active_group.id }};
         WEBCLIENT.USER = {'id': {{ ome.user.id }}, 'fullName': "{{ ome.user.getFullName }}"};
         WEBCLIENT.active_user = {'id': {{ ome.user_id }}, 'fullName': "{{ active_user.getFullName }}"};
-        WEBCLIENT.eventContext = {{ ome.eventContext|json_dumps|safe }};
+        WEBCLIENT.member_of_groups = {{ member_of_groups|json_dumps|safe }};
         WEBCLIENT.isAdmin = {% if ome.user.isAdmin %}true{% else %}false{% endif %};
         WEBCLIENT.CAN_CREATE = {{ ome.can_create|json_dumps|safe }};
         WEBCLIENT.current_admin_privileges = {{ current_admin_privileges|json_dumps|safe }};

programming_language: HTML
filename: toolbar_forms.html
change_type: ModificationType.MODIFY
diff: @@ -3,7 +3,7 @@
 
 {% comment %}
 <!--
-  Copyright (C) 2011 University of Dundee & Open Microscopy Environment.
+  Copyright (C) 2011-2021 University of Dundee & Open Microscopy Environment.
   All rights reserved.
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as
@@ -25,82 +25,33 @@
 if (typeof OME === "undefined") { OME={}; }
 
     OME.createShare = function() {
-
-        var productListQuery = [];
-
-        // we do inst.get_selected() here, since we then get objects
-        // instead of ids for some reason?
-        var inst = $.jstree.reference('#dataTree');
-        data = inst.get_selected(true);
-        data.forEach(function(node){
-            productListQuery.push(node.type + "=" + node.data.id);
-        });
-
-        var query = '{% url 'manage_action_containers' "add" "share" %}' + "?"+productListQuery.join("&");
         $("#create_share_form").dialog("open");
-        $("#create_share_form").attr("action", query)
-        $("#create_share_form").load(query);
         return false;
     }
 
     $(document).ready(function(){
 
-        // AJAX handling of create-discussion form
-        $("#create_share_form").ajaxForm({
-            success: function(html) {
-                if (html.indexOf("shareId") > -1) {
-                    var shareId = html.replace("shareId:", "");
-                    $("#create_share_form").dialog( "close" );
-                    $("#shareCreatedId").text(shareId);
-                    $("#share_dialog_form").dialog("open").show();
-                } else {
-                    $("#create_share_form").html(html);
-                }
-            },
-        });
-
-        $("#share_dialog_form").dialog({
-            autoOpen: false,
-            resizable: true,
-            height: 150,
-            width:300,
-            modal: true,
-            buttons: {
-                "OK": function() {
-                    $( this ).dialog( "close" );
-                }
-            }
-        });
-
         $("#create_share_form").dialog({
+            title: "Shares not supported",
             autoOpen: false,
             resizable: true,
-            height: 600,
+            height: 250,
             width:450,
             modal: true,
             buttons: {
-                "Accept": function() {
-                    // simply submit the form
-                    $("#create_share_form").submit();
-                },
-                "Cancel": function() {
+                "OK": function() {
                     $( this ).dialog( "close" );
                 }
             }
         });
-
-
     });
 </script>
 
 
-
-<!-- hidden form for creating share - shown in dialog & loaded by AJAX -->
-<form id="create_share_form" action="#" method="post" title="Create Share" class="standard_form">{% csrf_token %}
-</form>
-
-<form id="share_dialog_form" action="#" title="Create Share" style="display:none">
-    <p style="font-size: 120%; font-weight: bold">
-        Share <span id="shareCreatedId"></span> was created successfully.
+<!-- hidden dialog -->
+<div id="create_share_form" style="display:none">
+    <p>Share functionality is no longer supported.</p>
+    <p>Please see <a target="_blank" href="https://www.openmicroscopy.org/omero/features/share/">Sharing your data in OMERO</a>
+        for alternative workflows.
     </p>
-</form>
+</div>

programming_language: HTML
filename: containers.html
change_type: ModificationType.MODIFY
diff: @@ -208,9 +208,9 @@
             // If we are filtering to show another user's data,
             // we 'should' have writeOwned privilege
 
-            var writeOwned = WEBCLIENT.eventContext.adminPrivileges.indexOf("WriteOwned") > -1;
+            var writeOwned = WEBCLIENT.current_admin_privileges.indexOf("WriteOwned") > -1;
             var $f = $("#new-container-form");
-            var memberOfGroup = WEBCLIENT.eventContext.memberOfGroups.indexOf(WEBCLIENT.active_group_id) > -1;
+            var memberOfGroup = WEBCLIENT.member_of_groups.indexOf(WEBCLIENT.active_group_id) > -1;
 
             // clear fields
             $("input[name='owner']", $f).val("");
@@ -289,8 +289,8 @@
 
             // We 'canCreate' top level items, E.g. Project, Dataset, Screen, if the current userId is self or 'All Members'
             var userId = {{ ome.user_id }},
-                memberOfGroup = WEBCLIENT.eventContext.memberOfGroups.indexOf(WEBCLIENT.active_group_id) > -1,
-                writeOwned = WEBCLIENT.eventContext.adminPrivileges.indexOf("WriteOwned") > -1,
+                memberOfGroup = WEBCLIENT.member_of_groups.indexOf(WEBCLIENT.active_group_id) > -1,
+                writeOwned = WEBCLIENT.current_admin_privileges.indexOf("WriteOwned") > -1,
                 allMembers = userId === -1,
                 // canCreate if looking at your own data or 'All Members' OR User's data with writeOwned
                 canCreate = (userId === WEBCLIENT.USER.id || (allMembers && memberOfGroup) ||

programming_language: HTML
filename: public.html
change_type: ModificationType.MODIFY
diff: @@ -489,7 +489,15 @@
 
 <div class="left_panel_tree_container">
 
-    <div id="tree_details" class="left_panel_tree">
+    <div style="height: 110px; padding: 15px; box-sizing: border-box;">
+        <p>Creating new shares is no longer supported. Previously created shares are shown below.</p>
+        <p>Please see <a target="_blank" href="https://www.openmicroscopy.org/omero/features/share/">Sharing your data in
+                OMERO</a>
+            for alternative workflows.
+        </p>
+    </div>
+
+    <div id="tree_details" class="left_panel_tree" style="height: calc(100% - 110px)">
         <div class="datashareTree" id="dataTree"></div>
     </div>
 

programming_language: HTML
filename: views.py
change_type: ModificationType.MODIFY
diff: @@ -35,6 +35,7 @@ import sys
 import warnings
 from past.builtins import unicode
 from future.utils import bytes_to_native_str
+from django.utils.http import is_safe_url
 
 from time import time
 
@@ -67,7 +68,7 @@ from django.shortcuts import render
 
 from omeroweb.webclient.webclient_utils import _formatReport, _purgeCallback
 from .forms import GlobalSearchForm, ContainerForm
-from .forms import ShareForm, BasketShareForm
+from .forms import ShareForm
 from .forms import ContainerNameForm, ContainerDescriptionForm
 from .forms import CommentAnnotationForm, TagsAnnotationForm
 from .forms import MetadataFilterForm, MetadataDetectorForm
@@ -176,6 +177,17 @@ def get_bool_or_default(request, name, default):
     return toBoolean(request.GET.get(name, default))
 
 
+def validate_redirect_url(url):
+    """
+    Returns a URL is safe to redirect to.
+    If url is a different host, not in settings.REDIRECT_ALLOWED_HOSTS
+    we return webclient index URL.
+    """
+    if not is_safe_url(url, allowed_hosts=settings.REDIRECT_ALLOWED_HOSTS):
+        url = reverse("webindex")
+    return url
+
+
 ##############################################################################
 # custom index page
 
@@ -257,6 +269,8 @@ class WebclientLoginView(LoginView):
                 url = parse_url(settings.LOGIN_REDIRECT)
             except Exception:
                 url = reverse("webindex")
+        else:
+            url = validate_redirect_url(url)
         return HttpResponseRedirect(url)
 
     def handle_not_logged_in(self, request, error=None, form=None):
@@ -335,6 +349,7 @@ def change_active_group(request, conn=None, url=None, **kwargs):
     """
     switch_active_group(request)
     url = url or reverse("webindex")
+    url = validate_redirect_url(url)
     return HttpResponseRedirect(url)
 
 
@@ -534,6 +549,7 @@ def _load_template(request, menu, conn=None, url=None, **kwargs):
     context["thumbnails_batch"] = settings.THUMBNAILS_BATCH
     context["current_admin_privileges"] = conn.getCurrentAdminPrivileges()
     context["leader_of_groups"] = conn.getEventContext().leaderOfGroups
+    context["member_of_groups"] = conn.getEventContext().memberOfGroups
 
     return context
 
@@ -2871,47 +2887,6 @@ def manage_action_containers(
                 d.update({e[0]: unicode(e[1])})
             rdict = {"bad": "true", "errs": d}
             return JsonResponse(rdict)
-    elif action == "add":
-        template = "webclient/public/share_form.html"
-        experimenters = list(conn.getExperimenters())
-        experimenters.sort(key=lambda x: x.getOmeName().lower())
-        if o_type == "share":
-            img_ids = request.GET.getlist("image", request.POST.getlist("image"))
-            if request.method == "GET" and len(img_ids) == 0:
-                return HttpResponse("No images specified")
-            images_to_share = list(conn.getObjects("Image", img_ids))
-            if request.method == "POST":
-                form = BasketShareForm(
-                    initial={"experimenters": experimenters, "images": images_to_share},
-                    data=request.POST.copy(),
-                )
-                if form.is_valid():
-                    images = form.cleaned_data["image"]
-                    message = form.cleaned_data["message"]
-                    expiration = form.cleaned_data["expiration"]
-                    members = form.cleaned_data["members"]
-                    # guests = request.POST['guests']
-                    enable = form.cleaned_data["enable"]
-                    host = "%s?server=%i" % (
-                        request.build_absolute_uri(
-                            reverse("load_template", args=["public"])
-                        ),
-                        int(conn.server_id),
-                    )
-                    shareId = manager.createShare(
-                        host, images, message, members, enable, expiration
-                    )
-                    return HttpResponse("shareId:%s" % shareId)
-            else:
-                initial = {
-                    "experimenters": experimenters,
-                    "images": images_to_share,
-                    "enable": True,
-                    "selected": request.GET.getlist("image"),
-                }
-                form = BasketShareForm(initial=initial)
-        template = "webclient/public/share_form.html"
-        context = {"manager": manager, "form": form}
 
     elif action == "edit":
         # form for editing Shares only

programming_language: Python
filename: core_html.html
change_type: ModificationType.MODIFY
diff: @@ -25,6 +25,7 @@
 
 <head>
     <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
+    <meta name="referrer" content="{{ html.meta_referrer|default:"origin-when-crossorigin" }}">
 
     {% block link %}
 		<link rel="stylesheet" href="{% static "webgateway/css/reset.css"|add:url_suffix %}" type="text/css" />   

programming_language: HTML
filename: views.py
change_type: ModificationType.MODIFY
diff: @@ -2960,10 +2960,10 @@ def _table_query(request, fileid, conn=None, query=None, lazy=False, **kwargs):
             limit = (
                 int(request.GET.get("limit"))
                 if request.GET.get("limit") is not None
-                else None
+                else rows
             )
         range_start = offset
-        range_size = kwargs.get("limit", rows)
+        range_size = limit
         range_end = min(rows, range_start + range_size)
 
         if query == "*":

programming_language: Python