aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/SignatureManager.java
blob: 0c6acb4ab85bc35439d0fd1670b429e487c70c9f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
 * Copyright (C) 2008-2020, 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.context.ApplicationEventPublisher;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
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.MissingRequiredHeaderException;
import org.tomitribe.auth.signatures.Signature;
import org.tomitribe.auth.signatures.Signer;
import org.tomitribe.auth.signatures.Verifier;
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.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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.info("Sending context to {}: {}", to.getId(), payload);
        ResponseEntity<Void> response = apClient.postForEntity(inbox, request, Void.class);
        logger.info("Remote response: {}", response.getStatusCodeValue());
    }

    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);
        Optional<Context> context = getContext(
                UriComponentsBuilder.fromUriString(signature.getKeyId()).fragment(null).build().toUri());
        if (context.isPresent() && context.get() instanceof Actor) {
            Actor actor = (Actor) context.get();
            Key key = KeystoreManager.publicKeyOf(actor);

            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("Invalid signature {}: {}", signatureString, e.getMessage());
            }
        } else {
            logger.warn("Unknown keyId");
        }
        return AnonymousUser.INSTANCE;
    }

    public Optional<Context> getContext(URI contextUri) {
        try {
            Context context = apClient.getForEntity(contextUri, Context.class).getBody();
            if (context == null) {
                logger.warn("Cannot identify {}", contextUri);
                return Optional.empty();
            }
            return Optional.of(context);
        } catch (Exception e) {
            logger.warn("REST Exception on {}: {}", contextUri, 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", String.format("%s", acctId.toEscapedString())).build().toUri();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "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.getLinks()) {
                        if (l.getRel().equals("self") && l.getType().equals(ACTIVITY_MEDIA_TYPE)) {
                            return getContext(URI.create(l.getHref()));
                        }
                    }
                }
            }
        } catch (RestClientException e) {
            logger.warn("Cannot discover person {}: {}", acct, e.getMessage());
            return Optional.empty();
        }
        return Optional.empty();
    }
}