Thursday, January 17, 2019

389 Directory Server 1.3.x LDAP client authentication

389 Directory Server 1.3.x LDAP client authentication

Last time we did a multi-master replication setup, see 389 Directory Server 1.3.x Replication.

Setting up LDAP client authentication on RHEL7 is next on the list. Let's install and configure SSSD today.

[root@ldap01 ~]# yum -y install sssd-ldap
...

Since we don't allow anonymous binds (nsslapd-allow-anonymous-access: rootdse), we need a special proxy user with no password expiration for this to work.

dirsrv@ldap01 $ PAPW="$(pwmake 192)"
dirsrv@ldap01 $ echo -n "$PAPW" > /etc/dirsrv/.papw
dirsrv@ldap01 $ chmod 400 /etc/dirsrv/.papw
dirsrv@ldap01 $ ldapadd -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
dn: cn=proxyagent,ou=Special Users,dc=unix,dc=mycompany,dc=com
objectclass: top
objectclass: organizationalRole
objectClass: simpleSecurityObject
cn: proxyagent
userPassword: $(pwdhash -s PBKDF2_SHA256 $(< /etc/dirsrv/.papw))
passwordExpirationTime: 20380119031407Z
^D
adding new entry "cn=proxyagent,ou=Special Users,dc=unix,dc=mycompany,dc=com"

With the proxyagent user in place we can configure SSSD now.

[root@ldap01 ~]# cat << EOF > /etc/sssd/sssd.conf
[sssd]
services = nss, pam
domains = LDAP

[nss]
filter_users = root
filter_groups = root
entry_cache_nowait_percentage = 75

[pam]
offline_credentials_expiration = 2
offline_failed_login_attempts = 3
offline_failed_login_delay = 5

[domain/LDAP]
id_provider = ldap
auth_provider = ldap
chpass_provider = ldap

ldap_uri = ldap://ldap01.mycompany.com,ldap://ldap02.mycompany.com
ldap_search_base = dc=unix,dc=mycompany,dc=com
ldap_default_bind_dn = cn=proxyagent,ou=Special Users,dc=unix,dc=mycompany,dc=com
ldap_default_authtok = $(< /etc/dirsrv/.papw)

ldap_tls_reqcert = demand
ldap_tls_cacert = /etc/openldap/certs/CA.crt
ldap_id_use_start_tls = true
enumerate = true
EOF

[root@ldap01 ~]# chmod 600 /etc/sssd/sssd.conf
[root@ldap01 ~]# authconfig --enablesssd --enablesssdauth --enablemkhomedir --update
[root@ldap01 ~]# systemctl enable sssd && systemctl start sssd

[root@ldap01 ~]# getent passwd smiddy6
smiddy6:x:1125:1001:Shrinkers Smiddy, smiddy6@mycompany.com:/home/smiddy6:/bin/bash
[root@ldap01 ~]# getent group uat
uat:*:1002:
[root@ldap01 ~]# ssh smiddy6@$(hostname -s)
smiddy6@ldap01's password:
Password expired. Change your password now.
WARNING: Your password has expired.
You must change your password now and login again!
Changing password for user smiddy6.
Current Password: ...

Very good.

Links

Thursday, January 10, 2019

389 Directory Server 1.3.x Replication

389 Directory Server 1.3.x Replication

Last time we added users and groups to our directory, see 389 Directory Server 1.3.x Users, Groups and ACIs.

Let's create some redundancy by using multi-master replication today. The outline is as following (first supplier is ldap01, second supplier will be ldap02):

  • Install a second VM with an empty userRoot, but with the same TLS and password policy settings
  • Enable the change log
  • Configure read-write replicas (replication settings and replication manager)
  • Set up replication agreements
  • Start the replication on the first supplier, pushing all changes to the second supplier

We have to create another 389-ds instance on a new VM, see 389 Directory Server 1.3.x on Red Hat Enterprise Linux 7.6. We just have to change a single line in setup.inf. Instead of /tmp/userRoot.ldif make it InstallLdifFile=none.

Done that? Fresh 389-ds instance ldap02 up and running? Same suffix (dc=unix,dc=mycompany,dc=com)? SSL key/certificate created and TLS enabled? Password policy (you can't set passwordAdminDN right now because the directory is empty, you'll have to do that later when both directory servers are in sync) in place? Good!

Let's start with the changelog, replica settings and replication manager on ldap01.

dirsrv@ldap01 $ ldapadd -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
dn: cn=changelog5,cn=config
changetype: add
objectClass: top
objectClass: extensibleObject
cn: changelog5
nsslapd-changelogdir: /var/lib/dirsrv/slapd-$(hostname -s)/changelogdb
# Red Hat recommends setting the maximum changelog age to 7 days.
# the following attribute should match nsds5ReplicaPurgeDelay (604800s == 7d)
nsslapd-changelogmaxage: 7d

dn: cn=replica,cn=dc\=unix\,dc\=mycompany\,dc\=com,cn=mapping tree,cn=config
changetype: add
objectClass: top
objectClass: nsds5replica
objectClass: extensibleObject
cn: replica
nsDS5ReplicaRoot: dc=unix,dc=mycompany,dc=com
# set a unique ID for suppliers
nsDS5ReplicaId: 1
# 3 consumer/supplier (updateable)
nsDS5ReplicaType: 3
# 1: The replica writes to the changelog; this is the default for hubs and suppliers.
nsDS5Flags: 1
# the following attribute should match nsslapd-changelogmaxage (7d == 604800s)
nsDS5ReplicaPurgeDelay: 604800
nsDS5ReplicaBindDN: cn=Replication Manager,cn=config
^D

dirsrv@ldap01 $ RMPW="$(pwmake 192)"
dirsrv@ldap01 $ echo -n $RMPW > /etc/dirsrv/.rmpw
dirsrv@ldap01 $ chmod 400 /etc/dirsrv/.rmpw
dirsrv@ldap01 $ ldapadd -D "cn=Directory Manager" -xy /etc/dirsrv/.dmpw -ZZ
dn: cn=Replication Manager,cn=config
objectClass: top
objectClass: device
objectClass: simpleSecurityObject
cn: Replication Manager
userPassword: $(pwdhash -s PBKDF2_SHA256 $(< /etc/dirsrv/.rmpw))
passwordExpirationTime: 20380119031407Z
nsIdleTimeout: 0
^D

Let's do the same on ldap02. The only difference here is nsDS5ReplicaId which has to be unique.

dirsrv@ldap02 $ ldapadd -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
dn: cn=changelog5,cn=config
changetype: add
objectClass: top
objectClass: extensibleObject
cn: changelog5
nsslapd-changelogdir: /var/lib/dirsrv/slapd-$(hostname -s)/changelogdb
nsslapd-changelogmaxage: 7d

dn: cn=replica,cn=dc\=unix\,dc\=mycompany\,dc\=com,cn=mapping tree,cn=config
changetype: add
objectClass: top
objectClass: nsds5replica
objectClass: extensibleObject
cn: replica
nsDS5ReplicaRoot: dc=unix,dc=mycompany,dc=com
# set a unique ID for suppliers!
nsDS5ReplicaId: 2
nsDS5ReplicaType: 3
nsDS5Flags: 1
nsDS5ReplicaPurgeDelay: 604800
nsDS5ReplicaBindDN: cn=Replication Manager,cn=config
^D

dirsrv@ldap02 $ RMPW="$(pwmake 192)"
dirsrv@ldap02 $ echo -n $RMPW > /etc/dirsrv/.rmpw
dirsrv@ldap02 $ chmod 400 /etc/dirsrv/.rmpw
dirsrv@ldap02 $ ldapadd -D "cn=Directory Manager" -xy /etc/dirsrv/.dmpw -ZZ
dn: cn=Replication Manager,cn=config
objectClass: top
objectClass: device
objectClass: simpleSecurityObject
cn: Replication Manager
userPassword: $(pwdhash -s PBKDF2_SHA256 $(< /etc/dirsrv/.rmpw))
passwordExpirationTime: 20380119031407Z
nsIdleTimeout: 0

That's it for ldap02 for now, back to ldap01. Next on the list is the replication agreement. We need the clear-text Replication Manager password (see /etc/dirsrv/.rmpw) from ldap02 for this. Let's do a connection test, too, before we start the replication refresh.

dirsrv@ldap01 $ openssl s_client -connect ldap02.mycompany.com:389 -starttls ldap -CAfile /etc/openldap/certs/CA.crt < /dev/null
...
    Verify return code: 0 (ok)
...
dirsrv@ldap01 $ ldapadd -D "cn=Directory Manager" -xy /etc/dirsrv/.dmpw -ZZ
dn: cn=ReplicaAgreement,cn=replica,cn=dc\=unix\,dc\=mycompany\,dc\=com,cn=mapping tree,cn=config
objectClass: top
objectClass: nsds5ReplicationAgreement
cn: ReplicaAgreement
nsDS5ReplicaHost: ldap02.mycompany.com
nsDS5ReplicaPort: 389
nsDS5ReplicaBindDN: cn=Replication Manager,cn=config
nsDS5ReplicaCredentials: ***clear-text RMPW from ldap02***
nsDS5ReplicaBindMethod: SIMPLE
nsDS5ReplicaTransportInfo: TLS
nsDS5ReplicaRoot: dc=unix,dc=mycompany,dc=com
description: replication agreement between ldap01 and ldap02
nsDS5ReplicaUpdateSchedule: 0000-2359 0123456

dn: cn=ReplicaAgreement,cn=replica,cn=dc\=unix\,dc\=mycompany\,dc\=com,cn=mapping tree,cn=config
changetype: modify
replace: nsDS5BeginReplicaRefresh
nsDS5BeginReplicaRefresh: start
^D

dirsrv@ldap01 $ tail /var/log/dirsrv/slapd-$(hostname -s)/errors
[...] NSMMReplicationPlugin - repl5_tot_run - Finished total update of replica "agmt="cn=ReplicaAgreement" (ldap02:389)". Sent 207 entries.

dirsrv@ldap02 $ tail /var/log/dirsrv/slapd-$(hostname -s)/errors
[...] NSMMReplicationPlugin - multimaster_be_state_change - Replica dc=unix,dc=mycompany,dc=com is coming online; enabling replication

And do the same on ldap02. We're not starting a nsDS5BeginReplicaRefresh here because the sync was already done on ldap01.

dirsrv@ldap02 $ ldapadd -D "cn=Directory Manager" -xy /etc/dirsrv/.dmpw -ZZ
dn: cn=ReplicaAgreement,cn=replica,cn=dc\=unix\,dc\=mycompany\,dc\=com,cn=mapping tree,cn=config
objectClass: top
objectClass: nsds5ReplicationAgreement
cn: ReplicaAgreement
nsDS5ReplicaHost: ldap01.mycompany.com
nsDS5ReplicaPort: 389
nsDS5ReplicaBindDN: cn=Replication Manager,cn=config
nsDS5ReplicaCredentials: ***clear-text RMPW from ldap01 ***
nsDS5ReplicaBindMethod: SIMPLE
nsDS5ReplicaTransportInfo: TLS
nsDS5ReplicaRoot: dc=unix,dc=mycompany,dc=com
description: replication agreement between ldap02 and ldap01
nsDS5ReplicaUpdateSchedule: 0000-2359 0123456
^D

dirsrv@ldap02 $ ldapsearch -LLL -D "cn=Directory Manager" -xy /etc/dirsrv/.dmpw -ZZ \
  -b 'cn=ReplicaAgreement,cn=replica,cn=dc\=unix\,dc\=mycompany\,dc\=com,cn=mapping tree,cn=config' \
  nsds5replicaLastUpdateStatus
dn: cn=ReplicaAgreement,cn=replica,cn=dc\3Dunix\2Cdc\3Dmycompany\2Cdc\3Dcom,cn
 =mapping tree,cn=config
nsds5replicaLastUpdateStatus: Error (0) Replica acquired successfully: Increme
 ntal update succeeded

And that's it. Our directory is nicely replicated to another instance and all changes made on any server are transferred to the other now.

Read the next part at 389 Directory Server 1.3.x LDAP client authentication.

Links

Tuesday, January 8, 2019

389 Directory Server 1.3.x Users, Groups and ACIs

389 Directory Server 1.3.x Users, Groups and ACIs

