99

We have a site which is accessed entirely over HTTPS, but sometimes display external content which is HTTP (images from RSS feeds, mainly). The vast majority of our users are also stuck on IE6.

I would ideally like to do both of the following

  • Prevent the IE warning message about insecure content (so that I can show a less intrusive one, e.g. by replacing the images with a default icon as below)
  • Present something useful to users in place of the images that they can't otherwise see; if there was some JS I could run to figure out which images haven't been loaded and replace them with an image of ours instead that would be great.

I suspect that the first aim is simply not possible, but the second may be sufficient.

A worst case scenario is that I parse the RSS feeds when we import them, grab the images store them locally so that the users can access them that way, but it seems like a lot of pain for reasonably little gain.

El Yobo
  • 14,823
  • 5
  • 60
  • 78

10 Answers10

156

Your worst case scenario isn't as bad as you think.

You are already parsing the RSS feed, so you already have the image URLs. Say you have an image URL like http://otherdomain.example/someimage.jpg. You rewrite this URL as https://mydomain.example/imageserver?url=http://otherdomain.example/someimage.jpg&hash=abcdeafad. This way, the browser always makes request over HTTPS, so you get rid of the problems.

The next part - create a proxy page or servlet that does the following -

  1. Read the URL parameter from the query string, and verify the hash
  2. Download the image from the server, and proxy it back to the browser
  3. Optionally, cache the image on disk

This solution has some advantages. You don't have to download the image at the time of creating the HTML. You don't have to store the images locally. Also, you are stateless; the URL contains all the information necessary to serve the image.

Finally, the hash parameter is for security; you only want your servlet to serve images for URLs you have constructed. So, when you create the URL, compute md5(image_url + secret_key) and append it as the hash parameter. Before you serve the request, recompute the hash and compare it to what was passed to you. Since the secret_key is only known to you, nobody else can construct valid URLs.

If you are developing in Java, the Servlet is just a few lines of code. You should be able to port the code below on any other back-end technology.

/*
targetURL is the url you get from RSS feeds
request and response are wrt to the browser
Assumes you have commons-io in your classpath
*/

