Restrict a Socket Server to specific IP adresses

Just as some kind of promotional code, I implemented a Webservice based on Axis and its SimpleAxisServer. It turned out, that the SimpleAxisServer was to simple:

  • it only filled certain fields of the MessageContext and particularly not anything to see the Remote IP Adresse.

After some thinking I decided to fully copy the SimpleAxisServer and Worker to my ow classes (because the are not made to be extended….) and changed some minor stuff.

First of all, I use Commons Configurations to load me a list of IP Adresses and Hostnames. Like:

allowed_ips = google.com, mydomain.com, 127.0.0.1

I convert these into a List of Java InetAdresses with that:

	public void setAllowedHosts(String[] hosts) {
		for (String host : hosts) {
			try {
				this.allowedIPs.addAll(Arrays.asList(InetAddress.getAllByName(host)));
			} catch (UnknownHostException e) {
				log.error(String.format("Allowed IP could not be set successfully.", e));
			}
		}
	}

and in the run() Method of my SimpleAxisServer I added some lines:

	public void run() {
		log.info(Messages.getMessage("start01", "SimpleAxisServer", new Integer(getServerSocket().getLocalPort()).toString(),
				getCurrentDirectory()));
		if (allowedIPs.size() == 0) {
			log.warn("No IP Restrictin inplace. Service is exposed to everyone.");
		} else {
			log.info(String.format("Service Call are allowed from IP: %s", allowedIPs));
		}
		// Accept and process requests from the socket
		while (!stopped) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				if (allowedIPs.size() > 0) {
					if (!allowedIPs.contains(socket.getInetAddress())) {
						log.debug(String.format("Discarding connection from: %s, because it isn't in the list of supported IP's: %s",
								socket.getInetAddress(), allowedIPs));
						socket.close();
						socket = null;
					}
				}
			} catch (java.io.InterruptedIOException iie) {
			} catch (Exception e) {
				log.debug(Messages.getMessage("exception00"), e);
				break;
			}
			if (socket != null) {
				MPAxisWorker worker = new MPAxisWorker(this, socket);
				if (doThreads) {
					pool.addWorker(worker);
				} else {
					worker.run();
				}
			}
		}
		log.info(Messages.getMessage("quit00", "SimpleAxisServer"));
	}

Making a Java UI for editing Properties

Java Properties suck. But Apache Confoigurations sucks a bit less, so I’m using it to have a small configuration framework.

It consists of

  • Constant values, like the Application title, version, and so on.
  • Default values, like database url, username, …
  • User Properties, which are generated based on the default values

Then I have a JFrame which takes the user properties and iterates and displays them in a gui.

The final UI looks like this:

Continue reading