Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

mail sending program using ssl using gmail account

// sending mail using ruby through ssl

require 'rubygems'
require 'action_mailer'
require "net/smtp"
require "tlsmail"

class MailSent < ActionMailer::Base
  def message(r = "", m = "", s = "", f = "", c = nil)
    begin
      fail StandardError, "No Recipient" if r.empty? #and b.empty?
      fail StandardError, "No Message" if m.empty? 
      fail StandardError, "No Subject" if s.empty?
      fail StandardError, "No From" if s.empty?
      from f
      recipients r
      cc c if c and !c.empty?
      subject s
      body m
    rescue Exception => e
      puts e
    end
  end
end

class SentMail
  def get_value(to,msg,sub,from,pass=nil,cc=nil)
    begin

      Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
      ActionMailer::Base.smtp_settings = {
        :address => "smtp.gmail.com",
        :port => "587",
        :domain => "gmail.com",
        :user_name => "example.com,
        :password => "youraccountpassword",
        :authentication => :plain
      }
      MailSent.deliver_message(to,msg,sub,from,cc)
    rescue Exception=>e
      puts e
    end
  end
end

SSL : Download certificate chain from a remote host and add the certificates to a local keystore

// Code from http://blogs.sun.com/andreas/entry/no_more_unable_to_find
// /*
// * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
// *
// * Redistribution and use in source and binary forms, with or without
// * modification, are permitted provided that the following conditions
// * are met:
// *
// * - Redistributions of source code must retain the above copyright
// * notice, this list of conditions and the following disclaimer.
// *
// * - Redistributions in binary form must reproduce the above copyright
// * notice, this list of conditions and the following disclaimer in the
// * documentation and/or other materials provided with the distribution.
// *
// * - Neither the name of Sun Microsystems nor the names of its
// * contributors may be used to endorse or promote products derived
// * from this software without specific prior written permission.
// *
// * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// */

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
	String host;
	int port;
	char[] passphrase;
	if ((args.length == 1) || (args.length == 2)) {
	    String[] c = args[0].split(":");
	    host = c[0];
	    port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
	    String p = (args.length == 1) ? "changeit" : args[1];
	    passphrase = p.toCharArray();
	} else {
	    System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
	    return;
	}

	File file = new File("jssecacerts");
	if (file.isFile() == false) {
	    char SEP = File.separatorChar;
	    File dir = new File(System.getProperty("java.home") + SEP
		    + "lib" + SEP + "security");
	    file = new File(dir, "jssecacerts");
	    if (file.isFile() == false) {
		file = new File(dir, "cacerts");
	    }
	}
	System.out.println("Loading KeyStore " + file + "...");
	InputStream in = new FileInputStream(file);
	KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	ks.load(in, passphrase);
	in.close();

	SSLContext context = SSLContext.getInstance("TLS");
	TrustManagerFactory tmf =
	    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	tmf.init(ks);
	X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
	SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
	context.init(null, new TrustManager[] {tm}, null);
	SSLSocketFactory factory = context.getSocketFactory();

	System.out.println("Opening connection to " + host + ":" + port + "...");
	SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
	socket.setSoTimeout(10000);
	try {
	    System.out.println("Starting SSL handshake...");
	    socket.startHandshake();
	    socket.close();
	    System.out.println();
	    System.out.println("No errors, certificate is already trusted");
	} catch (SSLException e) {
	    System.out.println();
	    e.printStackTrace(System.out);
	}

	X509Certificate[] chain = tm.chain;
	if (chain == null) {
	    System.out.println("Could not obtain server certificate chain");
	    return;
	}

	BufferedReader reader =
		new BufferedReader(new InputStreamReader(System.in));

	System.out.println();
	System.out.println("Server sent " + chain.length + " certificate(s):");
	System.out.println();
	MessageDigest sha1 = MessageDigest.getInstance("SHA1");
	MessageDigest md5 = MessageDigest.getInstance("MD5");
	for (int i = 0; i < chain.length; i++) {
	    X509Certificate cert = chain[i];
	    System.out.println
	    	(" " + (i + 1) + " Subject " + cert.getSubjectDN());
	    System.out.println("   Issuer  " + cert.getIssuerDN());
	    sha1.update(cert.getEncoded());
	    System.out.println("   sha1    " + toHexString(sha1.digest()));
	    md5.update(cert.getEncoded());
	    System.out.println("   md5     " + toHexString(md5.digest()));
	    System.out.println();
	}

	System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
	String line = reader.readLine().trim();
	int k;
	try {
	    k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
	} catch (NumberFormatException e) {
	    System.out.println("KeyStore not changed");
	    return;
	}

	X509Certificate cert = chain[k];
	String alias = host + "-" + (k + 1);
	ks.setCertificateEntry(alias, cert);

	OutputStream out = new FileOutputStream("jssecacerts");
	ks.store(out, passphrase);
	out.close();

	System.out.println();
	System.out.println(cert);
	System.out.println();
	System.out.println
		("Added certificate to keystore 'jssecacerts' using alias '"
		+ alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
	StringBuilder sb = new StringBuilder(bytes.length * 3);
	for (int b : bytes) {
	    b &= 0xff;
	    sb.append(HEXDIGITS[b >> 4]);
	    sb.append(HEXDIGITS[b & 15]);
	    sb.append(' ');
	}
	return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

	private final X509TrustManager tm;
	private X509Certificate[] chain;

	SavingTrustManager(X509TrustManager tm) {
	    this.tm = tm;
	}

	public X509Certificate[] getAcceptedIssuers() {
	    throw new UnsupportedOperationException();
	}

	public void checkClientTrusted(X509Certificate[] chain, String authType)
		throws CertificateException {
	    throw new UnsupportedOperationException();
	}

	public void checkServerTrusted(X509Certificate[] chain, String authType)
		throws CertificateException {
	    this.chain = chain;
	    tm.checkServerTrusted(chain, authType);
	}
    }

}