Now that our password policy is in place (see 389 Directory Server 1.3.x Password Policy), it's time to add some users and groups to our directory.

Let's generate some random users to get started and three POSIX + organizational groups as well.

[root@ldap01 ~]# yum -y install words
...
dirsrv@ldap01 $ cat << EOF > genUsers.sh
#!/bin/bash

set -o errexit
set -o nounset
set -o pipefail

LDAP_GRP=(PROD UAT DEV)
declare -A LDAP_GRPID=([PROD]=1001 [UAT]=1002 [DEV]=1003)
NAMES=( $(egrep -v '[[:punct:]]' /usr/share/dict/words) )

NUMNAMES="${#NAMES[*]}"

RNDNR=( $(shuf -i 0-$NUMNAMES -n 400) )

mkdir -p People

for i in {0..200}; do
  GN="${NAMES[${RNDNR[$i]}]}"
  SN="${NAMES[${RNDNR[$i+100]}]}"
  UIDN="$(( 1001 + $i ))"
  UIDL="${SN:0:6}$(( $RANDOM % 99 ))"
  UIDL="${UIDL,,}"
  GRPRND="$(( $RANDOM % 3 ))"
  GRPL="${LDAP_GRP[$GRPRND]}"

  echo "Creating People/${UIDL}.ldif ..."
  cat << EOT > People/${UIDL}.ldif
dn: uid=$UIDL,ou=People,dc=unix,dc=mycompany,dc=com
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
ou: $GRPL
sn: ${SN^}
cn: ${GN^} ${SN^}
uid: $UIDL
uidNumber: $UIDN
gidNumber: ${LDAP_GRPID[$GRPL]}
homeDirectory: /home/$UIDL
loginShell: /bin/bash
gecos: ${GN^} ${SN^}, $UIDL@mycompany.com
mail: $UIDL@mycompany.com
userPassword: changeme987

EOT
done
EOF
dirsrv@ldap01 $ chmod +x genUsers.ldif
dirsrv@ldap01 $ ./genUsers.sh
...
Creating People/smiddy6.ldif ...
...

dirsrv@ldap01 $ ldapadd -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
dn: cn=prod,ou=Groups,dc=unix,dc=mycompany,dc=com
objectClass: top
objectClass: posixGroup
cn: prod
gidNumber: 1001

dn: cn=uat,ou=Groups,dc=unix,dc=mycompany,dc=com
objectClass: top
objectClass: posixGroup
cn: uat
gidNumber: 1002

dn: cn=dev,ou=Groups,dc=unix,dc=mycompany,dc=com
objectClass: top
objectClass: posixGroup
cn: dev
gidNumber: 1003
^D
...
dirsrv@ldap01 $ cat People/*.ldif | ldapadd -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
...

We should have 200 LDAP users and 3 LDAP groups now. Next we want some manager groups and ACIs so that our users are able to edit certain attributes. I'll show this only for the PROD group (which is for POSIX group prod with gid 1001).

dirsrv@ldap01 $ ldapsearch -D "cn=Directory Manager" -xy /etc/dirsrv/.dmpw -ZZ -LLL \
  -b "ou=People,dc=unix,dc=mycompany,dc=com" "(&(objectclass=posixAccount)(gidNumber=1001))" uid gidNumber
...
dn: uid=aeger10,ou=People,dc=unix,dc=mycompany,dc=com
uid: aeger10
gidNumber: 1001
...
dn: uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com
uid: smiddy6
gidNumber: 1001
...

dirsrv@ldap01 $ ldapadd -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
dn: cn=PROD Managers,ou=Groups,dc=unix,dc=mycompany,dc=com
objectClass: groupOfUniqueNames
objectClass: top
cn: PROD Managers
description: People who can manage PROD entries
ou: Groups
uniqueMember: uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com
^D
...

The LDAP user smiddy6 is now a group manager for the PROD group. Let's create an ACI so that the PROD Managers group can actually do something.

dirsrv@ldap01 $ ldapadd -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
dn: ou=People,dc=unix,dc=mycompany,dc=com
changetype: modify
add: aci
aci: (targetattr = "gecos || loginShell || userPassword")(targetfilter ="(ou
 =PROD)")(version 3.0;acl "PROD Group Permissions";allow (write)(groupdn = "
 ldap:///cn=PROD Managers,ou=Groups,dc=unix,dc=mycompany,dc=com");)
^D
...

Let's check if those ACIs work.

dirsrv@ldap01 $ ldappasswd -D "uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com" -xW -ZZ -AS
Old password: changeme987
Re-enter old password: changeme987
New password: xxx
Re-enter new password: xxx
Enter LDAP Password: changeme987

dirsrv@ldap01 $ ldapsearch -D "uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com" -xLLL -W \
  -b "uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com" -ZZ \
  -E '!1.3.6.1.4.1.42.2.27.9.5.2=:dn:uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com' "(objectClass=*)"
...
entryLevelRights: v
attributeLevelRights: objectClass:rsc, ou:rsc, sn:rsc, cn:rsc, uid:rsc, uidNum
 ber:rsc, gidNumber:rsc, homeDirectory:rscwo, loginShell:rscwo, gecos:rscwo, s
 hadowLastChange:rsc, userPassword:wo

With those access controls in place users can change their own gecos, loginShell (r(ead), s(search), c(ompare), w(rite) and (o)bliterate) and userPassword (w(rite), (o)bliterate) attributes. PROD group managers (like smiddy6) should be able to change the same attributes for other PROD group members (like aeger10) as well.

dirsrv@ldap01 $ ldapsearch -D "uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com" -xLLL -W -b "uid=aeger10,ou=People,dc=unix,dc=mycompany,dc=com" -ZZ -E '!1.3.6.1.4.1.42.2.27.9.5.2=:dn:uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com' "(objectClass=*)"
...
entryLevelRights: v
attributeLevelRights: objectClass:rsc, ou:rsc, sn:rsc, cn:rsc, uid:rsc, uidNum
 ber:rsc, gidNumber:rsc, homeDirectory:rscwo, loginShell:rscwo, gecos:rscwo, s
 hadowLastChange:rsc, userPassword:wo
...

Looks good. LDAP user aeger10 on the other hand is not a group manager, so (s)he should have no rights to update any attributes for smiddy6.

dirsrv@ldap01 $ ldappasswd -D "uid=aeger10,ou=People,dc=unix,dc=mycompany,dc=com" -xW -ZZ -AS
...
dirsrv@ldap01 $ ldapsearch -D "uid=aeger10,ou=People,dc=unix,dc=mycompany,dc=com" -xLLL -W \
  -b "uid=smiddy6,ou=People,dc=unix,dc=mycompany,dc=com" -ZZ \
  -E '!1.3.6.1.4.1.42.2.27.9.5.2=:dn:uid=aeger10,ou=People,dc=unix,dc=mycompany,dc=com' "(objectClass=*)"
...
entryLevelRights: v
attributeLevelRights: objectClass:rsc, ou:rsc, sn:rsc, cn:rsc, uid:rsc, uidNum
 ber:rsc, gidNumber:rsc, homeDirectory:rsc, loginShell:rsc, gecos:rsc, shadowL
 astChange:rsc, userPassword:none

I call that a win.

Keep in mind that you don't want any user to be able to change the uidNumber attribute! Otherwise you'll end up with a bunch of LDAP users with uid 0 on your servers.

Read the next part at 389 Directory Server 1.3.x Replication.

Links

Saturday, December 29, 2018

389 Directory Server 1.3.x Password Policy

389 Directory Server 1.3.x Password Policy

Last time we installed 389-ds and did some basic configuration, see 389 Directory Server 1.3.x on Red Hat Enterprise Linux 7.6.

Let's implement a password policy now. We have the following requirements:

  • Password Minimum Length: 8
  • Maximum Password Failures: 100
  • Reset Password Failure Count After: 30 days
  • Password Must Change: yes (we want our users to change their password when they first bind to the directory server or when the password has been reset by the Manager DN)
  • Password Storage Scheme: we want the strongest, which is currently PBKDF2_SHA256 with 30,000 iterations

Let's enforce those rules:

dirsrv@ldap01 $ ldapmodify -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
dn: cn=config
changetype: modify
replace: passwordCheckSyntax
passwordCheckSyntax: on
-
replace: passwordLockout
passwordLockout: on
-
replace: passwordMaxFailure
passwordMaxFailure: 100
-
replace: passwordMinCategories
passwordMinCategories: 1
-
replace: passwordMinLength
passwordMinLength: 8
-
replace: passwordResetFailureCount
passwordResetFailureCount: 2592000
-
replace: passwordMustChange
passwordMustChange: on
-
replace: passwordStorageScheme
passwordStorageScheme: PBKDF2_SHA256
-
replace: passwordTrackUpdateTime
passwordTrackUpdateTime: on
-
replace: passwordUnlock
passwordUnlock: off
-
replace: nsslapd-rootpwstoragescheme
nsslapd-rootpwstoragescheme: PBKDF2_SHA256
^D
modifying entry "cn=config"

This should make us comply (well mostly) with NIST's Special Publication 800-63 Digital Identity Guidelines.

If you have more strict password rules (like passwords can only be changed after xx hours), don't forget to add your directory admins to the passwordAdminDN role to bypass those rules:

dirsrv@ldap01 $ ldapmodify -D "cn=Directory Manager" -y /etc/dirsrv/.dmpw -x -ZZ
dn: cn=config
changetype: modify
replace: passwordAdminDN
passwordAdminDN: cn=Directory Administrators,ou=Groups,dc=unix,dc=mycompany,dc=com
^D

Read the next part here 389 Directory Server 1.3.x Users, Groups and ACIs.

Links

Friday, December 28, 2018

389 Directory Server 1.3.x on Red Hat Enterprise Linux 7.6

389 Directory Server 1.3.x on Red Hat Enterprise Linux 7.6

Well you know the saying, all good things must come to an end. So we're going to replace Oracle's DSEE with 389 Directory Server today.

To get started we need to install 389-ds and do a silent setup:

[root@ldap01~]# yum -y install 389-ds-base
Loaded plugins: ulninfo
Resolving Dependencies
--> Running transaction check
---> Package 389-ds-base.x86_64 0:1.3.8.4-18.el7_6 will be installed
...

[root@ldap01~]# cat << EOF > /etc/sudoers.d/dirsrv
dirsrv $(hostname -s) = (root) NOPASSWD: /bin/systemctl start dirsrv@$(hostname -s), \
  /bin/systemctl stop dirsrv@$(hostname -s), \
  /bin/systemctl restart dirsrv@$(hostname -s)
EOF
[root@ldap01~]# chmod 440 /etc/sudoers.d/dirsrv
[root@ldap01~]# visudo -c

[root@ldap01~]# pwmake 192 | tr -d '\n' > /etc/dirsrv/.dmpw
[root@ldap01~]# chown dirsrv:dirsrv /etc/dirsrv/.dmpw
[root@ldap01~]# chmod 400 /etc/dirsrv/.dmpw

[root@ldap01~]# cat << EOF > /tmp/userRoot.ldif
dn: dc=unix,dc=mycompany,dc=com
objectClass: top
objectClass: domain
# https://tools.ietf.org/html/rfc4519
#  The 'dc' ('domainComponent' in RFC 1274) attribute type is a string
# holding one component, a label, of a DNS domain name.
# Examples: Valid values include "example" and "com" but not
# "example.com". The latter is invalid as it contains multiple
# domain components.
dc: unix
aci: (targetattr != "userPassword")(version 3.0;acl "Anonymous read-search acc
 ess"; allow (read, search, compare)(userdn = "ldap:///anyone");)
aci: (targetattr = "*")(version 3.0; acl "allow all Admin group"; allow(all) g
 roupdn = "ldap:///cn=Directory Administrators,ou=Groups,dc=mycompany,dc=com";
 )

dn: ou=Groups,dc=unix,dc=mycompany,dc=com
objectclass: top
objectclass: organizationalUnit
ou: Groups

dn: cn=Directory Administrators,ou=Groups,dc=unix,dc=mycompany,dc=com
objectClass: top
objectClass: groupOfUniqueNames
cn: Directory Administrators
ou: Groups
uniqueMember: cn=Directory Manager

dn: ou=People,dc=unix,dc=mycompany,dc=com
objectClass: top
objectClass: organizationalUnit
ou: People
aci: (targetattr = "gecos || loginShell || userPassword")(version 3.0;acl "All
 ow self entry modification";allow (write)(userdn = "ldap:///self");)

dn: ou=Special Users,dc=unix,dc=mycompany,dc=com
objectClass: top
objectClass: organizationalUnit
ou: Special Users
description: Special Administrative Accounts
EOF

[root@ldap01~]# cat << EOF > /tmp/setup.inf
[General]
FullMachineName=$(hostname -f)
StrictHostCheck=true
SuiteSpotGroup=dirsrv
SuiteSpotUserID=dirsrv

[slapd]
AddSampleEntries=No
InstallLdifFile=/tmp/userRoot.ldif
RootDN=cn=Directory Manager
RootDNPwd=$(pwdhash -s PBKDF2_SHA256 $(< /etc/dirsrv/.dmpw))
SchemaFile=/usr/share/dirsrv/data/60rfc4876.ldif
ServerIdentifier=$(hostname -s)
ServerPort=389
Suffix=dc=unix,dc=mycompany,dc=com
UseExistingMC=0
EOF

[root@ldap01~]# setup-ds.pl -s -f /tmp/setup.inf
...
Your new DS instance 'ldap01' was successfully created.
[root@ldap01~]# systemctl enable dirsrv@$(hostname -s)

We want a STARTTLS/LDAPS only server, so we need to create a CA, certificate and a key. See nginx on Solaris 11.3 SRU 19 with EC crypto and HTTP/2 support for how to do that with OpenSSL or How to create a SSL CA/certificate/key with pktool. I will just use the ECC files for now but I'm pretty sure I'll need all of them for older, non ECC clients.

Either way, you should have the following files now: CA.crt, server.crt, server.key and/or server-ecc.crt, server-ecc.key.

[root@ldap01~]# su -m dirsrv
dirsrv@ldap01 $ ldapadd -D "cn=Directory Manager" -xy /etc/dirsrv/.dmpw -h localhost -p 389
# enable the RSA cipher family,
# setting the NSS database security device,
# and the server certificate nickname
dn: cn=RSA,cn=encryption,cn=config
changetype: add
objectClass: top
objectClass: nsEncryptionModule
nsSSLPersonalitySSL: server-cert
nsSSLActivation: on
nsSSLToken: internal (software)
cn: RSA

# Enable TLS, tweak some defaults and sprinkle some security settings
dn: cn=config
changetype: modify
replace: nsslapd-security
nsslapd-security: on
-
# Preventing Directory Server to Start If the Certificate Has Been Expired
replace: nsslapd-validate-cert
nsslapd-validate-cert: on
-
# require simple binds to occur over a secure connection (SSL/TLS or Start TLS)
replace: nsslapd-require-secure-binds
nsslapd-require-secure-binds: on
-
# Disable anon binds except for the root dse
replace: nsslapd-allow-anonymous-access
nsslapd-allow-anonymous-access: rootdse
-
# A file descriptor is used whenever a client connects to the server
# and also for some server activities, such as index maintenance.
replace: nsslapd-maxdescriptors
nsslapd-maxdescriptors: 16384
-
replace: nsslapd-listen-backlog-size
nsslapd-listen-backlog-size: 256

# only accept TLS 1.2 connections
# leave the TLS1.0 default for older clients
# such as RHEL6, SLES11, Solaris 10!
dn: cn=encryption,cn=config
changetype: modify
replace: sslVersionMin
sslVersionMin: TLS1.2

dn: cn=config
changetype: modify
# Set a minimum SSF to disable insecure connections to a directory
# XXX changing the SSF has effects immediately!
# only change this at the very end or the ldapadd connection will drop!
replace: nsslapd-minssf
nsslapd-minssf: 128
^D

dirsrv@ldap01 $ sudo systemctl stop dirsrv@$(hostname -s)

dirsrv@ldap01 $ NSSPW="$(pwmake 192)"
dirsrv@ldap01 $ echo -n "$NSSPW" > /etc/dirsrv/.nsspw
dirsrv@ldap01 $ chmod 400 /etc/dirsrv/.nsspw
dirsrv@ldap01 $ certutil -d /etc/dirsrv/slapd-$(hostname -s)/ -N -f /etc/dirsrv/.nsspw
dirsrv@ldap01 $ chmod 600 /etc/dirsrv/slapd-$(hostname -s)/*.db
dirsrv@ldap01 $ echo -n "Internal (Software) Token:$NSSPW" > /etc/dirsrv/slapd-$(hostname -s)/pin.txt
dirsrv@ldap01 $ chmod 400 /etc/dirsrv/slapd-$(hostname -s)/pin.txt
dirsrv@ldap01 $ touch /etc/dirsrv/slapd-$(hostname -s)/pkcs11.txt
dirsrv@ldap01 $ chmod 600 /etc/dirsrv/slapd-$(hostname -s)/pkcs11.txt
dirsrv@ldap01 $ certutil -d /etc/dirsrv/slapd-$(hostname -s)/ -A -n "CA" -t "CT,," -f /etc/dirsrv/.nsspw -i .../CA.crt
dirsrv@ldap01 $ openssl pkcs12 -export -in .../server-ecc.crt -inkey .../server-ecc.key \
                  -out /tmp/servercert.p12 -name "server-cert" -passout file:/etc/dirsrv/.nsspw
dirsrv@ldap01 $ pk12util -i /tmp/servercert.p12 -d /etc/dirsrv/slapd-$(hostname -s)/ -k /etc/dirsrv/.nsspw -w /etc/dirsrv/.nsspw
pk12util: PKCS12 IMPORT SUCCESSFUL
dirsrv@ldap01 $ certutil -d /etc/dirsrv/slapd-$(hostname -s)/ -V -n "server-cert" -u V
certutil: certificate is valid

[root@ldap01~]# systemctl restart dirsrv@$(hostname -s)
[root@ldap01~]# cp .../CA.crt /etc/openldap/certs/
[root@ldap01~]# cat << EOF > /etc/openldap/ldap.conf
BASE dc=unix,dc=mycompany,dc=com
URI ldap://$(hostname -f)

TLS_CACERT /etc/openldap/certs/CA.crt
TLS_PROTOCOL_MIN 3.3
TLS_REQCERT demand
EOF

dirsrv@ldap01 $ openssl s_client -connect $(hostname -f):389 -starttls ldap -CAfile /etc/openldap/certs/CA.crt < /dev/null
...
    Verify return code: 0 (ok)
dirsrv@ldap01 $ openssl s_client -connect $(hostname -f):636 -CAfile /etc/openldap/certs/CA.crt < /dev/null
...
    Verify return code: 0 (ok)
dirsrv@ldap01 $ ldapsearch -LLL -D "cn=Directory Manager" -xy /etc/dirsrv/.dmpw \
                  -ZZ -s base -b 'cn=encryption,cn=config' sslVersionMin
dn: cn=encryption,cn=config
sslVersionMin: TLS1.2

And that was the first part. Short recap we have installed 389-ds on RHEL, we configured it with our chosen suffix, created a new SSL certificate/key and enabled TLS-only connections to the directory server. Also we did some LDAP client configuration in /etc/openldap/ldap.conf.

Read the next part here 389 Directory Server 1.3.x Password Policy.

Links

Friday, May 18, 2018

Puppetizing ntpd on Solaris 11.4

Puppetizing ntpd on Solaris 11.4

Last time we configured a Puppet master, see Puppet Master on Solaris 11.3 SRU 23.

Let's do some basic configuration with Puppet today. I'm doing this on Solaris 11.4 Beta with Puppet 5.3.3 so some paths on the master are slightly different. Keep this in mind when you're still on Solaris 11.3.

First things first, setup hiera.

root@master # cat /etc/puppetlabs/puppet/hiera.yaml
---
version: 5
defaults:
  datadir: /var/lib/hiera
  data_hash: yaml_data
hierarchy:
  - name: "Per-node data"
    path: "nodes/%{trusted.certname}.yaml"

  - name: "Per-net data"
    paths:
      - "net/%{::network_net0}.yaml"
      - "net/%{::network_ipmp0}.yaml"

  - name: "Other YAML hierarchy levels"
    path: "common.yaml"

root@master # cat /var/lib/hiera/common.yaml
---
classes:
  - ntp

# https://forge.puppetlabs.com/puppetlabs/ntp
ntp::enable: true
ntp::iburst_enable: true
# fix "ntpd[12345]: [ID 702911 daemon.warning] restrict default: KOD does nothing without LIMITED."
ntp::restrict:
  - default nomodify notrap nopeer noquery
  - -6 default nomodify notrap nopeer noquery
  - 127.0.0.1
  - -6 ::1
ntp::servers:
  - 10.1.2.3
  - 10.4.5.6

root@master # cat /var/lib/hiera/net/192.168.1.0.yaml
---
ntp::servers:
  - 192.168.1.1

I pulled a lot of hair out while figuring this out... when changing hiera.yaml you have to restart puppet!

Puppet master note: If you modify hiera.yaml between agent runs, you’ll have to restart your Puppet master for your changes to take effect.

And we're almost done. We just have to add one line to site.pp and restart puppet:master because we changed hiera.yaml.

root@master # cat /etc/puppetlabs/code/environments/production/manifests/site.pp
include(lookup('classes', Array[String], 'unique'))

root@master # svcadm restart puppet:master
root@master # tail /var/log/puppetlabs/puppet/puppet-master.log
2018-05-18 13:09:22 +0200 Puppet (notice): Starting Puppet master version 5.3.3

Let's hop on to the agent and see if it works.

# puppet agent --test --noop --server master.mycompany.com
Info: Using configured environment 'production'
Info: Retrieving pluginfacts
Info: Retrieving plugin
Info: Loading facts
Info: Applying configuration version '1526649508'
Notice: /Stage[main]/Ntp::Config/File[/etc/inet/ntp.conf]/ensure: current_value 'absent', should be 'file' (noop)
Notice: Class[Ntp::Config]: Would have triggered 'refresh' from 1 event
Info: Class[Ntp::Config]: Scheduling refresh of Class[Ntp::Service]
Notice: Class[Ntp::Service]: Would have triggered 'refresh' from 1 event
Info: Class[Ntp::Service]: Scheduling refresh of Service[ntp]
Notice: /Stage[main]/Ntp::Service/Service[ntp]/ensure: current_value 'stopped', should be 'running' (noop)
Info: /Stage[main]/Ntp::Service/Service[ntp]: Unscheduling refresh on Service[ntp]
Notice: Class[Ntp::Service]: Would have triggered 'refresh' from 1 event
Notice: Class[Ntp]: Would have triggered 'refresh' from 2 events
Notice: Stage[main]: Would have triggered 'refresh' from 3 events
Notice: Applied catalog in 1.90 seconds

# svcadm enable puppet:agent
# svcs ntp
STATE          STIME    FMRI
online         15:19:34 svc:/network/ntp:default
# ntpq -pn
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*192.168.1.1     LOCAL(0)         2 u   58   64  377    1.010    0.017   0.037

Neat, we have puppetized NTP with a few lines of code.

Links

Puppet Master on Solaris 11.3 SRU 23

Puppet Master on Solaris 11.3 SRU 23

I wasn't really happy with Puppet on Solaris 11.3. But SRU 23 had the following highlight.

Puppet has been updated to 3.8.6 (Bug 22264785). Along with the Puppet update, Facter has been updated to 2.4.6 (Bug 22308383).

Let's give Puppet another try. We'll start with configuring the Puppet master.

# pkg install --no-backup-be system/management/puppet
           Packages to install:        14
...
root@master # svccfg -s puppet:master setprop config/server=$(uname -n).mycompany.com
root@master # svccfg -s puppet:master setprop config/bindaddress=0.0.0.0
root@master # svccfg -s puppet:master refresh
root@master # svcadm enable puppet:master
root@master # tail /var/log/puppet/puppet-master.log
2017-10-19 09:05:16 +0200 Puppet (notice): Starting Puppet master version 3.8.6

We'll configure a client as well.

# pkg install --no-backup-be system/management/puppet
...
# svccfg -s puppet:agent setprop config/server=master.mycompany.com
# svccfg -s puppet:agent refresh

# puppet agent --test --server master.mycompany.com
...
Notice: Finished catalog run in 0.10 seconds

Let's sign the client certificate on the master.

root@master # puppet cert list
  "agent.mycompany.com" (SHA256) XX:XX:XX:XX:...

root@master # puppet cert sign agent.mycompany.com
Signing Certificate Request for:
  "agent.mycompany.com" (SHA256) XX:XX:XX:XX:...
Notice: Signed certificate request for agent.mycompany.com
Notice: Removing file Puppet::SSL::CertificateRequest agent.mycompany.com at '/etc/puppet/ssl/certificate_requests/agent.mycompany.com.pem'

The puppet agent should now be able to communicate with our puppet master.

# puppet agent --test
Info: Using configured environment 'production'
Info: Retrieving pluginfacts
Info: Retrieving plugin
Info: Loading facts
Info: Caching catalog for agent.mycompany.com
Info: Applying configuration version '1526560515'
Notice: Applied catalog in 0.20 seconds

# svcadm enable puppet:agent

And now our Puppet master is pulling the strings.

Read the next part at Puppetizing ntpd on Solaris 11.4.

Links

Monday, May 14, 2018

Vendor lock-in or let's have some fun with libucrypto

Vendor lock-in or let's have some fun with libucrypto

So one of the new features of Solaris 11.4 is the libucrypto library. They sell it as:

a lightweight library that provides access to hardware accelerated cryptography

Sadly the documentation is... scarce. The only opensource program that seems to be using it is Java.

Anyway, let's code a small sample RC4 (don't ever use RC4 for real world crypto!) program today and verify the cipher text against a known-good test vector. And yes, the plain text input is all zeros.

$ cat ucrypto_rc4.c
#include <libucrypto.h>

#include <assert.h>
#include <stdio.h>
#include <strings.h> // memcmp()

// https://tools.ietf.org/html/rfc6229
static const uchar_t key_str[] = {
    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
};

static const uchar_t tv3_out[] = {
    0x97, 0xab, 0x8a, 0x1b, 0xf0, 0xaf, 0xb9, 0x61,
    0x32, 0xf2, 0xf6, 0x72, 0x58, 0xda, 0x15, 0xa8,
    0x82, 0x63, 0xef, 0xdb, 0x45, 0xc4, 0xa1, 0x86,
    0x84, 0xef, 0x87, 0xe6, 0xb1, 0x9e, 0x5b, 0x09
};

int
main(void)
{
    const ucrypto_mech_t mech = CRYPTO_RC4;
    int rv = CRYPTO_FAILED;
    int ret = -1;

    size_t out_len = sizeof(tv3_out);

    uchar_t in[out_len];
    memset(&in, 0x0, sizeof(in));

    uchar_t out[out_len];
    memset(&out, 0x1, sizeof(out));

    printf("RFC 6229 key: 0x0102030405060708\n");
    rv = ucrypto_encrypt(mech, key_str, sizeof(key_str),
            NULL, 0,
            in, sizeof(in),
            out, &out_len);
    //printf("errror is %s\n", ucrypto_strerror(rv));
    assert(rv == CRYPTO_SUCCESS);
    ret = memcmp(out, tv3_out, sizeof(tv3_out));
    assert(ret == 0);

    printf("All tests passed\n");

    return 0;
}

$ cc -m64 -Wall ucrypto_rc4.c -lucrypto
$ ./a.out
RFC 6229 key: 0x0102030405060708
All tests passed

Well I'm pretty sure it would be more lines of code with OpenSSL. I'd still advice to use NaCL or OpenSSL though. And please don't use RC4 for anything anymore!

Links

Friday, March 16, 2018

Updating Intel microcode on Solaris 11.3 with ucodeadm

Updating Intel microcode on Solaris 11.3 with ucodeadm

So it's seems Intel finally released a working microcode update for the Spectre CPU flaw. You can download it at https://downloadcenter.intel.com/download/27591/Linux-Processor-Microcode-Data-File.

Done that? Good, let's apply it.

# gzcat microcode-20180312.tgz | tar xf -
# ln -s microcode.dat intel-ucode.txt
# ucodeadm -u intel-ucode.txt
# ucodeadm -v
CPU     Microcode Version
0       0x24
1       0x24
2       0x24
3       0x24
# dmesg | tail
...
Mar 16 10:06:36 solaris unix: [ID 518058 kern.info] cpu0: microcode has been updated from version 0x1c to 0x24
Mar 16 10:06:36 solaris unix: [ID 518058 kern.info] cpu1: microcode has been updated from version 0x1c to 0x24
Mar 16 10:06:36 solaris unix: [ID 518058 kern.info] cpu2: microcode has been updated from version 0x1c to 0x24
Mar 16 10:06:36 solaris unix: [ID 518058 kern.info] cpu3: microcode has been updated from version 0x1c to 0x24

You could copy intel-ucode.txt to /platform/i86pc/ucode/intel-ucode.txt to make this permanent. This will break pkg verify system/kernel/platform though.

Links

Tuesday, January 30, 2018

Kernel Zone Storage Live Migration with ZOSS

Kernel Zone Storage Live Migration with ZOSS

So we have some Kernel Zones on shared storage that need to migrate to another shared storage. Let's do that without any service interruption.

Current status is:

root@global:~ # zonecfg -z kz1 info
...
device 0:
        match not specified
        storage: lu:luname.naa.6006016027802e00084ff53eefdae511
        id: 1
        bootpri not specified
device 1:
        match not specified
        storage: lu:luname.naa.6006016027802e00965dc37eefdae511
        id: 0
        bootpri: 1
...
root@global:~ # fcinfo lu -v
OS Device Name: /dev/rdsk/c0t600000E00D2B0000002B021000940000d0s2
        HBA Port WWN: 2100000e1ed...
                Remote Port WWN: 500000e0dac...
                        LUN: 0
                Remote Port WWN: 500000e0dac...
                        LUN: 0
        HBA Port WWN: 2100000e1ed...
                Remote Port WWN: 500000e0dac...
                        LUN: 0
                Remote Port WWN: 500000e0dac...
                        LUN: 0
        Vendor: FUJITSU
        Product: ETERNUS_DXH
        Device Type: Disk Device
...
OS Device Name: /dev/rdsk/c0t600000E00D2B0000002B021000980000d0s2
        HBA Port WWN: 2100000e1ed...
                Remote Port WWN: 500000e0dac...
                        LUN: 150
                Remote Port WWN: 500000e0dac...
                        LUN: 150
        HBA Port WWN: 2100000e1ed...
                Remote Port WWN: 500000e0dac...
                        LUN: 150
                Remote Port WWN: 500000e0dac...
                        LUN: 150
        Vendor: FUJITSU
        Product: ETERNUS_DXH
        Device Type: Disk Device

Looks good, we see the new LUNs, let's convert the OS Device Name to a ZOSS Storage URI.

root@global:~ # suriadm lookup-uri -t lu /dev/dsk/c0t600000E00D2B0000002B021000940000d0
lu:luname.naa.600000e00d2b0000002b021000940000
...
root@global:~ # suriadm lookup-uri -t lu /dev/dsk/c0t600000E00D2B0000002B021000980000d0
lu:luname.naa.600000e00d2b0000002b021000980000

Let's add them to our kz1 zone config and do a live zone reconfiguration.

root@global:~ # zonecfg -z kz1
zonecfg:kz1> add device
zonecfg:kz1:device> set storage=lu:luname.naa.600000e00d2b0000002b021000980000
zonecfg:kz1:device> set bootpri=1
zonecfg:kz1:device> set id=2
zonecfg:kz1:device> end
zonecfg:kz1> add device
zonecfg:kz1:device> set storage=lu:luname.naa.600000e00d2b0000002b021000940000
zonecfg:kz1:device> set id=3
zonecfg:kz1:device> end
zonecfg:kz1> verify
zonecfg:kz1> commit
zonecfg:kz1> exit
root@global:~ # zoneadm -z kz1 apply
zone 'kz1': Checking: Adding device storage=lu:luname.naa.600000e00d2b0000002b021000940000
zone 'kz1': Checking: Adding device storage=lu:luname.naa.600000e00d2b0000002b021000980000
zone 'kz1': Applying the changes
...

Next steps are inside the Kernel Zone now.

root@kz1:~ # echo | format
Searching for disks...done


AVAILABLE DISK SELECTIONS:
       0. c1d0 <DGC-VRAID-0532-15.00GB>
          /kz-devices@ff/disk@0
       1. c1d1 <DGC-VRAID-0532-65.00GB>
          /kz-devices@ff/disk@1
       2. c1d2 <FUJITSU-ETERNUS_DXH-1070 cyl 1920 alt 0 hd 256 sec 64>
          /kz-devices@ff/disk@2
       3. c1d3 <FUJITSU-ETERNUS_DXH-1070 cyl 8320 alt 0 hd 256 sec 64>
          /kz-devices@ff/disk@3
Specify disk (enter its number): Specify disk (enter its number):

root@kz1:~ # zpool attach rpool c1d0 c1d2
Make sure to wait until resilver is done before rebooting.
root@kz1:~ # zpool attach tank c1d1 c1d3
# wait some time...
root@kz1:~ # zpool status -v
  pool: rpool
 state: ONLINE
  scan: resilvered 7.53G in 33s with 0 errors on Tue Jan 30 15:09:55 2018

config:

        NAME        STATE     READ WRITE CKSUM
        rpool       ONLINE       0     0     0
          mirror-0  ONLINE       0     0     0
            c1d0    ONLINE       0     0     0
            c1d2    ONLINE       0     0     0

errors: No known data errors

  pool: tank
 state: ONLINE
  scan: resilvered 28.9G in 7m40s with 0 errors on Tue Jan 30 15:17:26 2018

config:

        NAME        STATE     READ WRITE CKSUM
        tank        ONLINE       0     0     0
          mirror-0  ONLINE       0     0     0
            c1d1    ONLINE       0     0     0
            c1d3    ONLINE       0     0     0

errors: No known data errors
root@kz1:~ # zpool detach rpool c1d0
root@kz1:~ # zpool detach tank c1d1
root@kz1:~ # bootadm install-bootloader

And that's almost it. Last thing is to remove the old storage LUNs from the Kernel Zone.

root@global:~ # zonecfg -z kz1
zonecfg:kz1> remove device id=0
zonecfg:kz1> remove device id=1
zonecfg:kz1> verify
zonecfg:kz1> commit
zonecfg:kz1> exit
root@global:~ # zoneadm -z kz1 apply
zone 'kz1': Checking: Removing device storage=lu:luname.naa.6006016027802e00084ff53eefdae511
zone 'kz1': Checking: Removing device storage=lu:luname.naa.6006016027802e00965dc37eefdae511
zone 'kz1': Applying the changes

And we're done.

Links

Thursday, November 16, 2017

Veritas InfoScale 7.3.1 IPS repo

Veritas InfoScale 7.3.1 IPS repo

Let's create a Veritas InfoScale 7.3.1 IPS repo today. Log in into the VERITAS Entitlement Management System to download Veritas_InfoScale_7.3.1_Solaris_SPARC.tar.gz. We just need one file from the archive to proceed.

$ gzcat Veritas_InfoScale_7.3.1_Solaris_SPARC.tar.gz | tar xf - ./dvd1-sol_sparc/sol11_sparc/pkgs/VRTSpkgs.p5p

Good, let's create the IPS repo now.

# zfs create install/pkgrepo/vrts_sparc
# pkgrepo create /install/pkgrepo/vrts_sparc
# pkgrepo add-publisher -s /install/pkgrepo/vrts_sparc Veritas
# pkgrecv -s VRTSpkgs.p5p -d /install/pkgrepo/vrts_sparc '*'
Processing packages for publisher Veritas ...
Retrieving and evaluating 27 package(s)...
PROCESS                                         ITEMS    GET (MB)   SEND (MB)
Completed                                       27/27 488.4/488.4 465.7/465.7

# pkgrepo -s /install/pkgrepo/vrts_sparc list VRTSvxvm
PUBLISHER NAME                                          O VERSION
Veritas   VRTSvxvm                                        7.3.1.0,5.11:20171013T065743Z
# svccfg -s pkg/server add vrts_sparc
# svccfg -s pkg/server add vrts_sparc
# svccfg -s pkg/server:vrts_sparc
svc:/application/pkg/server:vrts_sparc> setprop pkg/inst_root = /install/pkgrepo/vrts_sparc
svc:/application/pkg/server:vrts_sparc> setprop pkg/standalone = boolean: false
svc:/application/pkg/server:vrts_sparc> setprop pkg/readonly = boolean: true
svc:/application/pkg/server:vrts_sparc> refresh
svc:/application/pkg/server:vrts_sparc> ^D
# svcadm enable -s svc:/application/pkg/server:vrts_sparc
# svcadm restart svc:/application/pkg/depot:default

Don't forget to check for updates and/or a newer ASL on https://sort.veritas.com/patch/finder and https://sort.veritas.com/asl as well.

Links

Thursday, September 28, 2017

Using Jenkins to build nginx

Using Jenkins to build nginx

Last time we installed and configured Jenkins (see Leeeroooy Jenkins or let's do some CI/CD). Let's build nginx with Jenkins today.

We want everything in Git for this. This means we have to install Git and the Git Jenkins plugin (internal network here, that's why the wget calls instead of the built-in Jekins plugin manager).

# pkg install --no-backup-be git
           Packages to install:  1
            Services to change:  1
...

# su - jenkins
$ cd /tank/jenkins/plugins
$ wget https://updates.jenkins-ci.org/latest/git.hpi \
       https://updates.jenkins-ci.org/latest/scm-api.hpi \
       https://updates.jenkins-ci.org/latest/workflow-scm-step.hpi \
       https://updates.jenkins-ci.org/latest/workflow-step-api.hpi \
       https://updates.jenkins-ci.org/latest/mailer.hpi \
       https://updates.jenkins-ci.org/latest/display-url-api.hpi \
       https://updates.jenkins-ci.org/latest/matrix-project.hpi \
       https://updates.jenkins-ci.org/latest/junit.hpi \
       https://updates.jenkins-ci.org/latest/script-security.hpi \
       https://updates.jenkins-ci.org/latest/credentials.hpi \
       https://updates.jenkins-ci.org/latest/git-client.hpi \
       https://updates.jenkins-ci.org/latest/ssh-credentials.hpi \
       https://updates.jenkins-ci.org/latest/structs.hpi
...
$ chown jenkins:jenkins *.hpi

# svcadm restart tomcat8

There should be a Git plugin an the Jenkins website when you click on "Manage Jenkins" -> "Manage Plugins" -> "Installed"

There is? Good, time to switch to a personal user to create our first Git repo (or use an existing one).

$ git init
Initialized empty Git repository in /home/sparcy/jenkins/.git/
$ git config --global user.email "sparcy@jenkins.mycompany.com"
$ git config --global user.name "SPARCy"

And populate it with the bits we need to compile nginx. See How to build software on Solaris 11/SPARC for an explanation where the compiler flags are taken from. Some background on building nginx can be found at nginx on Solaris 11.3 SRU 19 with EC crypto and HTTP/2 support as well.

$ cat << EOF > compiler.sh
export SHELL='/bin/bash'
export NM='/usr/gnu/bin/nm'
export MAKE='/usr/bin/gmake'
export PATH="$(getconf PATH):/opt/solarisstudio12.6/bin"

CPP_LF64="$(getconf LFS64_CFLAGS)"
CPP_XPG6MODE='-D_XOPEN_SOURCE=600 -D__EXTENSIONS__=1 -D_XPG6'
export CPPFLAGS="$CPP_LF64 $CPP_XPG6MODE"

studio_XBITS='-xarch=sparcvis2'
studio_C99_ENABLE='-xc99=all'
studio_FEATURES_EXTENSIONS='-features=extensions'
studio_OPT='-xO4'
studio_PIC='-KPIC -DPIC'
studio_IROPTS='-W2,-xwrap_int'
studio_XREGS='-Qoption cg -xregs=no%appl'
studio_ALIGN='-xmemalign=16s'
studio_MT='-mt'

export CC='/opt/developerstudio12.6/bin/cc'
export CFLAGS="-m64 $studio_OPT $studio_XBITS $studio_XREGS $studio_IROPTS $studio_C99_ENABLE $studio_MT $studio_PIC $studio_ALIGN"

studio_NORUNPATH='-norunpath'
studio_CXXLIB_CSTD='-library=Cstd,Crun'

export CXX='/opt/developerstudio12.6/bin/CC'
export CXXFLAGS="-m64 $studio_OPT $studio_XBITS $studio_XREGS $studio_IROPTS $studio_PIC $studio_NORUNPATH $studio_CXXLIB_CSTD $studio_ALIGN"

LD_Z_IGNORE='-zignore'
LD_Z_STRIP_CLASS='-zstrip-class=comment'
LD_B_DIRECT='-Bdirect'
LD_Z_PIE_ENABLE='-ztype=pie'
ASLR_ENABLE='-zaslr=enable'
NXSTACK_ENABLE='-znxstack=enable'
NXHEAP_ENABLE='-znxheap=enable'
LD_MAP_NOEXBSS='-M /usr/lib/ld/map.noexbss'
LD_MAP_PAGEALIGN='-M /usr/lib/ld/map.pagealign'

export LDFLAGS="-m64 $LD_MAP_NOEXBSS $LD_MAP_PAGEALIGN $LD_B_DIRECT $LD_Z_IGNORE $LD_Z_STRIP_CLASS $ASLR_ENABLE $NXSTACK_ENABLE $NXHEAP_ENABLE $LD_Z_PIE_ENABLE"

export PKG_CONFIG_PATH="/usr/lib/64/pkgconfig"

# also change package.sh when changing DESTDIR
export DESTDIR="$WORKSPACE/$JOB_NAME/proto"
EOF

$ mkdir nginx
$ cd nginx
$ cat << EOF > build.sh
#!/bin/bash

set -ex

. $WORKSPACE/compiler.sh

VER="1.13.5"
rm -rf nginx-$VER
wget https://mirror.mycompany.com/distfiles/nginx-${VER}.tar.gz
gzcat nginx-${VER}.tar.gz | pax -r
cd nginx-$VER
#gpatch -p1 < $WORKSPACE/$JOB_NAME/nginx.patch

./configure --prefix=/opt/nginx --user=webservd --group=webservd \
    --with-cc-opt="$CPPFLAGS $CFLAGS" --with-ld-opt="$LDFLAGS" \
    --with-cpu-opt=sparc64 --with-threads --with-http_ssl_module \
    --with-http_v2_module --pid-path=/var/run/nginx.pid
perl -w -pi -e 's/-fast -xipo //; s/-g //' objs/Makefile
$MAKE build

# Install

rm -rf $DESTDIR
$MAKE DESTDIR=$DESTDIR install

rmdir $DESTDIR/var/run $DESTDIR/var

mkdir -p $DESTDIR/lib/svc/manifest/site $DESTDIR/etc/logadm.d

#/usr/sbin/svccfg validate $WORKSPACE/$JOB_NAME/nginx.xml
#cp $WORKSPACE/$JOB_NAME/nginx.xml $DESTDIR/lib/svc/manifest/site/

#cp $WORKSPACE/$JOB_NAME/nginx.conf $DESTDIR/opt/nginx/conf/
openssl dhparam -engine pkcs11 -out $DESTDIR/opt/nginx/conf/dhparam.pem 2048

#cp $WORKSPACE/$JOB_NAME/nginx.logadm.conf $DESTDIR/etc/logadm.d/
EOF

$ chmod +x build.sh
$ cd ..
$ git add compiler.sh nginx
$ git commit -m "Initial nginx import"

The next steps assume we have the Developer Studio compiler installed, again see How to build software on Solaris 11/SPARC on how to get it. We need some tools like GNU make and binutils, too.

# pkg install --no-backup-be developer/build/gnu-make developer/gnu-binutils
           Packages to install:  2
            Services to change:  1
...

Time to create our first item in Jenkins now. We use nginx for Enter an item name and make it a Freestyle project.

Jenkins System Properties

Select Git as Source Code Management and insert the path to the git repo you initialized above.

Jenkins System Properties

In Build, select Execute Shell and make it execute the following two lines.

cd $WORKSPACE/nginx
./build.sh
Jenkins System Properties

Click Build Now and Jenkins will start building nginx for us.

Links

Wednesday, September 20, 2017

Leeeroooy Jenkins or let's do some CI/CD

Leeeroooy Jenkins or let's do some CI/CD

Let's have some fun with Jenkins today. I could run the war file right ahead, but I don't want to write a SMF service to start/stop it. So let's go with Tomcat instead.

# pkg install --no-backup-be tomcat-8

# zfs create -o compression=lz4 tank/tomcat8
# rsync -av /var/tomcat8/ /tank/tomcat8/
# rm -rf /tank/tomcat8/webapps/ROOT

# cat << EOF > /usr/tomcat8/bin/setenv.sh
UMASK="0022"
CATALINA_BASE="/tank/tomcat8"
CATALINA_OPTS="-DJENKINS_HOME=/tank/jenkins/ -Dhudson.model.UpdateCenter.never=true -Dhudson.DNSMultiCast.disabled=true -Dhudson.udp=-1"
JAVA_OPTS="-Xms256m -Xmx1g -XX:+UseLargePages"
EOF

Let's fix those nasty consider increasing the maximum size of the cache warnings, too.

# tail -f /tank/tomcat8/logs/catalina.out
19-Sep-2017 12:52:48.777 WARNING [Handling GET /static/30e0a8de/assets/jquery-detached/jsmodules/jquery2.js from 127.0.0.1 : http-nio-127.0.0.1-8080-exec-1] org.apache.catalina.webresources.Cache.getResource Unable to add the resource at [/WEB-INF/classes/assets/jquery-detached/jsmodules/jquery2.js] to the cache for web application [] because there was insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache
...

# perl -w -pi  -e 's|^(</Context>)$|    <Resources cachingAllowed="true" cacheMaxSize="100000" />\n$1|' /tank/tomcat8/conf/context.xml

We want Tomcat to listen on localhost only because we'll proxy it later through an TLS Apache httpd (you know, compliance...). Also make sure to change XXX_REPLACE_WITH_YOUR_FQDN to the FQDN you're using.

# groupadd -g 5213 jenkins
# useradd -u 5213 -g jenkins -d /tank/jenkins -s /bin/ksh93 -m jenkins
# passwd -N jenkins

# zfs create -o compression=lz4 tank/jenkins
# chown jenkins:jenkins /tank/jenkins

# wget -O /tank/tomcat8/webapps/ROOT.war http://mirrors.jenkins.io/war-stable/latest/jenkins.war
# chown jenkins:jenkins /tank/tomcat8/webapps/ROOT.war

# perl -w -pi -e 's|(<Connector port="8080" protocol="HTTP/1.1")|$1 address="127.0.0.1" proxyName="XXX_REPLACE_WITH_YOUR_FQDN" proxyPort="443"|' /tank/tomcat8/conf/server.xml
# perl -w -pi -e 's|^(\s+<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />)$|<!-- $1 -->|' /tank/tomcat8/conf/server.xml

# svccfg -s tomcat8 setprop start/user=jenkins
# svccfg -s tomcat8 setprop start/group=jenkins
# svcadm refresh tomcat8
# svcadm enable tomcat8
# tail -f /tank/tomcat8/logs/catalina.out
...
19-Sep-2017 12:58:45.093 INFO [Jenkins initialization thread] hudson.WebAppMain$3.run Jenkins is fully up and running

Tomcat is running as a non-root user and serving Jenkins on localhost now. Time to configure the Apache httpd proxy.

Steps for creating a new SSL certificate/key with pktool can be found here How to create a SSL CA/certificate/key with pktool. Done? Good.

# cp CA.crt /etc/apache2/2.2/server-ca.crt
# cp server.crt /etc/apache2/2.2/
# cp server.key /etc/apache2/2.2/
# chown webservd:webservd /etc/apache2/2.2/server*

# cat << 'EOF' > /etc/apache2/2.2/conf.d/ssl-jenkins.conf
SSLRandomSeed startup file:/dev/urandom 512
SSLRandomSeed connect file:/dev/urandom 512

SSLCryptoDevice pkcs11

Listen XXX_REPLACE_WITH_YOUR_FQDN:443

AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl    .crl

SSLCipherSuite AESGCM:AES
SSLProxyCipherSuite AESGCM:AES
SSLHonorCipherOrder on
SSLProtocol TLSv1.2
SSLProxyProtocol TLSv1.2
SSLSessionCache "shmcb:/var/run/apache2/2.2/ssl_scache(512000)"
SSLSessionCacheTimeout 300
SSLMutex "file:/var/run/apache2/2.2/ssl_mutex"

ProxyRequests off
ProxyPreserveHost on

<VirtualHost _default_:443>
  ServerName XXX_REPLACE_WITH_YOUR_FQDN
  ServerAdmin webservd@XXX_REPLACE_WITH_YOUR_FQDN

  SSLEngine on
  SSLCompression off
  SSLSessionTickets off
  SSLCertificateFile "/etc/apache2/2.2/server.crt"
  SSLCertificateKeyFile "/etc/apache2/2.2/server.key"
  SSLCertificateChainFile "/etc/apache2/2.2/server-ca.crt"

  Header always set Strict-Transport-Security "max-age=15768000"

  RequestHeader set X-Forwarded-Proto "https"
  RequestHeader set X-Forwarded-Port "443"
  AllowEncodedSlashes NoDecode

  ProxyPass / http://127.0.0.1:8080/ nocanon
  ProxyPassReverse / https://XXX_REPLACE_WITH_YOUR_FQDN/

  CustomLog "/var/apache2/2.2/logs/ssl_request_log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
EOF

# /usr/apache2/2.2/bin/apachectl -t
Syntax OK

# svcadm enable apache22

Fetch the admin password from /tank/jenkins/secrets/initialAdminPassword and you're ready to go.

Jenkins System Properties

Read the next part at Using Jenkins to build nginx.

Links

Thursday, September 14, 2017

When fstrim trims all our SAN paths on SLES12

When fstrim trims all our SAN paths on SLES12

Let's venture into Linux land today. We had several unplanned outages the last weeks and it all boiled down to... fstrim(8)

Sep 11 00:04:40 sles12db multipathd[2086]: sdai: mark as failed
Sep 11 00:04:40 sles12db multipathd[2086]: mpath-lvm--002: remaining active paths: 3
Sep 11 00:04:40 sles12db kernel: [...] sd 0:0:3:0: [sdai] tag#0 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
Sep 11 00:04:40 sles12db kernel: [...] sd 0:0:3:0: [sdai] tag#0 Sense Key : Illegal Request [current]
Sep 11 00:04:40 sles12db kernel: [...] sd 0:0:3:0: [sdai] tag#0 ASC=0x27 <<vendor>>ASCQ=0xb0
Sep 11 00:04:40 sles12db kernel: [...] sd 0:0:3:0: [sdai] tag#0 CDB: Write same(16) 93 08 00 00 00 00 05 04 08 00 00 00 10 a8 00 00
Sep 11 00:04:40 sles12db kernel: [...] blk_update_request: 38 callbacks suppressed
Sep 11 00:04:40 sles12db kernel: [...] blk_update_request: I/O error, dev sdai, sector 84150272
Sep 11 00:04:40 sles12db kernel: [...] EXT4-fs (dm-17): discard request in group:321 block:0 count:533 failed with -5
...
Sep 11 00:04:41 sles12db multipathd[2086]: sdaf: mark as failed
Sep 11 00:04:41 sles12db multipathd[2086]: mpath-lvm--002: remaining active paths: 2
Sep 11 00:04:41 sles12db multipathd[2086]: sdz: mark as failed
Sep 11 00:04:41 sles12db multipathd[2086]: mpath-lvm--002: remaining active paths: 1
Sep 11 00:04:41 sles12db multipathd[2086]: sdac: mark as failed
Sep 11 00:04:41 sles12db multipathd[2086]: mpath-lvm--002: remaining active paths: 0

Ooops. There goes our Oracle database filesystem...

We came to the conclusion that HBA, cables, Fibre Channel switch and storage system are fine because it only affected 3 LUNs out of 7 and everything was back to normal after 4 seconds. The following message was suspicious though.

Sep 11 00:04:40 sles12db fstrim[138568]: fstrim: /oracle/SID/oraarch: FITRIM ioctl failed: Input/output error

And guess what...

# systemctl list-timers
NEXT LEFT LAST PASSED UNIT
...
Mon 2017-09-18 00:00:00 CEST 5 days left Mon 2017-09-11 00:00:00 CEST 1 day 8h ago fstrim.timer

Luckily we were able to reproduce this on a test server using filebench rather quickly.

#  grep -Hv "zz" /sys/block/sdai/queue/discard_max_bytes
/sys/block/sdai/queue/discard_max_bytes:8183808

# mount -v
...
/dev/mapper/testvg-oraarch on /mnt/oraarch type ext4 (rw,relatime,discard,nobarrier,data=ordered)

# cat fileserver.f
set $dir=/mnt/oraarch
set $nfiles=10000
set $meandirwidth=40
set $filesize=cvar(type=cvar-gamma,parameters=mean:16m;gamma:1.5)
set $nthreads=50
set $iosize=1m
set $meanappendsize=16k
set $runtime=600

define fileset name=bigfileset,path=$dir,size=$filesize,entries=$nfiles,dirwidth=$meandirwidth,prealloc=80

define process name=filereader,instances=1
{
  thread name=filereaderthread,memsize=10m,instances=$nthreads
  {
    flowop createfile name=createfile1,filesetname=bigfileset,fd=1
    flowop writewholefile name=wrtfile1,srcfd=1,fd=1,iosize=$iosize
    flowop closefile name=closefile1,fd=1
    flowop openfile name=openfile1,filesetname=bigfileset,fd=1
    flowop appendfilerand name=appendfilerand1,iosize=$meanappendsize,fd=1
    flowop closefile name=closefile2,fd=1
    flowop openfile name=openfile2,filesetname=bigfileset,fd=1
    flowop readwholefile name=readfile1,fd=1,iosize=$iosize
    flowop closefile name=closefile3,fd=1
    flowop deletefile name=deletefile1,filesetname=bigfileset
    flowop statfile name=statfile1,filesetname=bigfileset
  }
}

echo  "File-server Version 3.0 personality successfully loaded"

run $runtime
# ./bin/filebench -f fileserver.f
...
160.033: Failed to open file 9103, /mnt/oraarch/bigfileset/00000001/00000004/00000002/00000001/00000065/00000056/00000023/00000018, with status 10: Read-only file system
160.033: filereaderthread-39: flowop createfile1-1 failed
160.033: failed to create file createfile1
160.034: filereaderthread-1: flowop createfile1-1 failed
160.034: failed to create file createfile1
160.034: filereaderthread-35: flowop createfile1-1 failed
160.033: failed to create file createfile1
160.034: filereaderthread-44: flowop createfile1-1 failed
160.193: Run took 159 seconds...

# mount -v
...
/dev/mapper/testvg-oraarch on /mnt/oraarch type ext4 (ro,relatime,discard,nobarrier,data=ordered)

Software affected so far: SuSE SLES 12 SP2, kernel-default-4.4.59-92.24.2.x86_64, Fujitsu Eternus DX8700 S3 with thin provisioned storage.

Update 2017-11-06 -- And here is the official SuSE KB document Read-only or corrupted filesystem after fstrim operation on Eternus DXM provided storage LUN.

Links

Wednesday, July 26, 2017

sudo and RBAC, or which privilege to pick

sudo and RBAC, or which privilege to pick

Robert Milkowski's recently posted how to use sudo with Solaris privileges, see Sudo and Solaris Privileges.

milek    ALL=()PRIVS="basic,sys_admin" NOPASSWD:/usr/sbin/fmadm faulty

Solaris 11.3 SRU 21 currently has 87 privileges (see ppriv -l. But why do I need "sys_admin" for fmadm?

Well the fmadm(1M) manpage says so. ;-)

The fmadm utility requires the user to possess the SYS_ADMIN privilege.

But how to check if we don't know which privilege is needed? Let's start with a small non-blackbox example.

$ cat p.c
#include <assert.h>
#include <priv.h>
#include <stdio.h>

int
main(void)
{
    priv_set_t *sp = priv_allocset();
    assert(sp != NULL);

    int ret = getppriv(PRIV_EFFECTIVE, sp);
    assert(ret == 0);

    if (!priv_ismember(sp, PRIV_SYS_ADMIN)) {
        printf("Nope\n");
    }

    priv_freeset(sp);
    return 0;
}

$ cc -m64 -g -Wall p.c

$ apptrace -v priv_ismember ./a.out
-> a.out    -> libc.so.1:boolean_t priv_ismember(const priv_set_t * = 0xffff80ffbf690290, const char * = 0x400cde "sys_admin")
        arg0 = (const priv_set_t *) 0xffff80ffbf690290
        arg1 = (const char *) 0x400cde "sys_admin"
Nope

When we try the same with fmadm faulty there are no priv_ismember calls. But we see a lot of door calls and we recall there's a fault manager daemon running.

$ svcs -p svc:/system/fmd:default
STATE          STIME    FMRI
online         Jul_19   svc:/system/fmd:default
               Jul_19        998 fmd

Let's fire up DTrace to check if there are any priv_ismember calls in /usr/lib/fm/fmd/fmd.

# cat priv.d
#!/usr/sbin/dtrace -Cs

#include <sys/priv_const.h>

#pragma D option quiet

pid$target::priv_ismember:entry
{
    trace(stringof(copyinstr(arg1)));
}

# ./priv.d -p 998

$ fmadm faulty
fmadm: failed to get case list from fmd: operation requires additional privilege

# ./priv.d -p 998
sys_admin

And there's our priv_ismember call checking for the "PRIV_SYS_ADMIN" privilege.

Links

  • privileges(5)
  • apptrace(1)

Friday, June 30, 2017

Periodic services with SMF

Periodic services with SMF

Solaris 11.3 extended SMF to support periodic and scheduled services. It was done mostly to ease IPS packagers because you can't just drop a file in /etc/cron.d and it will magically self-assemble to a cronjob (unlike e.g. /etc/logadm.d).

What's the difference between periodic and scheduled? You want a periodic service for tasks that have to run say every 15 minutes.

Each invocation of a periodic service instance start method occurs at a time relative to the last invocation.

And a scheduled service for tasks that have to run at a specific time.

Each invocation of a scheduled service instance start method occurs at a specific absolute time. Use a scheduled service when the task must run at a certain time, such as during off-peak hours.

The svcbundle command was extended as well to create periodic and scheduled service manifests.

For the periodic example we'll use fetchmail to check for new mails every 15 minutes (== 900s).

$ echo $(( 15 * 60 ))
900
$ svcbundle -o periodic_fetchmail.xml -s service-name=site/periodic/fetchmail \
  -s start-method='/usr/bin/fetchmail -s' -s period=900
# cp periodic_fetchmail.xml /lib/svc/manifest/site/
# svcadm restart svc:/system/manifest-import:default
$ svcs -o NRUN svc:/site/periodic/fetchmail:default
NRUN
22:15:27

We could also use a method_credential (see svc.periodicd(8)) so that the manifest runs as the specified user.

Let's create a scheduled service that runs every night around 00:00 o'clock now.

The crontab entry would look like the following.

0 0 * * * /usr/sbin/audit -n

Let's convert that to SMF with svcbundle.

$ svcbundle -o scheduled_auditrotate.xml -s service-name=site/scheduled/auditrotate \
  -s start-method='/usr/sbin/audit -n' \
  -s hour=0 -s minute=0 \
  -s interval=day
# cp scheduled_auditrotate.xml /lib/svc/manifest/site/
# svcadm restart svc:/system/manifest-import:default
$ svcs -o NRUN svc:/site/scheduled/auditrotate:default
NRUN
 0:00:51

We should edit the manifest and remove the dependency on vc:/milestone/multi-user and instead depend on svc:/system/auditd:default and fill in common_name and description.

For the last example we'll follow Oracle's advice and do a monthly scrub of our disks. See Recommended Storage Pool Practices.

Scrub your ZFS storage pools routinely, such as monthly, if you are using datacenter quality services.

Let's do another scheduled service which runs every month.

$ svcbundle -o scheduled_rpoolscrub.xml -s service-name=site/scheduled/rpoolscrub \
  -s start-method='/usr/sbin/zpool scrub rpool' \
  -s day_of_month=13 -s hour=4 \
  -s interval=month
# cp scheduled_rpoolscrub.xml /lib/svc/manifest/site/
# svcadm restart svc:/system/manifest-import:default

... wait till it executed

$ svcs -o LRUN svc:/site/scheduled/rpoolscrub:default
LRUN
 4:17:49
$ svcs -o NRUN svc:/site/scheduled/rpoolscrub:default
NRUN
Jul_13

Also note there are log files in /var/svc/log in case something goes wrong.

$ svcs -Lv site/scheduled/rpoolscrub
svc:/site/scheduled/rpoolscrub:default (Monthly rpool scrub)
Logfile not found for svc:/site/scheduled/rpoolscrub:default. Error: unknown error.

$ tail /var/svc/log/site-scheduled-rpoolscrub:default
Jun 13 04:17:49/6:Executing start method ("/usr/sbin/zpool scrub rpool")
Jun 13 04:17:55/5:Method "start" exited with status 0.

When you're an IPS packager, don't forget to mogrify your SMF manifests.

<transform dir path=lib/svc/manifest -> set group sys>
<transform file path=lib/svc/manifest -> set group sys>
<transform file path=lib/svc/method/.* -> set mode 0555>
<transform file path=(var|lib)/svc/manifest/.*\.xml$ -> \
    default restart_fmri svc:/system/manifest-import:default>

Links

Tuesday, June 13, 2017

How to build software on Solaris 11/SPARC

How to build software on Solaris 11/SPARC

Today we'll figure out the default build flags used by the Solaris Userland Consolidation.

We already used them while building nginx, see nginx on Solaris 11.3 SRU 19 with ECC crypto and HTTP/2 support.

We need a compiler before we can build anything. My preferred choice is the Solaris Developer Studio compiler. You can download a tarball at Developer Studio or request a solarisstudio repository certificate at Oracle Repositories.

Either way, you should have a decent compiler now.

$ /opt/developerstudio12.5/bin/cc -V
cc: Studio 12.5 Sun C 5.14 SunOS_sparc 2016/05/31

Good. Let get the default 64bit *FLAGS used to build software from shared-macros.mk.

# Enables large file support for components that have no other means of doing
# so.  Use CPP_LARGEFILES and not the .32/.64 variety directly
CPP_LARGEFILES.64 := $(shell getconf LFS64_CFLAGS)
CPP_LARGEFILES =  $(CPP_LARGEFILES.$(BITS))

# XPG6 mode.  This option enables XPG6 conformance, plus extensions.
# Amongst other things, this option will cause system calls like
# popen (3C) and system (3C) to invoke the standards-conforming
# shell, /usr/xpg4/bin/sh, instead of /usr/bin/sh.  Add studio_XPG6MODE to
# CFLAGS instead of using this directly
CPP_XPG6MODE= -D_XOPEN_SOURCE=600 -D__EXTENSIONS__=1 -D_XPG6

This should equal the following CPPFLAGS:

CPPFLAGS="$(getconf LFS64_CFLAGS) -D_XOPEN_SOURCE=600 -D__EXTENSIONS__=1 -D_XPG6"

Let's do the same for CFLAGS.

BITS ?=   64

MACH :=  $(shell uname -p)
MACH64_1 = $(MACH:sparc=sparcv9)

CC_BITS = -m$(BITS)

studio_XBITS.sparc.64 += -xarch=sparcvis -xchip=ultra2
studio_XBITS = $(studio_XBITS.$(MACH).$(BITS))

# Turn on recognition of supported C99 language features and enable the 1999 C
# standard library semantics of routines that appear in both the 1990 and
# 1999 C standard. To use set studio_C99MODE=$(studio_C99_ENABLE) in your
# component Makefile.
studio_C99_ENABLE =  -xc99=all

# Allow zero-sized struct/union declarations and void functions with return
# statements.
studio_FEATURES_EXTENSIONS = -features=extensions

studio_OPT.sparc.64 ?= -xO4
studio_OPT ?=  $(studio_OPT.$(MACH).$(BITS))

# Studio PIC code generation.  Use CC_PIC instead to select PIC code generation.
studio_PIC =  -KPIC -DPIC

# The Sun Studio 11 compiler has changed the behaviour of integer
# wrap arounds and so a flag is needed to use the legacy behaviour
# (without this flag panics/hangs could be exposed within the source).
# This is used through studio_IROPTS, not the 'sparc' variety.
studio_IROPTS.sparc = -W2,-xwrap_int
studio_IROPTS =  $(studio_IROPTS.$(MACH))

# Control register usage for generated code.  SPARC ABI requires system
# libraries not to use application registers.  x86 requires 'no%frameptr' at
# x04 or higher.

# We should just use -xregs but we need to workaround 7030022. Note
# that we can't use the (documented) -Wc,-xregs workaround because
# libtool really hates -Wc and thinks it should be -Wl. Instead
# we use an (undocumented) option which actually happens to be what
# CC would use.
studio_XREGS.sparc = -Qoption cg -xregs=no%appl
studio_XREGS =  $(studio_XREGS.$(MACH))

# Set data alignment on sparc to reasonable values, 8 byte alignment for 32 bit
# objects and 16 byte alignment for 64 bit objects.  This is added to CFLAGS by
# default.
studio_ALIGN.sparc.64 = -xmemalign=16s
studio_ALIGN =  $(studio_ALIGN.$(MACH).$(BITS))

# Studio shorthand for building multi-threaded code,  enables -D_REENTRANT and
# linking with threadin support.  This is added to CFLAGS by default, override
# studio_MT to turn this off.
studio_MT =  -mt

CFLAGS.studio += $(studio_OPT) $(studio_XBITS) $(studio_XREGS) \
   $(studio_IROPTS) $(studio_C99MODE) $(studio_ALIGN) \
   $(studio_MT)

This should equal the following CFLAGS:

CFLAGS="-m64 -xO4 -xarch=sparcvis -xchip=ultra2 \
  -Qoption cg -xregs=no%appl -W2,-xwrap_int -xc99=all -xmemalign=16s \
  -mt -KPIC -DPIC"

And last but not least, for LDFLAGS.

# set the bittedness that we want to link
LD_BITS = -$(BITS)

# eliminate unreferenced dynamic dependencies
LD_Z_IGNORE =  -zignore

# eliminate comments
LD_Z_STRIP_CLASS = -zstrip-class=comment

# use direct binding
LD_B_DIRECT =  -Bdirect

# build a PIE binary
# to enable creating a PIE binary, add LD_Z_PIE_MODE = $(LD_Z_PIE_ENABLE)
# to the component makefile, and ensure that it's built PIC (CC_PIC_ENABLE).
LD_Z_PIE_ENABLE = -ztype=pie

# by default, turn on Address Space Layout Randomization, non-executable
# stack and non-executable heap for ELF executables;
ASLR_ENABLE =    -zaslr=enable
NXSTACK_ENABLE =  -znxstack=enable
NXHEAP_ENABLE =   -znxheap=enable

# Create a non-executable bss segment when linking.
LD_MAP_NOEXBSS.sparc = -M /usr/lib/ld/map.noexbss

# Create a non-executable data segment when linking.  Due to PLT needs, the
# data segment must be executable on sparc, but the bss does not.
# see mapfile comments for more information
LD_MAP_NOEXDATA.sparc = $(LD_MAP_NOEXBSS.$(MACH))

# Page alignment
LD_MAP_PAGEALIGN = -M /usr/lib/ld/map.pagealign

# Default linker options that everyone should get.  Do not add additional
# libraries to this macro, as it will apply to everything linked during the
# component build.
LD_OPTIONS += $(LD_MAP_NOEXDATA.$(MACH)) \
  $(LD_MAP_PAGEALIGN) $(LD_B_DIRECT) $(LD_Z_IGNORE) \
  $(LD_Z_STRIP_CLASS)

This should equal the following LDFLAGS:

LDFLAGS="-m64 -M /usr/lib/ld/map.noexbss \
  -M /usr/lib/ld/map.pagealign -Bdirect -zignore \
  -zstrip-class=comment -ztype=pie \
  -zaslr=enable -znxstack=enable -znxheap=enable"

Some software also doesn't like the Solaris nm, so we'll use GNU nm instead. See configure.mk.

# temporarily work around some issues
CONFIGURE_ENV += "ac_cv_func_realloc_0_nonnull=yes"
CONFIGURE_ENV += "NM=/usr/gnu/bin/nm"

Putting everything together, here is an example of how I usually invoke configure when building FOSS:

$ getconf PATH
/usr/xpg6/bin:/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/developerstudio12.5/bin:...
$ PATH=$(getconf PATH) ./configure PKG_CONFIG_PATH=/usr/lib/64/pkgconfig NM=/usr/gnu/bin/nm SHELL=bash MAKE=gmake \
  CPPFLAGS="$(getconf LFS64_CFLAGS) -D_XOPEN_SOURCE=600 -D__EXTENSIONS__=1 -D_XPG6" \
  CC=cc CFLAGS='-m64 -xO4 -xarch=sparcvis2 -Qoption cg -xregs=no%appl -W2,-xwrap_int \
    -xc99=all -xmemalign=16s -mt -KPIC -DPIC' \
  LDFLAGS='-m64 -M /usr/lib/ld/map.noexbss -M /usr/lib/ld/map.pagealign \
     -zaslr=enable -znxstack=enable -znxheap=enable \
     -Bdirect -zignore -zstrip-class=comment -ztype=pie' \
   --prefix=/opt/local ...
$ PATH=$(getconf PATH) gmake
...

Links

Tuesday, May 23, 2017

They joy of replacing a local disk with SVM

They joy of replacing a local disk with SVM

We still have some old Sun Fire V245 server here and I had the pleasure to replace a failed disk today.

The server is still running Solaris 10 and using SVM to mirror the root disks.

What's the failed disk in question?

# iostat -En
c0t0d0           Soft Errors: 3039 Hard Errors: 75 Transport Errors: 14
Vendor: FUJITSU  Product: MAY2073RCSUN72G  Revision: 0501 Serial No: xxxxxxxxxx
Size: 73.41GB <73407865856 bytes>
Media Error: 64 Device Not Ready: 0 No Device: 11 Recoverable: 3039
Illegal Request: 2 Predictive Failure Analysis: 12

Nasty, let's configure it out.

# disk=c0t0d0
# metastat -p > /etc/lvm/md.tab
# grep $disk /etc/lvm/md.tab
d21 1 1 c0t0d0s1
d11 1 1 c0t0d0s0
# metadetach d10 d11
d10: submirror d11 is detached
# metadetach d20 d21
metadetach: solaris: d20: attempt an operation on a submirror that has erred components

Ooops, I hope the force is still with me...

# metastat d20
d20: Mirror
    Submirror 0: d21
      State: Needs maintenance
    Submirror 1: d22
      State: Okay
...
# metadetach -f d20 d21
d20: submirror d21 is detached

I had such anger, but it's all good now. Let's continue.

# metaclear d11
d11: Concat/Stripe is cleared
# metaclear d21
d11: Concat/Stripe is cleared
...
# metadb | grep $disk
     a m  p  luo        16              8192            /dev/dsk/c0t0d0s7
     a    p  luo        8208            8192            /dev/dsk/c0t0d0s7
     a    p  luo        16400           8192            /dev/dsk/c0t0d0s7
# metadb -d ${disk}s7
# cfgadm -al | grep $disk
c0::dsk/c0t0d0                 disk         connected    configured   unknown
# cfgadm -c unconfigure c0::dsk/c0t0d0

Now we can physically replace the failed disk.

# tail -f /var/adm/messages
...
May 23 12:30:20 solaris genunix: [ID 408114 kern.info] /pci@1e,600000/pci@0/pci@a/pci@0/pci@8/scsi@1/sd@0,0 (sd0) offline
May 23 12:30:27 solaris scsi: [ID 107833 kern.warning] WARNING: /pci@1e,600000/pci@0/pci@a/pci@0/pci@8/scsi@1 (mpt0):
May 23 12:30:27 solaris    mpt_handle_event_sync : SAS target 0 added.
May 23 12:30:27 solaris scsi: [ID 583861 kern.info] sd0 at mpt0: unit-address 0,0: target 0 lun 0
May 23 12:30:27 solaris genunix: [ID 936769 kern.info] sd0 is /pci@1e,600000/pci@0/pci@a/pci@0/pci@8/scsi@1/sd@0,0
May 23 12:30:28 solaris scsi: [ID 107833 kern.warning] WARNING: /pci@1e,600000/pci@0/pci@a/pci@0/pci@8/scsi@1/sd@0,0 (sd0):
May 23 12:30:28 solaris    Corrupt label - label checksum failed
May 23 12:30:28 solaris genunix: [ID 408114 kern.info] /pci@1e,600000/pci@0/pci@a/pci@0/pci@8/scsi@1/sd@0,0 (sd0) online

Alright, let's configure the new disk in.

# cfgadm -c configure c0::dsk/c0t0d0
# format $disk

c0t0d0: configured with capacity of 68.35GB
selecting c0t0d0
[disk formatted]
...
format> label
Ready to label disk, continue? y

format> quit

Time to rebuild our SVM mirror.

# metastat d20
...
Device Relocation Information:
Device   Reloc  Device ID
c0t1d0   Yes    id1,sd@n500000e016af27c0

# sourcedisk=c0t1d0
# prtvtoc /dev/rdsk/${sourcedisk}s2 | fmthard -s - /dev/rdsk/${disk}s2
# metadb -a -c3 ${disk}s7
# metainit d11
# metainit d21
# metattach d10 d11
d10: submirror d11 is attached
# metattach d20 d21
d20: submirror d21 is attached
# metadevadm -u $disk
Updating Solaris Volume Manager device relocation information for c0t0d0
Old device reloc information:
        id1,sd@n500000e0135e2dd0
New device reloc information:
        id1,sd@n500000e0135e2dd0

# installboot /usr/platform/$(uname -i)/lib/fs/ufs/bootblk /dev/rdsk/${disk}s0

# metastat -c
d20              m   4.0GB d22 d21 (resync-1%)
    d22          s   4.0GB c0t1d0s1
    d21          s   4.0GB c0t0d0s1

Once the resync is done we have our OS disks mirrored again.

Links

Thursday, May 11, 2017

Ansible 2.3 on Solaris 11.3

Ansible 2.3 on Solaris 11.3

Let's automate some tasks we do all the time.

Yes I know, I could use Puppet, but the Puppet version bundled with Solaris 11.3 is rather old (3.6.2) and some modules are broken (e.g. "ldap provider always finds authentication_method out of sync (Bug 22166490)"). So we'll use Ansible instead.

$ wget http://releases.ansible.com/ansible/ansible-2.3.1.0.tar.gz

# cd /opt
# gzcat .../ansible-2.3.1.0.tar.gz | tar xf -
# cat ansible-2.3.1.0/requirements.txt
...
jinja2
PyYAML
paramiko
pycrypto >= 2.6
setuptools

Seems like we need some Python modules to get Ansible working. Let's install them.

# pkg install --no-backup-be jinja2 pyyaml setuptools
           Packages to install: 22
...

We don't need paramiko and pycrypto (we'll use SSH instead), see Replace PyCrypto usage with cryptography.io #13075.

To speed things up we need an SSH client that supports ControlPersist. So let's install OpenSSH as well and make it the default.

# pkg install --no-backup-be network/openssh
           Packages to install:  1
...
# pkg set-mediator --no-backup-be -I openssh ssh
            Packages to change:  3
...

Does it work?

# PYTHONPATH=/opt/ansible-2.3.1.0/lib /opt/ansible-2.3.1.0/bin/ansible --version
ansible 2.3.1.0
  config file =
  configured module search path = Default w/o overrides
  python version = 2.7.9 (default, Dec  1 2016, 10:32:39) [C]

# PYTHONPATH=/opt/ansible-2.3.1.0/lib /opt/ansible-2.3.1.0/bin/ansible localhost -m ping
 [WARNING]: Host file not found: /etc/ansible/hosts

 [WARNING]: provided hosts list is empty, only localhost is available

localhost | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

Good. Time to write our first Playbook...

Links

Monday, May 8, 2017

FreeBSD aesni(4) and openssl

FreeBSD aesni(4) and openssl

I have to admit, I also like FreeBSD. There was a question if you need to kldload aesni to speed up openssl (or any application that's using libcrypto) and the short answer is no. The long answer...

What is AES-NI again?

The new AES-NI instruction set is comprised of six new instructions that perform several compute intensive parts of the AES algorithm. These instructions can execute using significantly less clock cycles than a software solution.

So AES-NI is basically just another mnemonic like ADD, SUB, XOR, MOV, AND, etc. You can just call them from user space. And that's what OpenSSL/LibreSSL does, see aesni-x86_64.S.

.globl aesni_cbc_encrypt
...
aesni_cbc_encrypt:
...
.byte 102,15,56,220,209
...

And there's our AESENC opcode. It's in .bytes notation because FreeBSD is still using a GPLv2 binutils that's too old for AES-NI mnemonics.

In Intel® 64 and IA-32 Architectures Software Developer’s Manual Volume 2 we see that the AESENC instruction has the following opcode.

66 0F 38 DC /r
AESENC xmm1, xmm2/m128

So ".byte 102,15,56,220,209" translates with some decimal to hexadecimal conversion to "0x66, 0x0F, 0x38, 0xDC". Which is just the opcode for AESENC above.

So there is no kernel stuff involved. What is aesni(4) used for then?

The aesni driver registers itself to accelerate AES operations for crypto(4).

In sys/crypto/aesni/aesni.c we see that the AES-NI kernel module registers itself as being hardware capable and for the following ciphers (see sys/crypto/aesni/aesni.c and crypto(9)).

static int
aesni_attach(device_t dev)
{
 struct aesni_softc *sc;
...
 sc->cid = crypto_get_driverid(dev, CRYPTOCAP_F_HARDWARE |
     CRYPTOCAP_F_SYNC);
...
 crypto_register(sc->cid, CRYPTO_AES_CBC, 0, 0);
 crypto_register(sc->cid, CRYPTO_AES_ICM, 0, 0);
 crypto_register(sc->cid, CRYPTO_AES_NIST_GCM_16, 0, 0);
 crypto_register(sc->cid, CRYPTO_AES_128_NIST_GMAC, 0, 0);
 crypto_register(sc->cid, CRYPTO_AES_192_NIST_GMAC, 0, 0);
 crypto_register(sc->cid, CRYPTO_AES_256_NIST_GMAC, 0, 0);
 crypto_register(sc->cid, CRYPTO_AES_XTS, 0, 0);
...

So the aesni kernel module provides crypto services with the OpenCrypto framework for both user space (that's the /dev/crypto device) via crypto(4) and kernel space (think of GELI and IPSec) via crypto(9).

Still not convinced that openssl is not using aesni(4)? Let's fire up DTrace just to be sure...

For the first test, no aesni(4) kernel module is loaded. We use openssl with -evp to make sure we're actually using hardware crypto (and you'll see it's calling libcrypto's aesni_cbc_encrypt function we talked about earlier). Notice there is almost no user/kernel space boundary crossing.

# kldstat 
Id Refs Address            Size     Name
 1    6 0xffffffff80200000 1fa7c38  kernel
 2    1 0xffffffff82219000 249d     ulpt.ko
 3    1 0xffffffff8221c000 adec     tmpfs.ko

# kldload dtraceall

# dtrace -n 'pid$target:libcrypto.so.8:*aesni*:entry { @[probefunc] = count(); }' \
  -c "openssl speed -elapsed -evp aes-128-cbc"
...
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
aes-128-cbc       5973.14k    23210.84k    84090.94k   238951.75k   543361.71k
...
  aesni_cbc_encrypt                                           4105425

# dtrace -n 'fbt:kernel:copy*:entry /pid == $target/ { @bytes[probefunc] = quantize(arg2); }' \
  -c "openssl speed -elapsed -evp aes-128-cbc"
...
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
aes-128-cbc     602153.10k   640760.18k   643890.94k   660515.73k   666079.99k
...
  copyin                                            
           value  ------------- Distribution ------------- count    
               4 |                                         0        
               8 |@                                        2        
              16 |@@@@@@@@@@@@                             16       
              32 |@@@@@@@@@@@@@@@@                         22       
              64 |@@@                                      4        
             128 |                                         0        
             256 |@@@@                                     5        
             512 |@@@@                                     5        
            1024 |                                         0        

  copyinstr                                         
           value  ------------- Distribution ------------- count    
             512 |                                         0        
            1024 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 6        
            2048 |                                         0        

  copyout                                           
           value  ------------- Distribution ------------- count    
               4 |                                         0        
               8 |@                                        1        
              16 |@@@@@@@@@                                15       
              32 |@@@@@@@@                                 14       
              64 |@                                        2        
             128 |@@@@@@@@@@@@                             21       
             256 |@@@                                      5        
             512 |@@@                                      6        
            1024 |                                         0        
            2048 |@@@                                      5        
            4096 |                                         0      

Let's load the aesni(4) kernel module now and check if any kernel aesni probes fire.

# kldload aesni
aesni0: <AES-CBC,AES-XTS,AES-GCM,AES-ICM> on motherboard

# dtrace -n 'fbt:aesni::entry /pid == $target/ { @[probefunc] = count(); }' \
  -c "openssl speed -elapsed -evp aes-128-cbc"
...
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
aes-128-cbc     616989.41k   668602.69k   670494.73k   673865.32k   679105.88k
...

No probes fired. That means openssl is not using the aesni kernel functions at all.

BUT, we can make openssl use aesni(4) with -engine cryptodev. Let's check if any kernel aesni and user/kernel space boundary crossing probes fire now.

# kldload cryptodev
# openssl engine -c -tt
(cryptodev) BSD cryptodev engine
 [RSA, DSA, DH, AES-128-CBC, AES-192-CBC, AES-256-CBC]
     [ available ]
...

# dtrace -n 'fbt:aesni::entry /pid == $target/ { @[probefunc] = count(); }' \
  -c "openssl speed -elapsed -evp aes-128-cbc"
...
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
aes-128-cbc       4056.66k    15608.91k    57565.04k   183731.20k   492147.10k
...
  aesni_cipher_setup_common                                         8
  aesni_freesession                                                 8
  aesni_newsession                                                  8
  aesni_cipher_alloc                                          3036256
  aesni_encrypt_cbc                                           3036256
  aesni_process                                               3036256

# dtrace -n 'fbt:kernel:copy*:entry /pid == $target/ { @bytes[probefunc] = quantize(arg2); }' \
  -c "openssl speed -elapsed -evp aes-128-cbc"
...
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
aes-128-cbc       3602.78k    13827.67k    51851.57k   168562.00k   472572.78k
...
  copyinstr                                         
           value  ------------- Distribution ------------- count    
             512 |                                         0        
            1024 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 6        
            2048 |                                         0        

  copyout                                           
           value  ------------- Distribution ------------- count    
               2 |                                         0        
               4 |                                         8        
               8 |                                         1        
              16 |@@@@@                                    675536   
              32 |@@@@@@@@@@@@@@@@@@@@                     2603253  
              64 |@@@@@                                    649862   
             128 |                                         21       
             256 |@@@@@                                    609223   
             512 |                                         6        
            1024 |@@@@                                     495120   
            2048 |                                         5        
            4096 |                                         0        
            8192 |@                                        173512   
           16384 |                                         0        

  copyin                                            
           value  ------------- Distribution ------------- count    
               2 |                                         0        
               4 |                                         15       
               8 |                                         3        
              16 |@@@@@@@@@@@@@@@@@                        3278781  
              32 |@@@@@@@@@@@@@                            2603265  
              64 |@@@                                      649864   
             128 |                                         0        
             256 |@@@                                      609223   
             512 |                                         5        
            1024 |@@@                                      495120   
            2048 |                                         0        
            4096 |                                         0        
            8192 |@                                        173512   
           16384 |                                         0  

That's weird, -engine cryptodev seems to be on by default as soon as we loaded the cryptodev kernel module. Also note the huge amount of user/kernel space boundary crossing. That's a lot of data to be copied from user space to kernel space and back again for nothing. Mental note here, don't load the cryptodev kernel module ever unless using a hifn(4), safe(4) or ubsec(4) crypto accelerator.

Links

389 Directory Server 1.3.x LDAP client authentication

389 Directory Server 1.3.x LDAP client authentication Last time we did a multi-master replication setup, see 389 Directory Server 1.3.x Repl...