SNMP v1 trap send not working with snmp4j - java

I'm trying to send a trap v1 using snmp4j. It doesn't throwns any exception and execute everything, but the trap is not reaching its destiny. Am I missing something? Is there another way to do it? The IP and the ports in the code are corrects. What would be wrong?
Here's the code:
public class SNMPv1 {
public static final String community = "public";
public static final String trapOid = ".1.3.6.1.4.1.2595.1.2";
public static final String ipAddress = "10.200.1.220";
public static final String agentIPAddress = "10.200.1.120";
public static final int port = 164;
private static final int specificTrap = 1;
public static void main(String[] args)
{
SNMPv1 snmp4JTrap = new SNMPv1();
/* Sending V1 Trap */
snmp4JTrap.sendSnmpV1Trap();
}
public void sendSnmpV1Trap()
{
try
{
//Create Transport Mapping
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
//Create Target
CommunityTarget comtarget = new CommunityTarget();
comtarget.setCommunity(new OctetString(community));
comtarget.setVersion(SnmpConstants.version1);
comtarget.setAddress(new UdpAddress(ipAddress + "/" + port));
comtarget.setRetries(4);
comtarget.setTimeout(10000);
//Create PDU for V1
PDUv1 pdu = new PDUv1();
pdu.setType(PDU.V1TRAP);
pdu.setEnterprise(new OID(trapOid));
pdu.setGenericTrap(PDUv1.ENTERPRISE_SPECIFIC); // 6
pdu.setSpecificTrap(specificTrap);
pdu.setAgentAddress(new IpAddress(agentIPAddress));
VariableBinding v = new VariableBinding();
v.setOid(SnmpConstants.sysName);
v.setVariable(new OctetString("Param1"));
pdu.add(v);
VariableBinding v2 = new VariableBinding();
v2.setOid(SnmpConstants.sysName);
v2.setVariable(new OctetString("Param2"));
pdu.add(v2);
VariableBinding v3 = new VariableBinding();
v3.setOid(SnmpConstants.sysName);
v3.setVariable(new OctetString("Param3"));
pdu.add(v3);
VariableBinding v4 = new VariableBinding();
v4.setOid(SnmpConstants.sysName);
v4.setVariable(new OctetString("Param4"));
pdu.add(v4);
VariableBinding v5 = new VariableBinding();
v5.setOid(SnmpConstants.sysName);
v5.setVariable(new OctetString("Param5"));
pdu.add(v5);
VariableBinding v6 = new VariableBinding();
v6.setOid(SnmpConstants.sysName);
v6.setVariable(new OctetString("Param6"));
pdu.add(v6);
//Send the PDU
Snmp snmp = new Snmp(transport);
System.out.println("Sending trap to" + ipAddress + ":" + port);
snmp.send(pdu, comtarget);
snmp.close();
System.out.println("Trap send successfully!!");
}
catch (Exception e)
{
System.err.println("Error sending Trap to " + ipAddress + ":" + port);
System.err.println("Exception Message = " + e.getMessage());
}
}
}

Related

UDP Socket: java.net.SocketException: socket closed

MessageCreator: Encapsulate and resolve ports and device unique identifiers.
public class MessageCreator {
private static final String HEADER_PORT = "to port:";
private static final String HEADER_SN = "My sn:";
public static String buildWithPort(int port) {
return HEADER_PORT + port;
}
public static int parsePort(String data) {
if (data.startsWith(HEADER_PORT)) {
return Integer.parseInt(data.substring(HEADER_PORT.length()));
}
return -1;
}
public static String buildWithSn(String sn) {
return HEADER_SN + sn;
}
public static String parseSn(String data) {
if (data.startsWith(HEADER_SN)) {
return data.substring(HEADER_SN.length());
}
return null;
}
}
UdpProvider: Loop to listen to a specific port, then parse the received data, determine whether the data conforms to the predetermined format, get the sender's response port from it, and respond with the uniquely identified UUID value to the UDP searcher.
public class UdpProvider {
public static void main(String[] args) throws IOException {
String sn = UUID.randomUUID().toString();
Provider provider = new Provider(sn);
provider.start();
// Warning: Result of 'InputStream.read()' is ignored
System.in.read();
provider.exit();
}
private static class Provider extends Thread {
private DatagramSocket ds = null;
private boolean done = false;
private final String sn;
public Provider(String sn) {
super();
this.sn = sn;
}
#Override
public void run() {
super.run();
try {
ds = new DatagramSocket(20000);
while (!done) {
final byte[] buf = new byte[512];
DatagramPacket receivePak = new DatagramPacket(buf, buf.length);
ds.receive(receivePak);
String ip = receivePak.getAddress().getHostAddress();
int port = receivePak.getPort();
byte[] receivePakData = receivePak.getData();
String receiveData = new String(receivePakData, 0, /*receivePakData.length*/receivePak.getLength());
System.out.println("received from -> ip: " + ip + ", port: " + port + ", data: " + receiveData);
int responsePort = MessageCreator.parsePort(receiveData.trim());
if (responsePort != -1) {
String responseData = MessageCreator.buildWithSn(sn);
byte[] bytes = responseData.getBytes(StandardCharsets.UTF_8);
DatagramPacket responsePak = new DatagramPacket(bytes, bytes.length,
/*InetAddress.getLocalHost()*/
receivePak.getAddress(),
responsePort);
ds.send(responsePak);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
public void exit() {
done = true;
close();
}
public void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
}
}
UdpSearcher: Listening to a specific port and sending a LAN broadcast, sending a broadcast sets the listening port in the data, so you need to turn on listening first to finish before you can send a broadcast, and once you receive the response data, you can parse the device information
public class UdpSearcher {
private static final int LISTENER_PORT = 30000;
public static void main(String[] args) throws IOException, InterruptedException {
Listener listener = listen();
sendBroadcast();
// Warning: Result of 'InputStream.read()' is ignored
System.in.read();
List<Device> deviceList = listener.getDevicesAndClose();
for (Device device : deviceList) {
System.out.println(device);
}
}
public static void sendBroadcast() throws IOException {
DatagramSocket ds = new DatagramSocket();
String sendData = MessageCreator.buildWithPort(LISTENER_PORT);
byte[] sendDataBytes = sendData.getBytes(StandardCharsets.UTF_8);
DatagramPacket sendPak = new DatagramPacket(sendDataBytes, sendDataBytes.length);
sendPak.setAddress(InetAddress.getByName("255.255.255.255"));
sendPak.setPort(20000);
ds.send(sendPak);
ds.close();
}
public static Listener listen() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
Listener listener = new Listener(LISTENER_PORT, countDownLatch);
listener.start();
countDownLatch.await();
return listener;
}
private static class Listener extends Thread {
private final int listenPort;
private DatagramSocket ds = null;
private boolean done = false;
private final CountDownLatch countDownLatch;
private List<Device> devices = new ArrayList<>();
public Listener(int listenPort, CountDownLatch countDownLatch) {
super();
this.listenPort = listenPort;
this.countDownLatch = countDownLatch;
}
#Override
public void run() {
super.run();
countDownLatch.countDown();
try {
ds = new DatagramSocket(listenPort);
while (!done) {
final byte[] buf = new byte[512];
DatagramPacket receivePak = new DatagramPacket(buf, buf.length);
ds.receive(receivePak);
String ip = receivePak.getAddress().getHostAddress();
int port = receivePak.getPort();
byte[] data = receivePak.getData();
String receiveData = new String(data, 0, /*data.length*/receivePak.getLength());
String sn = MessageCreator.parseSn(receiveData);
System.out.println("received from -> ip: " + ip + ", port: " + port + ", data: " + receiveData);
if (sn != null) {
Device device = new Device(ip, port, sn);
devices.add(device);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
public void close() {
if (ds != null) {
ds.close();
ds = null;
}
}
public List<Device> getDevicesAndClose() {
done = true;
close();
return devices;
}
}
private static class Device {
private String ip;
private int port;
private String sn;
public Device(String ip, int port, String sn) {
this.ip = ip;
this.port = port;
this.sn = sn;
}
#Override
public String toString() {
return "Device{" +
"ip='" + ip + '\'' +
", port=" + port +
", sn='" + sn + '\'' +
'}';
}
}
}
UdpProvider and UdpSearcher worked fine and printed corrresponding data until I input a char sequence from keyboard follwed by pressing Enter key on each console window, both threw an exception on this line ds.receive(receivePak); :

SNMP code that does not work with TCP

I got one example of SNMPV3 trap,it is working fine when i use DefaultUdpTransportMapping but when i use DefaultTcpTransportMapping ,it will return null response event.
I have also attached code below .
public class SnmpUtilSendTrapV3 {
private Snmp snmp = null;
private Address targetAddress = null;
// private TcpAddress targetAddress = null;
public void initComm() throws IOException {
targetAddress = new TcpAddress(Inet4Address.getLocalHost(), 162);
// targetAddress = GenericAddress.parse("127.0.0.1/162");
TransportMapping transport = new DefaultTcpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
}
/**
* send trap
*
* #throws IOException
*/
public void sendPDU() throws IOException {
UserTarget target = new UserTarget();
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
// snmp version
target.setVersion(SnmpConstants.version3);
// target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString("MD5DES"));
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
MPv3.createLocalEngineID()), 0);
usm.setEngineDiscoveryEnabled(true);
SecurityModels.getInstance().addSecurityModel(usm);
UsmUser user = new UsmUser(new OctetString("MD5DES"), AuthMD5.ID,
new OctetString("MD5DESUserAuthPassword"), PrivDES.ID,
new OctetString("MD5DESUserPrivPassword"));
snmp.getUSM().addUser(new OctetString("MD5DES"), user);
// create PDU
ScopedPDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.0"),
new OctetString("DemoTrapv3")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.5.0"),
new OctetString("Demo")));
pdu.setType(PDU.TRAP);
// send PDU to Agent and recieve Response
ResponseEvent respEvnt = snmp.send(pdu, target);
// analyze Response
if (respEvnt != null && respEvnt.getResponse() != null) {
Vector<VariableBinding> variableBindings = (Vector<VariableBinding>) respEvnt
.getResponse().getVariableBindings();
Vector<VariableBinding> recVBs = variableBindings;
for (int i = 0; i < recVBs.size(); i++) {
VariableBinding recVB = recVBs.elementAt(i);
System.out
.println(recVB.getOid() + " : " + recVB.getVariable());
}
}
snmp.close();
}
public static void main(String[] args) {
try {
SnmpUtilSendTrapV3 util = new SnmpUtilSendTrapV3();
util.initComm();
util.sendPDU();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class MultiThreadedTrapReceiver implements CommandResponder {
private Address address = GenericAddress.parse("0.0.0.0/162");
private int numDispatcherThreads = 2;
private OID authProtocol = AuthMD5.ID;
private OID privProtocol = PrivDES.ID;
private OctetString securityName = new OctetString("MD5DES");
private OctetString privPassphrase = new OctetString(
"MD5DESUserPrivPassword");
private OctetString authPassphrase = new OctetString(
"MD5DESUserAuthPassword");
public MultiThreadedTrapReceiver() {
try {
listen();
} catch (IOException ex) {
System.out.println(ex);
}
}
public synchronized void listen() throws IOException {
AbstractTransportMapping transport;
if (address instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping((TcpAddress) address);
} else {
transport = new DefaultUdpTransportMapping((UdpAddress) address);
}
ThreadPool threadPool = ThreadPool.create("DispatcherPool",
numDispatcherThreads);
MessageDispatcher mtDispatcher = new MultiThreadedMessageDispatcher(
threadPool, new MessageDispatcherImpl());
// add message processing models
mtDispatcher.addMessageProcessingModel(new MPv1());
mtDispatcher.addMessageProcessingModel(new MPv2c());
mtDispatcher.addMessageProcessingModel(new MPv3(new OctetString(MPv3
.createLocalEngineID()).getValue()));
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
Snmp snmp = new Snmp(mtDispatcher, transport);
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
// Add the configured user to the USM
addUsmUser(snmp);
snmp.addCommandResponder(this);
transport.listen();
try {
this.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
private void addUsmUser(Snmp snmp) {
snmp.getUSM().addUser(
securityName,
new UsmUser(securityName, authProtocol, authPassphrase,
privProtocol, privPassphrase));
}
#Override
public void processPdu(CommandResponderEvent respEvnt) {
System.out.println(respEvnt.getPDU());
InetAddress pduAgentAddress = null;
// System.out.println(respEvnt.getPDU() + " recieved;");
// this.setPdu(respEvnt.getPDU());
OctetString community = new OctetString(respEvnt.getSecurityName());
System.out.println("community: " + community.toString());
// handle the SNMP v1
if (respEvnt.getPDU().getType() == PDU.V1TRAP) {
Address address = respEvnt.getPeerAddress();
String hostName = address.toString().split("/")[0];
int nPort = Integer.parseInt(address.toString().split("/")[1]);
try {
pduAgentAddress = InetAddress.getByName(hostName);
} catch (UnknownHostException ex) {
}
System.out.println("hostname: " + pduAgentAddress.getHostAddress()
+ "; port: " + nPort);
} else {
Address address = respEvnt.getPeerAddress();
String hostName = address.toString().split("/")[0];
int nPort = Integer.parseInt(address.toString().split("/")[1]);
try {
pduAgentAddress = InetAddress.getByName(hostName);
} catch (UnknownHostException ex) {
}
System.out.println("hostname: " + pduAgentAddress.getHostAddress()
+ "; port: " + nPort);
}
}
public static void main(String[] args) {
MultiThreadedTrapReceiver trap = new MultiThreadedTrapReceiver();
}
}
I have changed in SnmpUtilSendTrapV3 class,
.use TcpAddress targetAddress instead of Address targetAddress
use targetAddress = new TcpAddress(Inet4Address.getLocalHost(),
162); instead of targetAddress =
GenericAddress.parse("127.0.0.1/164");
TransportMapping transport = new DefaultTcpTransportMapping();
instead of TransportMapping transport = new
DefaultUdpTransportMapping();
after this implementation error is solved but , after sending pdu using snmp.send(pdu, target) everytime ResponseEvent have null value.
Anyone have a solution of this problem ,please help me

java client and C# server working with unicode

I'm trying to build a tcp client and a server that will work with unicode. the server is in C# and looks like that:
static void Main(string[] args)
{
// tcp setup
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
// waiting for client to connect
clientSocket = serverSocket.AcceptTcpClient();
// client comunication
string resAscii = Recv(clientSocket);
Send(clientSocket, "got from you: " + resAscii);
string resUnicode = Recv(clientSocket);
Send(clientSocket, "קיבלתי ממך: " + resUnicode);
Console.ReadKey();
}
public static void Send(TcpClient client, string msg)
{
Byte[] sendtBytes = Encoding.Unicode.GetBytes(msg + "$");
client.GetStream().Write(sendtBytes, 0, sendtBytes.Length);
client.GetStream().Flush();
}
public static string Recv(TcpClient client)
{
byte[] recvBytes = new byte[65537];
client.GetStream().Read(recvBytes, 0, (int)client.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.Unicode.GetString(recvBytes);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf('$'));
return dataFromClient;
}
and the client is in java (android):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
#Override
public void run() {
try {
Socket s = new Socket("192.168.0.102", 8888);
Send(s, "this is ascii");
String asciiString = Recv(s);
Send(s, "זה יוניקוד");
String unicodeString = Recv(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private String Recv(Socket s) throws IOException {
byte[] b = new byte[10080];
int read = s.getInputStream().read(b, 0, 1000);
String ret = new String(b, "UTF16");
ret = ret.substring(0, ret.indexOf('$'));
return ret;
}
private void Send(Socket s, String msg) throws IOException {
s.getOutputStream().write((msg + "$").getBytes("UTF16"));
}
When I'm sending from the client to the server I get the message. But when the server sending to the client I get only Chinese letters:
client (android) error
how can I fix it?
As #flakes said that was the answer.
change this line in the Recv function:
String ret = new String(b, "UTF16");
with this line:
String ret = new String(b, StandardCharsets.UTF_16LE);
and
s.getOutputStream().write((msg + "$").getBytes("UTF16"));
with this line in the Send file:
s.getOutputStream().write((msg + "$").getBytes(StandardCharsets.UTF_16LE));

access LTPA token outside of WebSphere context

I've a web app which is deployed in tomcat and from this web app, i have to consume a SOAP service which is deployed in Websphere. To access this service, i need to pass LTPA token. I'm very new to websphere, don't know how can i get LTPA token in my web app ? I can't modify the implementation of the app which is deployed in web sphere.
I could acheive this by using HttpBasicAuthentication. Here is the code snippet -
public class TokenHelper {
private static Logger logger = LoggerFactory.getLogger(TokenHelper.class);
private static final int HTTP_TIMEOUT_MILISEC = 100000;
private static String lineSeparator = System.getProperty("line.separator");
#Value("#{'${hostname}'}")
private String hostName;
#Value("#{'${port}'}")
private int port;
#Value("#{'${contextpath}'}")
private String contextPath;
#Value("#{'${isbasicauthentication}'}")
private boolean isBasicAuthentication;
#Value("#{'${username}'}")
private String basicAuthenticationUserName;
#Value("#{'${userpassword}'}")
private String basicAuthenticationPassword;
public Map<String, String> getLtpaToken() throws Exception {
Cookie[] cookies = null;
Protocol protocol = null;
Map<String, String> cookiesMap = new HashMap<String, String>();
GetMethod method = new GetMethod();
HttpClient client = new HttpClient();
method.getParams().setSoTimeout(HTTP_TIMEOUT_MILISEC);
protocol = new Protocol("http", new DefaultProtocolSocketFactory(), getPort());
if (isBasicAuthentication) {
client.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(getBasicAuthenticationUserName(), getBasicAuthenticationPassword());
client.getState().setCredentials(new AuthScope(getHostName(), getPort(), AuthScope.ANY_REALM), defaultcreds);
}
// Execute request
try {
client.getHostConfiguration().setHost(getHostName(), getPort(), protocol);
method = new GetMethod(getContextPath());
method.setFollowRedirects(true);
logger.info(methodName, "URL to get:" + getContextPath());
// Execute the GET method
int statusCode = client.executeMethod(method);
if (statusCode != -1) {
cookies = client.getState().getCookies();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < cookies.length; j++) {
cookiesMap.put(cookies[j].getName(), cookies[j].getValue());
sb.append("CookieName=" + cookies[j].getName() + lineSeparator);
sb.append("Value=" + cookies[j].getValue() + lineSeparator);
sb.append("Domain=" + cookies[j].getDomain() + lineSeparator);
}
sb.append("Status Text>>>" + HttpStatus.getStatusText(statusCode));
logger.debug("Cookies are: {}" + sb.toString());
method.releaseConnection();
}
} catch (Exception e) {
logger.error("Error while getting LTPA token using HttpBasicAuthentication for URL {}" +e);
throw new RuntimeException("Error while getting LTPA token using HttpBasicAuthentication for URL:" + contextPath, e);
} finally {
// Release current connection to the connection pool once you
// are done
method.releaseConnection();
}
return cookiesMap;
}

XMPP with Java Asmack library supporting X-FACEBOOK-PLATFORM

I'm trying to make a Facebook Chat on Android with the Smack library. I've read the Chat API from Facebook, but I cannot understand how I have to authenticate with Facebook using this library.
Can anyone point me how to accomplish this?
Update: According to the no.good.at.coding answer, I have this code adapted to the Asmack library. All works fine except I receive as response to the login: not-authorized. Here is the code I use:
public class SASLXFacebookPlatformMechanism extends SASLMechanism
{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String applicationSecret = "";
private String sessionKey = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException
{
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKeyAndSessionKey, String host,
String applicationSecret) throws IOException, XMPPException
{
if (apiKeyAndSessionKey == null || applicationSecret == null)
{
throw new IllegalArgumentException("Invalid parameters");
}
String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
if (keyArray.length < 2)
{
throw new IllegalArgumentException(
"API key or session key is not present");
}
this.apiKey = keyArray[0];
Log.d("API_KEY", apiKey);
this.applicationSecret = applicationSecret;
Log.d("SECRET_KEY", applicationSecret);
this.sessionKey = keyArray[1];
Log.d("SESSION_KEY", sessionKey);
this.authenticationId = sessionKey;
this.password = applicationSecret;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
this);
authenticate();
}
#Override
protected String getName()
{
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException
{
byte[] response = null;
if (challenge != null)
{
String decodedChallenge = new String(Base64.decode(challenge));
Log.d("DECODED", decodedChallenge);
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis() / 1000L;
String sig =
"api_key=" + apiKey + "call_id=" + callId + "method="
+ method + "nonce=" + nonce + "session_key="
+ sessionKey + "v=" + version + applicationSecret;
try
{
sig = md5(sig);
sig = sig.toUpperCase();
} catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException(e);
}
String composedResponse =
"api_key=" + URLEncoder.encode(apiKey, "utf-8")
+ "&call_id=" + callId + "&method="
+ URLEncoder.encode(method, "utf-8") + "&nonce="
+ URLEncoder.encode(nonce, "utf-8")
+ "&session_key="
+ URLEncoder.encode(sessionKey, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8") + "&sig="
+ URLEncoder.encode(sig, "utf-8");
Log.d("COMPOSED", composedResponse);
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null)
{
authenticationText =
Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query)
{
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params)
{
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
private String md5(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("utf-8"), 0, text.length());
return convertToHex(md.digest());
}
private String convertToHex(byte[] data)
{
StringBuilder buf = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i++)
{
int halfByte = (data[i] >>> 4) & 0xF;
int twoHalfs = 0;
do
{
if (0 <= halfByte && halfByte <= 9)
{
buf.append((char) ('0' + halfByte));
}
else
{
buf.append((char) ('a' + halfByte - 10));
}
halfByte = data[i] & 0xF;
} while (twoHalfs++ < 1);
}
return buf.toString();
}
}
And this, is the communication with the server with the sent and received messages:
PM SENT (1132418216): <stream:stream to="chat.facebook.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0">
PM RCV (1132418216): <?xml version="1.0"?><stream:stream id="C62D0F43" from="chat.facebook.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xml:lang="en"><stream:features><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>X-FACEBOOK-PLATFORM</mechanism><mechanism>DIGEST-MD5</mechanism></mechanisms></stream:features>
PM SENT (1132418216): <auth mechanism="X-FACEBOOK-PLATFORM" xmlns="urn:ietf:params:xml:ns:xmpp-sasl"></auth>
PM RCV (1132418216): <challenge xmlns="urn:ietf:params:xml:ns:xmpp-sasl">dmVyc2lvbj0xJm1ldGhvZD1hdXRoLnhtcHBfbG9naW4mbm9uY2U9NzFGNkQ3Rjc5QkIyREJCQ0YxQTkwMzA0QTg3OTlBMzM=</challenge>
PM SENT (1132418216): <response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">YXBpX2tleT0zMWYzYjg1ZjBjODYwNjQ3NThiZTZhOTQyNjVjZmNjMCZjYWxsX2lkPTEzMDA0NTYxMzUmbWV0aG9kPWF1dGgueG1wcF9sb2dpbiZub25jZT03MUY2RDdGNzlCQjJEQkJDRjFBOTAzMDRBODc5OUEzMyZzZXNzaW9uX2tleT0yNjUzMTg4ODNkYWJhOGRlOTRiYTk4ZDYtMTAwMDAwNTAyNjc2Nzc4JnY9MS4wJnNpZz04RkRDRjRGRTgzMENGOEQ3QjgwNjdERUQyOEE2RERFQw==</response>
PM RCV (1132418216): <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>
As read in the developers Facebook forum, it is needed to disable the "Disable Deprecated Auth Methods" setting from the Facebook settings page of your app. But, even doing that, I can't login. And the session key is the second part of the OAuth token in the form AAA|BBB|CCC, I mean, BBB.
Finally, thanks to the no.good.at.coding code and the suggestion of harism, I've been able to connect to the Facebook chat. This code is the Mechanism for the Asmack library (the Smack port for Android). For the Smack library is necessary to use the no.good.at.coding mechanism.
SASLXFacebookPlatformMechanism.java:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.harmony.javax.security.auth.callback.CallbackHandler;
import org.apache.harmony.javax.security.sasl.Sasl;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.sasl.SASLMechanism;
import org.jivesoftware.smack.util.Base64;
public class SASLXFacebookPlatformMechanism extends SASLMechanism
{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String applicationSecret = "";
private String sessionKey = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException
{
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKeyAndSessionKey, String host,
String applicationSecret) throws IOException, XMPPException
{
if (apiKeyAndSessionKey == null || applicationSecret == null)
{
throw new IllegalArgumentException("Invalid parameters");
}
String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
if (keyArray.length < 2)
{
throw new IllegalArgumentException(
"API key or session key is not present");
}
this.apiKey = keyArray[0];
this.applicationSecret = applicationSecret;
this.sessionKey = keyArray[1];
this.authenticationId = sessionKey;
this.password = applicationSecret;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh)
throws IOException, XMPPException
{
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
cbh);
authenticate();
}
#Override
protected String getName()
{
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException
{
byte[] response = null;
if (challenge != null)
{
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String sig =
"api_key=" + apiKey + "call_id=" + callId + "method="
+ method + "nonce=" + nonce + "session_key="
+ sessionKey + "v=" + version + applicationSecret;
try
{
sig = md5(sig);
} catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException(e);
}
String composedResponse =
"api_key=" + URLEncoder.encode(apiKey, "utf-8")
+ "&call_id=" + callId + "&method="
+ URLEncoder.encode(method, "utf-8") + "&nonce="
+ URLEncoder.encode(nonce, "utf-8")
+ "&session_key="
+ URLEncoder.encode(sessionKey, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8") + "&sig="
+ URLEncoder.encode(sig, "utf-8");
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null)
{
authenticationText =
Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query)
{
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params)
{
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
private String md5(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("utf-8"), 0, text.length());
return convertToHex(md.digest());
}
private String convertToHex(byte[] data)
{
StringBuilder buf = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i++)
{
int halfByte = (data[i] >>> 4) & 0xF;
int twoHalfs = 0;
do
{
if (0 <= halfByte && halfByte <= 9)
{
buf.append((char) ('0' + halfByte));
}
else
{
buf.append((char) ('a' + halfByte - 10));
}
halfByte = data[i] & 0xF;
} while (twoHalfs++ < 1);
}
return buf.toString();
}
}
To use it:
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
config.setSASLAuthenticationEnabled(true);
XMPPConnection xmpp = new XMPPConnection(config);
try
{
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM", SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
xmpp.connect();
xmpp.login(apiKey + "|" + sessionKey, sessionSecret, "Application");
} catch (XMPPException e)
{
xmpp.disconnect();
e.printStackTrace();
}
apiKey is the API key given in the application settings page in Facebook. sessionKey is the second part of the access token. If the token is in this form, AAA|BBB|CCC, the BBB is the session key. sessionSecret is obtained using the old REST API with the method auth.promoteSession. To use it, it's needed to make a Http get to this url:
https://api.facebook.com/method/auth.promoteSession?access_token=yourAccessToken
Despite of the Facebook Chat documentation says that it's needed to use your application secret key, only when I used the key that returned that REST method I was able to make it works. To make that method works, you have to disable the Disable Deprecated Auth Methods option in the Advance tab in your application settings.
I'd used this about 6 months ago with Smack (not asmack) so I'm not sure how it'll hold up now but here goes, hope it helps!
I found an implementation of Facebook's X-FACEBOOK-PLATFORM authentication mechanism on the Ignite Realtime Smack forum where someone got it from the fbgc project. You'll find the a ZIP with the SASLXFacebookPlatformMechanism.java source in the answer I linked to. You can use it as follows:
public void login() throws XMPPException
{
SASLAuthentication.registerSASLMechanism(SASLXFacebookPlatformMechanism.NAME,
SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism(SASLXFacebookPlatformMechanism.NAME, 0);
ConnectionConfiguration connConfig = new ConnectionConfiguration(host, port);
XMPPConnection connection = new XMPPConnection(connConfig);
connection.connect();
log.info("XMPP client connected");
connection.login(Utils.FB_APP_ID + "|" + this.user.sessionId, Utils.FB_APP_SECRET, "app_name");
log.info("XMPP client logged in");
}
I was doing this on the server without an SDK. I don't remember the details (and the Facebook documentation isn't very good) but from what I can tell from my code, after getting the user to authorize the app, I get a callback request from Facebook with a code parameter. I open a URLConnection to https://graph.facebook.com/oauth/access_token?client_id=<app_id>&redirect_uri=http://myserver/context/path/&client_secret=<app_secret>&code=<code>. The response should be the access token where the session id is the part after the | - something of the form XXX|<sessionId>.
Here's code I've been using successfully for authentication. Maybe this helps even though this is not related to Smack in any way. You can get sessionKey from access token received from FB, and for getting sessionSecret I've been using oldish REST API;
http://developers.facebook.com/docs/reference/rest/auth.promoteSession/
private final void processChallenge(XmlPullParser parser, Writer writer,
String sessionKey, String sessionSecret) throws IOException,
NoSuchAlgorithmException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, null, "challenge");
String challenge = new String(Base64.decode(parser.nextText(),
Base64.DEFAULT));
String params[] = challenge.split("&");
HashMap<String, String> paramMap = new HashMap<String, String>();
for (int i = 0; i < params.length; ++i) {
String p[] = params[i].split("=");
p[0] = URLDecoder.decode(p[0]);
p[1] = URLDecoder.decode(p[1]);
paramMap.put(p[0], p[1]);
}
String api_key = "YOUR_API_KEY";
String call_id = "" + System.currentTimeMillis();
String method = paramMap.get("method");
String nonce = paramMap.get("nonce");
String v = "1.0";
StringBuffer sigBuffer = new StringBuffer();
sigBuffer.append("api_key=" + api_key);
sigBuffer.append("call_id=" + call_id);
sigBuffer.append("method=" + method);
sigBuffer.append("nonce=" + nonce);
sigBuffer.append("session_key=" + sessionKey);
sigBuffer.append("v=" + v);
sigBuffer.append(sessionSecret);
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(sigBuffer.toString().getBytes());
byte[] digest = md.digest();
StringBuffer sig = new StringBuffer();
for (int i = 0; i < digest.length; ++i) {
sig.append(Integer.toHexString(0xFF & digest[i]));
}
StringBuffer response = new StringBuffer();
response.append("api_key=" + URLEncoder.encode(api_key));
response.append("&call_id=" + URLEncoder.encode(call_id));
response.append("&method=" + URLEncoder.encode(method));
response.append("&nonce=" + URLEncoder.encode(nonce));
response.append("&session_key=" + URLEncoder.encode(sessionKey));
response.append("&v=" + URLEncoder.encode(v));
response.append("&sig=" + URLEncoder.encode(sig.toString()));
StringBuilder out = new StringBuilder();
out.append("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>");
out.append(Base64.encodeToString(response.toString().getBytes(),
Base64.NO_WRAP));
out.append("</response>");
writer.write(out.toString());
writer.flush();
}
I'm sorry to make new answer but I had to include the new code #YShinkarev sorry for being late
By modifying #Adrian answer to make challengeReceived we can use APIKey and accessToken all I modified was the composedResponse
#Override
public void challengeReceived(String challenge) throws IOException {
byte[] response = null;
if (challenge != null) {
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String composedResponse = "api_key="
+ URLEncoder.encode(apiKey, "utf-8") + "&call_id=" + callId
+ "&method=" + URLEncoder.encode(method, "utf-8")
+ "&nonce=" + URLEncoder.encode(nonce, "utf-8")
+ "&access_token="
+ URLEncoder.encode(access_token, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8");
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null) {
authenticationText = Base64.encodeBytes(response,
Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
What do you want to do?
If you just want to login on FB chat, you connect to FB just like any other XMPP server.
I would look at and use "Authenticating with Username/Password" from Chat API, wich is supported by Smack. Unless I would like to write an FaceBook-application. Then I would try to login in with "Authenticating with Facebook Platform".
So, just use Smack to connect to FB chat as you would do with your ordinary Jabber client.
For the username, use your Facebook username. (see http://www.facebook.com/username/ )
For the domain, use: chat.facebook.com
For the password, use your Facebook password
Turn off SSL and TSL
Set connect port to: 5222 (which is the default for XMPP)
Set connect server to chat.facebook.com

Categories