auth.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package dbus
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "io"
  7. "os"
  8. "strconv"
  9. )
  10. // AuthStatus represents the Status of an authentication mechanism.
  11. type AuthStatus byte
  12. const (
  13. // AuthOk signals that authentication is finished; the next command
  14. // from the server should be an OK.
  15. AuthOk AuthStatus = iota
  16. // AuthContinue signals that additional data is needed; the next command
  17. // from the server should be a DATA.
  18. AuthContinue
  19. // AuthError signals an error; the server sent invalid data or some
  20. // other unexpected thing happened and the current authentication
  21. // process should be aborted.
  22. AuthError
  23. )
  24. type authState byte
  25. const (
  26. waitingForData authState = iota
  27. waitingForOk
  28. waitingForReject
  29. )
  30. // Auth defines the behaviour of an authentication mechanism.
  31. type Auth interface {
  32. // Return the name of the mechnism, the argument to the first AUTH command
  33. // and the next status.
  34. FirstData() (name, resp []byte, status AuthStatus)
  35. // Process the given DATA command, and return the argument to the DATA
  36. // command and the next status. If len(resp) == 0, no DATA command is sent.
  37. HandleData(data []byte) (resp []byte, status AuthStatus)
  38. }
  39. // Auth authenticates the connection, trying the given list of authentication
  40. // mechanisms (in that order). If nil is passed, the EXTERNAL and
  41. // DBUS_COOKIE_SHA1 mechanisms are tried for the current user. For private
  42. // connections, this method must be called before sending any messages to the
  43. // bus. Auth must not be called on shared connections.
  44. func (conn *Conn) Auth(methods []Auth) error {
  45. if methods == nil {
  46. uid := strconv.Itoa(os.Getuid())
  47. methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
  48. }
  49. in := bufio.NewReader(conn.transport)
  50. err := conn.transport.SendNullByte()
  51. if err != nil {
  52. return err
  53. }
  54. err = authWriteLine(conn.transport, []byte("AUTH"))
  55. if err != nil {
  56. return err
  57. }
  58. s, err := authReadLine(in)
  59. if err != nil {
  60. return err
  61. }
  62. if len(s) < 2 || !bytes.Equal(s[0], []byte("REJECTED")) {
  63. return errors.New("dbus: authentication protocol error")
  64. }
  65. s = s[1:]
  66. for _, v := range s {
  67. for _, m := range methods {
  68. if name, data, status := m.FirstData(); bytes.Equal(v, name) {
  69. var ok bool
  70. err = authWriteLine(conn.transport, []byte("AUTH"), []byte(v), data)
  71. if err != nil {
  72. return err
  73. }
  74. switch status {
  75. case AuthOk:
  76. err, ok = conn.tryAuth(m, waitingForOk, in)
  77. case AuthContinue:
  78. err, ok = conn.tryAuth(m, waitingForData, in)
  79. default:
  80. panic("dbus: invalid authentication status")
  81. }
  82. if err != nil {
  83. return err
  84. }
  85. if ok {
  86. if conn.transport.SupportsUnixFDs() {
  87. err = authWriteLine(conn, []byte("NEGOTIATE_UNIX_FD"))
  88. if err != nil {
  89. return err
  90. }
  91. line, err := authReadLine(in)
  92. if err != nil {
  93. return err
  94. }
  95. switch {
  96. case bytes.Equal(line[0], []byte("AGREE_UNIX_FD")):
  97. conn.EnableUnixFDs()
  98. conn.unixFD = true
  99. case bytes.Equal(line[0], []byte("ERROR")):
  100. default:
  101. return errors.New("dbus: authentication protocol error")
  102. }
  103. }
  104. err = authWriteLine(conn.transport, []byte("BEGIN"))
  105. if err != nil {
  106. return err
  107. }
  108. go conn.inWorker()
  109. return nil
  110. }
  111. }
  112. }
  113. }
  114. return errors.New("dbus: authentication failed")
  115. }
  116. // tryAuth tries to authenticate with m as the mechanism, using state as the
  117. // initial authState and in for reading input. It returns (nil, true) on
  118. // success, (nil, false) on a REJECTED and (someErr, false) if some other
  119. // error occured.
  120. func (conn *Conn) tryAuth(m Auth, state authState, in *bufio.Reader) (error, bool) {
  121. for {
  122. s, err := authReadLine(in)
  123. if err != nil {
  124. return err, false
  125. }
  126. switch {
  127. case state == waitingForData && string(s[0]) == "DATA":
  128. if len(s) != 2 {
  129. err = authWriteLine(conn.transport, []byte("ERROR"))
  130. if err != nil {
  131. return err, false
  132. }
  133. continue
  134. }
  135. data, status := m.HandleData(s[1])
  136. switch status {
  137. case AuthOk, AuthContinue:
  138. if len(data) != 0 {
  139. err = authWriteLine(conn.transport, []byte("DATA"), data)
  140. if err != nil {
  141. return err, false
  142. }
  143. }
  144. if status == AuthOk {
  145. state = waitingForOk
  146. }
  147. case AuthError:
  148. err = authWriteLine(conn.transport, []byte("ERROR"))
  149. if err != nil {
  150. return err, false
  151. }
  152. }
  153. case state == waitingForData && string(s[0]) == "REJECTED":
  154. return nil, false
  155. case state == waitingForData && string(s[0]) == "ERROR":
  156. err = authWriteLine(conn.transport, []byte("CANCEL"))
  157. if err != nil {
  158. return err, false
  159. }
  160. state = waitingForReject
  161. case state == waitingForData && string(s[0]) == "OK":
  162. if len(s) != 2 {
  163. err = authWriteLine(conn.transport, []byte("CANCEL"))
  164. if err != nil {
  165. return err, false
  166. }
  167. state = waitingForReject
  168. }
  169. conn.uuid = string(s[1])
  170. return nil, true
  171. case state == waitingForData:
  172. err = authWriteLine(conn.transport, []byte("ERROR"))
  173. if err != nil {
  174. return err, false
  175. }
  176. case state == waitingForOk && string(s[0]) == "OK":
  177. if len(s) != 2 {
  178. err = authWriteLine(conn.transport, []byte("CANCEL"))
  179. if err != nil {
  180. return err, false
  181. }
  182. state = waitingForReject
  183. }
  184. conn.uuid = string(s[1])
  185. return nil, true
  186. case state == waitingForOk && string(s[0]) == "REJECTED":
  187. return nil, false
  188. case state == waitingForOk && (string(s[0]) == "DATA" ||
  189. string(s[0]) == "ERROR"):
  190. err = authWriteLine(conn.transport, []byte("CANCEL"))
  191. if err != nil {
  192. return err, false
  193. }
  194. state = waitingForReject
  195. case state == waitingForOk:
  196. err = authWriteLine(conn.transport, []byte("ERROR"))
  197. if err != nil {
  198. return err, false
  199. }
  200. case state == waitingForReject && string(s[0]) == "REJECTED":
  201. return nil, false
  202. case state == waitingForReject:
  203. return errors.New("dbus: authentication protocol error"), false
  204. default:
  205. panic("dbus: invalid auth state")
  206. }
  207. }
  208. }
  209. // authReadLine reads a line and separates it into its fields.
  210. func authReadLine(in *bufio.Reader) ([][]byte, error) {
  211. data, err := in.ReadBytes('\n')
  212. if err != nil {
  213. return nil, err
  214. }
  215. data = bytes.TrimSuffix(data, []byte("\r\n"))
  216. return bytes.Split(data, []byte{' '}), nil
  217. }
  218. // authWriteLine writes the given line in the authentication protocol format
  219. // (elements of data separated by a " " and terminated by "\r\n").
  220. func authWriteLine(out io.Writer, data ...[]byte) error {
  221. buf := make([]byte, 0)
  222. for i, v := range data {
  223. buf = append(buf, v...)
  224. if i != len(data)-1 {
  225. buf = append(buf, ' ')
  226. }
  227. }
  228. buf = append(buf, '\r')
  229. buf = append(buf, '\n')
  230. n, err := out.Write(buf)
  231. if err != nil {
  232. return err
  233. }
  234. if n != len(buf) {
  235. return io.ErrUnexpectedEOF
  236. }
  237. return nil
  238. }