Yesterday I did the first release of my OpenPGP compatible keyserver, onak, in 4 years. Actually, 2 releases because I discovered my detection for various versions of libnettle needed some fixing.
It was largely driven by the need to get an updated package sorted for Debian due to the removal of dh-systemd, but it should have come sooner. This release has a number of clean-ups for dealing with the hostility shown to the keyserver network in recent years. In particular it implements some of dkg s Abuse-Resistant OpenPGP Keystores, and finally adds support for verifying signatures fully. That opens up the ability to run a keyserver that will only allow verifiable updates to keys. This doesn t tie in with folk who want to run PGP based systems because of the anonymity, but for those of us who think PGP s strength is in the web of trust it s pretty handy. And it s all configurable to taste; you can turn off all the verification if you want, or verify everything but not require any signatures, or even enable v3 keys if you feel like it.
The main reason this release didn t come sooner is that I m painfully aware of the bits that are missing. In particular:
0.6.0 - 13th September 20200.6.1 - 13th September 2020
- Move to CMake over autoconf
- Add support for issuer fingerprint subpackets
- Add experimental support for v5 keys
- Add read-only OpenPGP keyring backed DB backend
- Move various bits into their own subdirectories in the source tree
- Add support for full signature verification
- Drop v3 keys by default when cleaning keys
- Various code cleanups
- Implement pieces of draft-dkg-openpgp-abuse-resistant-keystore-03
- Add support for a fingerprint blacklist (e.g. Evil32)
- Deprecate the .conf configuration file format
- Drop version info from armored output
- Add option to deny new keys and only allow updates to existing keys
- Various pieces of work removing support for 32 bit key IDs and coping with colliding 64 bit key IDs.
- Remove support for libnettle versions that lack the full SHA2 suite
- Fixes for compilation without nettle + with later releases of nettle
Step by step cups debugging ( here with a network printer)/etc/cups/printers.conf and change the ErrorPolicy for each printer from stop-printer to retry-job.| Editor: | Maya Schenwar |
| Editor: | Joe Macar |
| Editor: | Alana Yu-lan Price |
| Publisher: | Haymarket Books |
| Copyright: | June 2016 |
| ISBN: | 1-60846-684-1 |
| Format: | Kindle |
| Pages: | 250 |
Old laptop I ve been meaning to get a new laptop for a while now. My ThinkPad X250 is now 5 years old and even though it s still adequate in many ways, I tend to run out of memory especially when running a few virtual machines. It only has one memory slot, which I maxed out at 16GB shortly after I got it. Memory has been a problem in considering a new machine. Most new laptops have soldered RAM and local configurations tend to ship with 8GB RAM. Getting a new machine with only a slightly better CPU and even just the same amount of RAM as what I have in the X250 seems a bit wasteful. I was eyeing the Lenovo X13 because it s a super portable that can take up to 32GB of RAM, and it ships with an AMD Ryzen 4000 series chip which has great performance. With Lenovo s discount for Debian Developers it became even more attractive. Unfortunately that s in North America only (at least for now) so that didn t work out this time.
Enter Tongfang I ve been reading a bunch of positive reviews about the Tuxedo Pulse 14 and KDE Slimbook 14. Both look like great AMD laptops, supports up to 64GB of RAM and clearly runs Linux well. I also noticed that they look quite similar, and after some quick searches it turns out that these are made by Tongfang and that its model number is PF4NU1F. I also learned that a local retailer (Wootware) sells them as the Wootbook. I ve seen one of these before although it was an Intel-based one, but it looked like a nice machine and I was already curious about it back then. After struggling for a while to find a local laptop with a Ryzen CPU and that s nice and compact and that breaks the 16GB memory barrier, finding this one that jumped all the way to 64GB sealed the deal for me. This is the specs for the configuration I got:


Overall remarks When maxing out the CPU, the fan is louder than on a ThinkPad, I definitely noticed it while compiling the zfs-dkms module. On the plus side, that happened incredibly fast. Comparing the Wootbook to my X250, the biggest downfall it has is really it s pointing device. It doesn t have a trackpad and the touchpad is ok and completely usable, but not great. I use my laptop on a desk most of the time so using an external mouse will mostly solve that. If money were no object, I would definitely choose a maxed out ThinkPad for its superior keyboard/mouse, but the X13 configured with 32GB of RAM and 128GB of SSD retails for just about double of what I paid for this machine. It doesn t seem like you can really buy the perfect laptop no matter how much money you want to spend, there s some compromise no matter what you end up choosing, but this machine packs quite a punch, especially for its price, and so far I m very happy with my purchase and the incredible performance it provides. I m also very glad that Wootware went with the gray/black colours, I prefer that by far to the white and silver variants. It s also the first laptop I ve had since 2006 that didn t come with Windows on it. The Wootbook is also comfortable/sturdy enough to carry with one hand while open. The ThinkPads are great like this and with many other brands this just feels unsafe. I don t feel as confident carrying it by it s display because it s very thin (I know, I shouldn t be doing that with the ThinkPads either, but I ve been doing that for years without a problem :) ). There s also a post on Reddit that tracks where you can buy these machines from various vendors all over the world.
/admin1-> console com2 console: Serial Device 2 is currently in useSo far the only way I ve discovered to get console access again after that is the command racadm racreset . If anyone knows of a better way please let me know. As an aside having racreset being so close to racresetcfg (which resets the configuration to default and requires a hard reboot to configure it again) seems like a really bad idea. Host Based Management
deb http://linux.dell.com/repo/community/ubuntu xenial openmanageThe above apt sources.list line allows installing Dell management utilities (Xenial is old but they work on Debian/Buster). Probably the packages srvadmin-storageservices-cli and srvadmin-omacore will drag in enough dependencies to get it going. Here are some useful commands:
# show hardware event log omreport system esmlog # show hardware alert log omreport system alertlog # give summary of system information omreport system summary # show versions of firmware that can be updated omreport system version # get chassis temp omreport chassis temps # show physical disk details on controller 0 omreport storage pdisk controller=0RAID Control The RAID controller is known as PERC (PowerEdge Raid Controller), the Dell web site has an rpm package of the perccli tool to manage the RAID from Linux. This is statically linked and appears to have different versions of libraries used to make it. The command perccli show gives an overview of the configuration, but the command perccli /c0 show to give detailed information on controller 0 SEGVs and the kernel logs a vsyscall attempted with vsyscall=none message. Here s an overview of the vsyscall enmulation issue [2]. Basically I could add vsyscall=emulate to the kernel command line and slightly reduce security for the system to allow system calls from perccli that are called from old libc code to work, or I could run code from a dubious source as root. Some versions of IDRAC have a racadm raid command that can be run from a ssh session to perform RAID administration remotely, mine doesn t have that. As an aside the help for the RAC system doesn t list all commands and the Dell documentation is difficult to find so blog posts from other sysadmins is the best source of information. I have configured IDRAC to have all of the BIOS output go to the virtual serial console over ssh so I can see the BIOS prompt me for PERC administration but it didn t accept my key presses when I tried to do so. In any case this requires downtime and I d like to be able to change hard drives without rebooting. I found vsyscall_trace on Github [3], it uses the ptrace interface to emulate vsyscall on a per process basis. You just run vsyscall_trace perccli and it works! Thanks Geoffrey Thomas for writing this! Here are some perccli commands:
# show overview perccli show # help on adding a vd (RAID) perccli /c0 add help # show controller 0 details perccli /c0 show # add a vd (RAID) of level RAID0 (r0) with the drive 32:0 (enclosure:slot from above command) perccli /c0 add vd r0 drives=32:0When a disk is added to a PERC controller about 525MB of space is used at the end for RAID metadata. So when you create a RAID-0 with a single device as in the above example all disk data is preserved by default except for the last 525MB. I have tested this by running a BTRFS scrub on a disk from another system after making it into a RAID-0 on the PERC.
DEFLATE'd zip files. Basically if the data is already compressed then there's little hope Brotli will gain much.
I raised that it was interesting that they chose Brotli, in part, due to the availability of a pure Rust implementation of Brotli. Lars mentioned that Microsoft and others talk about how huge quantities of C code has unexpected memory safety issues and so perhaps that is related. Daniel mentioned that the document talked about Dropbox having a policy of not running unconstrained C code which was interesting.
Vince noted that in their deployment challenges it seemed like a very poor general strategy to cope with crasher errors; but Daniel pointed out that it might be an over-simplified description, and Mark suggested that it might be sufficient until a fix can be pushed out. Vince agreed that it's plausible this is a tiered/sharded deployment process and thus a good way to smoke out problems.
Daniel found it interesting that their block storage sounds remarkably like every other content-addressible storage and that while they make it clear in the article that encryption, client identification etc are elided, it looks like they might be able to deduplicate between theoretically hostile clients.
We think that the compressed-data plus type plus hash (which we assume also contains length) is an interesting and nice approach to durability and integrity validation in the protocol.
And the compressed blocks can then be passed to the storage backend quickly and effectively which is nice for latency.
Daniel raised that he thought it was fun that their rust-brotli library is still workable on Rust 1.12 which is really quite old.
We ended up on a number of tangential discussions, about Rust, about deployment strategies, and so on. While the article itself was a little thin, we certainly had a lot of good chatting around topics it raised.
We'll meet again in a month (on the 28th Sept) so perhaps we'll have a chunkier article next time. (Possibly this and/or related articles)
In our monthly reports, we summarise the things that we have been up to over the past month. The motivation behind the Reproducible Builds effort is to ensure no flaws have been introduced from the original free software source code to the pre-compiled binaries we install on our systems. If you re interested in contributing to the project, please visit our main website.
One hiccup we ve encountered in SecureDrop development is that not all Python wheels can be built reproducibly. We ship multiple (Python) projects in Debian packages, with Python dependencies included in those packages as wheels. In order for our Debian packages to be reproducible, we need that wheel build process to also be reproducibleParallel to this, transparencylog.com was also launched, a service that verifies the contents of URLs against a publicly recorded cryptographic log. It keeps an append-only log of the cryptographic digests of all URLs it has seen. (GitHub repo)
On 18th September, Bernhard M. Wiedemann will give a presentation in German, titled Wie reproducible builds Software sicherer machen ( How reproducible builds make software more secure ) at the Internet Security Digital Days 2020 conference.
Holger gave a talk titled Reproducing Bullseye in practice , focusing on independently verifying that the binaries distributed from ftp.debian.org are made from their claimed sources. It also served as a general update on the status of reproducible builds within Debian. The video (145 MB) and slides are available.
There were also a number of other talks that involved Reproducible Builds too. For example, the Malayalam language mini-conference had a talk titled , ? ( I want to join Debian, what should I do? ) presented by Praveen Arimbrathodiyil, the Clojure Packaging Team BoF session led by Elana Hashman, as well as Where is Salsa CI right now? that was on the topic of Salsa, the collaborative development server that Debian uses to provide the necessary tools for package maintainers, packaging teams and so on.
Jonathan Bustillos (Jathan) also gave a talk in Spanish titled Un camino verificable desde el origen hasta el binario ( A verifiable path from source to binary ). (Video, 88MB)
After many years of development work, the compiler for the Rust programming language now generates reproducible binary code. This generated some general discussion on Reddit on the topic of reproducibility in general.
Paul Spooren posted a request for comments to OpenWrt s openwrt-devel mailing list asking for clarification on when to raise the PKG_RELEASE identifier of a package. This is needed in order to successfully perform rebuilds in a reproducible builds context.
In openSUSE, Bernhard M. Wiedemann published his monthly Reproducible Builds status update.
Chris Lamb provided some comments and pointers on an upstream issue regarding the reproducibility of a Snap / SquashFS archive file. [ ]
.buildinfo build certificates have been tainted on the official Debian build servers, as these environments have files underneath the /usr/local/sbin directory [ ]. He also filed against bug for debrebuild after spotting that it can fail to download packages from snapshot.debian.org [ ].
This month, several issues were uncovered (or assisted) due to the efforts of reproducible builds.
For instance, Debian bug #968710 was filed by Simon McVittie, which describes a problem with detached debug symbol files (required to generate a traceback) that is unlikely to have been discovered without reproducible builds. In addition, Jelmer Vernooij called attention that the new Debian Janitor tool is using the property of reproducibility (as well as diffoscope when applying archive-wide changes to Debian:
New merge proposals also include a link to the diffoscope diff between a vanilla build and the build with changes. Unfortunately these can be a bit noisy for packages that are not reproducible yet, due to the difference in build environment between the two builds. [ ]56 reviews of Debian packages were added, 38 were updated and 24 were removed this month adding to our knowledge about identified issues. Specifically, Chris Lamb added and categorised the
nondeterministic_version_generated_by_python_param and the lessc_nondeterministic_keys toolchain issues. [ ][ ]
Holger Levsen sponsored Lukas Puehringer s upload of the python-securesystemslib pacage, which is a dependency of in-toto, a framework to secure the integrity of software supply chains. [ ]
Lastly, Chris Lamb further refined his merge request against the debian-installer component to allow all arguments from sources.list files (such as [check-valid-until=no]) in order that we can test the reproducibility of the installer images on the Reproducible Builds own testing infrastructure and sent a ping to the team that maintains that code.
asymptote (shell/Perl date)getfem (embeds datetime and user, submitted via email)getdp (hostname and user)getdp (user)guix (disable parallelism)httpcomponents-client (Java documentation generator readdir order)kuberlr (date)lal (date and time issue, submitted via email)libmesh (host)OBS (discuss how to track old build prjconf metadata in buildinfo)openblas (disable CPU detection)openfoam-selector (date)perl (toolchain, date)python-blosc (CPU detection)python-eventlet (fails to build far in the future)rna-star (date and hostname)trilinos (date)xz/b4 (workaround CPU count influencing output, reported upstream)json-c (forwarded upstream).nmh.golang-gonum-v1-plot.chirp.pixelmed-codec.debhelper.muroar.serd.pencil2d.tpot.evolution.aflplusplus.plexus-archiver (timezone/DST issue)libjpeg-turbo.jack-audio-connection-kit.glusterfs.155, 156, 157 and 158 to Debian:
<!ENTITY> declarations inside the Document Type Definition (DTD), or when a DTD or entity references an external resource. (#212)pgpdump(1) can successfully parse some binary files, so check that the parsed output contains something sensible before accepting it. [ ]gnumeric from the Debian build-dependencies as it has been removed from the testing distribution. (#968742)fallback_recognises to prevent matching .xsb binary XML files.file(1) returns data . (#211)ppudump version does not match our file header. [ ]repr(object) output in Calling external command messages. [ ].ppu files requires ppudump version 3.2.0 or higher. [ ]setup.py that diffoscope works with Python version 3.8 [ ] and Frazer Clews applied some Pylint suggestions [ ] and removed some deprecated methods [ ].
This month, Chris Lamb updated the main Reproducible Builds website and documentation to:
SOURCE_DATE_EPOCH age. [ ]
The Reproducible Builds project operate a Jenkins-based testing framework to power tests.reproducible-builds.org. This month, Holger Levsen made the following changes:
arm64 architecture. [ ]armhf. [ ][ ][ ]ruby-jekyll-polyglot package to needed for the recently-added internationalisation and translation support on the Reproducible Builds website. [ ]jenkins.debian.net, www.reproducible-builds.org, diffoscope.org, buildinfos.debian.net, etc.). [ ][ ][ ][ ][ ]arm64 architecture anymore. [ ]If you think you know how to spread the word about reproducibility in the context of Bitcoin wallets through WalletScrutiny, your contributions are highly welcome on this PR [ ]Julien Lepiller posted to the list linking to a blog post by Tavis Ormandy titled You don t need reproducible builds. Morten Linderud (foxboron) responded with a clear rebuttal that Tavis was only considering the narrow use-case of proprietary vendors and closed-source software. He additionally noted that the criticism that reproducible builds cannot prevent against backdoors being deliberately introduced into the upstream source ( bugdoors ) are decidedly (and deliberately) outside the scope of reproducible builds to begin with. Chris Lamb included the Reproducible Builds mailing list in a wider discussion regarding a tentative proposal to include
.buildinfo files in .deb packages, adding his remarks regarding requiring a custom tool in order to determine whether generated build artifacts are identical in a reproducible context. [ ]
Jonathan Bustillos (Jathan) posted a quick email to the list requesting whether there was a list of To do tasks in Reproducible Builds.
Lastly, Chris Lamb responded at length to a query regarding the status of reproducible builds for Debian ISO or installation images. He noted that most of the technical work has been performed but there are at least four issues until they can be generally advertised as such . He pointed that the privacy-oriented Tails operation system, which is based directly on Debian, has had reproducible builds for a number of years now. [ ]
#reproducible-builds on irc.oftc.net.
rb-general@lists.reproducible-builds.org
Debconf2020 took place when I was on personal vacations time. But anyway I m lucky enough that my
company, the Wikimedia Foundation, paid the conference registration fee for me and allowed me to
take the time (after my vacations) to watch recordings from the conference.
This is my first time attending (or watching) a full-online conference, and I was curious to see
first hand how it would develop. I was greatly surprised to see it worked pretty nicely, so kudos
to the organization, video team, volunteers, etc!
What follows is my summary of the conference, from the different sessions and talks I watched
(again, none of them live but recordings).
The first thing I saw was the Welcome to Debconf 2020 opening session. It is obvious
the video was made with lots of love, I found it entertaining and useful.
I love it :-)
Then I watched the BoF Can Free Software improve social equality. It was introduced
and moderated by Hong Phuc Dang. Several participants, about 10 people, shared their visions
on the interaction between open source projects and communities. I m pretty much aware of the
interesting social advancement that FLOSS can enable in communities, but sometimes is not so easy,
it may also present challenges and barriers. The BoF was joined by many people from the Asia
Pacific region, and for me, it has been very interesting to take a step back from the usual western
vision of this topic. Anyway, about the session itself, I have the feeling the participants may
have spent too much time on presentations, sharing their local stories (which are interesting,
don t get me wrong), perhaps leaving little room for actual proposal discussions or the like.
Next I watched the Bits from the DPL talk. In the session, Jonathan Carter goes over
several topics affecting the project, both internally and externally. It was interesting to know
more about the status of the project from a high level perspective, as an organization, including
subjects such as money, common project problems, future issues we are anticipating, the social
aspect of the project, etc.
The Lightning Talks session grabbed my attention. It is usually very funny to watch and
not as dense as other talks. I m glad I watched this as it includes some interesting talks, ranging
from HAM radios (I love them!), to personal projects to help in certain tasks, and even some
general reflections about life.
Just when I m writing this very sentence, the video for the
Come and meet your Debian Publicity team! talk has been uploaded. This team does an
incredible work in keeping project information flowing, and social networks up-to-date and alive.
Mind that the work of this team is mostly non-engineering, but still, is a vital part of the
project. The folks in session explain what the team does, and they also discuss how new people can
contribute, the different challenges related to language barriers, etc.
I have to admit I also started watching a couple other sessions that turned out to don t be
interesting to me (and therefore I didn t finish the video). Also, I tried to watch a couple more
sessions that didn t publish their video recording just yet, for example the
When We Virtualize the Whole Internet talk by Sam Hartman. Will check again in a couple of
days.
It is a real pleasure the video recordings from the conference are made available online.
One can join the conference anytime (like I m doing!) and watch the sessions at any pace at any
time. The video archive is big, I won t be able to go over all of it. I won t lie, I still have
some pending videos to watch from last year Debconf2019 :-)

To ensure Dronefly always remains free, the Dronefly project has been relicensed under two copyleft licenses. Read the license change and learn more about copyleft at these links.
I was prompted to make this change after a recent incident in the Red DiscordBot development community that made me reconsider my prior position that the liberal MIT license was best for our project. While on the face of it, making your license as liberal as possible might seem like the most generous and hassle-free way to license any project, I was shocked into the realization that its liberality was also its fatal flaw: all is well and good so long as everyone is being cooperative, but it does not afford any protection to developers or users should things suddenly go sideways in how a project is run. A copyleft license is the best way to avoid such issues.
In this incident a sad story of conflict between developers I respect on both sides of the rift, and owe a debt to for what they ve taught me three cogs we had come to depend on suddenly stopped being viable for us to use due to changes to the license & the code. Effectively, those cogs became unsupported and unsupportable. To avoid any such future disaster with the Dronefly project, I started shopping for a new license that would protect developers and users alike from similarly losing support, or losing control of their contributions. I owe thanks to Dale Floer, a team member who early on advised me the AGPL might be a better fit, and later was helpful in selecting the doc license and encouraging me to follow through. We ran the new licenses by each contributor and arrived at this consensus: the AGPL is best suited for our server-based code, and CC-BY-SA is best suited for our documentation. The relicensing was made official this morning.
On Discord platform alternatives
You might well question what I, a Debian developer steeped in free software culture and otherwise in agreement with its principles, am doing encouraging a community to grow on the proprietary Discord platform! I have no satisfying answer to that. I explained when I introduced my project here some of the backstory, but that s more of an account of its beginnings than justification for it to continue on this platform. Honestly, all I can offer is a rather dissatisfying it seemed like the right thing to do at the time.
Time will tell whether we could successfully move off of it to a freedom-respecting and privacy-respecting alternative chat platform that is both socially and technically viable to migrate to. That platform would ideally:
Previously: v5.5.
Linux v5.6 was released back in March. Here s my quick summary of various features that caught my attention:
WireGuardopenat2() syscall and RESOLVE_* flagsopen() handling, covering things like not walking above a specific point in a path hierarchy (RESOLVE_BENEATH), disabling the resolution of various magic links (RESOLVE_NO_MAGICLINKS) in procfs (e.g. /proc/$pid/exe) and other pseudo-filesystems, and treating a given lookup as happening relative to a different root directory (as if it were in a chroot, RESOLVE_IN_ROOT). As part of this, it became clear that there wasn t a way to correctly extend the existing openat() syscall, so he added openat2() (which is a good example of the efforts being made to codify Extensible Syscall arguments). The RESOLVE_* set of flags also cover prior behaviors like RESOLVE_NO_XDEV and RESOLVE_NO_SYMLINKS.
pidfd_getfd() syscallpidfd_getfd() syscall which is a way to gain access to file descriptors of a process in a race-less way (or when /proc is not mounted). Before, it wasn t always possible make sure that opening file descriptors via /proc/$pid/fd/$N was actually going to be associated with the correct PID. Much more detail about this has been written up at LWN.
openat() via io_uringio_uring() family of APIs, but I can t deny their utility for certain kinds of workloads. Being able to pipeline reads and writes without the overhead of actually making syscalls is pretty great for performance. Jens Axboe has added the IORING_OP_OPENAT command so that existing io_urings can open files to be added on the fly to the mapping of available read/write targets of a given io_uring. While LSMs are still happily able to intercept these actions, I remain wary of the growing syscall multiplexer that io_uring is becoming. I am, of course, glad to see that it has a comprehensive (if out of tree ) test suite as part of liburing.
removal of blocking random pool/dev/urandom is unchanged. /dev/random will still block just after booting, but it will block less than it used to. See LWN for more details on the history and discussion of the series.
arm64 support for on-chip RNGSYS_RNDR_EL0), which is, from the kernel s perspective, similar to x86 s RDRAND instruction. This will provide a bootloader-independent way to add entropy to the kernel s pRNG for early boot randomness (e.g. stack canary values, memory ASLR offsets, etc). Until folks are running on ARMv8.5 systems, they can continue to depend on the bootloader for randomness (via the UEFI RNG interface) on arm64.
arm64 E0PDTCR_E0PD1), which causes all memory accesses from userspace into kernel space to fault in constant time. This is an attempt to remove any possible timing side-channel signals when probing kernel memory layout from userspace, as an alternative way to protect against Meltdown-style attacks. The expectation is that E0PD would be used instead of the more expensive Kernel Page Table Isolation (KPTI) features on arm64.
powerpc32 VMAP_STACKthread_info, had already been moved away from the bottom of the stack by Christophe Leroy in Linux v5.1.)
generic Page Table dumping/sys/fs/debug/kernel_page_tables), Steven Price extracted the existing implementations from multiple architectures and created a common page table dumping framework (and then refactored all the other architectures to use it). I m delighted to have this because I still remember when not having a working page table dumper for ARM delayed me for a while when trying to implement upstream kernel memory protections there. Anything that makes it easier for architectures to get their kernel memory protection working correctly makes me happy.
That s in for now; let me know if there s anything you think I missed. Next up: Linux v5.7.
2020, Kees Cook. This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 License.
community.mysql collection from Ansible Galaxy
provides a mysql_query module to run arbitrary MySQL queries.
Unfortunately, it does not support check mode nor the --diff flag.
It is also unable to tell if there was a change. Let s write a
specific Ansible module to workaround these issues.
Notice I recommend that you read Writing a custom Ansible module as an introduction.
mysql_sync: sql: DELETE FROM rules WHERE name LIKE 'CMDB:%'; INSERT INTO rules (name, rule) VALUES ('CMDB: check for cats', ':is(object, "CAT")'), ('CMDB: check for dogs', ':is(object, "DOG")'); REPLACE INTO webhooks (name, url) VALUES ('OpsGenie', 'https://opsgenie/something/token'), ('Slack', 'https://slack/something/token'); user: monitoring password: Yooghah5 database: monitoring tables: - rules - webhooks
rules table is deleted and
recreated from scratch while the rows in the webhooks table are
replaced if they already exist.
You need the PyMySQL package.
module_args = dict( sql=dict(type='str', required=True), user=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), database=dict(type='str', required=True), tables=dict(type='list', required=True, elements='str'), ) result = dict( changed=False ) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True )
no_log to ensure it won t be displayed
or stored, notably when ansible-playbook runs in verbose mode. There
is no host option as the module is executed on the MySQL host.
Strong authentication using certificates is not implemented either.
This matches our goal with custom modules: only implement what you
strictly need.
got dictionary is a mapping from table names to the list of rows
they contain:
got = tables = module.params['tables'] connection = pymysql.connect( user=module.params['user'], password=module.params['password'], db=module.params['database'], charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) with connection.cursor() as cursor: for table in tables: cursor.execute("SELECT * FROM ".format(table)) got[table] = cursor.fetchall()
wanted dictionary. The trick is to execute the
SQL statements in a transaction without issuing a final commit. The
changes will be invisible1 to other readers and we can
compare the final rows with the rows collected in got:
wanted = sql = module.params['sql'] statements = [statement.strip() for statement in sql.split(";\n") if statement.strip()] with connection.cursor() as cursor: for statement in statements: try: cursor.execute(statement) except pymysql.OperationalError as err: code, message = err.args result['msg'] = "MySQL error for : ".format( statement, message) module.fail_json(**result) for table in tables: cursor.execute("SELECT * FROM ".format(table)) wanted[table] = cursor.fetchall()
for loop executes each statement. On error, we return a
helpful message containing the faulty one. The second for loop
records the final rows of each table in wanted.
got and wanted when not running with check
mode. The diff object is a bit more elaborate as it is built table
by table. This enables Ansible to display the name of each table
before the diff representation:
if got != wanted: result['changed'] = True result['diff'] = [dict( before_header=table, after_header=table, before=yaml.safe_dump(got[table]), after=yaml.safe_dump(wanted[table])) for table in tables if got[table] != wanted[table]] if module.check_mode or not result['changed']: module.exit_json(**result)
connection.commit()
mysql_query module, this one supports the check mode, signals
correctly if there is a change and displays the differences. However,
it should not be used with huge tables, as it would try to load them
in memory.
cisco.iosxr collection from Ansible Galaxy
provides an iosxr_user module to manage local users,
along with their SSH keys. However, the module is quite slow, do not
display a diff for changed SSH keys, never signal change when a key is
modified, and does not delete obsolete keys. Let s write a custom
Ansible module managing only the SSH keys while fixing these issues.
Notice I recommend that you read Writing a custom Ansible module as an introduction.
$ awk ' print $2 ' id_rsa.pub \ base64 -d \ > publickey_vincent.raw
harddisk:/publickey_vincent.raw
and import it for the current user with the following IOS command:
crypto key import authentication rsa harddisk:/publickey_vincent.b64
root-system group:
username vincent group root-lr group root-system
admin crypto key import authentication rsa username cedric harddisk:/publickey_cedric.b64
iosxr_users: keys: vincent: ssh-rsa AAAAB3NzaC1yc2EAA[ ]ymh+YrVWLZMJR cedric: ssh-rsa AAAAB3NzaC1yc2EAA[ ]RShPA8w/8eC0n
iosxr_user module, our custom module only handles SSH
keys, one per user. Therefore, the user definitions have to already
exist in the running configuration.1 Moreover, the user defined
in ansible_user needs to be in the root-system group. The
cisco.iosxr collection must also be installed as the module relies
on its code.
When running the module, ansible_connection needs to be set to
network_cli and ansible_network_os to iosxr. These variables are
usually defined in the inventory.
module_args = dict( keys=dict(type='dict', elements='str', required=True), ) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) result = dict( changed=False )
# show crypto key authentication rsa all Key label: vincent Type : RSA public key authentication Size : 2048 Imported : 16:17:08 UTC Tue Aug 11 2020 Data : 30820122 300D0609 2A864886 F70D0101 01050003 82010F00 3082010A 02820101 00D81E5B A73D82F3 77B1E4B5 949FB245 60FB9167 7CD03AB7 ADDE7AFE A0B83174 A33EC0E6 1C887E02 2338367A 8A1DB0CE 0C3FBC51 15723AEB 07F301A4 B1A9961A 2D00DBBD 2ABFC831 B0B25932 05B3BC30 B9514EA1 3DC22CBD DDCA6F02 026DBBB6 EE3CFADA AFA86F52 CAE7620D 17C3582B 4422D24F D68698A5 52ED1E9E 8E41F062 7DE81015 F33AD486 C14D0BB1 68C65259 F9FD8A37 8DE52ED0 7B36E005 8C58516B 7EA6C29A EEE0833B 42714618 50B3FFAC 15DBE3EF 8DA5D337 68DAECB9 904DE520 2D627CEA 67E6434F E974CF6D 952AB2AB F074FBA3 3FB9B9CC A0CD0ADC 6E0CDB2A 6A1CFEBA E97AF5A9 1FE41F6C 92E1F522 673E1A5F 69C68E11 4A13C0F3 0FFC782D 27020301 0001 [ ]
ansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.iosxr
contains a run_commands() function we can use:
command = "show crypto key authentication rsa all" out = run_commands(module, command) out = out[0].replace(' \n', '\n')
template = r""" Value Required Label (\w+) Value Required,List Data ([A-F0-9 ]+) Start ^Key label: $ Label ^Data\s+: -> GetData GetData ^ $ Data ^$$ -> Record Start """.lstrip() re_table = textfsm.TextFSM(io.StringIO(template)) got = data[0]: "".join(data[1]).replace(' ', '') for data in re_table.ParseText(out)
got is a dictionary associating key labels, considered as usernames,
with a hexadecimal representation of the public key currently
installed. It looks like this:
>>> pprint(got) 'alfred': '30820122300D0609[ ]6F0203010001', 'cedric': '30820122300D0609[ ]710203010001', 'vincent': '30820122300D0609[ ]270203010001'
wanted dictionary using the same structure. In
module.params['keys'], we have a dictionary associating usernames
to public SSH keys in the OpenSSH format:
>>> pprint(module.params['keys']) 'cedric': 'ssh-rsa AAAAB3NzaC1yc2[ ]', 'vincent': 'ssh-rsa AAAAB3NzaC1yc2[ ]'
ssh-keygen command and some glue can do the
conversion:2
$ ssh-keygen -f id_rsa.pub -e -mPKCS8 \ grep -v '^---' \ base64 -d \ hexdump -e '4/1 "%0.2X"' 30820122300D06092[ ]782D270203010001
ssh2cisco() function doing that, we can build the
wanted dictionary:
wanted = k: ssh2cisco(v) for k, v in module.params['keys'].items()
got and wanted when not running with check
mode. The part comparing got and wanted is taken verbatim from the
skeleton module:
if got != wanted: result['changed'] = True result['diff'] = dict( before=yaml.safe_dump(got), after=yaml.safe_dump(wanted) ) if module.check_mode or not result['changed']: module.exit_json(**result)
get_connection() and
copy_file() functions from
ansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.iosxr.
conn = get_connection(module) for user in wanted: if user not in got or wanted[user] != got[user]: dst = f"/harddisk:/publickey_ user .raw" with tempfile.NamedTemporaryFile() as src: decoded = base64.b64decode( module.params['keys'][user].split()[1]) src.write(decoded) src.flush() copy_file(module, src.name, dst) command = ("admin crypto key import authentication rsa " f"username user dst ") conn.send_command(command, prompt="yes/no", answer="yes")
for user in got: if user not in wanted: command = ("admin crypto key zeroize authentication rsa " f"username user ") conn.send_command(command, prompt="yes/no", answer="yes")
iosxr_user module, this one displays a diff when
running with --diff, correctly signals a change, is faster,
3 and deletes unwanted SSH keys. However, it is unable to
create users and cannot configure passwords or multiple SSH keys.
ssh-keygen, the format
used by Cisco is not PKCS#8. This is the ASN.1 representation of a
Subject Public Key Info structure, as defined in RFC 2459.
Moreover, PKCS#8 is a format for a private key, not a public one.
--diff --check and
shows the changes it would apply. When run twice in a row, the second
run won t apply or signal changes. The last bullet point suggests the
module should be able to delete outdated objects configured during
previous runs.2
The module code should be minimal and tailored to your needs. Making
the module generic for use by other users is a non-goal. Less code
usually means less bugs and easier to understand.
I do not cover testing here. It is undeniably a good practice, but it
requires a significant effort. In my opinion, it is preferable to have
a well written module matching the above characteristics rather than a
module that is well tested but without them or a module requiring
further (untested) assembly to meet your needs.
custom_module: user: someone password: something data: "some random string"
library/
subdirectory, create an empty __init__.py file and a
custom_module.py file with the following code:3
#!/usr/bin/python import yaml from ansible.module_utils.basic import AnsibleModule def main(): # Define options accepted by the module. module_args = dict( user=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), data=dict(type='str', required=True), ) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) result = dict( changed=False ) got = wanted = # Populate both got and wanted . # [...] if got != wanted: result['changed'] = True result['diff'] = dict( before=yaml.safe_dump(got), after=yaml.safe_dump(wanted) ) if module.check_mode or not result['changed']: module.exit_json(**result) # Apply changes. # [...] module.exit_json(**result) if __name__ == '__main__': main()
argument_spec for more details.
The second part, in , builds the got and wanted variables. got
is the current state while wanted is the target state. For
example, if you need to modify records in a database server, got
would be the current rows while wanted would be the modified rows.
Then, we compare got and wanted. If there is a difference,
changed is switched to True and we prepare the diff object.
Ansible uses it to display the differences between the states. If we
are running in check mode or if no change is detected, we stop here.
The last part, in , applies the changes. Usually, it means
iterating over the two structures to detect the differences and create
the missing items, delete the unwanted ones and update the existing
ones.
DOCUMENTATION = """ --- module: custom_module.py short_description: Pass provided data to remote service description: - Mention anything useful for your workmate. - Also mention anything you want to remember in 6 months. options: user: description: - user to identify to remote service password: description: - password for authentication to remote service data: description: - data to send to remote service """
module.fail_json():
module.fail_json( msg=f"remote service answered with code : message ", **result )
register directive.
For this purpose, you can add arbitrary fields to the result
dictionary. Have a look at the documentation for common return
values. You should try to add these fields before exiting the
module when in check mode. The returned values can be documented.
/usr/bin/python. Ansible will modify it to match the chosen
interpreter on the remote host. You can write Python 3 code if
ansible_python_interpreter evaluates to a Python 3 interpreter.
argument_spec. I think an
auto-documenting structure would avoid this.
Next.