protected void proxyResponse (String targetURL, HttpServletRequest request,
 HttpServletResponse response) throws IOException {
    GetMethod get = new GetMethod(targetURL);
    get.setFollowRedirects(true);
    /*
     * Proxy the request headers from the browser to the target server
     */
    Enumeration headers = request.getHeaderNames();
    while(headers!=null && headers.hasMoreElements())
    {
        String headerName = (String)headers.nextElement();

        String headerValue = request.getHeader(headerName);

        if(headerValue != null)
        {
            get.addRequestHeader(headerName, headerValue);
        }
    }

    /*Make a request to the target server*/
    m_httpClient.executeMethod(get);
    /*
     * Set the status code
     */
    response.setStatus(get.getStatusCode());

    /*
     * proxy the response headers to the browser
     */
    Header responseHeaders[] = get.getResponseHeaders();
    for(int i=0; i<responseHeaders.length; i++)
    {
        String headerName = responseHeaders[i].getName();
        String headerValue = responseHeaders[i].getValue();

        if(headerValue != null)
        {
            response.addHeader(headerName, headerValue);
        }
    }

    /*
     * Proxy the response body to the browser
     */
    InputStream in = get.getResponseBodyAsStream();
    OutputStream out = response.getOutputStream();

    /*
     * If the server sends a 204 not-modified response, the InputStream will be null.
     */
    if (in !=null) {
        IOUtils.copy(in, out);
    }
}
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Sripathi Krishnan
  • 30,948
  • 4
  • 76
  • 83
  • 1
    Very sound, and I think this is what I'll roll with. We're using PHP, but the implementation will also be trivial. I'll also implement caching on our side, as I don't want to download the image every time someone requests it (for performance and bandwith usage). The suggestions for the security approach are sound (although we'll also apply our standard security model as well as the above) as well. Thanks for your suggestion. – El Yobo Jun 17 '10 at 13:22
  • 37
    The only serious downside to this approach is that you are routing all external resources through your own systems. Which is not only a liability, but also can get rather costly. – Tim Molendijk Feb 18 '11 at 04:40
  • I second @TimMolendijk, adding that it not only adds cost and maintenance but also defeats any CDNs which supposed to route to near servers or balance to idle ones. – Levente Pánczél Nov 19 '15 at 18:04
  • 2
    What is the solution for NodeJS? – stkvtflw Feb 16 '16 at 05:24
  • 1
    another +1 for @TimMolendijk but what would be solution then? site served over HTTPS doesn't seem to play nicely with images delivered via HTTP – FullStackForger May 11 '16 at 16:30
  • Try using your webserver as a proxy, like mentioned here: https://stackoverflow.com/a/21537530/840315 apache 2.4 url: https://httpd.apache.org/docs/2.4/rewrite/proxy.html – szab.kel Aug 29 '18 at 05:48
  • Can you make this for audio mp3? php server – Alberto Acuña Apr 03 '19 at 20:47
22

If you're looking for a quick solution to load images over HTTPS then the free reverse proxy service at https://images.weserv.nl/ may interest you. It was exactly what I was looking for.

If you're looking for a paid solution, I have previously used Cloudinary.com which also works well but is too expensive solely for this task, in my opinion.

nullable
  • 2,513
  • 1
  • 29
  • 32
  • What's the catch? Works great – Jack Nov 09 '17 at 23:15
  • 6
    @JackNicholson I've been using it under relatively heavy load for 2 years. Works great! Kudos to the two devs. – nullable Nov 10 '17 at 08:46
  • I have some links(video or site)starting with Http and I am unable to display them in an Iframe on our https site. As this is nonsecure link it is not working. for an image, I have solved the issue using image cache. Anyone have any idea – pca Jul 30 '19 at 09:54
  • 1
    @int14 You will need to set up a reverse proxy for the http site, you can do this with something like AWS API Gateway. – nullable Jul 30 '19 at 18:03
  • You are a lifesaver!! /images.weserv.nl it is working perfectly – ExpertWeblancer Jun 29 '22 at 17:11
3

I don't know if this would fit what you are doing, but as a quick fix I would "wrap" the http content into an https script. For instance, on your page that is served through https i would introduce an iframe that would replace your rss feed and in the src attr of the iframe put a url of a script on your server that captures the feed and outputs the html. the script is reading the feed through http and outputs it through https (thus "wrapping")

Just a thought

hndcrftd
  • 3,180
  • 1
  • 21
  • 18
  • It seems to me that this would leave me in the same situation as I am in now; I'm already showing the content in an HTTPS page - the problem is that there are tags in the content with http:// src values - which don't get shown and cause an annoying message to occur. – El Yobo Jun 14 '10 at 07:59
  • well, yes, if you keep the original links to the images, there is no way to avoid the issue. The wrapper script would have to scan the rss feed content for images and remove those. As you mentioned in another comment - you don't want to load the content that causes the popup and show something informative instead. That's the reason for the "script in the middle" – hndcrftd Jun 14 '10 at 22:29
  • You may even do this without the iframe, right in your main backend script, but in this case you are waiting for the rss feed to come back before being processed and output on a page. I would do an iFrame so that your page loads asynchronously with the rss feed. There's also ajax option if you want to go there to avoid the iframe. Just curious - what is your backend platform? – hndcrftd Jun 14 '10 at 22:42
2

Regarding your second requirement - you might be able to utilise the onerror event, ie. <img onerror="some javascript;"...

Update:

You could also try iterating through document.images in the dom. There is a complete boolean property which you might be able to use. I don't know for sure whether this will be suitable, but might be worth investigating.

UpTheCreek
  • 31,444
  • 34
  • 152
  • 221
  • Interesting, I didn't even know there _was_ an onerror event. I'd have to rewrite the HTML (as it's coming from an external source), but it's already being sanitised with HTML purifier, so adding that as a filter may be possible. – El Yobo Jun 14 '10 at 07:57
  • Won't any browser security warning occur _before_ JavaScript has had a chance to do anything? – MrWhite Sep 18 '16 at 15:26
2

The accepted answer helped me update this both to PHP as well as CORS, so I thought I would include the solution for others:

pure PHP/HTML:

<?php // (the originating page, where you want to show the image)
// set your image location in whatever manner you need
$imageLocation = "http://example.com/exampleImage.png";

// set the location of your 'imageserve' program
$imageserveLocation = "https://example.com/imageserve.php";

// we'll look at the imageLocation and if it is already https, don't do anything, but if it is http, then run it through imageserve.php
$imageURL = (strstr("https://",$imageLocation)?"": $imageserveLocation . "?image=") . $imageLocation;

?>
<!-- this is the HTML image -->
<img src="<?php echo $imageURL ?>" />

javascript/jQuery:

<img id="theImage" src="" />
<script>
    var imageLocation = "http://example.com/exampleImage.png";
    var imageserveLocation = "https://example.com/imageserve.php";
    var imageURL = ((imageLocation.indexOf("https://") !== -1) ? "" : imageserveLocation + "?image=") + imageLocation;
    // I'm using jQuery, but you can use just javascript...        
    $("#theImage").prop('src',imageURL);
</script>

imageserve.php see http://stackoverflow.com/questions/8719276/cors-with-php-headers?noredirect=1&lq=1 for more on CORS

<?php
// set your secure site URL here (where you are showing the images)
$mySecureSite = "https://example.com";

// here, you can set what kinds of images you will accept
$supported_images = array('png','jpeg','jpg','gif','ico');

// this is an ultra-minimal CORS - sending trusted data to yourself 
header("Access-Control-Allow-Origin: $mySecureSite");

$parts = pathinfo($_GET['image']);
$extension = $parts['extension'];
if(in_array($extension,$supported_images)) {
    header("Content-Type: image/$extension");
    $image = file_get_contents($_GET['image']);
    echo $image;
}
Apps-n-Add-Ons
  • 2,026
  • 1
  • 17
  • 28
1

Sometimes like in facebook apps we can not have non-secure contents in secure page. also we can not make local those contents. for example an app which will load in iFrame is not a simple content and we can not make it local.

I think we should never load http contents in https, also we should not fallback https page to http version to prevent error dialog.

the only way which will ensure user's security is to use https version of all contents, http://web.archive.org/web/20120502131549/http://developers.facebook.com/blog/post/499/

Yaroslav Nikitenko
  • 1,695
  • 2
  • 23
  • 31
Mohammad Ali Akbari
  • 10,345
  • 11
  • 44
  • 62
  • 3
    That may be possible with facebook, but not for all content and this question was not about facebook. – El Yobo May 04 '12 at 13:30
0

It would be best to just have the http content on https

Daniel
  • 3,017
  • 12
  • 44
  • 61
  • 6
    If I didn't make this clear in my question, the HTTP content is on other people's server's not mine. Specifically, it is links in HTML that I have retrieved from RSS feeds. I have emphasised this in the question now. – El Yobo Jun 14 '10 at 12:09
  • Oh ok, would http://www.webproworld.com/webmaster-forum/threads/81513-https-images-and-css-files help at all? – Daniel Jun 14 '10 at 12:18
-1

Simply: DO NOT DO IT. Http Content within a HTTPS page is inherently insecure. Point. This is why IE shows a warning. Getting rid of the warning is a stupid hogwash approach.

Instead, a HTTPS page should only have HTTPS content. Make sure the content can be loaded via HTTPS, too, and reference it via https if the page is loaded via https. For external content this will mean loading and caching the elements locally so that they are available via https - sure. No way around that, sadly.

The warning is there for a good reason. Seriously. Spend 5 minutes thinking how you could take over a https shown page with custom content - you will be surprised.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • 3
    Easy there, I'm aware that there's a good reason for it; I think that IE's behaviour is better than FF in this regard. What I am aiming for is _not_ to load the content; I just want to avoid the intrusive popup style warning and to show something informative in place of the content. – El Yobo Jun 14 '10 at 07:55
  • 2
    No chance for that - unless you rewrite the HTML on the way out. Any javascript post load attempt already has shown the dialog. – TomTom Jun 14 '10 at 08:10
  • He was just asking about images and he is not requesting any insecure text or script so we can by pass the warning by rewriting urls. – Jayapal Chandran Sep 01 '11 at 01:39
  • 1
    No change to the answer. Images can also be insecure. It isa general thing - either it is coming from the secured source, orit may be replaced by a man in the middle attack. – TomTom Sep 01 '11 at 04:42
  • 8
    Downvoted because this _"answer"_ didn't answer how to achieve the OP's goal. – MikeSchinkel Jan 19 '14 at 21:11
  • @MikeSchinkel actually, it kind of did -- vaguely -- but he basically suggested the same thing the accepted answer did (see: paragraph 2, sentence 3 of this answer) -- he just didn't provide any implementation, or security details -- still, it's a well known pattern... – BrainSlugs83 Nov 22 '15 at 18:53
  • All solutions are bad,google proxy also doesnt work,seems to me than that is imposible. – Goran_Ilic_Ilke Mar 18 '22 at 10:16
-4

Best way work for me

<img src="/path/image.png" />// this work only online
    or
    <img src="../../path/image.png" /> // this work both
    or asign variable
    <?php 
    $base_url = '';
    if($_SERVER['HTTP_HOST'] == 'localhost')
    {
         $base_url = 'localpath'; 
    }
    ?>
    <img src="<?php echo $base_url;?>/path/image.png" /> 
Sandeep Sherpur
  • 2,418
  • 25
  • 27
-5

I realise that this is an old thread but one option is just to remove the http: part from the image URL so that 'http://some/image.jpg' becomes '//some/image.jpg'. This will also work with CDNs

Shmarkus
  • 178
  • 1
  • 11
  • 9
    This will sometimes work and sometimes not; it depends whether the upstream content is available via HTTPS. If not, it will just break. – El Yobo Jan 12 '16 at 22:13