Make sure your site (or directory) is SSL encrypted

Need a simple way to make sure all http requests get redirected to https?
This apache config snippet will redirect all requests at or below the specified location to its https equivilant.

<Location "/">
        RewriteEngine on
        Options +FollowSymLinks
        Allow from all
        RewriteCond %{SERVER_PORT} !^443$
        RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
</Location>

SSL Cert on the cheap.

Stolen from: http://groups.google.com/group/rubyonrails-talk/browse_frm/thread/148ada4b0d33cfac?hl=en

If cost is an issue, you may wish to investigate Reverse Proxying with a
single external certificate and multiple internal certificates (either
self-signed or issued from an internal CA).

Extract a server certificate from a HTTPS connection.

You can simply extract information about the SSL certificate of HTTP connections using OpenSSL

openssl s_client -connect ${URL}:${PORT}


For example:

openssl s_client -connect checkout.google.com:443


From there, it is only redirecting the output to a file or extracting information out of the stream with Perl.

Lighttpd Rails Script with SSL options

#!/usr/bin/env ruby

require 'optparse'
require 'fileutils'
require 'tmpdir'

OPTIONS = {
  :port        => 3000,
  :ip          => "0.0.0.0",
  :daemon      => false,
  :environment => "development",
  :app_name    => Process::pid.to_s,
  :max_procs   => 3,
  :min_procs   => 1,
  :ssl         => false,
  :pemfile     => "server.pem",
}

ARGV.options do |opts|
  script_name = File.basename($0)
  opts.banner = "Usage: ruby #{script_name} [options]"

  opts.separator ""

  opts.on("-p", "--port=port", Integer,
          "Runs Rails on the specified port.",
          "Default: 8000") { |OPTIONS[:port]| }
  opts.on("-b", "--binding=ip", String,
          "Binds Rails to the specified ip.",
          "Default: 0.0.0.0") { |OPTIONS[:ip]| }
  opts.on("-e", "--environment=name", String,
          "Specifies the environment to run this server under (test/development/production).",
          "Default: development") { |OPTIONS[:environment]| }
  opts.on("-a", "--app-name=name", String,
          "Specifies the application name.",
          "Default: process_id") { |OPTIONS[:app_name]| }
  opts.on("-d", "--daemon",
          "Make lighttpd / Rails run as a Daemon (only works if fork is available -- meaning on *nix)."
          ) { OPTIONS[:daemon] = true }
  opts.on("-n", "--min-procs=number", Integer,
          "Minimum number of FastCGI processes allowed.",
          "Default: 1") { |OPTIONS[:min_procs]| }
  opts.on("-m", "--max-procs=number", Integer,
          "Maximum number of FastCGI processes allowed.",
          "Default: 3") { |OPTIONS[:max_procs]| }
  opts.on("-l", "--enable-ssl",
          "Enable SSL."
          ) { OPTIONS[:ssl] = true }
  opts.on("-f", "--pemfile=pemfile", String,
          "path to the PEM file for SSL support."
          ) { |OPTIONS[:pemfile]| }
  
  opts.separator ""

  opts.on("-h", "--help",
          "Show this help message.") { puts opts; exit }

  opts.parse!

end

ENV["RAILS_ENV"] = OPTIONS[:environment]
RAILS_ROOT = Dir.pwd + "/./"
TMP_DIR = Dir.tmpdir
LIGHTTPD_CONF_FILE = TMP_DIR + "/lighttpd.#{OPTIONS[:app_name]}.conf"

conf = DATA.read
conf.gsub!('__PORT__', OPTIONS[:port].to_s)
conf.gsub!('__BINDING__', OPTIONS[:ip])
conf.gsub!('__RAILS_ROOT__', File.expand_path(RAILS_ROOT))
conf.gsub!('__APP_NAME__', OPTIONS[:app_name])
conf.gsub!('__MIN_PROCS__', OPTIONS[:min_procs].to_s)
conf.gsub!('__MAX_PROCS__', OPTIONS[:max_procs].to_s)
conf.gsub!('__RAILS_ENV__', ENV['RAILS_ENV'])
conf.gsub!('__TMP_DIR__', TMP_DIR)
conf.gsub!('__SSL__', OPTIONS[:ssl] ? "enable" : "disable")
conf.gsub!('__PEMFILE__', OPTIONS[:pemfile])
File.open(LIGHTTPD_CONF_FILE, "w") { |output| output.write(conf) }

