epgsql_cmd_connect.erl 11 KB

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