aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/SignatureManager.java
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2023-01-05 11:00:50 +0300
committerGravatar Vitaly Takmazov2023-01-05 20:58:47 +0300
commitcdd03aa64548810591e043fb59a287a1b36c92ba (patch)
tree665ad1e3f1162d0be76c95a814ec4500bcf5ce55 /src/main/java/com/juick/SignatureManager.java
parent120b26c55069f89cc60ef862514d5cf09566f348 (diff)
ActivityPub: signed GET requests, fix Signature verification
Diffstat (limited to 'src/main/java/com/juick/SignatureManager.java')
-rw-r--r--src/main/java/com/juick/SignatureManager.java200
1 files changed, 0 insertions, 200 deletions
diff --git a/src/main/java/com/juick/SignatureManager.java b/src/main/java/com/juick/SignatureManager.java
deleted file mode 100644
index 792cc8cd..00000000
--- a/src/main/java/com/juick/SignatureManager.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2008-2022, Juick
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-package com.juick;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.juick.model.AnonymousUser;
-import com.juick.model.User;
-import com.juick.service.UserService;
-import com.juick.service.activities.DeleteUserEvent;
-import com.juick.util.DateFormattersHolder;
-import com.juick.www.api.activity.model.Context;
-import com.juick.www.api.activity.model.objects.Actor;
-import com.juick.www.api.webfinger.model.Account;
-import com.juick.www.api.webfinger.model.Link;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.cache.annotation.Cacheable;
-import org.springframework.context.ApplicationEventPublisher;
-import org.springframework.http.*;
-import org.springframework.web.client.RestClientException;
-import org.springframework.web.client.RestTemplate;
-import org.springframework.web.util.UriComponentsBuilder;
-import org.tomitribe.auth.signatures.Base64;
-import org.tomitribe.auth.signatures.*;
-import rocks.xmpp.addr.Jid;
-
-import javax.inject.Inject;
-import java.io.IOException;
-import java.net.URI;
-import java.security.Key;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.SignatureException;
-import java.time.Instant;
-import java.util.*;
-
-import static com.juick.www.api.activity.model.Context.ACTIVITY_MEDIA_TYPE;
-
-public class SignatureManager {
- private static final Logger logger = LoggerFactory.getLogger("ActivityPub");
- @Inject
- private KeystoreManager keystoreManager;
- @Inject
- private ObjectMapper jsonMapper;
- @Inject
- private UserService userService;
- @Inject
- private RestTemplate apClient;
- @Inject
- private ApplicationEventPublisher applicationEventPublisher;
-
- public void post(Actor from, Actor to, Context data) throws IOException, NoSuchAlgorithmException {
- UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(to.getInbox());
- URI inbox = uriComponentsBuilder.build().toUri();
- Instant now = Instant.now();
- String requestDate = DateFormattersHolder.getHttpDateFormatter().format(now);
- String host = inbox.getPort() > 0 ? String.format("%s:%d", inbox.getHost(), inbox.getPort()) : inbox.getHost();
- var finalContext = Context.build(data);
- var payload = jsonMapper.writeValueAsString(finalContext);
- final byte[] digest = MessageDigest.getInstance("SHA-256").digest(payload.getBytes()); // (1)
- final String digestHeader = "SHA-256=" + new String(Base64.encodeBase64(digest));
- String signatureString = addSignature(from, host, "POST", inbox.getPath(), requestDate, digestHeader);
-
- HttpHeaders requestHeaders = new HttpHeaders();
- requestHeaders.add("Content-Type", Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE);
- requestHeaders.add("Date", requestDate);
- requestHeaders.add("Host", host);
- requestHeaders.add("Digest", digestHeader);
- requestHeaders.add("Signature", signatureString);
- HttpEntity<String> request = new HttpEntity<>(payload, requestHeaders);
- logger.debug("Sending context to {}: {}", to.getId(), payload);
- ResponseEntity<Void> response = apClient.postForEntity(inbox, request, Void.class);
- logger.debug("Remote response: {}", response.getStatusCode());
- }
-
- public String addSignature(Actor from, String host, String method, String path, String dateString,
- String digestHeader) throws IOException {
- return addSignature(from, host, method, path, dateString, digestHeader, keystoreManager);
- }
-
- public String addSignature(Actor from, String host, String method, String path, String dateString,
- String digestHeader, KeystoreManager keystoreManager) throws IOException {
- List<String> requiredHeaders = StringUtils.isEmpty(digestHeader)
- ? Arrays.asList("(request-target)", "host", "date")
- : Arrays.asList("(request-target)", "host", "date", "digest");
- Signature templateSignature = new Signature(from.getPublicKey().getId(), "rsa-sha256", null, requiredHeaders);
- Map<String, String> headers = new HashMap<>();
- headers.put("host", host);
- headers.put("date", dateString);
- if (StringUtils.isNotEmpty(digestHeader)) {
- headers.put("digest", digestHeader);
- }
- Signer signer = new Signer(keystoreManager.getPrivateKey(), templateSignature);
- Signature signature = signer.sign(method, path, headers);
- // remove "Signature: " from result
- return signature.toString().substring(10);
- }
-
- public User verifySignature(String method, String path, Map<String, String> headers) {
- String signatureString = headers.get("signature");
- Signature signature = Signature.fromString(signatureString);
- var keyId = UriComponentsBuilder.fromUriString(signature.getKeyId()).fragment(null).build().toUri();
- var context = getContext(keyId);
- if (context.isPresent() && context.get() instanceof Actor actor) {
- Key key = KeystoreManager.publicKeyOf(actor);
- if (key != null) {
- Verifier verifier = new Verifier(key, signature);
- try {
- boolean result = verifier.verify(method, path, headers);
- if (result) {
- User user = new User();
- user.setUri(URI.create(actor.getId()));
- if (key.equals(keystoreManager.getPublicKey())) {
- return userService.getUserByName(actor.getName());
- }
- if (actor.isSuspended()) {
- logger.info("{} is suspended, deleting", actor.getId());
- applicationEventPublisher.publishEvent(new DeleteUserEvent(this, actor.getId()));
- }
- return user;
- } else {
- return AnonymousUser.INSTANCE;
- }
- } catch (NoSuchAlgorithmException | SignatureException | MissingRequiredHeaderException
- | IOException e) {
- logger.warn("Verification error for {}: {}", signature.getKeyId(), e.getMessage());
- }
- } else {
- logger.warn("Public key missing for {}", actor.getId());
- }
- } else {
- logger.warn("Public key error for {}", signature.getKeyId());
- }
- return AnonymousUser.INSTANCE;
- }
-
- @Cacheable("profiles")
- public Optional<Context> getContext(URI contextUri) {
- try {
- HttpHeaders headers = new HttpHeaders();
- headers.setAccept(Collections.singletonList(MediaType.valueOf(ACTIVITY_MEDIA_TYPE)));
- HttpEntity<Void> activityRequest = new HttpEntity<>(headers);
- var response = apClient.exchange(contextUri, HttpMethod.GET, activityRequest, Context.class);
- if (response.getStatusCode().is2xxSuccessful() && response.hasBody()) {
- var context = response.getBody();
- if (context == null) {
- logger.warn("Cannot identify {}", contextUri);
- return Optional.empty();
- }
- return Optional.of(context);
- }
- } catch (Exception e) {
- logger.warn("{}", e.getMessage());
- }
- return Optional.empty();
- }
-
- public Optional<Context> discoverPerson(String acct) {
- Jid acctId = Jid.of(acct);
- URI resourceUri = UriComponentsBuilder.fromPath("/.well-known/webfinger").host(acctId.getDomain())
- .scheme("https").queryParam("resource", "acct:" + acct).build().toUri();
- HttpHeaders headers = new HttpHeaders();
- headers.setAccept(Collections.singletonList(MediaType.valueOf("application/jrd+json")));
- HttpEntity<Void> webfingerRequest = new HttpEntity<>(headers);
- try {
- ResponseEntity<Account> response = apClient.exchange(resourceUri, HttpMethod.GET, webfingerRequest,
- Account.class);
- if (response.getStatusCode().is2xxSuccessful()) {
- Account acctData = response.getBody();
- if (acctData != null) {
- for (Link l : acctData.links()) {
- if (l.rel().equals("self") && l.type().equals(ACTIVITY_MEDIA_TYPE)) {
- return getContext(URI.create(l.href()));
- }
- }
- }
- }
- } catch (RestClientException e) {
- logger.warn("Cannot discover person {}: {}", acct, e.getMessage());
- return Optional.empty();
- }
- return Optional.empty();
- }
-}