CMD = "/usr/sbin/lighttpd -f #{LIGHTTPD_CONF_FILE}"
CMD << " -D" if not OPTIONS[:daemon]

puts "=> Rails application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
puts "=> Ctrl-C to shutdown server; call with --help for options" if not OPTIONS[:daemon]

puts CMD
`#{CMD}`

FileUtils.rm Dir.glob(TMP_DIR + "/lighttpd.#{OPTIONS[:app_name]}.*") if not OPTIONS[:daemon]

__END__
server.port                = __PORT__
server.bind                = "__BINDING__"
server.pid-file             = "__TMP_DIR__/lighttpd.__APP_NAME__.pid"
server.max-keep-alive-requests = 4
server.max-keep-alive-idle = 4

ssl.engine = "__SSL__"
ssl.pemfile = "__PEMFILE__"

#server.event-handler = "freebsd-kqueue"

server.modules = ( "mod_rewrite", "mod_redirect", "mod_access", "mod_fastcgi", "mod_accesslog" )
server.document-root        = "__RAILS_ROOT__/public/"
server.indexfiles           = ( "index.html" ,"dispatch.fcgi")
accesslog.filename          = "__RAILS_ROOT__/log/lighttpd.__RAILS_ENV__.access.log"
server.errorlog             = "__RAILS_ROOT__/log/lighttpd.__RAILS_ENV__.error.log"
server.error-handler-404 = "/dispatch.fcgi"

#### fastcgi module

## read fastcgi.txt for more info
fastcgi.server =  (
                   ".fcgi" => (
                               "__APP_NAME__" => (
                                                  "socket" => "__TMP_DIR__/lighttpd.__APP_NAME__.fcgi.socket",
                                                  "bin-path" => "__RAILS_ROOT__/public/dispatch.fcgi",
                                                  "min-procs" => __MIN_PROCS__,
                                                  "max_procs" => __MAX_PROCS__
                                                  )
                               )
                   )


mimetype.assign             = (
                               ".rpm"          =>      "application/x-rpm",
                               ".pdf"          =>      "application/pdf",
                               ".sig"          =>      "application/pgp-signature",
                               ".spl"          =>      "application/futuresplash",
                               ".class"        =>      "application/octet-stream",
                               ".ps"           =>      "application/postscript",
                               ".torrent"      =>      "application/x-bittorrent",
                               ".dvi"          =>      "application/x-dvi",
                               ".gz"           =>      "application/x-gzip",
                               ".pac"          =>      "application/x-ns-proxy-autoconfig",
                               ".swf"          =>      "application/x-shockwave-flash",
                               ".tar.gz"       =>      "application/x-tgz",
                               ".tgz"          =>      "application/x-tgz",
                               ".tar"          =>      "application/x-tar",
                               ".zip"          =>      "application/zip",
                               ".mp3"          =>      "audio/mpeg",
                               ".m3u"          =>      "audio/x-mpegurl",
                               ".wma"          =>      "audio/x-ms-wma",
                               ".wax"          =>      "audio/x-ms-wax",
                               ".ogg"          =>      "audio/x-wav",
                               ".wav"          =>      "audio/x-wav",
                               ".gif"          =>      "image/gif",
                               ".jpg"          =>      "image/jpeg",
                               ".jpeg"         =>      "image/jpeg",
                               ".png"          =>      "image/png",
                               ".xbm"          =>      "image/x-xbitmap",
                               ".xpm"          =>      "image/x-xpixmap",
                               ".xwd"          =>      "image/x-xwindowdump",
                               ".css"          =>      "text/css",
                               ".html"         =>      "text/html",
                               ".htm"          =>      "text/html",
                               ".js"           =>      "text/javascript",
                               ".asc"          =>      "text/plain",
                               ".c"            =>      "text/plain",
                               ".conf"         =>      "text/plain",
                               ".text"         =>      "text/plain",
                               ".txt"          =>      "text/plain",
                               ".dtd"          =>      "text/xml",
                               ".xml"          =>      "text/xml",
                               ".mpeg"         =>      "video/mpeg",
                               ".mpg"          =>      "video/mpeg",
                               ".mov"          =>      "video/quicktime",
                               ".qt"           =>      "video/quicktime",
                               ".avi"          =>      "video/x-msvideo",
                               ".asf"          =>      "video/x-ms-asf",
                               ".asx"          =>      "video/x-ms-asf",
                               ".wmv"          =>      "video/x-ms-wmv",
                               ".bz2"          =>      "application/x-bzip",
                               ".tbz"          =>      "application/x-bzip-compressed-tar",
                               ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
                               )
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS