OtrService.java

  1package eu.siacs.conversations.crypto;
  2
  3import android.util.Log;
  4
  5import net.java.otr4j.OtrEngineHost;
  6import net.java.otr4j.OtrException;
  7import net.java.otr4j.OtrPolicy;
  8import net.java.otr4j.OtrPolicyImpl;
  9import net.java.otr4j.crypto.OtrCryptoEngineImpl;
 10import net.java.otr4j.crypto.OtrCryptoException;
 11import net.java.otr4j.session.FragmenterInstructions;
 12import net.java.otr4j.session.InstanceTag;
 13import net.java.otr4j.session.SessionID;
 14
 15import org.json.JSONException;
 16import org.json.JSONObject;
 17
 18import java.math.BigInteger;
 19import java.security.KeyFactory;
 20import java.security.KeyPair;
 21import java.security.KeyPairGenerator;
 22import java.security.NoSuchAlgorithmException;
 23import java.security.PrivateKey;
 24import java.security.PublicKey;
 25import java.security.spec.DSAPrivateKeySpec;
 26import java.security.spec.DSAPublicKeySpec;
 27import java.security.spec.InvalidKeySpecException;
 28
 29import eu.siacs.conversations.Config;
 30import eu.siacs.conversations.entities.Account;
 31import eu.siacs.conversations.entities.Conversation;
 32import eu.siacs.conversations.services.XmppConnectionService;
 33import eu.siacs.conversations.xmpp.chatstate.ChatState;
 34import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 35import eu.siacs.conversations.xmpp.jid.Jid;
 36import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 37
 38public class OtrService extends OtrCryptoEngineImpl implements OtrEngineHost {
 39
 40	private Account account;
 41	private OtrPolicy otrPolicy;
 42	private KeyPair keyPair;
 43	private XmppConnectionService mXmppConnectionService;
 44
 45	public OtrService(XmppConnectionService service, Account account) {
 46		this.account = account;
 47		this.otrPolicy = new OtrPolicyImpl();
 48		this.otrPolicy.setAllowV1(false);
 49		this.otrPolicy.setAllowV2(true);
 50		this.otrPolicy.setAllowV3(true);
 51		this.keyPair = loadKey(account.getKeys());
 52		this.mXmppConnectionService = service;
 53	}
 54
 55	private KeyPair loadKey(JSONObject keys) {
 56		if (keys == null) {
 57			return null;
 58		}
 59		try {
 60			BigInteger x = new BigInteger(keys.getString("otr_x"), 16);
 61			BigInteger y = new BigInteger(keys.getString("otr_y"), 16);
 62			BigInteger p = new BigInteger(keys.getString("otr_p"), 16);
 63			BigInteger q = new BigInteger(keys.getString("otr_q"), 16);
 64			BigInteger g = new BigInteger(keys.getString("otr_g"), 16);
 65			KeyFactory keyFactory = KeyFactory.getInstance("DSA");
 66			DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, p, q, g);
 67			DSAPrivateKeySpec privateKeySpec = new DSAPrivateKeySpec(x, p, q, g);
 68			PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
 69			PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
 70			return new KeyPair(publicKey, privateKey);
 71		} catch (JSONException e) {
 72			return null;
 73		} catch (NoSuchAlgorithmException e) {
 74			return null;
 75		} catch (InvalidKeySpecException e) {
 76			return null;
 77		}
 78	}
 79
 80	private void saveKey() {
 81		PublicKey publicKey = keyPair.getPublic();
 82		PrivateKey privateKey = keyPair.getPrivate();
 83		KeyFactory keyFactory;
 84		try {
 85			keyFactory = KeyFactory.getInstance("DSA");
 86			DSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(
 87					privateKey, DSAPrivateKeySpec.class);
 88			DSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(publicKey,
 89					DSAPublicKeySpec.class);
 90			this.account.setKey("otr_x", privateKeySpec.getX().toString(16));
 91			this.account.setKey("otr_g", privateKeySpec.getG().toString(16));
 92			this.account.setKey("otr_p", privateKeySpec.getP().toString(16));
 93			this.account.setKey("otr_q", privateKeySpec.getQ().toString(16));
 94			this.account.setKey("otr_y", publicKeySpec.getY().toString(16));
 95		} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
 96			e.printStackTrace();
 97		}
 98
 99    }
