Skip to content

Instantly share code, notes, and snippets.

@dertom95
Last active January 5, 2017 15:06
Show Gist options
  • Save dertom95/63dabeeacd0fd99a4d2eb6eea57012c1 to your computer and use it in GitHub Desktop.
Save dertom95/63dabeeacd0fd99a4d2eb6eea57012c1 to your computer and use it in GitHub Desktop.
// the error will occur after a couple of seconds. It seems that the ZAP-Request to configure
// plain is not processed before the sockets start with their work.
// this will show that loadpasswords throws a nullpointer-exception because it assumes the password file is already
// loaded.
// Adding a sleep after auth.configurePlain(..) helps but is very hacky.
package org.tt.zmq.security;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import org.zeromq.ZAuth;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
public class TestPlain {
private static final boolean VERBOSE_MODE=true;
private static final boolean SHOW_ERROR = false;
public static String woodhouse() {
// Create context
ZContext ctx = new ZContext();
// Start an authentication engine for this context. This engine
// allows or denies incoming connections (talking to the libzmq
// core over a protocol called ZAP).
ZAuth auth = new ZAuth(ctx);
// Get some indication of what the authenticator is deciding
auth.setVerbose(VERBOSE_MODE);
// Whitelist our address; any other address will be rejected
auth.allow("127.0.0.1");
auth.configurePlain("*", "passwords");
if (!SHOW_ERROR){
try {
Thread.sleep(50);
}
catch (Exception e) {
e.printStackTrace();
}
}
// Create and bind server socket
ZMQ.Socket server = ctx.createSocket(ZMQ.PUSH);
server.setPlainServer(true);
server.setZAPDomain("global".getBytes());
server.bind("tcp://*:9000");
System.out.println("wh5");
// Create and connect client socket
ZMQ.Socket client = ctx.createSocket(ZMQ.PULL);
client.setPlainUsername("admin".getBytes());
client.setPlainPassword("secret".getBytes());
client.connect("tcp://127.0.0.1:9000");
System.out.println("wh6");
// Send a single message from server to client
server.send("Hello");
System.out.println("wh7");
String message = client.recvStr(0,Charset.defaultCharset());
auth.destroy();
ctx.close();
return message;
}
public static void main(String[] args) {
try {
FileWriter write = new FileWriter("passwords");
write.write("guest=guest\n");
write.write("tourist=1234\n");
write.write("admin=secret\n");
write.close();
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
String result = woodhouse();
System.out.println(System.currentTimeMillis()+":"+result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment