Browse Source

Nuevo formato y añade gitea-sendxmpp

drymer 2 years ago
parent
commit
11bf679876

+ 1
- 0
.gitignore View File

@@ -0,0 +1 @@
1
+README.org

+ 457
- 3
README.md View File

@@ -1,4 +1,458 @@
1
-Sysadmin
2
-========
3 1
 
4
-Scripts y archivos de configuración varios
2
+
3
+# Índice     :TOC_5_org:
4
+
5
+-   [Prosody](#org09538d6)
6
+    -   [Actualizar módulos que no forman parte del núcleo](#org207e8c5)
7
+    -   [Archivo de configuración de prosoy de daemons.it](#org90fed92)
8
+-   [Gitea](#org3e31091)
9
+    -   [Avisos de nuevos usuarios de gitea](#orgbafa553)
10
+    -   [Webhook](#org037c36d)
11
+-   [Sendxmpp](#orgeca98b8)
12
+
13
+
14
+<a id="org09538d6"></a>
15
+
16
+# Prosody
17
+
18
+
19
+<a id="org207e8c5"></a>
20
+
21
+## Actualizar módulos que no forman parte del núcleo
22
+
23
+    #!/bin/bash
24
+
25
+    MODULES=("mod_http_upload" "mod_smacks" "mod_mam" "mod_blocking" "mod_carbons" "mod_onions" "mod_csi" "mod_limit_auth" "mod_default_bookmarks")
26
+    MODULES_PATH="/usr/lib/prosody/modules/"
27
+
28
+    hg pull
29
+    hg update
30
+
31
+    for mod in ${MODULES[@]}
32
+    do
33
+        cp -r $mod $MODULES_PATH
34
+    done
35
+
36
+    chown -R prosody.prosody $MODULES_PATH
37
+
38
+En `MODULES` se concreta que módulos del [repositorio](http://modules.prosody.im/) que no forma parte del núcleo se quieren actualizar y `modules_path` es la ruta de estos.
39
+
40
+
41
+<a id="org90fed92"></a>
42
+
43
+## Archivo de configuración de prosoy de daemons.it
44
+
45
+    -- Prosody XMPP Server Configuration
46
+    --
47
+    -- Information on configuring Prosody can be found on our
48
+    -- website at http://prosody.im/doc/configure
49
+    --
50
+    -- Tip: You can check that the syntax of this file is correct
51
+    -- when you have finished by running: luac -p prosody.cfg.lua
52
+    -- If there are any errors, it will let you know what and where
53
+    -- they are, otherwise it will keep quiet.
54
+    --
55
+    -- Good luck, and happy Jabbering!
56
+
57
+
58
+    ---------- Server-wide settings ----------
59
+    -- Settings in this section apply to the whole server and are the default settings
60
+    -- for any virtual hosts
61
+
62
+    -- This is a (by default, empty) list of accounts that are admins
63
+    -- for the server. Note that you must create the accounts separately
64
+    -- (see http://prosody.im/doc/creating_accounts for info)
65
+    -- Example: admins = { "user1@example.com", "user2@example.net" }
66
+    admins = { "drymer@daemons.it" }
67
+
68
+    -- Enable use of libevent for better performance under high load
69
+    -- For more information see: http://prosody.im/doc/libevent
70
+    --use_libevent = true;
71
+
72
+    -- interfaces
73
+    interfaces = { "127.0.0.1", "185.101.93.221" }
74
+
75
+    -- This is the list of modules Prosody will load on startup.
76
+    -- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
77
+    -- Documentation on modules can be found at: http://prosody.im/doc/modules
78
+    modules_enabled = {
79
+    	-- Generally required
80
+    		"roster"; -- Allow users to have a roster. Recommended ;)
81
+    		"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
82
+    		"tls"; -- Add support for secure TLS on c2s/s2s connections
83
+    		"dialback"; -- s2s dialback support
84
+    		"disco"; -- Service discovery
85
+    		"posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
86
+
87
+    	-- Not essential, but recommended
88
+    		"private"; -- Private XML storage (for room bookmarks, etc.)
89
+    		"vcard"; -- Allow users to set vCards
90
+
91
+    	-- These are commented by default as they have a performance impact
92
+    		"privacy"; -- Support privacy lists
93
+    		-- "compression"; -- Stream compression (requires the lua-zlib package installed)
94
+
95
+    	-- Nice to have
96
+    		"version"; -- Replies to server version requests
97
+    		"uptime"; -- Report how long server has been running
98
+    		"time"; -- Let others know the time here on this server
99
+    		"ping"; -- Replies to XMPP pings with pongs
100
+    		"pep"; -- Enables users to publish their mood, activity, playing music and more
101
+    		--"register"; -- Allow users to register on this server using a client and change passwords
102
+
103
+    	-- Admin interfaces
104
+    		--"admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
105
+    		--"admin_telnet"; -- Opens telnet console interface on localhost port 5582
106
+
107
+    	-- HTTP modules
108
+    		--"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"
109
+    		--"http_files"; -- Serve static files from a directory over HTTP
110
+
111
+    	-- Other specific functionality
112
+    		--"groups"; -- Shared roster support
113
+    		"announce"; -- Send announcement to all online users
114
+    		"welcome"; -- Welcome users who register accounts
115
+    		"watchregistrations"; -- Alert admins of registrations
116
+    		"motd"; -- Send a message to users when they log in
117
+                    "smacks";
118
+                    "csi";
119
+                    "throttle_presence";
120
+                    "filter_chatstates";
121
+                    "mam";
122
+                    "onions";
123
+                    "carbons";
124
+    		"blocking";
125
+                    "limit_auth";
126
+                    "default_bookmarks";
127
+    };
128
+
129
+    -- Disable account creation by default, for security
130
+    -- For more information see http://prosody.im/doc/creating_accounts
131
+    allow_registration = false;
132
+
133
+    -- Force clients to use encrypted connections? This option will
134
+    -- prevent clients from authenticating unless they are using encryption.
135
+
136
+    c2s_require_encryption = true;
137
+
138
+    -- Force certificate authentication for server-to-server connections?
139
+    -- This provides ideal security, but requires servers you communicate
140
+    -- with to support encryption AND present valid, trusted certificates.
141
+    -- NOTE: Your version of LuaSec must support certificate verification!
142
+    -- For more information see http://prosody.im/doc/s2s#security
143
+
144
+    s2s_secure_auth = false;
145
+
146
+    -- Many servers don\'t support encryption or have invalid or self-signed
147
+    -- certificates. You can list domains here that will not be required to
148
+    -- authenticate using certificates. They will be authenticated using DNS.
149
+
150
+    -- s2s_insecure_domains = {"xmpp.elbinario.net", "salas.xmpp.elbinario.net", }
151
+
152
+    -- Even if you leave s2s_secure_auth disabled, you can still require valid
153
+    -- certificates for some domains by specifying a list here.
154
+
155
+    --s2s_secure_domains = { "jabber.org" }
156
+
157
+    -- Required for init scripts and prosodyctl
158
+    pidfile = "/var/run/prosody/prosody.pid"
159
+
160
+    -- Select the authentication backend to use. The 'internal' providers
161
+    -- use Prosody\'s configured data storage to store the authentication data.
162
+    -- To allow Prosody to offer secure authentication mechanisms to clients, the
163
+    -- default provider stores passwords in plaintext. If you do not trust your
164
+    -- server please see http://prosody.im/doc/modules/mod_auth_internal_hashed
165
+    -- for information about using the hashed backend.
166
+
167
+    authentication = "internal_hashed"
168
+
169
+    -- Logging configuration
170
+    -- For advanced logging see http://prosody.im/doc/logging
171
+    log = {
172
+    	-- info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging
173
+    	error = "/var/log/prosody/prosody.err";
174
+            -- debug = "/var/log/prosody/prosody.debug";
175
+    }
176
+
177
+    ssl = {
178
+    	dhparam = "/etc/nginx/ssl/dh-4096.pem";
179
+            certificate = "/etc/prosody/certs/daemons.cf/daemons.cf.fullchain";
180
+            key = "/etc/prosody/certs/daemons.cf/daemons.cf.privkey";
181
+            options = { "no_sslv2", "no_sslv3", "no_tlsv1", "no_ticket", "no_compression", "cipher_server_preference", "single_dh_use", "single_ecdh_use" }
182
+    }
183
+
184
+    -- Tor
185
+    onions_tor_all = true
186
+    onions_only = false
187
+    onions_map = {
188
+    	["taolo.ga"] = "l3ybpw4vs6ie5rv2.onion";
189
+    	["jabber.calyxinstitute.org"] = "ijeeynrc6x2uy5ob.onion";
190
+    	["riseup.net"] = "4cjw6cwpeaeppfqz.onion";
191
+    	["jabber.otr.im"] = "5rgdtlawqkcplz75.onion";
192
+    	["jabber.systemli.org"] = "x5tno6mwkncu5m3h.onion";
193
+    	["securejabber.me"] = "giyvshdnojeivkom.onion";
194
+    	["so36.net"] = "s4fgy24e2b5weqdb.onion";
195
+    	["autistici.org"] = "wi7qkxyrdpu5cmvr.onion";
196
+    	["inventati.org"] = "wi7qkxyrdpu5cmvr.onion";
197
+    	["jabber.ipredator.se"] = "3iffdebkzzkpgipa.onion";
198
+    	["cloak.dk"] = "m2dsl4banuimpm6c.onion";
199
+    	["im.koderoot.net"] = "ihkw7qy3tok45dun.onion";
200
+    	["anonymitaet-im-inter.net"] = "rwf5skuv5vqzcdit.onion";
201
+    	["jabber.ccc.de"] = "okj7xc6j2szr2y75.onion";
202
+    }
203
+
204
+    -- MAM
205
+    archive_expires_after = "1w"
206
+
207
+    -- HTTP Upload
208
+    https_ssl = {
209
+           certificate = "/etc/prosody/certs/daemons.it/imagenes.daemons.it.fullchain";
210
+           key = "/etc/prosody/certs/daemons.it/imagenes.daemons.it.privkey";
211
+    }
212
+
213
+    http_upload_file_size_limit = 4096
214
+    http_external_url = "https://imagenes.daemons.it"
215
+    Component "imagenes.daemons.it" "http_upload"
216
+
217
+    -- limit_auth
218
+    limit_auth_period = 30 -- over 30 seconds
219
+    limit_auth_max = 5 -- tolerate no more than 5 failed attempts
220
+
221
+    -- MUC
222
+    Component "salas.daemons.cf" "muc"
223
+        name = "Salas de Bad Daemons"
224
+    Component "salas.daemons.it" "muc"
225
+        name = "Salas de Bad Daemons"
226
+    Component "salas.daemon4jidu2oig6.onion" "muc"
227
+        name = "Salas de Bad Daemons"
228
+
229
+    -- Default MuC
230
+    default_bookmarks = {
231
+        { jid = "daemons@salas.daemons.it", name = "Bad Daemons" };
232
+    };
233
+
234
+    -- Welcome
235
+    welcome_message = "Bienvenida a este servidor, $user. Para que vea que no eres un bot, saluda en la sala daemons@salas.daemons.it. Solo tienes que hacerlo una vez y luego puedes borrar la sala. Si no lo haces, es posible que borre esta cuenta en un plazo de una semana. Saludos"
236
+
237
+    ----------- Virtual hosts -----------
238
+    -- You need to add a VirtualHost entry for each domain you wish Prosody to serve.
239
+    -- Settings under each VirtualHost entry apply *only* to that host.
240
+
241
+    VirtualHost "daemons.cf"
242
+
243
+    VirtualHost "daemon4jidu2oig6.onion"
244
+
245
+    VirtualHost "daemons.it"
246
+    ssl = {
247
+    	dhparam = "/etc/nginx/ssl/dh-4096.pem";
248
+            certificate = "/etc/prosody/certs/daemons.it/daemons.it.fullchain";
249
+            key = "/etc/prosody/certs/daemons.it/daemons.it.privkey";
250
+            options = { "no_sslv2", "no_sslv3", "no_tlsv1", "no_ticket", "no_compression", "cipher_server_preference", "single_dh_use", "single_ecdh_use" }
251
+    }
252
+
253
+
254
+<a id="org3e31091"></a>
255
+
256
+# Gitea
257
+
258
+
259
+<a id="orgbafa553"></a>
260
+
261
+## Avisos de nuevos usuarios de gitea
262
+
263
+Avisa por xmpp si se registran nuevos usuarios en gitea. Usa <a id="org12ab14e"></a>.
264
+
265
+    #!/bin/bash
266
+
267
+    user=""
268
+    password=""
269
+    gitea=""
270
+    users=$(curl --silent -u $user:$password $gitea | grep "User Manage Panel" | cut -d':' -f2 | cut -d')' -f1 | sed "s/^ //")
271
+    recipient=""
272
+
273
+    if [[ ! -d ~/.gitea/ ]]; then
274
+        mkdir ~/.gitea/
275
+        echo $users > ~/.gitea/users
276
+
277
+    else
278
+        old_users=$(cat ~/.gitea/users)
279
+
280
+        if [[ $users != $old_users ]]
281
+        then
282
+    	echo "Hay al menos un nuevo usuario en Gitea. Antes habian $old_users y ahora hay $users." >> "/tmp/users"
283
+    	sendxmpp /tmp/users $recipient
284
+    	rm /tmp/users
285
+        fi
286
+    fi
287
+
288
+
289
+<a id="org037c36d"></a>
290
+
291
+## Webhook
292
+
293
+Una aplicación en flask que monta un endpoint en el que recibe peticiones del webhook y las manda por xmpp a una sala.
294
+
295
+El script en python2:
296
+
297
+    #!/usr/bin/env python2
298
+    # -*- coding: utf-8 -*-
299
+
300
+    import xmpp
301
+    import json
302
+    from flask import Flask, request
303
+    import ConfigParser
304
+
305
+
306
+    app = Flask(__name__)
307
+
308
+
309
+    @app.route('/')
310
+    def root():
311
+        return redirect("/webhook", code=302)
312
+
313
+    @app.route("/webhook", methods=['POST'])
314
+    def webhook():
315
+        # read config file
316
+        config = ConfigParser.ConfigParser()
317
+        config.read('config.ini')
318
+        username = config.get('xmpp', 'username', 0)
319
+        password = config.get('xmpp', 'password', 0)
320
+        server = config.get('xmpp', 'server', 0)
321
+        room = config.get('xmpp', 'room', 0)
322
+        nick = config.get('xmpp', 'nick', 0)
323
+        secret = config.get('gitea', 'secret', 0)
324
+
325
+        # TODO: comprobar si funciona sin secret
326
+        if not secret:
327
+            secret = ''
328
+
329
+        if request.json['secret'] == secret:
330
+            data = json.loads(request.data.decode('utf-8'))
331
+            message = ''
332
+            print(data)
333
+
334
+            # commit
335
+            if 'compare_url' in data.keys():
336
+                message = data['pusher']['username'] + ' has pushed some changes:'\
337
+                          + ' ' + data['compare_url']
338
+            # pull request open
339
+            elif data['action'] == 'opened':
340
+                message = data['sender']['username'] + ' opened a new pull reques'\
341
+                          + 't: ' + data['pull_request']['html_url']
342
+            # close pull request
343
+            elif data['action'] == 'closed':
344
+                message = data['sender']['username'] + ' closed a pull request: ' \
345
+                          + data['pull_request']['html_url']
346
+            # reopen pull request
347
+            elif data['action'] == 'reopened':
348
+                message = data['sender']['username'] + ' reopened a pull request:'\
349
+                          + ' ' + data['pull_request']['html_url']
350
+            # add label
351
+            elif data['action'] == 'label_updated':
352
+                f_tag = ""
353
+                for tag in data['pull_request']['labels']:
354
+                    f_tag += '[' + tag['name'] + '] '
355
+                message = data['sender']['username'] + ' changed the labels ' \
356
+                               'of a pull request: ' + f_tag + \
357
+                               data['pull_request']['html_url']
358
+            # delete label
359
+            elif data['action'] == 'label_cleared':
360
+                message = data['sender']['username'] + ' deleted all the labels ' \
361
+                          'of a pull request: ' + data['pull_request']['html_url']
362
+
363
+            if message:
364
+                client = xmpp.Client(server, debug=[])
365
+                client.connect()
366
+                client.auth(username, password, 'gitea')
367
+
368
+                # send join
369
+                client.send(xmpp.Presence(to="%s/%s" % (room, nick)))
370
+
371
+                msg = xmpp.protocol.Message(body=message)
372
+                msg.setTo(room)
373
+                msg.setType('groupchat')
374
+
375
+                client.send(msg)
376
+                presence = xmpp.Presence(to=room)
377
+                presence.setAttr('type', 'unavailable')
378
+                client.send(presence)
379
+
380
+        return ":)"
381
+
382
+
383
+    if __name__ == "__main__":
384
+
385
+        app.run()
386
+
387
+Necesita un archivo de configuración en el mismo escritorio:
388
+
389
+    [xmpp]
390
+    username =
391
+    password =
392
+    server   =
393
+    room     =
394
+    nick     =
395
+
396
+    [gitea]
397
+    secret   =
398
+
399
+La configuración de uwsgi:
400
+
401
+    [uwsgi]
402
+
403
+    chdir = /var/www/gitea-sendxmpp/
404
+    module = gitea-sendxmpp:app
405
+
406
+    master = true
407
+    processes = 1
408
+    threads = 2
409
+
410
+    uid = www-data
411
+    gid = www-data
412
+    socket = /tmp/gitea-sendxmpp.sock
413
+    chmod-socket = 777
414
+
415
+    die-on-term = true
416
+
417
+La configuración de nginx:
418
+
419
+    server {
420
+        listen 80;
421
+        server_name daemons.it;
422
+
423
+        location / {
424
+            include uwsgi_params;
425
+            uwsgi_pass unix:/tmp/gitea-sendxmpp.sock;
426
+        }
427
+    }
428
+
429
+
430
+<a id="orgeca98b8"></a>
431
+
432
+# Sendxmpp
433
+
434
+<a id="org5f4534d"></a>
435
+Lee un fichero que se le pase como primer parámetro y lo envía al jid que se pase como segundo parámetro.
436
+
437
+    #!/usr/bin/env python
438
+
439
+    import xmpp
440
+    from os import sys as sys
441
+    import time
442
+
443
+    username = ''
444
+    passwd = ''
445
+    server = ''
446
+
447
+    file_name = sys.argv[1]
448
+    to = sys.argv[2]
449
+    file = open(file_name, 'r')
450
+    msg = file.read()
451
+    client = xmpp.Client(server, debug=[]) # poner debug en True si tal
452
+    client.connect()
453
+    client.auth(username, passwd, 'Mensajero')
454
+    client.sendInitPresence()
455
+    message = xmpp.Message(to, msg)
456
+    message.setAttr('type', 'chat')
457
+    client.send(message)
458
+    time.sleep(3) # Si se desconecta demasiad rápido, no envia el mensaje

prosody/actualiza_modulos.sh → archivos/actualiza-modulos-prosody.sh View File


+ 9
- 0
archivos/config.ini View File

@@ -0,0 +1,9 @@
1
+[xmpp]
2
+username =
3
+password =
4
+server   =
5
+room     =
6
+nick     =
7
+
8
+[gitea]
9
+secret   =

+ 84
- 0
archivos/gitea-sendxmpp.py View File

@@ -0,0 +1,84 @@
1
+#!/usr/bin/env python2
2
+# -*- coding: utf-8 -*-
3
+
4
+import xmpp
5
+import json
6
+from flask import Flask,request
7
+import ConfigParser
8
+
9
+
10
+app = Flask(__name__)
11
+
12
+@app.route("/webhook", methods=['POST'])
13
+def webhook():
14
+    # read config file
15
+    config = ConfigParser.ConfigParser()
16
+    config.read('config.ini')
17
+    username = config.get('xmpp', 'username', 0)
18
+    password = config.get('xmpp', 'password', 0)
19
+    server = config.get('xmpp', 'server', 0)
20
+    room = config.get('xmpp', 'room', 0)
21
+    nick = config.get('xmpp', 'nick', 0)
22
+    secret = config.get('gitea', 'secret', 0)
23
+
24
+    # TODO: comprobar si es cierto
25
+    if not secret:
26
+        secret = ''
27
+
28
+    if request.json['secret'] == secret:
29
+        data = json.loads(request.data.decode('utf-8'))
30
+        message = ''
31
+        print(data)
32
+
33
+        # commit
34
+        if 'compare_url' in data.keys():
35
+            message = data['pusher']['username'] + ' has pushed some changes: ' + \
36
+                      data['compare_url']
37
+        # pull request open
38
+        elif data['action'] == 'opened':
39
+            message = data['sender']['username'] + ' opened a new pull request: ' + \
40
+                      data['pull_request']['html_url']
41
+        # close pull request
42
+        elif data['action'] == 'closed':
43
+            message = data['sender']['username'] + ' closed a pull request: ' + \
44
+                      data['pull_request']['html_url']
45
+        # reopen pull request
46
+        elif data['action'] == 'reopened':
47
+            message = data['sender']['username'] + ' reopened a pull request: ' + \
48
+                      data['pull_request']['html_url']
49
+        # add label
50
+        elif data['action'] == 'label_updated':
51
+            f_tag = ""
52
+            for tag in data['pull_request']['labels']:
53
+                f_tag += '[' + tag['name'] + '] '
54
+            message = data['sender']['username'] + ' changed the labels ' \
55
+                      'of a pull request: ' + f_tag + \
56
+                      data['pull_request']['html_url']
57
+        # delete label
58
+        elif data['action'] == 'label_cleared':
59
+            message = data['sender']['username'] + ' deleted all the labels ' \
60
+                      'of a pull request: ' + data['pull_request']['html_url']
61
+
62
+        if message:
63
+            client = xmpp.Client(server, debug=[])
64
+            client.connect()
65
+            client.auth(username, password, 'gitea')
66
+
67
+            # send join
68
+            client.send(xmpp.Presence(to="%s/%s" % (room, nick)))
69
+
70
+            msg = xmpp.protocol.Message(body=message)
71
+            msg.setTo(room)
72
+            msg.setType('groupchat')
73
+
74
+            client.send(msg)
75
+            presence = xmpp.Presence(to=room)
76
+            presence.setAttr('type', 'unavailable')
77
+            client.send(presence)
78
+
79
+    return ":)"
80
+
81
+
82
+if __name__ == "__main__":
83
+
84
+    app.run()

gitea/gitea-users.sh → archivos/gitea-users.sh View File


prosody/prosody.cfg.lua → archivos/prosody.cfg.lua View File


sendxmpp.py → archivos/sendxmpp.py View File


+ 0
- 1
prosody/VERSION_PROSODY View File

@@ -1 +0,0 @@
1
-La versión de prosody para la que están pensados estos archivos es la 0.9.

Loading…
Cancel
Save