100
101	@Override
102	public void askForSecret(SessionID id, InstanceTag instanceTag, String question) {
103		try {
104			final Jid jid = Jid.fromSessionID(id);
105			Conversation conversation = this.mXmppConnectionService.find(this.account,jid);
106			if (conversation!=null) {
107				conversation.smp().hint = question;
108				conversation.smp().status = Conversation.Smp.STATUS_CONTACT_REQUESTED;
109				mXmppConnectionService.updateConversationUi();
110			}
111		} catch (InvalidJidException e) {
112			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": smp in invalid session "+id.toString());
113		}
114	}
115
116	@Override
117	public void finishedSessionMessage(SessionID arg0, String arg1)
118			throws OtrException {
119
120	}
121
122	@Override
123	public String getFallbackMessage(SessionID arg0) {
124		return "I would like to start a private (OTR encrypted) conversation but your client doesn’t seem to support that";
125	}
126
127	@Override
128	public byte[] getLocalFingerprintRaw(SessionID arg0) {
129		try {
130			return getFingerprintRaw(getPublicKey());
131		} catch (OtrCryptoException e) {
132			return null;
133		}
134	}
135
136	public PublicKey getPublicKey() {
137		if (this.keyPair == null) {
138			return null;
139		}
140		return this.keyPair.getPublic();
141	}
142
143	@Override
144	public KeyPair getLocalKeyPair(SessionID arg0) throws OtrException {
145		if (this.keyPair == null) {
146			KeyPairGenerator kg;
147			try {
148				kg = KeyPairGenerator.getInstance("DSA");
149				this.keyPair = kg.genKeyPair();
150				this.saveKey();
151				mXmppConnectionService.databaseBackend.updateAccount(account);
152			} catch (NoSuchAlgorithmException e) {
153				Log.d(Config.LOGTAG,
154						"error generating key pair " + e.getMessage());
155			}
156		}
157		return this.keyPair;
158	}
159
160	@Override
161	public String getReplyForUnreadableMessage(SessionID arg0) {
162		// TODO Auto-generated method stub
163		return null;
164	}
165
166	@Override
167	public OtrPolicy getSessionPolicy(SessionID arg0) {
168		return otrPolicy;
169	}
170
171	@Override
172	public void injectMessage(SessionID session, String body)
173			throws OtrException {
174		MessagePacket packet = new MessagePacket();
175		packet.setFrom(account.getJid());
176		if (session.getUserID().isEmpty()) {
177			packet.setAttribute("to", session.getAccountID());
178		} else {
179			packet.setAttribute("to", session.getAccountID() + "/" + session.getUserID());
180		}
181		packet.setBody(body);
182		packet.addChild("private", "urn:xmpp:carbons:2");
183		packet.addChild("no-copy", "urn:xmpp:hints");
184		packet.addChild("no-permanent-store", "urn:xmpp:hints");
185		packet.addChild("no-permanent-storage", "urn:xmpp:hints");
186		try {
187			Jid jid = Jid.fromSessionID(session);
188			Conversation conversation = mXmppConnectionService.find(account,jid);
189			if (conversation != null && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
190				if (mXmppConnectionService.sendChatStates()) {
191					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
192				}
193			}
194		} catch (final InvalidJidException ignored) {
195
196		}
197
198		packet.setType(MessagePacket.TYPE_CHAT);
199		account.getXmppConnection().sendMessagePacket(packet);
200	}
201
202	@Override
203	public void messageFromAnotherInstanceReceived(SessionID session) {
204		sendOtrErrorMessage(session, "Message from another OTR-instance received");
205	}
206
207	@Override
208	public void multipleInstancesDetected(SessionID arg0) {
209		// TODO Auto-generated method stub
210
211	}
212
213	@Override
214	public void requireEncryptedMessage(SessionID arg0, String arg1)
215			throws OtrException {
216		// TODO Auto-generated method stub
217
218	}
219
220	@Override
221	public void showError(SessionID arg0, String arg1) throws OtrException {
222		Log.d(Config.LOGTAG,"show error");
223	}
224
225	@Override
226	public void smpAborted(SessionID id) throws OtrException {
227		setSmpStatus(id, Conversation.Smp.STATUS_NONE);
228	}
229
230	private void setSmpStatus(SessionID id, int status) {
231		try {
232			final Jid jid = Jid.fromSessionID(id);
233			Conversation conversation = this.mXmppConnectionService.find(this.account,jid);
234			if (conversation!=null) {
235				conversation.smp().status = status;
236				mXmppConnectionService.updateConversationUi();
237			}
238		} catch (final InvalidJidException ignored) {
239
240		}
241	}
242
243	@Override
244	public void smpError(SessionID id, int arg1, boolean arg2)
245			throws OtrException {
246		setSmpStatus(id, Conversation.Smp.STATUS_NONE);
247	}
248
249	@Override
250	public void unencryptedMessageReceived(SessionID arg0, String arg1)
251			throws OtrException {
252		throw new OtrException(new Exception("unencrypted message received"));
253	}
254
255	@Override
256	public void unreadableMessageReceived(SessionID session) throws OtrException {
257		Log.d(Config.LOGTAG,"unreadable message received");
258		sendOtrErrorMessage(session, "You sent me an unreadable OTR-encrypted message");
259	}
260
261	public void sendOtrErrorMessage(SessionID session, String errorText) {
262		try {
263			Jid jid = Jid.fromSessionID(session);
264			Conversation conversation = mXmppConnectionService.find(account, jid);
265			String id = conversation == null ? null : conversation.getLastReceivedOtrMessageId();
266			if (id != null) {
267				MessagePacket packet = mXmppConnectionService.getMessageGenerator()
268						.generateOtrError(jid, id, errorText);
269				packet.setFrom(account.getJid());
270				mXmppConnectionService.sendMessagePacket(account,packet);
271				Log.d(Config.LOGTAG,packet.toString());
272				Log.d(Config.LOGTAG,account.getJid().toBareJid().toString()
273						+": unreadable OTR message in "+conversation.getName());
274			}
275		} catch (InvalidJidException e) {
276			return;
277		}
278	}
279
280	@Override
281	public void unverify(SessionID id, String arg1) {
282		setSmpStatus(id, Conversation.Smp.STATUS_FAILED);
283	}
284
285	@Override
286	public void verify(SessionID id, String fingerprint, boolean approved) {
287		Log.d(Config.LOGTAG,"OtrService.verify("+id.toString()+","+fingerprint+","+String.valueOf(approved)+")");
288		try {
289			final Jid jid = Jid.fromSessionID(id);
290			Conversation conversation = this.mXmppConnectionService.find(this.account,jid);
291			if (conversation!=null) {
292				if (approved) {
293					conversation.getContact().addOtrFingerprint(fingerprint);
294				}
295				conversation.smp().hint = null;
296				conversation.smp().status = Conversation.Smp.STATUS_VERIFIED;
297				mXmppConnectionService.updateConversationUi();
298				mXmppConnectionService.syncRosterToDisk(conversation.getAccount());
299			}
300		} catch (final InvalidJidException ignored) {
301		}
302	}
303
304	@Override
305	public FragmenterInstructions getFragmenterInstructions(SessionID sessionID) {
306		return null;
307	}
308
309}