/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2023, Arnaud Roques * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */ package net.sourceforge.plantuml.security; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.swing.ImageIcon; import net.sourceforge.plantuml.StringUtils; import net.sourceforge.plantuml.security.authentication.SecurityAccessInterceptor; import net.sourceforge.plantuml.security.authentication.SecurityAuthentication; import net.sourceforge.plantuml.security.authentication.SecurityCredentials; /** * Secure replacement for java.net.URL. *
* This class should be used instead of java.net.URL. *
* This class does some control access and manages access-tokens via URL. If a * URL contains a access-token, similar to a user prefix, SURL loads the * authorization config for this user-token and passes the credentials to the * host. *
* Example:
*
*
* SURL url = SURL.create ("https://jenkins-access@jenkins.mycompany.com/api/json") ** * The {@code jenkins-access} will checked against the Security context access * token configuration. If a configuration exists for this token name, the token * will be removed from the URL and the credentials will be added to the * headers. If the token is not found, the URL remains as it is and no separate * authentication will be performed. *
* TODO: Some methods should be moved to a HttpClient implementation, because
* SURL is not the valid class to manage it.
* The url must be http or https. Return null in case of error or if
*
* It takes into account credentials.
*
* @param url
* @return the secure URL
* @throws MalformedURLException if
* In some test cases (and maybe also needed for other functionality) the bad
* hosts cache must be cleared.
* This method allows access to an endpoint, with a configured
* SecurityCredentials object. The credentials will load on the fly and
* authentication fetched from an authentication-manager. Caching of tokens is
* not supported.
*
* authors: Alain Corbiere, Aljoscha Rittner
*
* @return data loaded data from endpoint
*/
public byte[] getBytes() {
if (isUrlOk() == false)
return null;
final SecurityCredentials credentials = SecurityUtils.loadSecurityCredentials(securityIdentifier);
final SecurityAuthentication authentication = SecurityUtils.getAuthenticationManager(credentials)
.create(credentials);
try {
final String host = internal.getHost();
final Long bad = BAD_HOSTS.get(host);
if (bad != null) {
if ((System.currentTimeMillis() - bad) < 1000L * 60)
return null;
BAD_HOSTS.remove(host);
}
try {
final Future
* This method allows a parametrized access to an endpoint, without a configured
* SecurityCredentials object. This is useful to access internally identity
* providers (IDP), or authorization servers (to request access tokens).
*
* This method don't use the "bad-host" functionality, because the access to
* infrastructure services should not be obfuscated by some internal management.
*
* Please don't use this method directly from DSL scripts.
*
* @param authentication authentication object data. Caller is responsible to
* erase credentials
* @param proxy proxy configuration
* @param headers additional headers, if needed
* @return loaded data from endpoint
*/
private byte[] getBytes(Proxy proxy, SecurityAuthentication authentication, Map
* This method allows a parametrized access to an endpoint, without a configured
* SecurityCredentials object. This is useful to access internally identity
* providers (IDP), or authorization servers (to request access tokens).
*
* This method don't use the "bad-host" functionality, because the access to
* infrastructure services should not be obfuscated by some internal management.
*
* Please don't use this method directly from DSL scripts.
*
* @param authentication authentication object data. Caller is responsible to
* erase credentials
* @param proxy proxy configuration
* @param data content to post
* @param headers headers, if needed
* @return loaded data from endpoint
*/
public byte[] getBytesOnPost(Proxy proxy, SecurityAuthentication authentication, String data,
Map
* TODO: BAD_HOSTS implementation should be reviewed and moved to HttpClient
* implementation with a circuit-breaker.
* TODO: Token expiration with refresh should be implemented in future.
*/
public class SURL {
/**
* Indicates, that we have no authentication to access the URL.
*/
public static final String WITHOUT_AUTHENTICATION = SecurityUtils.NO_CREDENTIALS;
/**
* Regex to remove the UserInfo part from a URL.
*/
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// private static final Pattern PATTERN_USERINFO = Pattern.compile("(^https?://)([-_:0-9a-zA-Z]+@)([^@]*)");
// FIXED:
private static final Pattern PATTERN_USERINFO = Pattern.compile("(^https?://)([-_0-9a-zA-Z]+@)([^@]*)");
private static final ExecutorService EXE = Executors.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(Runnable r) {
final Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
}
});
private static final Mapurl
is null
*
* @param url plain url starting by http:// or https//
* @return the secure URL or null
*/
public static SURL create(String url) {
if (url == null)
return null;
if (url.startsWith("http://") || url.startsWith("https://"))
try {
return create(new URL(url));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
/**
* Create a secure URL from a java.net.URL
object.
* url
is null
*/
public static SURL create(URL url) throws MalformedURLException {
if (url == null)
throw new MalformedURLException("URL cannot be null");
final String credentialId = url.getUserInfo();
if (credentialId == null || credentialId.indexOf(':') > 0)
// No user info at all, or a user with password (This is a legacy BasicAuth
// access, and we bypass it):
return new SURL(url, WITHOUT_AUTHENTICATION);
else if (SecurityUtils.existsSecurityCredentials(credentialId))
// Given userInfo, but without a password. We try to find SecurityCredentials
return new SURL(removeUserInfo(url), credentialId);
else
return new SURL(url, WITHOUT_AUTHENTICATION);
}
/**
* Creates a URL without UserInfo part and without SecurityCredentials.
*
* @param url plain URL
* @return SURL without any user credential information.
* @throws MalformedURLException
*/
static SURL createWithoutUser(URL url) throws MalformedURLException {
return new SURL(removeUserInfo(url), WITHOUT_AUTHENTICATION);
}
/**
* Clears the bad hosts cache.
*
* E.g., in a test we check the failure on missing credentials and then a test
* with existing credentials. With a bad host cache the second test will fail,
* or we have unpredicted results.
*/
static void resetBadHosts() {
BAD_HOSTS.clear();
}
@Override
public String toString() {
return internal.toString();
}
/**
* Check SecurityProfile to see if this URL can be opened.
*/
private boolean isUrlOk() {
if (SecurityUtils.getSecurityProfile() == SecurityProfile.SANDBOX)
// In SANDBOX, we cannot read any URL
return false;
if (SecurityUtils.getSecurityProfile() == SecurityProfile.LEGACY)
return true;
if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE)
// We are UNSECURE anyway
return true;
if (isInUrlAllowList())
return true;
if (SecurityUtils.getSecurityProfile() == SecurityProfile.INTERNET) {
if (forbiddenURL(cleanPath(internal.toString())))
return false;
final int port = internal.getPort();
// Using INTERNET profile, port 80 and 443 are ok
return port == 80 || port == 443 || port == -1;
}
return false;
}
private boolean forbiddenURL(String full) {
if (full.matches("^https?://[.0-9]+/.*"))
return true;
if (full.matches("^https?://[^.]+/.*"))
return true;
return false;
}
private boolean isInUrlAllowList() {
final String full = cleanPath(internal.toString());
for (String allow : getUrlAllowList())
if (full.startsWith(cleanPath(allow)))
return true;
return false;
}
private String cleanPath(String path) {
// Remove user information, because we don't like to store user/password or
// userTokens in allow-list
path = removeUserInfoFromUrlPath(path);
path = path.trim().toLowerCase(Locale.US);
// We simplify/normalize the url, removing default ports
path = path.replace(":80/", "");
path = path.replace(":443/", "");
return path;
}
private List