OtrService.java

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