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