epgsql_cmd_connect.erl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. %%% @doc Connects to the server and performs all the necessary handshakes.
  2. %%%
  3. %%% Special kind of command - it's exclusive: no other commands can run until
  4. %%% this one finishes.
  5. %%% It also uses some "private" epgsql_sock's APIs
  6. %%%
  7. -module(epgsql_cmd_connect).
  8. -behaviour(epgsql_command).
  9. -export([hide_password/1, opts_hide_password/1]).
  10. -export([init/1, execute/2, handle_message/4]).
  11. -export_type([response/0, connect_error/0]).
  12. -type response() :: connected
  13. | {error, connect_error()}.
  14. -type connect_error() ::
  15. invalid_authorization_specification
  16. | invalid_password
  17. | {unsupported_auth_method,
  18. kerberosV5 | crypt | scm | gss | sspi | {unknown, integer()} | {sasl, [binary()]}}
  19. | {sasl_server_final, any()}
  20. | epgsql:query_error().
  21. -include("epgsql.hrl").
  22. -include("protocol.hrl").
  23. -type auth_fun() :: fun((init | binary(), _, _) ->
  24. {send, byte(), iodata(), any()}
  25. | ok
  26. | {error, any()}
  27. | unknown).
  28. -record(connect,
  29. {opts :: map(),
  30. auth_fun :: auth_fun() | undefined,
  31. auth_state :: any() | undefined,
  32. auth_send :: {integer(), iodata()} | undefined,
  33. stage = connect :: connect | maybe_auth | auth | initialization}).
  34. -define(SCRAM_AUTH_METHOD, <<"SCRAM-SHA-256">>).
  35. -define(AUTH_OK, 0).
  36. -define(AUTH_CLEARTEXT, 3).
  37. -define(AUTH_MD5, 5).
  38. -define(AUTH_SASL, 10).
  39. -define(AUTH_SASL_CONTINUE, 11).
  40. -define(AUTH_SASL_FINAL, 12).
  41. init(#{host := _, username := _} = Opts) ->
  42. #connect{opts = Opts}.
  43. execute(PgSock, #connect{opts = #{host := Host} = Opts, stage = connect} = State) ->
  44. Timeout = maps:get(timeout, Opts, 5000),
  45. Deadline = deadline(Timeout),
  46. Port = maps:get(port, Opts, 5432),
  47. SockOpts = [{active, false}, {packet, raw}, binary, {nodelay, true}, {keepalive, true}],
  48. case gen_tcp:connect(Host, Port, SockOpts, Timeout) of
  49. {ok, Sock} ->
  50. client_handshake(Sock, PgSock, State, Deadline);
  51. {error, Reason} = Error ->
  52. {stop, Reason, Error, PgSock}
  53. end;
  54. execute(PgSock, #connect{stage = auth, auth_send = {PacketId, Data}} = St) ->
  55. ok = epgsql_sock:send(PgSock, PacketId, Data),
  56. {ok, PgSock, St#connect{auth_send = undefined}}.
  57. client_handshake(Sock, PgSock, #connect{opts = #{username := Username} = Opts} = State, Deadline) ->
  58. %% Increase the buffer size. Following the recommendation in the inet man page:
  59. %%
  60. %% It is recommended to have val(buffer) >=
  61. %% max(val(sndbuf),val(recbuf)).
  62. {ok, [{recbuf, RecBufSize}, {sndbuf, SndBufSize}]} =
  63. inet:getopts(Sock, [recbuf, sndbuf]),
  64. inet:setopts(Sock, [{buffer, max(RecBufSize, SndBufSize)}]),
  65. case maybe_ssl(Sock, maps:get(ssl, Opts, false), Opts, PgSock, Deadline) of
  66. {error, Reason} ->
  67. {stop, Reason, {error, Reason}, PgSock};
  68. PgSock1 ->
  69. Opts2 = ["user", 0, Username, 0],
  70. Opts3 = case maps:find(database, Opts) of
  71. error -> Opts2;
  72. {ok, Database} -> [Opts2 | ["database", 0, Database, 0]]
  73. end,
  74. {Opts4, PgSock2} =
  75. case Opts of
  76. #{replication := Replication} ->
  77. {[Opts3 | ["replication", 0, Replication, 0]],
  78. epgsql_sock:init_replication_state(PgSock1)};
  79. _ -> {Opts3, PgSock1}
  80. end,
  81. Opts5 = case Opts of
  82. #{application_name := ApplicationName} ->
  83. [Opts3 | ["application_name", 0, ApplicationName, 0]];
  84. _ ->
  85. Opts4
  86. end,
  87. ok = epgsql_sock:send(PgSock2, [<<196608:?int32>>, Opts5, 0]),
  88. PgSock3 = case Opts of
  89. #{async := Async} ->
  90. epgsql_sock:set_attr(async, Async, PgSock2);
  91. _ -> PgSock2
  92. end,
  93. {ok, PgSock3, State#connect{stage = maybe_auth}}
  94. end.
  95. %% @doc Replace `password' in Opts map with obfuscated one
  96. opts_hide_password(#{password := Password} = Opts) ->
  97. HiddenPassword = hide_password(Password),
  98. Opts#{password => HiddenPassword};
  99. opts_hide_password(Opts) -> Opts.
  100. %% @doc this function wraps plaintext password to a lambda function, so, if
  101. %% epgsql_sock process crashes when executing `connect' command, password will
  102. %% not appear in a crash log
  103. -spec hide_password(iodata()) -> fun( () -> iodata() ).
  104. hide_password(Password) when is_list(Password);
  105. is_binary(Password) ->
  106. fun() ->
  107. Password
  108. end;
  109. hide_password(PasswordFun) when is_function(PasswordFun, 0) ->
  110. PasswordFun.
  111. maybe_ssl(S, false, _, PgSock, _Deadline) ->
  112. epgsql_sock:set_net_socket(gen_tcp, S, PgSock);
  113. maybe_ssl(S, Flag, Opts, PgSock, Deadline) ->
  114. ok = gen_tcp:send(S, <<8:?int32, 80877103:?int32>>),
  115. Timeout0 = timeout(Deadline),
  116. case gen_tcp:recv(S, 1, Timeout0) of
  117. {ok, <<$S>>} ->
  118. SslOpts = maps:get(ssl_opts, Opts, []),
  119. Timeout = timeout(Deadline),
  120. case ssl:connect(S, SslOpts, Timeout) of
  121. {ok, S2} ->
  122. epgsql_sock:set_net_socket(ssl, S2, PgSock);
  123. {error, Reason} ->
  124. Err = {ssl_negotiation_failed, Reason},
  125. {error, Err}
  126. end;
  127. {ok, <<$N>>} ->
  128. case Flag of
  129. true ->
  130. epgsql_sock:set_net_socket(gen_tcp, S, PgSock);
  131. required ->
  132. {error, ssl_not_available}
  133. end;
  134. {error, Reason} ->
  135. {error, Reason}
  136. end.
  137. %% Auth sub-protocol
  138. auth_init(<<?AUTH_CLEARTEXT:?int32>>, Sock, St) ->
  139. auth_init(fun auth_cleartext/3, undefined, Sock, St);
  140. auth_init(<<?AUTH_MD5:?int32, Salt:4/binary>>, Sock, St) ->
  141. auth_init(fun auth_md5/3, Salt, Sock, St);
  142. auth_init(<<?AUTH_SASL:?int32, MethodsB/binary>>, Sock, St) ->
  143. Methods = epgsql_wire:decode_strings(MethodsB),
  144. case lists:member(?SCRAM_AUTH_METHOD, Methods) of
  145. true ->
  146. auth_init(fun auth_scram/3, undefined, Sock, St);
  147. false ->
  148. {stop, normal, {error, {unsupported_auth_method,
  149. {sasl, lists:delete(<<>>, Methods)}}}}
  150. end;
  151. auth_init(<<M:?int32, _/binary>>, Sock, _St) ->
  152. Method = case M of
  153. 2 -> kerberosV5;
  154. 4 -> crypt;
  155. 6 -> scm;
  156. 7 -> gss;
  157. 8 -> sspi;
  158. _ -> {unknown, M}
  159. end,
  160. {stop, normal, {error, {unsupported_auth_method, Method}}, Sock}.
  161. auth_init(Fun, InitState, PgSock, St) ->
  162. auth_handle(init, PgSock, St#connect{auth_fun = Fun, auth_state = InitState,
  163. stage = auth}).
  164. auth_handle(Data, PgSock, #connect{auth_fun = Fun, auth_state = AuthSt} = St) ->
  165. case Fun(Data, AuthSt, St) of
  166. {send, SendPacketId, SendData, AuthSt1} ->
  167. {requeue, PgSock, St#connect{auth_state = AuthSt1,
  168. auth_send = {SendPacketId, SendData}}};
  169. ok -> {noaction, PgSock, St};
  170. {error, Reason} ->
  171. {stop, normal, {error, Reason}};
  172. unknown -> unknown
  173. end.
  174. %% AuthenticationCleartextPassword
  175. auth_cleartext(init, _AuthState, #connect{opts = Opts}) ->
  176. Password = get_password(Opts),
  177. {send, ?PASSWORD, [Password, 0], undefined};
  178. auth_cleartext(_, _, _) -> unknown.
  179. %% AuthenticationMD5Password
  180. auth_md5(init, Salt, #connect{opts = Opts}) ->
  181. User = maps:get(username, Opts),
  182. Password = get_password(Opts),
  183. Digest1 = hex(erlang:md5([Password, User])),
  184. Str = ["md5", hex(erlang:md5([Digest1, Salt])), 0],
  185. {send, ?PASSWORD, Str, undefined};
  186. auth_md5(_, _, _) -> unknown.
  187. %% AuthenticationSASL
  188. auth_scram(init, undefined, #connect{opts = Opts}) ->
  189. User = maps:get(username, Opts),
  190. Nonce = epgsql_scram:get_nonce(16),
  191. ClientFirst = epgsql_scram:get_client_first(User, Nonce),
  192. SaslInitialResponse = [?SCRAM_AUTH_METHOD, 0, <<(iolist_size(ClientFirst)):?int32>>, ClientFirst],
  193. {send, ?SASL_ANY_RESPONSE, SaslInitialResponse, {auth_request, Nonce}};
  194. auth_scram(<<?AUTH_SASL_CONTINUE:?int32, ServerFirst/binary>>, {auth_request, Nonce}, #connect{opts = Opts}) ->
  195. User = maps:get(username, Opts),
  196. Password = get_password(Opts),
  197. ServerFirstParts = epgsql_scram:parse_server_first(ServerFirst, Nonce),
  198. {ClientFinalMessage, ServerProof} = epgsql_scram:get_client_final(ServerFirstParts, Nonce, User, Password),
  199. {send, ?SASL_ANY_RESPONSE, ClientFinalMessage, {server_final, ServerProof}};
  200. auth_scram(<<?AUTH_SASL_FINAL:?int32, ServerFinalMsg/binary>>, {server_final, ServerProof}, _Conn) ->
  201. case epgsql_scram:parse_server_final(ServerFinalMsg) of
  202. {ok, ServerProof} -> ok;
  203. Other -> {error, {sasl_server_final, Other}}
  204. end;
  205. auth_scram(_, _, _) ->
  206. unknown.
  207. %% --- Auth ---
  208. %% AuthenticationOk
  209. handle_message(?AUTHENTICATION_REQUEST, <<?AUTH_OK:?int32>>, Sock, State) ->
  210. {noaction, Sock, State#connect{stage = initialization,
  211. auth_fun = undefined,
  212. auth_state = undefined,
  213. auth_send = undefined}};
  214. handle_message(?AUTHENTICATION_REQUEST, Message, Sock, #connect{stage = Stage} = St) when Stage =/= auth ->
  215. auth_init(Message, Sock, St);
  216. handle_message(?AUTHENTICATION_REQUEST, Packet, Sock, #connect{stage = auth} = St) ->
  217. auth_handle(Packet, Sock, St);
  218. %% --- Initialization ---
  219. %% BackendKeyData
  220. handle_message(?CANCELLATION_KEY, <<Pid:?int32, Key:?int32>>, Sock, _State) ->
  221. {noaction, epgsql_sock:set_attr(backend, {Pid, Key}, Sock)};
  222. %% ReadyForQuery
  223. handle_message(?READY_FOR_QUERY, _, Sock, #connect{opts = Opts}) ->
  224. CodecOpts = maps:with([nulls], Opts),
  225. Codec = epgsql_binary:new_codec(Sock, CodecOpts),
  226. Sock1 = epgsql_sock:set_attr(codec, Codec, Sock),
  227. {finish, connected, connected, Sock1};
  228. %% ErrorResponse
  229. handle_message(?ERROR, #error{code = Code} = Err, Sock, #connect{stage = Stage} = _State) ->
  230. IsAuthStage = (Stage == auth) orelse (Stage == maybe_auth),
  231. Why = case Code of
  232. <<"28000">> when IsAuthStage ->
  233. invalid_authorization_specification;
  234. <<"28P01">> when IsAuthStage ->
  235. invalid_password;
  236. _ ->
  237. Err
  238. end,
  239. {stop, normal, {error, Why}, Sock};
  240. handle_message(_, _, _, _) ->
  241. unknown.
  242. get_password(Opts) ->
  243. PasswordFun = maps:get(password, Opts),
  244. PasswordFun().
  245. hex(Bin) ->
  246. HChar = fun(N) when N < 10 -> $0 + N;
  247. (N) when N < 16 -> $W + N
  248. end,
  249. <<<<(HChar(H)), (HChar(L))>> || <<H:4, L:4>> <= Bin>>.
  250. deadline(Timeout) ->
  251. erlang:monotonic_time(milli_seconds) + Timeout.
  252. timeout(Deadline) ->
  253. erlang:max(0, Deadline - erlang:monotonic_time(milli_seconds)).