Changeset 19711 in josm


Ignore:
Timestamp:
2026-11-27T21:55:54+01:00 (70 minutes ago)
Author:
stoecker
Message:

reduce privacy leaks when presenting log and debug information to users, patch by wangi - fix #25141

Location:
trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/actions/ShowStatusReportAction.java

    r19605 r19711  
    5252import org.openstreetmap.josm.tools.PlatformManager;
    5353import org.openstreetmap.josm.tools.Shortcut;
     54import org.openstreetmap.josm.tools.TextUtils;
    5455import org.openstreetmap.josm.tools.Utils;
    5556import org.openstreetmap.josm.tools.bugreport.BugReportSender;
    … …  
    309310    }
    310311
    311     private static String valueCleanup(Object value) {
     312    /**
     313     * Shortens and removes private information from a preference value used for status report, among them the API keys
     314     * and tokens of URLs, e.g. of custom imagery.
     315     * @param value preference value to cleanup
     316     * @return shortened/anonymized value
     317     */
     318    static String valueCleanup(Object value) {
     319        return valueCleanupStripped(stripUrls(value));
     320    }
     321
     322    private static Object stripUrls(Object value) {
     323        if (value instanceof String) {
     324            return TextUtils.stripUrl((String) value);
     325        } else if (value instanceof Map<?, ?>) {
     326            Map<Object, Object> map = new LinkedHashMap<>();
     327            ((Map<?, ?>) value).forEach((k, v) -> map.put(k, stripUrls(v)));
     328            return map;
     329        } else if (value instanceof Collection<?>) {
     330            return ((Collection<?>) value).stream().map(ShowStatusReportAction::stripUrls).collect(Collectors.toList());
     331        }
     332        return value;
     333    }
     334
     335    private static String valueCleanupStripped(Object value) {
    312336        String valueString = value.toString();
    313337        if (valueString.length() > 512 && value instanceof Collection<?>) {
  • trunk/src/org/openstreetmap/josm/io/remotecontrol/RequestProcessor.java

    r19629 r19711  
    5353import org.openstreetmap.josm.io.remotecontrol.handler.VersionHandler;
    5454import org.openstreetmap.josm.tools.Logging;
     55import org.openstreetmap.josm.tools.TextUtils;
    5556import org.openstreetmap.josm.tools.Utils;
    5657
    … …  
    225226                return;
    226227            }
    227             Logging.info("RemoteControl received: " + get);
     228            Logging.info("RemoteControl received: " + TextUtils.stripUrl(get)); // e.g. an OAuth 2.0 authorization code
    228229
    229230            StringTokenizer st = new StringTokenizer(get);
  • trunk/src/org/openstreetmap/josm/tools/HttpClient.java

    r19535 r19711  
    158158            try {
    159159                if (Logging.isDebugEnabled()) {
    160                     Logging.debug("REQUEST HEADERS: {0}", headers);
     160                    Logging.debug("REQUEST HEADERS: {0}", TextUtils.stripHeaders(headers));
    161161                }
    162162                cr = performConnection();
    … …  
    172172                if (Logging.isDebugEnabled()) {
    173173                    try {
    174                         Logging.debug("RESPONSE HEADERS: {0}", cr.getHeaderFields());
     174                        Logging.debug("RESPONSE HEADERS: {0}", TextUtils.stripHeaders(cr.getHeaderFields()));
    175175                    } catch (IllegalArgumentException e) {
    176176                        Logging.warn(e);
    … …  
    247247
    248248    protected final void logRequestBody() {
    249         logRequest("{0} {1} ({2}) ...", requestMethod, url, Utils.getSizeString(requestBody.length, Locale.getDefault()));
     249        logRequest("{0} {1} ({2}) ...", requestMethod, TextUtils.stripUrl(url.toString()),
     250                Utils.getSizeString(requestBody.length, Locale.getDefault()));
    250251        if (Logging.isTraceEnabled() && hasRequestBody()) {
    251             Logging.trace("BODY: {0}", new String(requestBody, StandardCharsets.UTF_8));
     252            final String body = new String(requestBody, StandardCharsets.UTF_8);
     253            final String contentType = headers.get("Content-Type");
     254            // a form-encoded body has the syntax of a query, e.g. an OAuth 2.0 token request with the client secret
     255            Logging.trace("BODY: {0}", contentType != null && contentType.contains("application/x-www-form-urlencoded")
     256                    ? TextUtils.stripUrl(body) : body);
    252257        }
    253258    }
  • trunk/src/org/openstreetmap/josm/tools/TextUtils.java

    r18657 r19711  
    11// License: GPL. For details, see LICENSE file.
    22package org.openstreetmap.josm.tools;
     3
     4import java.util.LinkedHashMap;
     5import java.util.List;
     6import java.util.Locale;
     7import java.util.Map;
     8import java.util.regex.Pattern;
     9import java.util.stream.Collectors;
    310
    411/**
    … …  
    714 */
    815public final class TextUtils {
     16
     17    /** What private information is replaced with */
     18    private static final String STRIPPED = "...stripped...";
     19    /**
     20     * The parameters which are private: API keys and tokens, and OAuth 2.0 client secrets, authorization codes and
     21     * their verifiers, and passwords. {@code code} is only matched as a whole name, so as not to strip e.g. a postcode.
     22     * A value ends at white space too, so that what follows a URL in a log line is kept.
     23     */
     24    private static final Pattern PRIVATE_PARAMETERS =
     25            Pattern.compile("(token|key|connectId|secret|password|(?<![\\w-])code|verifier)=[^&\\s]+");
    926
    1027    private TextUtils() {
    … …  
    2340
    2441    /**
    25      * Remove privacy related parts from output URL
     42     * Remove privacy related parts from output URL.
     43     * <p>
     44     * This works for a form-encoded ({@code application/x-www-form-urlencoded}) request body as well, which has the
     45     * syntax of a query, such as an OAuth 2.0 token request with its client secret.
    2646     * @param url Unmodified URL
    2747     * @return Stripped URL (privacy related issues removed)
    … …  
    2949     */
    3050    public static String stripUrl(String url) {
    31         return url.replaceAll("(token|key|connectId)=[^&]+", "$1=...stripped...");
     51        return PRIVATE_PARAMETERS.matcher(url).replaceAll("$1=" + STRIPPED);
     52    }
     53
     54    /**
     55     * Remove privacy related values from output HTTP headers: those of {@code Authorization} and
     56     * {@code Proxy-Authorization}, but for their scheme, so that the output still tells which kind of authentication
     57     * was used, and those of {@code Cookie} and {@code Set-Cookie}.
     58     * @param headers Unmodified headers, with a single value or a list of values for each
     59     * @return Stripped copy of the headers, in the same order (privacy related issues removed)
     60     * @since 19711
     61     */
     62    public static Map<String, Object> stripHeaders(Map<String, ?> headers) {
     63        final Map<String, Object> stripped = new LinkedHashMap<>(headers);
     64        stripped.replaceAll((key, value) -> {
     65            final String name = key == null ? "" : key.toLowerCase(Locale.ROOT);
     66            if ("authorization".equals(name) || "proxy-authorization".equals(name)) {
     67                return stripHeaderValue(value, true);
     68            } else if ("cookie".equals(name) || "set-cookie".equals(name)) {
     69                return stripHeaderValue(value, false);
     70            }
     71            return value;
     72        });
     73        return stripped;
     74    }
     75
     76    private static Object stripHeaderValue(Object value, boolean keepScheme) {
     77        if (value instanceof List) {
     78            return ((List<?>) value).stream().map(v -> stripHeaderValue(v, keepScheme)).collect(Collectors.toList());
     79        }
     80        final String text = String.valueOf(value);
     81        final int space = text.indexOf(' ');
     82        return (keepScheme && space > 0 ? text.substring(0, space + 1) : "") + STRIPPED;
    3283    }
    3384
  • trunk/test/unit/org/openstreetmap/josm/io/remotecontrol/RemoteControlTest.java

    r19056 r19711  
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertFalse;
     6import static org.junit.jupiter.api.Assertions.assertTrue;
    57
    68import java.io.IOException;
    … …  
    1012import java.nio.charset.StandardCharsets;
    1113import java.security.GeneralSecurityException;
     14import java.util.ArrayList;
     15import java.util.Collections;
     16import java.util.List;
     17import java.util.logging.Handler;
     18import java.util.logging.LogRecord;
    1219
    1320import org.junit.jupiter.api.AfterEach;
    … …  
    1724import org.openstreetmap.josm.testutils.annotations.AssertionsInEDT;
    1825import org.openstreetmap.josm.testutils.annotations.HTTPS;
     26import org.openstreetmap.josm.tools.Logging;
    1927
    2028/**
    … …  
    5462    }
    5563
     64    /**
     65     * The OAuth 2.0 authorization code of the redirect to Remote Control is not written to the log.
     66     * @throws Exception if an error occurs
     67     */
     68    @Test
     69    void testAuthorizationCodeIsNotLogged() throws Exception {
     70        final List<String> logged = Collections.synchronizedList(new ArrayList<>());
     71        final Handler handler = new Handler() {
     72            @Override
     73            public void publish(LogRecord logRecord) {
     74                logged.add(String.valueOf(logRecord.getMessage()));
     75            }
     76
     77            @Override
     78            public void flush() {
     79                // nothing to flush
     80            }
     81
     82            @Override
     83            public void close() {
     84                // nothing to close
     85            }
     86        };
     87        Logging.getLogger().addHandler(handler);
     88        try {
     89            HttpURLConnection connection = (HttpURLConnection) new URL(httpBase
     90                    + "/oauth_authorization?code=a-secret-code&state=a-state").openConnection();
     91            connection.connect();
     92            connection.getResponseCode();
     93            connection.disconnect();
     94        } finally {
     95            Logging.getLogger().removeHandler(handler);
     96        }
     97        final String log = String.join("\n", logged);
     98        assertTrue(log.contains("RemoteControl received: GET /oauth_authorization?code=...stripped...&state=a-state"), log);
     99        assertFalse(log.contains("a-secret-code"), log);
     100    }
     101
    56102    private void testListOfCommands(String url) throws IOException, ReflectiveOperationException {
    57103        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
Note: See TracChangeset for help on using the changeset viewer.