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