Merge branch 'features/admin-api-user-views' into 'develop'
[akkoma] / lib / pleroma / web / salmon / salmon.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Salmon do
6 @httpoison Application.get_env(:pleroma, :httpoison)
7
8 use Bitwise
9 alias Pleroma.Web.XML
10 alias Pleroma.Web.OStatus.ActivityRepresenter
11 alias Pleroma.User
12 require Logger
13
14 def decode(salmon) do
15 doc = XML.parse_document(salmon)
16
17 {:xmlObj, :string, data} = :xmerl_xpath.string('string(//me:data[1])', doc)
18 {:xmlObj, :string, sig} = :xmerl_xpath.string('string(//me:sig[1])', doc)
19 {:xmlObj, :string, alg} = :xmerl_xpath.string('string(//me:alg[1])', doc)
20 {:xmlObj, :string, encoding} = :xmerl_xpath.string('string(//me:encoding[1])', doc)
21 {:xmlObj, :string, type} = :xmerl_xpath.string('string(//me:data[1]/@type)', doc)
22
23 {:ok, data} = Base.url_decode64(to_string(data), ignore: :whitespace)
24 {:ok, sig} = Base.url_decode64(to_string(sig), ignore: :whitespace)
25 alg = to_string(alg)
26 encoding = to_string(encoding)
27 type = to_string(type)
28
29 [data, type, encoding, alg, sig]
30 end
31
32 def fetch_magic_key(salmon) do
33 with [data, _, _, _, _] <- decode(salmon),
34 doc <- XML.parse_document(data),
35 uri when not is_nil(uri) <- XML.string_from_xpath("/entry/author[1]/uri", doc),
36 {:ok, public_key} <- User.get_public_key_for_ap_id(uri),
37 magic_key <- encode_key(public_key) do
38 {:ok, magic_key}
39 end
40 end
41
42 def decode_and_validate(magickey, salmon) do
43 [data, type, encoding, alg, sig] = decode(salmon)
44
45 signed_text =
46 [data, type, encoding, alg]
47 |> Enum.map(&Base.url_encode64/1)
48 |> Enum.join(".")
49
50 key = decode_key(magickey)
51
52 verify = :public_key.verify(signed_text, :sha256, sig, key)
53
54 if verify do
55 {:ok, data}
56 else
57 :error
58 end
59 end
60
61 def decode_key("RSA." <> magickey) do
62 make_integer = fn bin ->
63 list = :erlang.binary_to_list(bin)
64 Enum.reduce(list, 0, fn el, acc -> acc <<< 8 ||| el end)
65 end
66
67 [modulus, exponent] =
68 magickey
69 |> String.split(".")
70 |> Enum.map(fn n -> Base.url_decode64!(n, padding: false) end)
71 |> Enum.map(make_integer)
72
73 {:RSAPublicKey, modulus, exponent}
74 end
75
76 def encode_key({:RSAPublicKey, modulus, exponent}) do
77 modulus_enc = :binary.encode_unsigned(modulus) |> Base.url_encode64()
78 exponent_enc = :binary.encode_unsigned(exponent) |> Base.url_encode64()
79
80 "RSA.#{modulus_enc}.#{exponent_enc}"
81 end
82
83 # Native generation of RSA keys is only available since OTP 20+ and in default build conditions
84 # We try at compile time to generate natively an RSA key otherwise we fallback on the old way.
85 try do
86 _ = :public_key.generate_key({:rsa, 2048, 65537})
87
88 def generate_rsa_pem do
89 key = :public_key.generate_key({:rsa, 2048, 65537})
90 entry = :public_key.pem_entry_encode(:RSAPrivateKey, key)
91 pem = :public_key.pem_encode([entry]) |> String.trim_trailing()
92 {:ok, pem}
93 end
94 rescue
95 _ ->
96 def generate_rsa_pem do
97 port = Port.open({:spawn, "openssl genrsa"}, [:binary])
98
99 {:ok, pem} =
100 receive do
101 {^port, {:data, pem}} -> {:ok, pem}
102 end
103
104 Port.close(port)
105
106 if Regex.match?(~r/RSA PRIVATE KEY/, pem) do
107 {:ok, pem}
108 else
109 :error
110 end
111 end
112 end
113
114 def keys_from_pem(pem) do
115 [private_key_code] = :public_key.pem_decode(pem)
116 private_key = :public_key.pem_entry_decode(private_key_code)
117 {:RSAPrivateKey, _, modulus, exponent, _, _, _, _, _, _, _} = private_key
118 public_key = {:RSAPublicKey, modulus, exponent}
119 {:ok, private_key, public_key}
120 end
121
122 def encode(private_key, doc) do
123 type = "application/atom+xml"
124 encoding = "base64url"
125 alg = "RSA-SHA256"
126
127 signed_text =
128 [doc, type, encoding, alg]
129 |> Enum.map(&Base.url_encode64/1)
130 |> Enum.join(".")
131
132 signature =
133 signed_text
134 |> :public_key.sign(:sha256, private_key)
135 |> to_string
136 |> Base.url_encode64()
137
138 doc_base64 =
139 doc
140 |> Base.url_encode64()
141
142 # Don't need proper xml building, these strings are safe to leave unescaped
143 salmon = """
144 <?xml version="1.0" encoding="UTF-8"?>
145 <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
146 <me:data type="application/atom+xml">#{doc_base64}</me:data>
147 <me:encoding>#{encoding}</me:encoding>
148 <me:alg>#{alg}</me:alg>
149 <me:sig>#{signature}</me:sig>
150 </me:env>
151 """
152
153 {:ok, salmon}
154 end
155
156 def remote_users(%{data: %{"to" => to} = data}) do
157 to = to ++ (data["cc"] || [])
158
159 to
160 |> Enum.map(fn id -> User.get_cached_by_ap_id(id) end)
161 |> Enum.filter(fn user -> user && !user.local end)
162 end
163
164 # push an activity to remote accounts
165 #
166 defp send_to_user(%{info: %{salmon: salmon}}, feed, poster),
167 do: send_to_user(salmon, feed, poster)
168
169 defp send_to_user(url, feed, poster) when is_binary(url) do
170 with {:ok, %{status: code}} <-
171 poster.(
172 url,
173 feed,
174 [{"Content-Type", "application/magic-envelope+xml"}]
175 ) do
176 Logger.debug(fn -> "Pushed to #{url}, code #{code}" end)
177 else
178 e -> Logger.debug(fn -> "Pushing Salmon to #{url} failed, #{inspect(e)}" end)
179 end
180 end
181
182 defp send_to_user(_, _, _), do: nil
183
184 @supported_activities [
185 "Create",
186 "Follow",
187 "Like",
188 "Announce",
189 "Undo",
190 "Delete"
191 ]
192
193 @doc """
194 Publishes an activity to remote accounts
195 """
196 @spec publish(User.t(), Pleroma.Activity.t(), Pleroma.HTTP.t()) :: none
197 def publish(user, activity, poster \\ &@httpoison.post/3)
198
199 def publish(%{info: %{keys: keys}} = user, %{data: %{"type" => type}} = activity, poster)
200 when type in @supported_activities do
201 feed = ActivityRepresenter.to_simple_form(activity, user, true)
202
203 if feed do
204 feed =
205 ActivityRepresenter.wrap_with_entry(feed)
206 |> :xmerl.export_simple(:xmerl_xml)
207 |> to_string
208
209 {:ok, private, _} = keys_from_pem(keys)
210 {:ok, feed} = encode(private, feed)
211
212 remote_users(activity)
213 |> Enum.each(fn remote_user ->
214 Task.start(fn ->
215 Logger.debug(fn -> "Sending Salmon to #{remote_user.ap_id}" end)
216 send_to_user(remote_user, feed, poster)
217 end)
218 end)
219 end
220 end
221
222 def publish(%{id: id}, _, _), do: Logger.debug(fn -> "Keys missing for user #{id}" end)
223 end